blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
91b8bb0bd6371c0bfbbdd0366f9a6c6ccaea55f9
113bc88ebf81afb4f90b0c53ef9011ebaad1da09
/src/main/java/com/aburgos/projectjsf/services/EmpleadoService.java
5964e8ec07dd9a02db86efcda70d28c164142b21
[]
no_license
Alexisburgos97/project-jsf
10c306f49e2d56e55362c0228834a582a76d5527
32c7c137e2e9436730d0fbd26c0c6e7df2b7721f
refs/heads/master
2023-08-25T02:53:41.125610
2021-10-21T22:10:11
2021-10-23T15:50:35
418,690,116
0
0
null
null
null
null
UTF-8
Java
false
false
2,444
java
/** * */ package com.aburgos.projectjsf.services; import java.util.ArrayList; import java.util.List; import com.aburgos.projectjsf.entity.Empleado; /** * @author Alexis * * Clase que permite realizar la lógica de negocio para empleados. * */ public class EmpleadoService { public List<Empleado> consultarEmpleados(){ List<Empleado> empleados = new ArrayList<Empleado>(); Empleado empleadoIBM = new Empleado(); Empleado empleadoMicrososft = new Empleado(); Empleado empleadoApple = new Empleado(); Empleado empleado1 = new Empleado(); Empleado empleado2 = new Empleado(); Empleado empleado3 = new Empleado(); Empleado empleado4 = new Empleado(); Empleado empleado5 = new Empleado(); Empleado empleado6 = new Empleado(); empleadoIBM.setNombre("Alexis"); empleadoIBM.setApellido("Burgos"); empleadoIBM.setPuesto("Developer java Jr"); empleadoIBM.setEstado(true); empleadoMicrososft.setNombre("Pedro"); empleadoMicrososft.setApellido("Lopez"); empleadoMicrososft.setPuesto("Developer java Senior"); empleadoMicrososft.setEstado(true); empleadoApple.setNombre("Juan"); empleadoApple.setApellido("Perez"); empleadoApple.setPuesto("Developer java Semi Senior"); empleadoApple.setEstado(true); empleado1.setNombre("Jose"); empleado1.setApellido("Lopez"); empleado1.setPuesto("Developer PHP Semi Senior"); empleado1.setEstado(true); empleado2.setNombre("Rodrigo"); empleado2.setApellido("Cortez"); empleado2.setPuesto("Developer PHP Senior"); empleado2.setEstado(true); empleado3.setNombre("Kyliam"); empleado3.setApellido("gonzalez"); empleado3.setPuesto("Developer PHP junior"); empleado3.setEstado(true); empleado4.setNombre("Raul"); empleado4.setApellido("Krats"); empleado4.setPuesto("Developer Javascript Senior"); empleado4.setEstado(true); empleado5.setNombre("Pedro"); empleado5.setApellido("Gonzalez"); empleado5.setPuesto("UX/UI"); empleado5.setEstado(true); empleado6.setNombre("Tiago"); empleado6.setApellido("Jino"); empleado6.setPuesto("Software engineer"); empleado6.setEstado(true); empleados.add(empleadoIBM); empleados.add(empleadoMicrososft); empleados.add(empleadoApple); empleados.add(empleado1); empleados.add(empleado2); empleados.add(empleado3); empleados.add(empleado4); empleados.add(empleado5); empleados.add(empleado6); return empleados; } }
[ "alexisburgos1997@gmail.com" ]
alexisburgos1997@gmail.com
0167b3d4eeaa026bd36f68f284a8e80abb77b941
d9c3ca3d9a47207c3d4a7c3bc24b87261c6ac29b
/Packages/openstep/appkit/OSDataLinkPanel.java
27898ef8c1eef5cea4d92e483535ce6161cbeaf5
[]
no_license
hugodro/OpenStep
92ba10e41cdea5ef47f42bc3705840f2a468a9f8
bff2f7a1825c5c6690d3afaa523de604762b2959
refs/heads/master
2022-08-23T18:33:59.699075
2020-05-20T03:04:57
2020-05-20T03:04:57
265,434,678
0
0
null
null
null
null
UTF-8
Java
false
false
1,361
java
/* Obj-C to Java: * Class: NSDataLinkPanel. * Source File: NSDataLinkPanel.h. * Module: OpenStep : AppKit. * Time stamp: Mon Jun 23 22:55:02 1997. */ package openstep.appkit; import openstep.foundation.*; import openstep.appkit.*; public class OSDataLinkPanel extends OSPanel implements OSCoding { // Methods. static OSDataLinkPanel sharedDataLinkPanel() { return null; } static void getLink_manager_isMultiple(OSDataLink link, OSDataLinkManager linkManager, boolean flag) { } static void setLink_manager_isMultiple(OSDataLink link, OSDataLinkManager linkManager, boolean flag) { } void getLink_manager_isMultiple(OSDataLink link, OSDataLinkManager linkManager, boolean flag) { } void setLink_manager_isMultiple(OSDataLink link, OSDataLinkManager linkManager, boolean flag) { } OSView accessoryView() { return null; } void setAccessoryView(OSView aView) { } void pickedBreakAllLinks(Object sender) { } void pickedBreakLink(Object sender) { } void pickedOpenSource(Object sender) { } void pickedUpdateDestination(Object sender) { } void pickedUpdateMode(Object sender) { } void encodeWithCoder(Object aCoder) { } Object initWithCoder(Object aDecoder) { return null; } }
[ "" ]
66ce5a507d0d016aee73fcd0214445607cf42420
8d859bcadb20132b3145b2d1194a4ecb3bb02626
/src/main/java/com/emk/product/hs/service/impl/EmkProductHsServiceImpl.java
c7bb0965cc311e8fe904afbef46a391d49ea9408
[]
no_license
panjs008/yun2
a7cbaf63becd15e33f0ee66376589b59721cda1c
88887593dcc1b29232e5fdef79439b1bcbbd1f0f
refs/heads/master
2022-12-21T00:16:13.405709
2020-02-19T01:14:49
2020-02-19T01:14:49
241,502,060
0
0
null
2022-12-16T04:25:16
2020-02-19T01:00:53
Java
UTF-8
Java
false
false
4,275
java
package com.emk.product.hs.service.impl; import com.emk.product.hs.entity.EmkProductHsEntity; import com.emk.product.hs.service.EmkProductHsServiceI; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.jeecgframework.core.common.service.impl.CommonServiceImpl; import org.jeecgframework.core.util.ApplicationContextUtil; import org.jeecgframework.core.util.MyClassLoader; import org.jeecgframework.core.util.StringUtil; import org.jeecgframework.web.cgform.enhance.CgformEnhanceJavaInter; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service("emkProductHsService") @Transactional public class EmkProductHsServiceImpl extends CommonServiceImpl implements EmkProductHsServiceI { public void delete(EmkProductHsEntity entity) throws Exception { super.delete(entity); doDelBus(entity); } public Serializable save(EmkProductHsEntity entity) throws Exception { Serializable t = super.save(entity); doAddBus(entity); return t; } public void saveOrUpdate(EmkProductHsEntity entity) throws Exception { super.saveOrUpdate(entity); doUpdateBus(entity); } private void doAddBus(EmkProductHsEntity t) throws Exception { } private void doUpdateBus(EmkProductHsEntity t) throws Exception { } private void doDelBus(EmkProductHsEntity t) throws Exception { } private Map<String, Object> populationMap(EmkProductHsEntity t) { Map<String, Object> map = new HashMap(); map.put("id", t.getId()); map.put("create_name", t.getCreateName()); map.put("create_by", t.getCreateBy()); map.put("create_date", t.getCreateDate()); map.put("sys_org_code", t.getSysOrgCode()); map.put("hs_code", t.getHsCode()); map.put("hs_name", t.getHsName()); map.put("bgys", t.getBgys()); map.put("zz_val", t.getZzVal()); map.put("ts_val", t.getTsVal()); map.put("sale_price", t.getSalePrice()); map.put("remark", t.getRemark()); return map; } public String replaceVal(String sql, EmkProductHsEntity t) { sql = sql.replace("#{id}", String.valueOf(t.getId())); sql = sql.replace("#{create_name}", String.valueOf(t.getCreateName())); sql = sql.replace("#{create_by}", String.valueOf(t.getCreateBy())); sql = sql.replace("#{create_date}", String.valueOf(t.getCreateDate())); sql = sql.replace("#{sys_org_code}", String.valueOf(t.getSysOrgCode())); sql = sql.replace("#{hs_code}", String.valueOf(t.getHsCode())); sql = sql.replace("#{hs_name}", String.valueOf(t.getHsName())); sql = sql.replace("#{bgys}", String.valueOf(t.getBgys())); sql = sql.replace("#{zz_val}", String.valueOf(t.getZzVal())); sql = sql.replace("#{ts_val}", String.valueOf(t.getTsVal())); sql = sql.replace("#{sale_price}", String.valueOf(t.getSalePrice())); sql = sql.replace("#{remark}", String.valueOf(t.getRemark())); sql = sql.replace("#{UUID}", UUID.randomUUID().toString()); return sql; } private void executeJavaExtend(String cgJavaType, String cgJavaValue, Map<String, Object> data) throws Exception { if (StringUtil.isNotEmpty(cgJavaValue)) { Object obj = null; try { if ("class".equals(cgJavaType)) { obj = MyClassLoader.getClassByScn(cgJavaValue).newInstance(); } else if ("spring".equals(cgJavaType)) { obj = ApplicationContextUtil.getContext().getBean(cgJavaValue); } if ((obj instanceof CgformEnhanceJavaInter)) { CgformEnhanceJavaInter javaInter = (CgformEnhanceJavaInter) obj; javaInter.execute("emk_product_hs", data); } } catch (Exception e) { e.printStackTrace(); throw new Exception("执行JAVA增强出现异常!"); } } } }
[ "245613376@qq.com" ]
245613376@qq.com
084eb633f6eb44803413ff7247c2d343c6c808e7
5440c44721728e87fb827fb130b1590b25f24989
/WPP/src/br/com/brasiltelecom/ppp/home/FilaRecargasHome.java
a2edfeb2c33090c1c25ee428601aac1a70a3236f
[]
no_license
amigosdobart/gpp
b36a9411f39137b8378c5484c58d1023c5e40b00
b1fec4e32fa254f972a0568fb7ebfac7784ecdc2
refs/heads/master
2020-05-15T14:20:11.462484
2019-04-19T22:34:54
2019-04-19T22:34:54
182,328,708
0
0
null
null
null
null
ISO-8859-1
Java
false
false
2,463
java
/* * Created on 02/03/2005 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ package br.com.brasiltelecom.ppp.home; import java.util.ArrayList; import java.util.Collection; import org.exolab.castor.jdo.Database; import org.exolab.castor.jdo.OQLQuery; import org.exolab.castor.jdo.PersistenceException; import org.exolab.castor.jdo.QueryResults; import br.com.brasiltelecom.ppp.portal.entity.FilaRecargas; /** * Classe responsavel pelas consultas/atualizações no banco de dados relativas aos registros da Fila de Recargas * * @author Daniel Ferreira * @since 02/03/2005 */ public class FilaRecargasHome { /** * Metodo estatico responsavel pela localizacao dos registros na fila de recargas, de acordo com os parametros * @param db Conexão com o Banco de Dados. * @throws PersistenceException Exceção lançada para possíveis erros de consulta dos dados. * @return result Objeto FilaRecargas com todas suas propriedades e funcionalidades. */ public static FilaRecargas findByParam(Database db, String idtMsisdn, String tipTransacao, Integer idtStatusProcessamento) throws PersistenceException { OQLQuery query = null; FilaRecargas result = null; QueryResults rs = null; try { query = db.getOQLQuery("select a from "+ "br.com.brasiltelecom.ppp.portal.entity.FilaRecargas a "+ "where a.idtMsisdn = $1 and a.tipTransacao = $2 and a.idtStatusProcessamento = $3 "); query.bind(idtMsisdn); query.bind(tipTransacao); query.bind(idtStatusProcessamento); rs = query.execute(); if(rs.hasMore()) { result = (FilaRecargas)rs.next(); } } finally { if(rs != null) rs.close(); if(query != null) { query.close(); } } return result; } public static Collection findAll(Database db) throws PersistenceException { OQLQuery query = null; Collection result = new ArrayList(); QueryResults rs = null; try { query = db.getOQLQuery("select a from "+ "br.com.brasiltelecom.ppp.portal.entity.FilaRecargas a " + "order by a.idtMsisdn, a.datCadastro"); rs = query.execute(); while(rs.hasMore()) { result.add((FilaRecargas) rs.next()); } } finally { if(rs != null) rs.close(); if(query!=null) { query.close(); } } return result; } }
[ "lucianovilela@gmail.com" ]
lucianovilela@gmail.com
485a55a513ddace7ce03dabc7497cb8bf96de0e8
78dc70df860e2f23f8430100ece6cdb447a4142c
/vap-browser/src/main/java/com/vrv/vap/browser/domain/SysRoleMenu.java
588371346bf9ab21f209adced5aba8d21c026630
[]
no_license
ljh205sy/vap-code
1e4f7e008e3cb588a06a0305367a3914833f60fd
793b7ba6af4c7ab0b1b219e915770dbf6e586907
refs/heads/main
2023-04-21T06:41:46.926171
2021-04-05T02:43:01
2021-04-05T02:43:01
353,185,550
1
0
null
null
null
null
UTF-8
Java
false
false
958
java
package com.vrv.vap.browser.domain; import javax.persistence.*; @Table(name = "sys_role_menu") public class SysRoleMenu { @Column(name = "role_id") private Integer roleId; @Column(name = "menu_id") private Integer menuId; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; /** * @return role_id */ public Integer getRoleId() { return roleId; } /** * @param roleId */ public void setRoleId(Integer roleId) { this.roleId = roleId; } /** * @return menu_id */ public Integer getMenuId() { return menuId; } /** * @param menuId */ public void setMenuId(Integer menuId) { this.menuId = menuId; } /** * @return id */ public Integer getId() { return id; } /** * @param id */ public void setId(Integer id) { this.id = id; } }
[ "liujinhui@vrvmail.com.cn" ]
liujinhui@vrvmail.com.cn
3e623a3328698fd432d13353e5ac080c70a48f8c
25f207b8884b609799eee3026a7f16144af1420a
/src/main/java/JavaExaplePractice/JavaExaplePractice/ArrayElementMultiply.java
320ca997190244977a8ae2ce4e25536103966db1
[]
no_license
sunnybce86/JavaExamples
b19d4325481ded8d5b657092214fddb34b30554a
1cd80a1a1c036653de0e44efead882057be1ffe4
refs/heads/master
2020-04-20T00:06:21.494789
2019-01-31T11:28:27
2019-01-31T11:28:27
168,513,569
0
0
null
null
null
null
UTF-8
Java
false
false
482
java
package JavaExaplePractice.JavaExaplePractice; import java.util.Arrays; public class ArrayElementMultiply { @SuppressWarnings("null") public static void main(String[] args) { int[] arr= {1,5,8,9,6}; int[] result = new int[5]; int res=0; for (int i = 0; i < arr.length; i++) { for (int j = i+1; j < arr.length; j++) { res += arr[i]*arr[j]; result[i] =res; } } System.out.println(Arrays.toString(result)); } }
[ "sunny.singh@csilhyd1.com" ]
sunny.singh@csilhyd1.com
354156b73c975dc64da6000acdb14e374e29460b
cc7cfa2106d95e0085ca6628de52b21012ad1b73
/Leetcode/src/main/java/leetcode/Linkedin/CanPlaceFlowers.java
80d8287717a1194e973c00b796bba0d8eed0d514
[]
no_license
chaocui/CodingPractise
101c7100f9967c989277a9899be9b879062be5b8
41c009a483e8783fa357d106a167bfa452c6cfdd
refs/heads/master
2021-01-02T08:48:20.381480
2017-08-02T04:44:38
2017-08-02T04:44:41
99,064,878
0
0
null
null
null
null
UTF-8
Java
false
false
1,085
java
package leetcode.Linkedin; /** * Created by cc on 2017/6/25. */ public class CanPlaceFlowers { /** * Pattern * * two 1s if there are 1 or 2 0s between them cannot plant anything, * if there are 3,4, can plant 1, 5,6 plant 2. * if there n 0s, * can plant (n-1)/2 * * special case, beginning and the end, two spaces can plant 1. * */ public boolean canPlaceFlowers(int[] flowerbed, int n) { /** * We set starting at -2. * so that end - start - 1 can be a normal equation to calculate number of zeros. * */ int start = -2; for(int i = 0; i < flowerbed.length; i++){ if(flowerbed[i] == 1){ n = n - (i - start - 1 - 1)/2; start = i; } } //we also need to handle the trailing zeros. //same as start, trailing 2,3 can plant 1, 4,5 can plant 2. //so (flowerbed.length - start - 1) is how many zeros. then divide 2. n = n - (flowerbed.length - start - 1)/2; return n <= 0; } }
[ "cc.chaocui@gmail.com" ]
cc.chaocui@gmail.com
43673746854576e56abee8612711bc6e2cf30585
19ccce8e68de4a4cb0659278cd674edb42059120
/RotaWeb/src/java/String/StringTool.java
4ea2d5cd669d49a88cb83ac0e1f29f012119e298
[]
no_license
DanielDerlando/Rota
e221caed3893d65414582cd57b4b3b31fd530a47
bbb233d1884a0d82394159ba438d37cc3c7001ff
refs/heads/master
2021-01-10T17:58:19.374527
2015-06-20T01:11:39
2015-06-20T01:11:39
36,896,779
0
0
null
null
null
null
UTF-8
Java
false
false
2,361
java
/* * 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 String; import Node.Node; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Daniel */ public class StringTool { FileWriter writeFile = null; File file = null; private final String path = "C:\\Users\\Daniel\\Documents\\NetBeansProjects\\RotaWeb\\web\\"; public StringTool() { } public void criaJson(String name, Node end) { String dados = "{\"coordenadas\":"; String json = "]"; while (end.getParent() != null) { json = ",[[" + end.getS().getArgs().get(0) + "],[" + end.getS().getArgs().get(1) + "]]" + json; end = end.getParent(); } json = "[[[" + end.getS().getArgs().get(0) + "],[" + end.getS().getArgs().get(1) + "]]" + json; dados = dados + json + "}"; try { file = new File(path + name + ".json"); if (file.exists()) { System.out.println(file.getPath()); file.delete(); } writeFile = new FileWriter(file); //Escreve no arquivo conteudo do Objeto JSON writeFile.write(dados); writeFile.flush(); System.out.println("Arquivo criado " + file.getPath()); } catch (IOException e) { e.printStackTrace(); } finally { try { writeFile.close(); } catch (IOException ex) { Logger.getLogger(StringTool.class.getName()).log(Level.SEVERE, null, ex); } } } public String nodeParseToWebString(Node end) { int numberOfNodes = 0; String dados = ""; while (end.getParent() != null) { dados = end.getS().getArgs().get(0).toString() + " " + end.getS().getArgs().get(1).toString() + " " + dados; numberOfNodes++; end = end.getParent(); } dados = end.getS().getArgs().get(0).toString() + " " + end.getS().getArgs().get(1).toString() + " " + dados; System.out.println("Comprimento do Caminho: " + numberOfNodes); return dados; } }
[ "danielderlando@hotmail.com" ]
danielderlando@hotmail.com
ee148656e555542eec84bf63f5cf2c7fd533e1e4
aab101d9b8d7e1b639b60c8e3dd1a65d0e865969
/SimpleGraph.java
de4b8c54f35a64e119b63ae0548d59a1d31524dc
[]
no_license
SaimumIslam/NumeriacalMethods
d41d27cd8e81f91632f2965d237ff4a0a3663df9
bdb2333ca29ceb100fc4b5e764a653fd6ed49062
refs/heads/master
2020-08-04T20:17:20.608225
2019-10-02T06:08:40
2019-10-02T06:08:40
212,267,200
0
0
null
null
null
null
UTF-8
Java
false
false
1,669
java
import java.awt.*; import javax.swing.*; public class SimpleGraph extends JFrame { private final int WIDTH = 330; private final int HEIGHT = 500; private Container drawable; private JPanel canvas; public SimpleGraph(double[] someData) { super("SimpleGraph"); drawable = getContentPane(); canvas = new GraphCanvas(someData); drawable.add(canvas); setSize(WIDTH, HEIGHT); } public class GraphCanvas extends JPanel { private double[] data; private int points; private double[] XData; private double[] YData; public GraphCanvas(double[] someData) { super(); data = someData; points = data.length / 2; XData = new double[points]; YData = new double[points]; for(int i = 0; i < points; i++) { XData[i] = data[i * 2]; YData[i] = data[i * 2 + 1]; } } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; this.setBackground(Color.BLUE); for(int i = 0; i < points - 1; i++) { int x0 = (int) (XData[i] * 15); int x1 = (int) (XData[i + 1] * 15); int y0 = (int) (YData[i] *15); int y1 = (int) (YData[i + 1] *15); g.setColor(Color.RED); g2.drawLine(x0, y0, x1, y1); if (i == 0) g2.drawString(("" + x0 + ", " + y0), x0 - 20, y0 + 10); if (i == points - 2) g2.drawString(("" + x1 + ", " + y1), x1, y1); } } } }
[ "saimumislam96@gmail.com" ]
saimumislam96@gmail.com
730481d52ae353095fb66fdddfbdd1bcc55c0ee0
5ce1ec56ea966181470af1f6b94cb7126f416543
/app/src/main/java/com/share/bag/utils/okhttp/callback/MyNetWorkCallback.java
b38ba30750e5ef92c95001875f30d0be4b5f5cdc
[]
no_license
Clxm/ShareBag
2eee6477fe990904257eee427270dedd0f2cc568
04bc3650399eb69ccd34fbfa63dd0b7e10380a14
refs/heads/master
2020-03-09T11:46:46.081029
2018-06-08T03:22:53
2018-06-08T03:22:53
128,769,392
0
0
null
null
null
null
UTF-8
Java
false
false
263
java
package com.share.bag.utils.okhttp.callback; import org.json.JSONException; /** * Created by xingge on 2017/7/11. */ public interface MyNetWorkCallback<T> { void onSuccess(T t) throws JSONException; void onError(int errorCode, String errorMsg); }
[ "luxiaozhao7011" ]
luxiaozhao7011
bb4f2960b88a5f3b34692ed6c29f53c3af22be8f
d382f4a2bc1d7cc6932d9c101c841e0bca15efcc
/src/com/servlet/ShopcarServlet.java
cd8e03299b03b3929bd687a3eeeadd80bbfa99f6
[]
no_license
cyjbenyy/Project_website_prototype
51a16c15df8912e3c0cdf669a8dfc493b7937a4b
ba555e7634f4bf9004f659763065f261e6e7cda8
refs/heads/master
2021-01-10T13:19:32.295305
2016-03-09T18:04:00
2016-03-09T18:43:48
53,518,028
0
0
null
null
null
null
GB18030
Java
false
false
12,978
java
package com.servlet; import java.io.IOException; import java.sql.SQLException; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.dao.GoodsDao; import com.dao.OrderformDao; import com.dao.ShopcarDao; import com.dao.TempDao; import com.toolsbean.StringHandler; import com.valuebean.OrderformBean; import com.valuebean.ShopcarBean; import com.valuebean.UserBean; public class ShopcarServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { doPost(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String servletpath=request.getServletPath(); if("/buy".equals(servletpath)) buy(request,response); else if("/showshopcar".equals(servletpath)) showshopcar(request,response); else if("/remove".equals(servletpath)) remove(request,response); else if("/clearshopcar".equals(servletpath)) clear(request,response); else if("/submitshopcar".equals(servletpath)) submitDispatcher(request,response); else if("/createorderform".equals(servletpath)) createorderform(request,response); } protected void buy(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String message=""; Integer buygoodsid=StringHandler.strToint(request.getParameter("buygoodsId")); if(buygoodsid==null){ message="<li>商品ID值错误!</li>"; message+="<a href='window.history.go(-1)'>返回</a>"; } else{ try { Date now=new Date(); TempDao tempDao=new TempDao(); String shopcarid=seeshopcarcookie(request,response); if(shopcarid==null||shopcarid.equals("")||!tempDao.isexist(shopcarid)){ shopcarid=addshopcarcookie(request,response,now); tempDao.saveShopcarCreateTime(shopcarid, StringHandler.timeTostr(now)); } int i=-1; ShopcarDao shopcarDao=new ShopcarDao(); Object[] params={shopcarid,buygoodsid}; if(shopcarDao.isBuy(params)) i=shopcarDao.addBuyNum(params); else{ params=new Object[]{shopcarid,buygoodsid,1}; i=shopcarDao.addBuyGoods(params); } shopcarDao.closed(); if(i<=0) message="<li>添加商品到购物车失败!</li><br>"; else message="<li>添加商品到购物车成功!</li><br>"; message+="<a href='javascript:window.history.go(-1)'>返回</a>"; message+="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; message+="<a href='showshopcar'>查看购物车<a/>"; } catch (SQLException e) { e.printStackTrace(); } } request.setAttribute("message",message); RequestDispatcher rd=request.getRequestDispatcher("/message.jsp"); rd.forward(request,response); } private String seeshopcarcookie(HttpServletRequest request,HttpServletResponse response){ String webname=request.getContextPath(); webname=webname.substring(1); Cookie[] coks=request.getCookies(); String shopcarid=""; int i=0; for(;i<coks.length;i++){ Cookie icok=coks[i]; if(icok.getName().equals(webname+".usershopcar")){ shopcarid=icok.getValue(); break; } } return shopcarid; } private String addshopcarcookie(HttpServletRequest request,HttpServletResponse response,Date date){ String webname=request.getContextPath(); webname=webname.substring(1); String shopcarid="car"+StringHandler.getSerial(date); Cookie shopcar=new Cookie(webname+".usershopcar",shopcarid); shopcar.setPath("/"); int maxage=60*60*24*3; shopcar.setMaxAge(maxage); response.addCookie(shopcar); return shopcarid; } protected void showshopcar(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String shopcarid=seeshopcarcookie(request,response); if(shopcarid!=null&&!shopcarid.equals("")){ ShopcarBean shopcar=new ShopcarDao().getShopcar(shopcarid); request.setAttribute("shopcar",shopcar); } RequestDispatcher rd=request.getRequestDispatcher("/showShopcar.jsp"); rd.forward(request,response); } protected void remove(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { Integer goodsId=StringHandler.strToint(request.getParameter("goodsId")); String shopcarid=seeshopcarcookie(request,response); if(shopcarid!=null&&!shopcarid.equals("")&&goodsId!=null){ ShopcarDao shopcarDao=new ShopcarDao(); int i=shopcarDao.deleteGoods(shopcarid,goodsId); if(i<=0) request.setAttribute("message","●删除商品失败!"); else request.setAttribute("message","●删除商品成功!"); shopcarDao.closed(); } showshopcar(request,response); } protected void clear(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String shopcarid=seeshopcarcookie(request,response); if(shopcarid!=null&&!shopcarid.equals("")){ ShopcarDao shopcarDao=new ShopcarDao(); int i=shopcarDao.clearShopcar(shopcarid); if(i<=0) request.setAttribute("message","●清空购物车失败!"); else request.setAttribute("message","●清空购物车成功!"); shopcarDao.closed(); } RequestDispatcher rd=request.getRequestDispatcher("/showShopcar.jsp"); rd.forward(request,response); } protected void submitDispatcher(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException { String whichsubmit=request.getParameter("whichsubmit"); if(whichsubmit==null) payforMoney(request,response); else updatebuyNum(request,response); } private void payforMoney(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException { if(shopcar_validateBuyNum(request, response)){ String buygoodsids=StringHandler.ArrayToString(request.getParameterValues("buygoodsids")); String buygoodsnum=StringHandler.ArrayToString(request.getParameterValues("buygoodsnum")); request.setAttribute("buygoodsids", buygoodsids); request.setAttribute("buygoodsnum", buygoodsnum); RequestDispatcher rd=request.getRequestDispatcher("/fillOrderform.jsp"); rd.forward(request,response); } else showshopcar(request,response); } protected void updatebuyNum(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException { shopcar_validateBuyNum(request, response); showshopcar(request,response); } private boolean shopcar_validateBuyNum(HttpServletRequest request,HttpServletResponse response){ boolean mark=true; String[] goodsStoreNums=request.getParameterValues("buygoodsstorenum"); String[] buyNums=request.getParameterValues("buygoodsnum"); String[] goodsIds=request.getParameterValues("buygoodsids"); String shopcarid=seeshopcarcookie(request,response); if(goodsIds!=null&&goodsIds.length!=0&&shopcarid!=null){ Map messages=new HashMap(); Object[] params=new Object[3]; ShopcarDao shopcarDao=new ShopcarDao(); for(int i=0;i<goodsIds.length;i++){ int int_buyNum=Integer.parseInt(buyNums[i]); int int_goodsStoreNums=Integer.parseInt(goodsStoreNums[i]); if(int_buyNum>int_goodsStoreNums){ mark=false; messages.put(i,"⊥库存不足!"); } else if(int_buyNum<=0) shopcarDao.deleteGoods(shopcarid, Integer.parseInt(goodsIds[i])); else{ params[0]=int_buyNum; params[1]=shopcarid; params[2]=goodsIds[i]; shopcarDao.updateBuyNum(params); messages.put(i,"√修改成功!"); } } request.setAttribute("messages",messages); shopcarDao.closed(); } else mark=false; return mark; } private boolean createorderform_validateBuyNum(HttpServletRequest request){ boolean mark=true; String ids=request.getParameter("buygoodsids"); String nums=request.getParameter("buygoodsnum"); String[] goodsIds=ids.split(","); String[] buyNums=nums.split(","); HashMap messages=new HashMap(); GoodsDao goodsDao=new GoodsDao(); for(int i=0;i<goodsIds.length;i++){ int int_buyNum=Integer.parseInt(buyNums[i]); int int_goodsStoreNums=goodsDao.getGoodsStoreNum(Integer.parseInt(goodsIds[i])); if(int_buyNum>int_goodsStoreNums){ mark=false; messages.put(i,"⊥库存不足!"); } } request.setAttribute("messages",messages); return mark; } private void createorderform(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException { String buygoodsids=request.getParameter("buygoodsids"); if(buygoodsids!=null&&!buygoodsids.equals("")){ if(!createorderform_validateBuyNum(request)) showshopcar(request,response); else{ String forward=""; String buygoodsnum=request.getParameter("buygoodsnum"); int loginerid=((UserBean)request.getSession().getAttribute("loginer")).getId(); String getter=request.getParameter("getter"); String address=request.getParameter("address"); String postalcode=request.getParameter("postalcode"); String telephone1=request.getParameter("telephone1"); String telephone2=request.getParameter("telephone2"); String linkphone=telephone1+","+telephone2; String shipment=request.getParameter("shipment"); String shipmenttime=request.getParameter("shipmenttime"); if(shipmenttime==null) shipmenttime="-1"; String payment=request.getParameter("payment"); String networkpayment=request.getParameter("networkpayment"); if(networkpayment==null) networkpayment="-1"; float goodsprices=Float.parseFloat(request.getParameter("goodsprices")); String time=StringHandler.timeTostr(new Date()); String status="1"; float totalprices=0; if(shipment.equals("1")) totalprices=20+goodsprices; else if(shipment.equals("2")) totalprices=30+goodsprices; else if(shipment.equals("3")) totalprices=40+goodsprices; request.setAttribute("goodsprices",goodsprices); request.setAttribute("totalprices",totalprices); Object[] params={loginerid,getter,address,postalcode,linkphone,shipment,shipmenttime,payment,networkpayment,totalprices,time,status,buygoodsids,buygoodsnum}; OrderformDao orderformDao=new OrderformDao(); int i=orderformDao.addOrderform(params); if(i<=0){ forward="/message.jsp"; String message="<li>生成订单失败!</li>"; message+="<a href='javascript:window.history.go(-1)'>返回</a>"; request.setAttribute("message",message); } else{ forward="/showOrderform.jsp"; int orderformnumber=orderformDao.getOrderformNumber(loginerid, time); List buygoodslist=orderformDao.getBuyGoodsToOrderform(orderformnumber); OrderformBean orderform=new OrderformBean(); orderform.setOrderformNumber(orderformnumber); orderform.setOrderformWhoid(loginerid); orderform.setOrderformGetter(getter); orderform.setOrderformAddress(address); orderform.setOrderformPostalcode(postalcode); orderform.setOrderformLinkphone(linkphone); orderform.setOrderformShipment(shipment); orderform.setOrderformShipmenttime(shipmenttime); orderform.setOrderformPayment(payment); orderform.setOrderformNetworkpayment(networkpayment); orderform.setOrderformTotalprices(totalprices); orderform.setOrderformTime(time); orderform.setOrderformStatus(status); orderform.setOrderformBuyGoods(buygoodslist); request.setAttribute("orderform", orderform); String[] goodsids=buygoodsids.split(","); String[] goodsnum=buygoodsnum.split(","); GoodsDao goodsDao=new GoodsDao(); for(int k=0;k<goodsids.length;k++) goodsDao.updateStoreNum(Integer.parseInt(goodsnum[k]),Integer.parseInt(goodsids[k])); goodsDao.closed(); deleteshopcarcookie(request,response); String shopcarid=seeshopcarcookie(request,response); TempDao tempDao=new TempDao(); tempDao.deleteShopcar(shopcarid); } orderformDao.closed(); RequestDispatcher rd=request.getRequestDispatcher(forward); rd.forward(request,response); } } else{ System.out.println("没有购买商品,不能生成订单!"); RequestDispatcher rd=request.getRequestDispatcher("/message.jsp"); rd.forward(request,response); } } private void deleteshopcarcookie(HttpServletRequest request,HttpServletResponse response){ String webname=request.getContextPath(); webname=webname.substring(1); Cookie shopcar=new Cookie(webname+".usershopcar",null); shopcar.setPath("/"); int maxage=0; shopcar.setMaxAge(maxage); response.addCookie(shopcar); } }
[ "zqs7550@gmail.com" ]
zqs7550@gmail.com
5beaba2e0a0e72bcc5b6af0064d79814f0a36f5c
107aa5c2427c35274bad0e955423d4cffcd9eeff
/src/main/java/com/pg/scripts/n1qlgenerator/model/storeRedabbo/StoreConfigurationExclusion.java
1d344cd9759b6e09ceade80ae1b7097966d94d4a
[]
no_license
lobuz-xps/generator
f85b14ce83ef4f3c29273f01397c0046e44143d8
6a1933eaa7375def7df37f6f9627539116d95201
refs/heads/master
2020-07-01T20:37:29.984595
2019-08-20T10:46:52
2019-08-20T10:46:52
201,293,563
0
0
null
null
null
null
UTF-8
Java
false
false
249
java
package com.pg.scripts.n1qlgenerator.model.storeRedabbo; import lombok.Data; @Data public class StoreConfigurationExclusion { private String name; private String date; private String timeOfDayBegin; private String timeOfDayEnd; }
[ "maciej.labus@nvt.pl" ]
maciej.labus@nvt.pl
a6b0ae4cedb9bc14ed5d99d3e20b6ff6d9448cd2
2796525584c5ef39347580f2ab61792711c51f36
/app/src/main/java/com/example/test_sel/UserSignUpActivity.java
08b2c350a8092f479d8174d1495148f1208d1b0d
[]
no_license
hadar23/test-sel11
fe9372aa4093cd48f019ab234f58843242b9c273
2e4ea79dad62659cd535c4073898577001d4b217
refs/heads/master
2021-04-09T20:10:10.579502
2020-03-21T00:02:46
2020-03-21T00:02:46
248,875,455
0
0
null
null
null
null
UTF-8
Java
false
false
9,826
java
package com.example.test_sel; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.example.test_sel.Classes.User; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.firestore.FirebaseFirestore; public class UserSignUpActivity extends AppCompatActivity { String[] arr = {"1", "2"}; // https://medium.com/@hannaholukoye/adding-an-icon-on-a-spinner-on-android-e99c7bc6c180 private EditText EDT_full_nameET, EDT_start_year, EDT_phone_numberET, EDT_description; private ImageView img_head; private Spinner SPN_engineering, SPN_academy; private Button BTNsign_up; private FirebaseAuth fAuth; private FirebaseFirestore fStore; private ProgressBar ProgressBar; private String fullName, phone, academy, start_year, userId, imagePath = "", engineering = "", description = ""; private DatabaseReference rootDataBase; private DatabaseReference refuser; private boolean isSignUp = true; Intent deleteIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_sign_up); EDT_full_nameET = findViewById(R.id.EDT_full_nameET); EDT_phone_numberET = findViewById(R.id.EDT_phone_numberET); EDT_start_year = findViewById(R.id.EDT_start_year); BTNsign_up = findViewById(R.id.BTNsign_up); img_head = findViewById(R.id.IMG_signup_img); EDT_description = findViewById(R.id.EDT_description); String type = getIntent().getExtras().getString("type"); isSignUp = type.equals("signUp") ? true : false; if (isSignUp) { EDT_phone_numberET.setText(getIntent().getExtras().getString("phone")); } fAuth = FirebaseAuth.getInstance(); fStore = FirebaseFirestore.getInstance(); ProgressBar = findViewById(R.id.pbarReg); userId = fAuth.getCurrentUser().getUid(); //save data on firebase rootDataBase = FirebaseDatabase.getInstance().getReference("Users"); if (isSignUp) { userId = fAuth.getCurrentUser().getUid(); phone = getIntent().getExtras().getString("phone"); } else { img_head.setImageResource(R.drawable.img_update); BTNsign_up.setText("UPDATE"); setMyData(); userId = getIntent().getExtras().getString("userid"); } //acadany spinner SPN_academy = findViewById(R.id.SPN_academy); ArrayAdapter<CharSequence> academicAdapter = ArrayAdapter.createFromResource(this, R.array.academy, android.R.layout.simple_spinner_item); academicAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); SPN_academy.setAdapter(academicAdapter); SPN_academy.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { academy = parent.getItemAtPosition(position).toString(); if (position == 0) { //select nothing SPN_academy.setSelection(1); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); //engineering spinner SPN_engineering = findViewById(R.id.SPN_engineering); ArrayAdapter<CharSequence> engineeringAdapter = ArrayAdapter.createFromResource(this, R.array.engineering, android.R.layout.simple_spinner_item); engineeringAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); SPN_engineering.setAdapter(engineeringAdapter); SPN_engineering.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { engineering = parent.getItemAtPosition(position).toString(); if (position == 0) { //select nothing SPN_engineering.setSelection(1); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); //if user save details BTNsign_up.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fullName = EDT_full_nameET.getText().toString(); phone = EDT_phone_numberET.getText().toString().trim(); start_year = EDT_start_year.getText().toString().trim(); description = EDT_description.getText().toString().trim(); //checks if (TextUtils.isEmpty(fullName)) { EDT_full_nameET.setError("name is required"); return; } if (TextUtils.isEmpty(start_year)) { EDT_start_year.setError("your start year is required"); return; } if (Integer.parseInt(start_year) > 2020 || Integer.parseInt(start_year) < 2000) { EDT_start_year.setError("the year that you start study is not legal"); return; } //ProgressBar after all the check ProgressBar.setVisibility(View.VISIBLE); User user = new User(userId, fullName, phone, academy, start_year, engineering, imagePath, description); // insert to the firebsae rootDataBase.child(userId).setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { startActivity(new Intent(getApplicationContext(), ProfileActivity.class)); finish(); } else { Toast.makeText(UserSignUpActivity.this, "data is not insert ", Toast.LENGTH_SHORT).show(); } } }); } }); } //TODO IT HAs WEIRD ERROR when i try to do ,1 ,method yo init spinner // public void mySpinner(int arr,final String insertStr, final Spinner spinner) { // ArrayAdapter<CharSequence> engineeringAdapter = ArrayAdapter.createFromResource(this, arr, android.R.layout.simple_spinner_item); // engineeringAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // spinner.setAdapter(engineeringAdapter); // spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { // @Override // public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // insertStr = parent.getItemAtPosition(position).toString(); //// engineering=String.valueOf(SPN_engineering.getSelectedItemId()); // if (position == 0) { // //select nothing // spinner.setSelection(1); // } // } // @Override // public void onNothingSelected(AdapterView<?> parent) { // // } // }); // } public boolean isEDempty(EditText etText) { if (etText.getText().toString().trim().length() == 0) { etText.setError("this box is empty"); return true; } return false; } boolean isEmailValid(CharSequence email) { return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches(); } public void setMyData() { //get data refuser = FirebaseDatabase.getInstance().getReference().child("Users").child(userId); refuser.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { EDT_full_nameET.setText(dataSnapshot.child("fullName").getValue().toString()); EDT_phone_numberET.setText(dataSnapshot.child("phone").getValue().toString()); // txt_fill_academy.setText(dataSnapshot.child("academy").getValue().toString()); EDT_start_year.setText(dataSnapshot.child("startYear").getValue().toString()); EDT_description.setText(dataSnapshot.child("description").getValue().toString()); //txt_fill_engineering.setText(dataSnapshot.child("engineering").getValue().toString()); imagePath = dataSnapshot.child("imagePath").getValue().toString(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override protected void onStop() { if(isSignUp){ fAuth.signOut(); } super.onStop(); } }
[ "aviasd06@gmail.com" ]
aviasd06@gmail.com
4b367275ffd2f09e1016f9517d95a1a02d0ae75f
4701351a761422e90fef2cb9d1efc06c1a077a4b
/design-patterns/template_adapter_work/src/main/java/template/t2/Member.java
60618390a7e2884c5951471892e4a8e02595aeed
[]
no_license
jingzhouwangbuer/GP018251
9a9a1220b3d78a04172a7f6e2c51b8d6e3bfdd49
406cce33fadc86ddaffdda279be5c3aae4e7ce75
refs/heads/master
2020-04-27T16:38:41.626675
2019-05-06T09:58:46
2019-05-06T09:58:46
174,488,951
2
0
null
null
null
null
UTF-8
Java
false
false
460
java
package template.t2; /** * @介绍 : * @作者 :RJT * @时间 :2019-03-22 16:12 */ public class Member { private String uid; private String uname; public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public Member() { } }
[ "1010927949@qq.com" ]
1010927949@qq.com
0d817e2c2e2ae5c33c22ff5c8933f6ce8e0ea412
67c86893a3d959bf7318b0823f1fdceac08ccf14
/src/java/vihtt/servlet/AddQuantityServlet.java
9adb1e5c7a1cf722fd29576d21ee450c981b882a
[]
no_license
vi-ht/HanaShop
62c0af4f7d30dbda6983b6b5ad04483a9679b4a0
7bfc2ee1eb9d0396beb71bc33f3732ae03b09241
refs/heads/master
2023-03-20T10:04:21.127116
2021-03-16T01:01:07
2021-03-16T01:01:07
346,759,454
0
0
null
null
null
null
UTF-8
Java
false
false
6,381
java
/* * 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 vihtt.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import javax.naming.NamingException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import vihtt.cart.cartObject; import vihtt.item.ItemDAO; /** * * @author Thanh Vi */ @WebServlet(name = "AddQuantityServlet", urlPatterns = {"/AddQuantityServlet"}) public class AddQuantityServlet extends HttpServlet { private final String VIEW_CART = "ViewCartServlet"; private static final Logger LOGGER = LogManager.getLogger(AddQuantityServlet.class); /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String url = VIEW_CART; String ID = request.getParameter("txtItemID"); String productName = request.getParameter("txtIProductName"); String orderQuantitySTR = request.getParameter("txtOderQuantity"); System.out.println("ID"+ID); if(ID == null){ response.sendRedirect("404.html"); out.close(); }else{ try { int orderQuantity = Integer.parseInt(orderQuantitySTR); ItemDAO dao = new ItemDAO(); int quantity = dao.searchQuantityByID(ID); HttpSession session = request.getSession(); cartObject cart = (cartObject) session.getAttribute("CUST_CART"); if (cart == null) { cart = new cartObject(); } if(quantity>0){ if((orderQuantity+1)<=quantity){ cart.addQuantityToCard(ID,orderQuantity+1); session.setAttribute("CUST_CART", cart); }else{ cart.addQuantityToCard(ID, quantity); session.setAttribute("CUST_CART", cart); request.setAttribute("SOLD_OUT_PRODUCT", productName); request.setAttribute("REMAINING_NUMBER", quantity); request.setAttribute("FAIL", true); } }else{ cart.removeItemFormCard(ID); session.setAttribute("CUST_CART", cart); request.setAttribute("SOLD_OUT_PRODUCT", productName); request.setAttribute("SOLD_OUT", true); } } catch (NumberFormatException e) { LOGGER.error("AddQuantityServlet_NumberFormatException", e); }catch(SQLException e) { LOGGER.error("AddQuantityServlet_SQLException ", e); }catch(NamingException ex) { LOGGER.error("AddQuantityServlet_NamingException ", ex); }finally{ RequestDispatcher rd = request.getRequestDispatcher(url); rd.forward(request, response); out.close(); } } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
[ "huynhthanhvi1102@gmail.com" ]
huynhthanhvi1102@gmail.com
15ef2e9b65fe4ca82c7b7eaf672b4a359ebd3cfb
b400269babf3541d64008e25725aa62f2c8feaea
/smt-http-mock/src/test/java/shiver/me/timbers/http/mock/HttpMockHeaderFilterTest.java
c94a97af4f89f4687b2b3e7c2672f5919d0b413c
[ "Apache-2.0" ]
permissive
shiver-me-timbers/smt-http-mock-parent
c9394f56b86b73ab753178325c6365324e9b2fe5
2935d4db78a79543b6430ebb8fe4a3a2c4cba363
refs/heads/master
2021-01-18T18:44:17.226801
2016-07-03T07:34:21
2016-07-03T07:34:21
60,521,875
0
0
null
null
null
null
UTF-8
Java
false
false
2,666
java
/* * Copyright 2016 Karl Bennett * * 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 shiver.me.timbers.http.mock; import org.junit.Before; import org.junit.Test; import shiver.me.timbers.http.Header; import shiver.me.timbers.http.Headers; import java.util.HashSet; import java.util.List; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertThat; import static shiver.me.timbers.data.random.RandomStrings.someString; import static shiver.me.timbers.matchers.Matchers.hasField; public class HttpMockHeaderFilterTest { private HttpMockHeaderFilter filter; @Before public void setUp() { filter = new HttpMockHeaderFilter(); } @Test public void Can_filter_headers() { // Given final String name1 = someString(); final String name2 = someString(); final String name3 = someString(); final Header header = new Header(name2, someString()); final List<Header> headerList = asList( new Header(name1, someString()), header, new Header(name3, someString()) ); final Headers headers = new Headers(new HashSet<>(headerList)); // When filter.ignoredHeaders(name1, name3); final Headers actual = filter.filter(headers); // Then assertThat(headers, hasField("headers", new HashSet<>(headerList))); assertThat(actual, contains(header)); } @Test public void Can_filter_no_headers() { // Given final List<Header> headerList = asList( new Header(someString(), someString()), new Header(someString(), someString()), new Header(someString(), someString()) ); final Headers headers = new Headers(new HashSet<>(headerList)); // When final Headers actual = filter.filter(headers); // Then assertThat(headers, hasField("headers", new HashSet<>(headerList))); assertThat(actual, containsInAnyOrder(headerList.toArray(new Header[headerList.size()]))); } }
[ "karl.bennett.smt@gmail.com" ]
karl.bennett.smt@gmail.com
85b974be73bb867f9204222579edb5a463b5267d
c69e583198f896e7fc9e760dffcc78296bab2ae6
/week6-105.GuessingGame/src/Main.java
4276434c3801844870f07b9b4bb8b7116dc14474
[]
no_license
PPindsle/2013-oo-programming-part1
170d69cfc069d1b2b839edaac2b2580132c9c58f
30f905f343569b7f7e1d37b59055c6094d1cd302
refs/heads/master
2021-09-25T15:25:20.433116
2018-10-23T16:51:18
2018-10-23T16:51:18
131,504,195
0
2
null
2018-08-08T17:25:40
2018-04-29T15:03:47
Java
UTF-8
Java
false
false
186
java
public class Main { public static void main(String[] args) { // test your program here GuessingGame game = new GuessingGame(); game.play(1,10); } }
[ "noreply@github.com" ]
PPindsle.noreply@github.com
01887b3abf5c42b371e5e75549a2882d19c3622f
40689f25da54c889193bb8a1c3dc9fd5cda261ac
/src/main/java/hr01/core/book/Book.java
741c9e93818aef18f19adbba9585fb73fd64d2bc
[]
no_license
sehor/hr01
2cec709ef27b6297acb6429ea1298ac7f0a02cbb
f2b8ffe9711dbea1f7ca2665e60a119f6baebdbf
refs/heads/master
2020-07-31T04:00:52.252670
2019-09-26T23:46:56
2019-09-26T23:46:56
210,478,167
0
0
null
null
null
null
UTF-8
Java
false
false
1,435
java
package hr01.core.book; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name = "t_book") public class Book implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "book_name") private String name; private String author; private float price; private String description; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String toString(){ return "Id: "+getId()+"\r\n" +"name: "+getName()+"\r\n" +"author: "+getAuthor()+"\r\n" +"price: "+getPrice()+"\r\n" +"description: "+getDescription()+"\r\n"; } public void print(){ System.out.println(toString()); } }
[ "714534524@qq.com" ]
714534524@qq.com
fc8624cbba1ab39e4824ad6da18ef5c17f451ae7
f98bf2ab01c6dd0be55bf554493e2642b415066b
/Game with shapes/Main.java
4b24a72e76ec2f5ab103e825ee63a14a15882219
[]
no_license
uday199826/Playground
08d976bdf040df95f86f9e56a3f8f0f3771ccf54
8359464126f6ad94eace9f84250a0c75fdd8f92e
refs/heads/master
2021-05-21T20:02:42.444244
2020-04-28T11:01:52
2020-04-28T11:01:52
252,781,048
0
0
null
null
null
null
UTF-8
Java
false
false
254
java
#include<iostream> #include<cmath> using namespace std; int main() { int side,radious; cin>>radious>>side; if((2*radious)<=side) { cout<<"circle can be inside a square"; } else { cout <<"circle cannot be inside a square"; } }
[ "51732248+uday199826@users.noreply.github.com" ]
51732248+uday199826@users.noreply.github.com
8e4951a9cada499da31215ccbf33507240079bf2
53890febb56da70296628a491698a18011c0da01
/TextAnalysisAndroid/app/src/main/java/com/likhtman/TextAnalysis/Model/FullText.java
d46173ae89ee938a2f0872929ab6ea46b848423c
[]
no_license
KonstantinRubinov/TextAnalysis
90d10c132d2ec43031cf849d2bf63e9a71ce4667
569aeae674d00612392d822fefa28fd5357ad20c
refs/heads/main
2021-08-18T11:12:59.413499
2021-07-12T04:09:05
2021-07-12T04:09:05
243,970,254
0
0
null
null
null
null
UTF-8
Java
false
false
990
java
package com.likhtman.TextAnalysis.Model; import org.json.JSONException; import org.json.JSONObject; public class FullText { private String textToCheck; private JSONObject jsonObject; public FullText(){ } public FullText(String _textToCheck){ setTextToCheck(_textToCheck); } private <T> void Try_JSON(String name, T input){ try { jsonObject.put(name, input); } catch (JSONException e) { e.printStackTrace(); } } public JSONObject toJSON(){ jsonObject = new JSONObject(); Try_JSON("textToCheck", textToCheck); return jsonObject; } public String getTextToCheck() { return textToCheck; } public void setTextToCheck(String textToCheck) { this.textToCheck = textToCheck; } @Override public String toString() { return "FullText{" + "textToCheck='" + textToCheck + '\'' + '}'; } }
[ "Konstantin.rubinov@gmail.com" ]
Konstantin.rubinov@gmail.com
25fb2c81fbeb998b56fa671bec866025ca03b942
4f25ee1bf07e9369177037c94ea3da7eb74b9fe9
/src/main/java/com/cqaos/RabbitApplication.java
8f02f97a71d00d28a40a6471d496d8e40829cdbb
[]
no_license
stonebox1122/rabbitmq
d308c02beaf2639ccebdc1a6b06b5171f420a4ba
73a64c67730cf4327332cdd81c3ae4c4e6a350d3
refs/heads/master
2023-01-06T13:43:14.306059
2020-10-14T06:42:16
2020-10-14T06:42:16
303,916,027
0
0
null
null
null
null
UTF-8
Java
false
false
317
java
package com.cqaos; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class RabbitApplication { public static void main(String[] args) { SpringApplication.run(RabbitApplication.class); } }
[ "287779438@qq.com" ]
287779438@qq.com
1646123f29cb27293ad7eadabfa7e3d542c280f6
8beac3ce754ef52202c33a0fcba627ffe45ff69f
/talent-studio-integration/src/test/java/com/zynap/talentstudio/integration/adapter/TestXmlAdaptor.java
76fed685ed6a3c13933a57dc93d651ef54d84b46
[]
no_license
bronwen-cassidy/talent-evolution
5723dd50bcd18b5e6ead5d9df812c7cb28f22cf5
0e8360ae344ac63101888185997e05eac014b56d
refs/heads/master
2021-01-20T12:10:10.207766
2017-11-17T21:30:09
2017-11-17T21:30:09
28,445,737
0
0
null
null
null
null
UTF-8
Java
false
false
20,149
java
/* * Copyright (c) 2002 Zynap Limited. All rights reserved. */ package com.zynap.talentstudio.integration.adapter; import com.zynap.exception.DomainObjectNotFoundException; import com.zynap.exception.TalentStudioException; import com.zynap.talentstudio.integration.BaseIntegrationTest; import com.zynap.talentstudio.integration.common.IZynapCommand; import com.zynap.talentstudio.organisation.IOrganisationUnitService; import com.zynap.talentstudio.organisation.OrganisationUnit; import com.zynap.talentstudio.organisation.attributes.NodeExtendedAttribute; import com.zynap.talentstudio.organisation.positions.IPositionService; import com.zynap.talentstudio.organisation.positions.Position; import com.zynap.talentstudio.organisation.positions.PositionAssociation; import com.zynap.talentstudio.organisation.subjects.ISubjectService; import com.zynap.talentstudio.organisation.subjects.Subject; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.io.FileWriter; import java.io.Reader; import java.io.StringReader; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Class or Interface description. * * @author bcassidy * @version $Revision: $ * $Id: $ */ public class TestXmlAdaptor extends BaseIntegrationTest { protected void setUp() throws Exception { super.setUp(); xmlAdapter = (IXmlAdapter) applicationContext.getBean("xmlAdapter"); } public void testExecute() throws Exception { xmlAdapter.execute(SIMPLE_XML, null, USER_NAME); } public void testExecuteToFile() throws Exception { Writer writer = new FileWriter("organisations.xml"); Reader reader = new StringReader(FIND_ALL_OU_XML); xmlAdapter.execute(writer, reader, null, "webserviceuser"); } public void testFindOU() throws Exception { final String output = xmlAdapter.execute(FIND_DEFAULT_OU_XML, null, USER_NAME); System.out.println("output = " + output); } public void testFindAllOU() throws Exception { final String output = xmlAdapter.execute(FIND_ALL_OU_XML, null, USER_NAME); System.out.println("output = " + output); } public void testFindPosition() throws Exception { final String output = xmlAdapter.execute(FIND_DEFAULT_POSITION_XML, null, USER_NAME); System.out.println("output = " + output); } public void testFindNonExistentPosition() throws Exception { try { xmlAdapter.execute(FIND_INVALID_POSITION_XML, null, USER_NAME); fail("Should have failed due to invalid position id"); } catch (DomainObjectNotFoundException ignored) { } } public void testFindAllPosition() throws Exception { final String output = xmlAdapter.execute(FIND_ALL_POSITION_XML, null, USER_NAME); System.out.println("output = " + output); } public void testCreateOrgUnits() throws Exception { xmlAdapter.execute(CREATE_ORG_UNITS_XML, ATTACHMENTS, USER_NAME); IOrganisationUnitService organisationUnitService = (IOrganisationUnitService) getBean("organisationUnitService"); final List hierarchy = organisationUnitService.findOrgUnitTree(OrganisationUnit.ROOT_ORG_UNIT_ID); // find grand child OrganisationUnit selectedOrganisationUnit = null; for (Iterator iterator = hierarchy.iterator(); iterator.hasNext();) { OrganisationUnit child = (OrganisationUnit) iterator.next(); if (child.getLabel().equals("Finance")) { selectedOrganisationUnit = child; break; } } // check has correct parent assertNotNull(selectedOrganisationUnit); final OrganisationUnit parent = organisationUnitService.findById(selectedOrganisationUnit.getParent().getId()); assertEquals(DEFAULT_ORG_UNIT_ID, parent.getParent().getId()); } public void testCreateSubject() throws Exception { xmlAdapter.execute(CREATE_SUBJECT_XML, ATTACHMENTS, USER_NAME); Subject selectedSubject = null; ISubjectService subjectService = (ISubjectService) getBean("subjectService"); final List all = subjectService.findAll(); for (Iterator iterator = all.iterator(); iterator.hasNext();) { Subject subject = (Subject) iterator.next(); if (subject.getFirstName().equals(FIRST_NAME)) { selectedSubject = subject; break; } } // check that the subject has been added assertNotNull(selectedSubject); // check subject associations assertFalse(selectedSubject.getSubjectAssociations().isEmpty()); } public void testCreatePosition() throws Exception { xmlAdapter.execute(CREATE_POSITION_XML, ATTACHMENTS, USER_NAME); Position selectedPosition = null; IPositionService positionService = (IPositionService) getBean("positionService"); final List all = positionService.findAll(); for (Iterator iterator = all.iterator(); iterator.hasNext();) { Position position = (Position) iterator.next(); if (position.getLabel().equals(POS_LABEL)) { selectedPosition = position; break; } } // check position - must have default org unit and position assertNotNull(selectedPosition); assertTrue(selectedPosition.getOrganisationUnit().isDefault()); assertTrue(selectedPosition.getParent().isDefault()); // check target associations assertTrue(selectedPosition.getTargetAssociations().isEmpty()); // check source association final Collection sourceAssociations = selectedPosition.getSourceAssociations(); assertEquals(1, sourceAssociations.size()); final PositionAssociation positionAssociation = (PositionAssociation) sourceAssociations.iterator().next(); assertEquals(selectedPosition.getParent(), positionAssociation.getTarget()); assertEquals(selectedPosition, positionAssociation.getSource()); assertTrue(positionAssociation.isPrimary()); // check portfolio items assertEquals(1, selectedPosition.getPortfolioItems().size()); // check extended attributes - must be 2 final Set extendedAttributes = selectedPosition.getExtendedAttributes(); assertEquals(2, extendedAttributes.size()); for (Iterator iterator = extendedAttributes.iterator(); iterator.hasNext();) { NodeExtendedAttribute nodeExtendedAttribute = (NodeExtendedAttribute) iterator.next(); assertEquals(selectedPosition, nodeExtendedAttribute.getNode()); assertNotNull(nodeExtendedAttribute.getValue()); } } public void testCreateTwoPositions() throws Exception { xmlAdapter.execute(CREATE_TWO_POSITIONS_XML, ATTACHMENTS, USER_NAME); } public void testUpdatePosition() throws Exception { xmlAdapter.execute(UPDATE_POSITION_XML, ATTACHMENTS, USER_NAME); } public void testCreatePortfolioItem() throws Exception { xmlAdapter.execute(CREATE_PORTFOLIO_XML, ATTACHMENTS, USER_NAME); } public void testExistsCommand() throws Exception { //use find position XML but change action to "exists" from "find" final String xml = FIND_DEFAULT_POSITION_XML.replaceFirst(IZynapCommand.FIND_ACTION, IZynapCommand.EXISTS_ACTION); final String output = xmlAdapter.execute(xml, ATTACHMENTS, USER_NAME); assertNotNull(output); // do a find and then check the only difference is the action final String result = xmlAdapter.execute(FIND_DEFAULT_POSITION_XML, ATTACHMENTS, USER_NAME); final String expected = result.replaceFirst(IZynapCommand.FIND_ACTION, IZynapCommand.EXISTS_ACTION); assertEquals(expected, output); } public void testExistsCommandInvalidId() throws Exception { // use find invalid position XML but change action to "exists" from "find" final String xml = FIND_INVALID_POSITION_XML.replaceFirst(IZynapCommand.FIND_ACTION, IZynapCommand.EXISTS_ACTION); final String output = xmlAdapter.execute(xml, ATTACHMENTS, USER_NAME); assertNotNull(output); assertTrue(output.indexOf(IZynapCommand.EXISTS_ACTION) > 0); } public void testNoAction() throws Exception { String[] commands = new String[]{""}; String xml = createComplexXML(commands, 1); try { xmlAdapter.execute(xml, null, USER_NAME); fail("Exception expected as command had no action"); } catch (InvalidDataException expected) { } } public void testInvalidNumberOfCommandInputs() throws Exception { String[] commands = {IZynapCommand.CREATE_ACTION}; int numberOfElementsPerCommand = 2; String xml = createComplexXML(commands, numberOfElementsPerCommand); try { xmlAdapter.execute(xml, null, USER_NAME); fail("Exception expected as more than one input item was supplied for the command"); } catch (InvalidDataException expected) { } } public void testExecuteErrors() throws Exception { String[] commands = {IZynapCommand.CREATE_ACTION, IZynapCommand.UPDATE_ACTION, IZynapCommand.DELETE_ACTION, IZynapCommand.FIND_ACTION}; int numberOfElementsPerCommand = 0; String xml = createComplexXML(commands, numberOfElementsPerCommand); try { xmlAdapter.execute(xml, null, USER_NAME); fail("Exception expected as no data was supplied for commands"); } catch (TalentStudioException expected) { } } public void testCreateUpdatePosition() throws Exception { try { loadAndExecute("com/zynap/talentstudio/integration/adapter/position-test-data.xml"); String targetPositionTitle = "Manager-Employment/Recruitment/Adapter & Test"; Position found = findPosition(targetPositionTitle); assertNotNull(found); assertEquals(3, found.getExtendedAttributes().size()); assertEquals(1, found.getSourceAssociations().size()); } catch (Exception e) { e.printStackTrace(); fail(); } } public void testCreateUpdatePositionAssociations() throws Exception { try { loadAndExecute("com/zynap/talentstudio/integration/adapter/position-test-data.xml"); String targetPositionTitle = "Manager-Employment/Recruitment/Adapter & Test"; Position found = findPosition(targetPositionTitle); final Set<PositionAssociation> associations = found.getSourceAssociations(); assertEquals(1, associations.size()); final PositionAssociation positionAssociation = associations.iterator().next(); assertFalse(new Long(1).equals(positionAssociation.getTarget().getId())); } catch (Exception e) { e.printStackTrace(); fail(); } } public void testCreatePositionAssociations() throws Exception { try { loadAndExecute("com/zynap/talentstudio/integration/adapter/position-create-test-data.xml"); String targetPositionTitle = "ManagerHead-Employment/Recruitment/Adapter & Sales"; Position found = findPosition(targetPositionTitle); // todo assert the parent is not null assertNotNull(found.getParent()); assertNotNull(found.getParentId()); } catch (Exception e) { e.printStackTrace(); fail(); } } public void testCreateUpdateSubjectAssociationsAndDas() throws Exception { try { loadAndExecute("com/zynap/talentstudio/integration/adapter/subject-test-data.xml"); String targetSubjectSurname = "Xanado"; Subject found = findSubject(targetSubjectSurname); assertNotNull(found); assertEquals(8, found.getExtendedAttributes().size()); assertEquals(1, found.getSubjectAssociations().size()); } catch (Exception e) { e.printStackTrace(); fail(); } } public void testCreateUpdateSubjectDasAssociationsRemain() throws Exception { try { loadAndExecute("com/zynap/talentstudio/integration/adapter/subject-test-data.xml"); String targetSubjectSurname = "Xanado"; Subject found = findSubject(targetSubjectSurname); assertEquals(1, found.getSubjectAssociations().size()); } catch (Exception e) { e.printStackTrace(); fail(); } } private Subject findSubject(String targetSubjectSurname) throws Exception { ISubjectService subjectService = (ISubjectService) getBean("subjectService"); final List all = subjectService.findAll(); Subject found = null; for (int i = 0; i < all.size(); i++) { Subject subject = (Subject) all.get(i); if (targetSubjectSurname.equals(subject.getCoreDetail().getSecondName())) { found = subject; break; } } return found; } private Position findPosition(String targetPositionTitle) throws Exception { IPositionService positionService = (IPositionService) getBean("positionService"); final List all = positionService.findAll(); Position found = null; for (int i = 0; i < all.size(); i++) { Position position = (Position) all.get(i); if (targetPositionTitle.equals(position.getTitle())) { found = position; break; } } return found; } private void loadAndExecute(String filename) throws IOException { String xml = getXmlString(filename); try { final String result = xmlAdapter.execute(xml, null, USER_NAME); System.out.println("result = " + result); } catch (Exception e) { e.printStackTrace(); fail("No exception expected"); } } public static String getXmlString(String filename) throws IOException { InputStream testFileUrl = ClassLoader.getSystemResourceAsStream(filename); byte[] xmlBytes = new byte[25000]; int numBytesRead = testFileUrl.read(xmlBytes); byte[] realBytes = new byte[numBytesRead]; System.arraycopy(xmlBytes, 0, realBytes, 0, numBytesRead); return new String(realBytes); } private String createComplexXML(String[] commands, int elementCount) { StringBuffer x = new StringBuffer(START_ROOT_XML); for (int i = 0; i < commands.length; i++) { String command = commands[i]; x.append("<command action=\"").append(command).append("\">"); for (int j = 0; j < elementCount; j++) { x.append("<organisationUnit><label>label_").append(i).append("</label><parent><id>0</id></parent></organisationUnit>"); } x.append("</command>"); } x.append(END_ROOT_XML); return x.toString(); } private IXmlAdapter xmlAdapter; private static final String START_ROOT_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><commands>"; private static final String END_ROOT_XML = "</commands>"; private static final String POS_LABEL = "Adapter Position"; private static final String OU_LABEL = "Adapter Org Unit"; private static final String SIMPLE_XML = START_ROOT_XML + "<command action=\"create\"><organisationUnit><id>funnyName</id><label>" + OU_LABEL + "</label><parent><id>#DEFAULT_ORGUNIT#</id></parent></organisationUnit></command></commands>"; // private static final String SECURITY_ATTRIBUTES_XML = "<securityAttribute><publicRead>T</publicRead><managerRead>T</managerRead><individualRead>T</individualRead><managerWrite>T</managerWrite><individualWrite>T</individualWrite></securityAttribute>"; private static final String SECURITY_ATTRIBUTES_XML = ""; private static final String PORTFOLIO_ITEM_XML = "<portfolioItem><label>Adapter Portfolio Item</label><comments>Comments</comments><node><id>1</id></node><contentType><id>DESC</id></contentType><contentSubType>TEXT</contentSubType><blobValue ref=\"0\"/><scope>PUBLIC</scope>"+SECURITY_ATTRIBUTES_XML+"</portfolioItem>"; private static final String POSITION_UPD_XML = "<position><id>#DEFAULT_POSITION#</id><organisationUnit><id>#DEFAULT_ORGUNIT#</id></organisationUnit><title>Adapter Position</title><competency>Competency description</competency><keyposition>YES</keyposition></position>"; private static final String FIRST_NAME = "Pepe"; private static final String POSITION_XML = "<position><id>posName</id><organisationUnit><id>#DEFAULT_ORGUNIT#</id></organisationUnit><title>" + POS_LABEL + "</title><competency>Competency description</competency><keyposition>YES</keyposition><portfolioItems>" + PORTFOLIO_ITEM_XML + "</portfolioItems><sourceAssociations><ptpAssociation type=\"DIRECT\"><target><id>#DEFAULT_POSITION#</id></target></ptpAssociation></sourceAssociations></position>"; private static final String SUBJECT_XML = "<person><id>subName</id><title>Mr</title><firstName>"+FIRST_NAME+"</firstName><secondName>Pepe</secondName><highpotential>YES</highpotential><subjectAssociations><stpAssociation type=\"ACTING\"><target><id>#DEFAULT_POSITION#</id></target></stpAssociation></subjectAssociations></person>"; private static final String CREATE_PORTFOLIO_XML = START_ROOT_XML + "<command action=\"create\">" + PORTFOLIO_ITEM_XML + "</command></commands>"; private static final String CREATE_TWO_POSITIONS_XML = START_ROOT_XML + "<command action=\"create\">" + POSITION_XML + "</command>" + "<command action=\"create\"><position><id>childPos</id><organisationUnit><id>#DEFAULT_ORGUNIT#</id></organisationUnit><title>Child Position</title><competency>Competency description</competency><sourceAssociations><ptpAssociation type=\"DIRECT\"><target><id>posName</id></target></ptpAssociation></sourceAssociations></position></command>" + END_ROOT_XML; private static final String CREATE_ORG_UNITS_XML = START_ROOT_XML + "<command action=\"create\"><organisationUnit><id>1</id><label>Corporate</label><parent><id>#DEFAULT_ORGUNIT#</id></parent></organisationUnit></command>" + "<command action=\"create\"><organisationUnit><id>2</id><label>Finance</label><parent><id>1</id></parent></organisationUnit></command>" + END_ROOT_XML; private static final String UPDATE_POSITION_XML = START_ROOT_XML + "<command action=\"update\">" + POSITION_UPD_XML + "</command></commands>"; private static final String CREATE_POSITION_XML = START_ROOT_XML + "<command action=\"create\">" + POSITION_XML + "</command></commands>"; private static final String CREATE_SUBJECT_XML = START_ROOT_XML + "<command action=\"create\">" + SUBJECT_XML + "</command></commands>"; private static final String FIND_DEFAULT_OU_XML = START_ROOT_XML + "<command action=\"find\"><organisationUnit><id>#DEFAULT_ORGUNIT#</id></organisationUnit></command></commands>"; private static final String FIND_ALL_OU_XML = START_ROOT_XML + "<command action=\"findAll\"><organisationUnit/></command></commands>"; private static final String FIND_DEFAULT_POSITION_XML = START_ROOT_XML + "<command action=\"find\"><position><id>#DEFAULT_POSITION#</id></position></command></commands>"; private static final String FIND_INVALID_POSITION_XML = START_ROOT_XML + "<command action=\"find\"><position><id>-999</id></position></command></commands>"; private static final String FIND_ALL_POSITION_XML = START_ROOT_XML + "<command action=\"findAll\"><position/></command></commands>"; private static final String USER_NAME = "webserviceuser"; private static final byte[][] ATTACHMENTS = new byte[][]{"Test of byte".getBytes(), "Hello World".getBytes()}; }
[ "bronwen.cassidy@gmail.com" ]
bronwen.cassidy@gmail.com
e8e20bbb795ba44bd268f39ae60b2ca71748c596
5e38292af670960132795cc0323248acc3ed83eb
/rito-admin/src/main/java/com/stylefeng/guns/core/beetl/BeetlConfiguration.java
414f0c130a248f1f7d2d6ab371e965af0a844ce3
[ "Apache-2.0" ]
permissive
527088995/dian
2144590a61177c6be43afce4f3b9667bde74c69c
5238b1c46290a3ab8281a2eb83590d27d8e020b1
refs/heads/master
2022-11-06T17:09:33.968961
2020-07-31T02:30:02
2020-07-31T02:30:02
193,050,897
20
7
NOASSERTION
2022-10-05T19:33:24
2019-06-21T07:19:51
Java
UTF-8
Java
false
false
1,142
java
package com.stylefeng.guns.core.beetl; import com.stylefeng.guns.core.util.KaptchaUtil; import com.stylefeng.guns.core.util.ToolUtil; import org.beetl.ext.spring.BeetlGroupUtilConfiguration; import java.util.HashMap; import java.util.Map; import static com.stylefeng.guns.core.common.constant.Const.DEFAULT_SYSTEM_NAME; import static com.stylefeng.guns.core.common.constant.Const.DEFAULT_WELCOME_TIP; /** * beetl拓展配置,绑定一些工具类,方便在模板中直接调用 * * @author ... * @Date 2018/2/22 21:03 */ public class BeetlConfiguration extends BeetlGroupUtilConfiguration { @Override public void initOther() { //全局共享变量 Map<String, Object> shared = new HashMap<>(); shared.put("systemName", DEFAULT_SYSTEM_NAME); shared.put("welcomeTip", DEFAULT_WELCOME_TIP); groupTemplate.setSharedVars(shared); //全局共享方法 groupTemplate.registerFunctionPackage("shiro", new ShiroExt()); groupTemplate.registerFunctionPackage("tool", new ToolUtil()); groupTemplate.registerFunctionPackage("kaptcha", new KaptchaUtil()); } }
[ "527088995@qq.com" ]
527088995@qq.com
588fef1a0b21a6b23fac69c57fb09bdf64c22600
ae27789afbca385c42e521b26ca5423e9101a487
/src/command/macro/receiver/Hottub.java
0e6edd6cabd3a6f2d4ce794dcd3c656dd2f9f535
[]
no_license
ville-chen/design-patterns
511298f748c50eec6d0b7a7a47024582410352a6
60dcf0c9552bfd8ecd47e4a504e71cc76e63bfa6
refs/heads/master
2021-05-05T05:52:20.315335
2019-01-02T06:04:21
2019-01-02T06:04:21
118,759,427
0
0
null
null
null
null
UTF-8
Java
false
false
785
java
package command.macro.receiver; public class Hottub { private boolean on; private int temperature; public Hottub() { } public void on() { on = true; } public void off() { on = false; } public void circulate() { if (on) { System.out.println("Hottub is bubbling!"); } } public void jetsOn() { if (on) { System.out.println("Hottub jets are on"); } } public void jetsOff() { if (on) { System.out.println("Hottub jets are off"); } } public void setTemperature(int temperature) { if (temperature > this.temperature) { System.out.println("Hottub is heating to a steaming " + temperature + " degrees"); } else { System.out.println("Hottub is cooling to " + temperature + " degrees"); } this.temperature = temperature; } }
[ "ville.chen@rubansh.com" ]
ville.chen@rubansh.com
96d8ce739cef4adbcac48d5f30e1f32088a6b742
118fd39a18220c4c592aed5fecda5b8ca6930706
/SpringOAuth2/client/src/main/java/com/gability/demos/oauth2/client/ClientController.java
37a17a9e1cc8365d930f90ce16ae1407fb70a7b1
[ "MIT" ]
permissive
gabrianoo/Demos
7a8aaeb978cc7b4ec68cbb0027b836c896950bf3
4bf7d19f5eb1a46dd8b0f1bbc87d3bc12c62bf97
refs/heads/master
2021-04-30T02:49:51.409630
2018-02-14T14:10:28
2018-02-14T14:10:28
121,507,169
1
0
null
null
null
null
UTF-8
Java
false
false
623
java
package com.gability.demos.oauth2.client; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.security.Principal; @RestController public class ClientController { @GetMapping("/*") // @PreAuthorize("#oauth2.hasScope('read')") public String home(HttpServletRequest request, Principal principal) { return "Hello OAuth2 User"; } @GetMapping("/redirected") public Principal redirected(Principal principal) { return principal; } }
[ "me@ahmedhassanien.com" ]
me@ahmedhassanien.com
cdd9e52113df5e9eeb9e81640f82182a6d2ad5ac
ae5eb1a38b4d22c82dfd67c86db73592094edc4b
/project469/src/test/java/org/gradle/test/performance/largejavamultiproject/project469/p2349/Test46988.java
f19f073450187199cf28d0cdca76d027736c9791
[]
no_license
big-guy/largeJavaMultiProject
405cc7f55301e1fd87cee5878a165ec5d4a071aa
1cd6a3f9c59e9b13dffa35ad27d911114f253c33
refs/heads/main
2023-03-17T10:59:53.226128
2021-03-04T01:01:39
2021-03-04T01:01:39
344,307,977
0
0
null
null
null
null
UTF-8
Java
false
false
2,113
java
package org.gradle.test.performance.largejavamultiproject.project469.p2349; import org.junit.Test; import static org.junit.Assert.*; public class Test46988 { Production46988 objectUnderTest = new Production46988(); @Test public void testProperty0() { String value = "value"; objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { String value = "value"; objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { String value = "value"; objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
[ "sterling.greene@gmail.com" ]
sterling.greene@gmail.com
9b29e982a6c95118a526aa30636bb1597fdaf281
69d05d3d3525f14766038d47e682626ae9bcf3a9
/cryptoService/src/main/java/com/emirates/citp/crypto/impl/RSAKey.java
4bb8633440c6ffd2d132ca5bee628f276021791e
[]
no_license
Rajatk95/pci_dss_ext_usb
509d8fb79ae14edef51b7ee4c9817c432c36a27b
693ebccf2b3414338ea4c4f3f017d157fa344113
refs/heads/master
2021-01-20T15:06:54.055728
2010-03-28T19:09:46
2010-03-28T19:09:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
640
java
package com.emirates.citp.crypto.impl; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; public class RSAKey { private RSAPrivateKey secretKey; public RSAPublicKey publicKey; private String appId; public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public RSAPrivateKey getSecretKey() { return secretKey; } public void setSecretKey(RSAPrivateKey secretKey) { this.secretKey = secretKey; } public RSAPublicKey getPublicKey() { return publicKey; } public void setPublicKey(RSAPublicKey publicKey) { this.publicKey = publicKey; } }
[ "khaliqgaffar@gmail.com" ]
khaliqgaffar@gmail.com
ea8d78638536d5bf2ce73887cba7a3552bc7b5ec
51cf73f27bd06af80e65d60e2ab7a8751dae8cb8
/app/src/main/java/com/example/taruc/roomtest/UserAdapter.java
97d355b705f217bcb0eff5c58aae7fa30b04c6a2
[]
no_license
azurawatii/RoomTest
b88dedd2943222029b5221b37a59a0c5b20d0fbe
93b4e58c47ed5de402a18232a4db6126415c4b8a
refs/heads/master
2020-03-18T11:02:17.427346
2018-05-24T02:49:34
2018-05-24T02:49:34
134,646,615
0
0
null
null
null
null
UTF-8
Java
false
false
569
java
package com.example.taruc.roomtest; import android.content.Context; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.widget.ArrayAdapter; import java.util.ArrayList; import java.util.List; /** * Created by taruc on 24/5/2018. */ public class UserAdapter extends ArrayAdapter { ArrayList<String> users; public UserAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull ArrayList<String> users) { super(context, resource, users); } }
[ "azurawatii@tarc.edu.my" ]
azurawatii@tarc.edu.my
b21408da7e2bf5859a56ecf5c007afcad50bd764
911f46d9722f1fae7ad4500318868630722179de
/src/Repository/IRepository.java
7a39a68e1c6035549692b3f73cb741bcadbf9b58
[]
no_license
alexandra-olahut/Toy-interpreter
925984b9b7433ab621b55f6caab8550b973321fa
6937cd61efd306fde5b8c1ef845ba54c68b7b177
refs/heads/main
2023-03-28T20:01:25.938118
2021-03-20T18:28:56
2021-03-20T18:28:56
348,821,884
0
0
null
null
null
null
UTF-8
Java
false
false
287
java
package Repository; import Model.ProgramState.PrgState; import java.util.List; public interface IRepository { List<PrgState> getPrgList(); void setPrgList(List<PrgState> newList); PrgState getMainPrg(); void logPrgStateExec(PrgState prg); void resetLogFile(); }
[ "70906697+alexandra-olahut@users.noreply.github.com" ]
70906697+alexandra-olahut@users.noreply.github.com
3e3663dd41e63993b3baef16fe69615e1886ae71
23a552b2b5e15ee7d35f490d87904e671f3fc562
/jsurfer/src/generated/java/com/goldensoftware/surfer/IPlotWindow.java
138023c599bb5a40ea162bec69c1b2be72490144
[]
no_license
alberts/fullung
3d52e3d911ef52aa0f552364940eb95cdd83b12a
9acd63cd0da6cf0ffe95493e174bba27eda24d2a
refs/heads/master
2021-01-20T05:32:15.286586
2008-09-27T10:34:12
2008-09-27T10:34:12
32,113,504
0
1
null
null
null
null
UTF-8
Java
false
false
2,129
java
package com.goldensoftware.surfer; import com4j.IID; import com4j.VTID; /** * IPlotWindow Interface */ @IID("{B2933408-9788-11D2-9780-00104B6D9C80}") public interface IPlotWindow extends com.goldensoftware.surfer.IWindow { /** * Enable/Disable Automatic Redraw */ @VTID(26) boolean autoRedraw(); /** * Enable/Disable Automatic Redraw */ @VTID(27) void autoRedraw(boolean pEnabled); /** * Show/hide rulers */ @VTID(28) boolean showRulers(); /** * Show/hide rulers */ @VTID(29) void showRulers(boolean pShow); /** * Show/hide the drawing grid */ @VTID(30) boolean showGrid(); /** * Show/hide the drawing grid */ @VTID(31) void showGrid(boolean pShow); /** * Redraw the contents of this window */ @VTID(32) void redraw(); /** * Zoom in or out */ @VTID(33) void zoom(com.goldensoftware.surfer.SrfZoomTypes type); /** * Zoom in or out about a specified point */ @VTID(34) void zoomPoint(double x, double y, double scale); /** * Zoom such that the specified rectangle occupies the entire window */ @VTID(35) void zoomRectangle(double left, double top, double right, double bottom); /** * Returns the horizontal ruler object */ @VTID(36) com.goldensoftware.surfer.IRuler horizontalRuler(); /** * Returns the vertical ruler object */ @VTID(37) com.goldensoftware.surfer.IRuler verticalRuler(); /** * Show/hide the page representation rectangle */ @VTID(38) boolean showPage(); /** * Show/hide the page representation rectangle */ @VTID(39) void showPage(boolean pShow); /** * Show/hide the margin representation rectangle */ @VTID(40) boolean showMargins(); /** * Show/hide the margin representation rectangle */ @VTID(41) void showMargins(boolean pShow); }
[ "fullung@76970873-ce3a-0410-a9b7-c9c6e07dc4f1" ]
fullung@76970873-ce3a-0410-a9b7-c9c6e07dc4f1
3bac951903c6e56b94f5189958b99857ee8bc530
b6376887c07ff1249eaf7e75ad34adf73bf7161e
/src/kerstein/ufo/TopTenUfoLocations.java
6e927dcd04feb6d8dd31fd93e936736c4deb732f
[]
no_license
renakerstein/kerstein-mco152
d0ad86ec163e15d341aad455208950e40ca3fe0e
004c43c10080fe58a41ca7d4f06d5c2ab6551864
refs/heads/master
2020-05-30T21:47:33.240802
2016-01-15T02:35:14
2016-01-15T02:35:14
42,276,696
0
0
null
null
null
null
UTF-8
Java
false
false
1,706
java
package kerstein.ufo; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.google.gson.Gson; public class TopTenUfoLocations { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader( "./ufo_awesome.json")); // construct GSON class Gson gson = new Gson(); UFOSightingList list = gson.fromJson(in, UFOSightingList.class); in.close(); // put all the locations from the UFO list into a hash map // with its value being the number of times its sighted HashMap<String, Integer> map = new HashMap<String, Integer>(); for (UFOSighting l : list) { Integer value = map.get(l.getLocation()); if (value == null) { map.put(l.getLocation(), 1); } else { map.put(l.getLocation(), value + 1); } } // initialize variables int largestValue = 0; String location = null; // loop through the map while i<10 so the top ten locations can be // accessed for (int i = 0; i < 10; i++) { largestValue = 0; // reset the largest value to 0 (so the next // largest value can be accessed) for (Map.Entry<String, Integer> entry : map.entrySet()) { if (entry.getValue() > largestValue) { largestValue = entry.getValue(); // get the largest value location = entry.getKey(); // get the key of that value - // the location } } System.out.println(location + " - " + largestValue + " sightings"); // remove the largest value found and its key from the map // so the next greatest value can now be accessed from the map map.remove(largestValue); map.remove(location); } } }
[ "renakerstein" ]
renakerstein
ed8c210e0afa30f34ad023410d3b7ff3e90708d9
a780513853ca912be1025e48421a66def2f821eb
/wicket-jquery-ui-samples/src/main/java/com/googlecode/wicket/jquery/ui/samples/pages/kendo/dragdrop/BehaviorDragDropPage.java
961933adceb0f31d88bf743290c97696012a38a9
[ "Apache-2.0" ]
permissive
calebematos/wicket-jquery-ui
563de9b8641228956a89da65f15baab7881a2ff2
994d71c6d56f102d7b4364178909838606a5f12e
refs/heads/master
2021-01-15T15:00:34.014306
2015-06-19T22:43:50
2015-06-19T22:43:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,832
java
package com.googlecode.wicket.jquery.ui.samples.pages.kendo.dragdrop; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.WebMarkupContainer; import com.googlecode.wicket.kendo.ui.console.Console; import com.googlecode.wicket.kendo.ui.interaction.draggable.DraggableBehavior; import com.googlecode.wicket.kendo.ui.interaction.droppable.DroppableBehavior; public class BehaviorDragDropPage extends AbstractDragDropPage { private static final long serialVersionUID = 1L; private final Console console; public BehaviorDragDropPage() { // console // this.console = new Console("console"); this.add(this.console); // draggable // WebMarkupContainer container = new WebMarkupContainer("draggable"); container.add(this.newDraggableBehavior()); this.add(container); // droppable // this.add(this.newDroppableBehavior("#wrapper-panel-frame")); } private DraggableBehavior newDraggableBehavior() { return new DraggableBehavior() { private static final long serialVersionUID = 1L; @Override public boolean isCancelEventEnabled() { // not enabled to prevent unnecessary server round-trips. return false; } @Override public void onDragStart(AjaxRequestTarget target, int top, int left) { info(target, String.format("Draggable: onDragStart, position [%d, %d]", top, left)); } @Override public void onDragStop(AjaxRequestTarget target, int top, int left) { info(target, String.format("Draggable: onDragStop, position [%d, %d]", top, left)); } @Override public void onDragCancel(AjaxRequestTarget target, int top, int left) { // noop } }; } private DroppableBehavior newDroppableBehavior(String selector) { return new DroppableBehavior(selector) { private static final long serialVersionUID = 1L; @Override public boolean isDragEnterEventEnabled() { // not enabled to prevent unnecessary server round-trips. return false; } @Override public boolean isDragLeaveEventEnabled() { // not enabled to prevent unnecessary server round-trips. return false; } @Override public void onDragEnter(AjaxRequestTarget target, Component component) { // noop } @Override public void onDragLeave(AjaxRequestTarget target, Component component) { // noop } @Override public void onDrop(AjaxRequestTarget target, Component component) { info(target, "Droppable: onDrop", component); } }; } protected void info(AjaxRequestTarget target, String message) { this.console.info(target, message); } protected void info(AjaxRequestTarget target, String message, Component component) { this.console.info(target, String.format("%s - %s", message, component.getMarkupId())); } }
[ "sebastien.briquet@amadeus.com" ]
sebastien.briquet@amadeus.com
9b32739fb2cd3d22e65aab68c76bb54cc3e6e0d0
7259106305cbae4e1e90e23bf6da1bb9e1f9ea22
/src/main/java/org/jenkinsci/plugins/systemmessage/user/UserReadSystemMessagesUserPropertyDescriptor.java
676ebdcd704ce48748bfb32cdcdcb989a0fa2e90
[ "MIT" ]
permissive
eaglerainbow/system-message-plugin
a35c54dd53ddf343548113c74ce26a1e953a8dac
09400d668fbb3e69f4aad5fc1aa4a993446ecb9f
refs/heads/master
2020-12-06T19:35:49.674370
2016-09-25T10:51:27
2016-09-25T10:51:27
67,734,651
0
0
null
null
null
null
UTF-8
Java
false
false
653
java
package org.jenkinsci.plugins.systemmessage.user; import hudson.Extension; import hudson.model.*; @Extension public class UserReadSystemMessagesUserPropertyDescriptor extends UserPropertyDescriptor { public UserReadSystemMessagesUserPropertyDescriptor() { super(UserReadSystemMessagesUserProperty.class); } @Override public UserProperty newInstance(User user) { UserReadSystemMessagesUserProperty usrsmup = new UserReadSystemMessagesUserProperty( user ); return usrsmup; } @Override public String getDisplayName() { return "User Property storing already read system messages of a user"; } }
[ "github@schmoigl-online.de" ]
github@schmoigl-online.de
ae4f598839fcbbacb42873ab9631652ac20e4a39
d598e6d37998300aeae20fc5362d83c4ce229204
/guava-libraries/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Sets.java
c1c1764c8b36605c5e410fa1faed0d442aaf71b9
[ "Apache-2.0" ]
permissive
peidachang/guava-1
21aae93538502fa78df69c73e622c6f29dc1b235
067fcb32ba43d7d23f2bbc7e971533879c7c1446
refs/heads/master
2021-01-24T03:11:44.170150
2013-05-23T11:32:42
2013-05-23T11:32:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
46,302
java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Collections2.FilteredCollection; import java.util.AbstractSet; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.Nullable; /** * Static utility methods pertaining to {@link Set} instances. Also see this * class's counterparts {@link Lists}, {@link Maps} and {@link Queues}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Sets"> * {@code Sets}</a>. * * @author Kevin Bourrillion * @author Jared Levy * @author Chris Povirk * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class Sets { private Sets() {} /** * {@link AbstractSet} substitute without the potentially-quadratic * {@code removeAll} implementation. */ abstract static class ImprovedAbstractSet<E> extends AbstractSet<E> { @Override public boolean removeAll(Collection<?> c) { return removeAllImpl(this, c); } @Override public boolean retainAll(Collection<?> c) { return super.retainAll(checkNotNull(c)); // GWT compatibility } } /** * Returns an immutable set instance containing the given enum elements. * Internally, the returned set will be backed by an {@link EnumSet}. * * <p>The iteration order of the returned set follows the enum's iteration * order, not the order in which the elements are provided to the method. * * @param anElement one of the elements the set should contain * @param otherElements the rest of the elements the set should contain * @return an immutable set containing those elements, minus duplicates */ // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028 @GwtCompatible(serializable = true) public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet( E anElement, E... otherElements) { return ImmutableEnumSet.asImmutable(EnumSet.of(anElement, otherElements)); } /** * Returns an immutable set instance containing the given enum elements. * Internally, the returned set will be backed by an {@link EnumSet}. * * <p>The iteration order of the returned set follows the enum's iteration * order, not the order in which the elements appear in the given collection. * * @param elements the elements, all of the same {@code enum} type, that the * set should contain * @return an immutable set containing those elements, minus duplicates */ // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028 @GwtCompatible(serializable = true) public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet( Iterable<E> elements) { if (elements instanceof ImmutableEnumSet) { return (ImmutableEnumSet<E>) elements; } else if (elements instanceof Collection) { Collection<E> collection = (Collection<E>) elements; if (collection.isEmpty()) { return ImmutableSet.of(); } else { return ImmutableEnumSet.asImmutable(EnumSet.copyOf(collection)); } } else { Iterator<E> itr = elements.iterator(); if (itr.hasNext()) { EnumSet<E> enumSet = EnumSet.of(itr.next()); Iterators.addAll(enumSet, itr); return ImmutableEnumSet.asImmutable(enumSet); } else { return ImmutableSet.of(); } } } /** * Returns a new {@code EnumSet} instance containing the given elements. * Unlike {@link EnumSet#copyOf(Collection)}, this method does not produce an * exception on an empty collection, and it may be called on any iterable, not * just a {@code Collection}. */ public static <E extends Enum<E>> EnumSet<E> newEnumSet(Iterable<E> iterable, Class<E> elementType) { EnumSet<E> set = EnumSet.noneOf(elementType); Iterables.addAll(set, iterable); return set; } // HashSet /** * Creates a <i>mutable</i>, empty {@code HashSet} instance. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableSet#of()} instead. * * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link * EnumSet#noneOf} instead. * * @return a new, empty {@code HashSet} */ public static <E> HashSet<E> newHashSet() { return new HashSet<E>(); } /** * Creates a <i>mutable</i> {@code HashSet} instance containing the given * elements in unspecified order. * * <p><b>Note:</b> if mutability is not required and the elements are * non-null, use an overload of {@link ImmutableSet#of()} (for varargs) or * {@link ImmutableSet#copyOf(Object[])} (for an array) instead. * * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link * EnumSet#of(Enum, Enum[])} instead. * * @param elements the elements that the set should contain * @return a new {@code HashSet} containing those elements (minus duplicates) */ public static <E> HashSet<E> newHashSet(E... elements) { HashSet<E> set = newHashSetWithExpectedSize(elements.length); Collections.addAll(set, elements); return set; } /** * Creates a {@code HashSet} instance, with a high enough "initial capacity" * that it <i>should</i> hold {@code expectedSize} elements without growth. * This behavior cannot be broadly guaranteed, but it is observed to be true * for OpenJDK 1.6. It also can't be guaranteed that the method isn't * inadvertently <i>oversizing</i> the returned set. * * @param expectedSize the number of elements you expect to add to the * returned set * @return a new, empty {@code HashSet} with enough capacity to hold {@code * expectedSize} elements without resizing * @throws IllegalArgumentException if {@code expectedSize} is negative */ public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize) { return new HashSet<E>(Maps.capacity(expectedSize)); } /** * Creates a <i>mutable</i> {@code HashSet} instance containing the given * elements in unspecified order. * * <p><b>Note:</b> if mutability is not required and the elements are * non-null, use {@link ImmutableSet#copyOf(Iterable)} instead. * * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use * {@link #newEnumSet(Iterable, Class)} instead. * * @param elements the elements that the set should contain * @return a new {@code HashSet} containing those elements (minus duplicates) */ public static <E> HashSet<E> newHashSet(Iterable<? extends E> elements) { return (elements instanceof Collection) ? new HashSet<E>(Collections2.cast(elements)) : newHashSet(elements.iterator()); } /** * Creates a <i>mutable</i> {@code HashSet} instance containing the given * elements in unspecified order. * * <p><b>Note:</b> if mutability is not required and the elements are * non-null, use {@link ImmutableSet#copyOf(Iterable)} instead. * * <p><b>Note:</b> if {@code E} is an {@link Enum} type, you should create an * {@link EnumSet} instead. * * @param elements the elements that the set should contain * @return a new {@code HashSet} containing those elements (minus duplicates) */ public static <E> HashSet<E> newHashSet(Iterator<? extends E> elements) { HashSet<E> set = newHashSet(); Iterators.addAll(set, elements); return set; } /** * Creates a thread-safe set backed by a hash map. The set is backed by a * {@link ConcurrentHashMap} instance, and thus carries the same concurrency * guarantees. * * <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be * used as an element. The set is serializable. * * @return a new, empty thread-safe {@code Set} * @since 15.0 */ public static <E> Set<E> newConcurrentHashSet() { return newSetFromMap(new ConcurrentHashMap<E, Boolean>()); } /** * Creates a thread-safe set backed by a hash map and containing the given * elements. The set is backed by a {@link ConcurrentHashMap} instance, and * thus carries the same concurrency guarantees. * * <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be * used as an element. The set is serializable. * * @param elements the elements that the set should contain * @return a new thread-safe set containing those elements (minus duplicates) * @throws NullPointerException if {@code elements} or any of its contents is * null * @since 15.0 */ public static <E> Set<E> newConcurrentHashSet( Iterable<? extends E> elements) { Set<E> set = newConcurrentHashSet(); Iterables.addAll(set, elements); return set; } // LinkedHashSet /** * Creates a <i>mutable</i>, empty {@code LinkedHashSet} instance. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableSet#of()} instead. * * @return a new, empty {@code LinkedHashSet} */ public static <E> LinkedHashSet<E> newLinkedHashSet() { return new LinkedHashSet<E>(); } /** * Creates a {@code LinkedHashSet} instance, with a high enough "initial * capacity" that it <i>should</i> hold {@code expectedSize} elements without * growth. This behavior cannot be broadly guaranteed, but it is observed to * be true for OpenJDK 1.6. It also can't be guaranteed that the method isn't * inadvertently <i>oversizing</i> the returned set. * * @param expectedSize the number of elements you expect to add to the * returned set * @return a new, empty {@code LinkedHashSet} with enough capacity to hold * {@code expectedSize} elements without resizing * @throws IllegalArgumentException if {@code expectedSize} is negative * @since 11.0 */ public static <E> LinkedHashSet<E> newLinkedHashSetWithExpectedSize( int expectedSize) { return new LinkedHashSet<E>(Maps.capacity(expectedSize)); } /** * Creates a <i>mutable</i> {@code LinkedHashSet} instance containing the * given elements in order. * * <p><b>Note:</b> if mutability is not required and the elements are * non-null, use {@link ImmutableSet#copyOf(Iterable)} instead. * * @param elements the elements that the set should contain, in order * @return a new {@code LinkedHashSet} containing those elements (minus * duplicates) */ public static <E> LinkedHashSet<E> newLinkedHashSet( Iterable<? extends E> elements) { if (elements instanceof Collection) { return new LinkedHashSet<E>(Collections2.cast(elements)); } LinkedHashSet<E> set = newLinkedHashSet(); Iterables.addAll(set, elements); return set; } // TreeSet /** * Creates a <i>mutable</i>, empty {@code TreeSet} instance sorted by the * natural sort ordering of its elements. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableSortedSet#of()} instead. * * @return a new, empty {@code TreeSet} */ public static <E extends Comparable> TreeSet<E> newTreeSet() { return new TreeSet<E>(); } /** * Creates a <i>mutable</i> {@code TreeSet} instance containing the given * elements sorted by their natural ordering. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableSortedSet#copyOf(Iterable)} instead. * * <p><b>Note:</b> If {@code elements} is a {@code SortedSet} with an explicit * comparator, this method has different behavior than * {@link TreeSet#TreeSet(SortedSet)}, which returns a {@code TreeSet} with * that comparator. * * @param elements the elements that the set should contain * @return a new {@code TreeSet} containing those elements (minus duplicates) */ public static <E extends Comparable> TreeSet<E> newTreeSet( Iterable<? extends E> elements) { TreeSet<E> set = newTreeSet(); Iterables.addAll(set, elements); return set; } /** * Creates a <i>mutable</i>, empty {@code TreeSet} instance with the given * comparator. * * <p><b>Note:</b> if mutability is not required, use {@code * ImmutableSortedSet.orderedBy(comparator).build()} instead. * * @param comparator the comparator to use to sort the set * @return a new, empty {@code TreeSet} * @throws NullPointerException if {@code comparator} is null */ public static <E> TreeSet<E> newTreeSet(Comparator<? super E> comparator) { return new TreeSet<E>(checkNotNull(comparator)); } /** * Creates an empty {@code Set} that uses identity to determine equality. It * compares object references, instead of calling {@code equals}, to * determine whether a provided object matches an element in the set. For * example, {@code contains} returns {@code false} when passed an object that * equals a set member, but isn't the same instance. This behavior is similar * to the way {@code IdentityHashMap} handles key lookups. * * @since 8.0 */ public static <E> Set<E> newIdentityHashSet() { return Sets.newSetFromMap(Maps.<E, Boolean>newIdentityHashMap()); } /** * Creates an {@code EnumSet} consisting of all enum values that are not in * the specified collection. If the collection is an {@link EnumSet}, this * method has the same behavior as {@link EnumSet#complementOf}. Otherwise, * the specified collection must contain at least one element, in order to * determine the element type. If the collection could be empty, use * {@link #complementOf(Collection, Class)} instead of this method. * * @param collection the collection whose complement should be stored in the * enum set * @return a new, modifiable {@code EnumSet} containing all values of the enum * that aren't present in the given collection * @throws IllegalArgumentException if {@code collection} is not an * {@code EnumSet} instance and contains no elements */ public static <E extends Enum<E>> EnumSet<E> complementOf( Collection<E> collection) { if (collection instanceof EnumSet) { return EnumSet.complementOf((EnumSet<E>) collection); } checkArgument(!collection.isEmpty(), "collection is empty; use the other version of this method"); Class<E> type = collection.iterator().next().getDeclaringClass(); return makeComplementByHand(collection, type); } /** * Creates an {@code EnumSet} consisting of all enum values that are not in * the specified collection. This is equivalent to * {@link EnumSet#complementOf}, but can act on any input collection, as long * as the elements are of enum type. * * @param collection the collection whose complement should be stored in the * {@code EnumSet} * @param type the type of the elements in the set * @return a new, modifiable {@code EnumSet} initially containing all the * values of the enum not present in the given collection */ public static <E extends Enum<E>> EnumSet<E> complementOf( Collection<E> collection, Class<E> type) { checkNotNull(collection); return (collection instanceof EnumSet) ? EnumSet.complementOf((EnumSet<E>) collection) : makeComplementByHand(collection, type); } private static <E extends Enum<E>> EnumSet<E> makeComplementByHand( Collection<E> collection, Class<E> type) { EnumSet<E> result = EnumSet.allOf(type); result.removeAll(collection); return result; } /** * Returns a set backed by the specified map. The resulting set displays * the same ordering, concurrency, and performance characteristics as the * backing map. In essence, this factory method provides a {@link Set} * implementation corresponding to any {@link Map} implementation. There is no * need to use this method on a {@link Map} implementation that already has a * corresponding {@link Set} implementation (such as {@link java.util.HashMap} * or {@link java.util.TreeMap}). * * <p>Each method invocation on the set returned by this method results in * exactly one method invocation on the backing map or its {@code keySet} * view, with one exception. The {@code addAll} method is implemented as a * sequence of {@code put} invocations on the backing map. * * <p>The specified map must be empty at the time this method is invoked, * and should not be accessed directly after this method returns. These * conditions are ensured if the map is created empty, passed directly * to this method, and no reference to the map is retained, as illustrated * in the following code fragment: <pre> {@code * * Set<Object> identityHashSet = Sets.newSetFromMap( * new IdentityHashMap<Object, Boolean>());}</pre> * * This method has the same behavior as the JDK 6 method * {@code Collections.newSetFromMap()}. The returned set is serializable if * the backing map is. * * @param map the backing map * @return the set backed by the map * @throws IllegalArgumentException if {@code map} is not empty */ public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) { return Platform.newSetFromMap(map); } /** * An unmodifiable view of a set which may be backed by other sets; this view * will change as the backing sets do. Contains methods to copy the data into * a new set which will then remain stable. There is usually no reason to * retain a reference of type {@code SetView}; typically, you either use it * as a plain {@link Set}, or immediately invoke {@link #immutableCopy} or * {@link #copyInto} and forget the {@code SetView} itself. * * @since 2.0 (imported from Google Collections Library) */ public abstract static class SetView<E> extends AbstractSet<E> { private SetView() {} // no subclasses but our own /** * Returns an immutable copy of the current contents of this set view. * Does not support null elements. * * <p><b>Warning:</b> this may have unexpected results if a backing set of * this view uses a nonstandard notion of equivalence, for example if it is * a {@link TreeSet} using a comparator that is inconsistent with {@link * Object#equals(Object)}. */ public ImmutableSet<E> immutableCopy() { return ImmutableSet.copyOf(this); } /** * Copies the current contents of this set view into an existing set. This * method has equivalent behavior to {@code set.addAll(this)}, assuming that * all the sets involved are based on the same notion of equivalence. * * @return a reference to {@code set}, for convenience */ // Note: S should logically extend Set<? super E> but can't due to either // some javac bug or some weirdness in the spec, not sure which. public <S extends Set<E>> S copyInto(S set) { set.addAll(this); return set; } } /** * Returns an unmodifiable <b>view</b> of the union of two sets. The returned * set contains all elements that are contained in either backing set. * Iterating over the returned set iterates first over all the elements of * {@code set1}, then over each element of {@code set2}, in order, that is not * contained in {@code set1}. * * <p>Results are undefined if {@code set1} and {@code set2} are sets based on * different equivalence relations (as {@link HashSet}, {@link TreeSet}, and * the {@link Map#keySet} of an {@code IdentityHashMap} all are). * * <p><b>Note:</b> The returned view performs better when {@code set1} is the * smaller of the two sets. If you have reason to believe one of your sets * will generally be smaller than the other, pass it first. * * <p>Further, note that the current implementation is not suitable for nested * {@code union} views, i.e. the following should be avoided when in a loop: * {@code union = Sets.union(union, anotherSet);}, since iterating over the resulting * set has a cubic complexity to the depth of the nesting. */ public static <E> SetView<E> union( final Set<? extends E> set1, final Set<? extends E> set2) { checkNotNull(set1, "set1"); checkNotNull(set2, "set2"); final Set<? extends E> set2minus1 = difference(set2, set1); return new SetView<E>() { @Override public int size() { return set1.size() + set2minus1.size(); } @Override public boolean isEmpty() { return set1.isEmpty() && set2.isEmpty(); } @Override public Iterator<E> iterator() { return Iterators.unmodifiableIterator( Iterators.concat(set1.iterator(), set2minus1.iterator())); } @Override public boolean contains(Object object) { return set1.contains(object) || set2.contains(object); } @Override public <S extends Set<E>> S copyInto(S set) { set.addAll(set1); set.addAll(set2); return set; } @Override public ImmutableSet<E> immutableCopy() { return new ImmutableSet.Builder<E>() .addAll(set1).addAll(set2).build(); } }; } /** * Returns an unmodifiable <b>view</b> of the intersection of two sets. The * returned set contains all elements that are contained by both backing sets. * The iteration order of the returned set matches that of {@code set1}. * * <p>Results are undefined if {@code set1} and {@code set2} are sets based * on different equivalence relations (as {@code HashSet}, {@code TreeSet}, * and the keySet of an {@code IdentityHashMap} all are). * * <p><b>Note:</b> The returned view performs slightly better when {@code * set1} is the smaller of the two sets. If you have reason to believe one of * your sets will generally be smaller than the other, pass it first. * Unfortunately, since this method sets the generic type of the returned set * based on the type of the first set passed, this could in rare cases force * you to make a cast, for example: <pre> {@code * * Set<Object> aFewBadObjects = ... * Set<String> manyBadStrings = ... * * // impossible for a non-String to be in the intersection * SuppressWarnings("unchecked") * Set<String> badStrings = (Set) Sets.intersection( * aFewBadObjects, manyBadStrings);}</pre> * * This is unfortunate, but should come up only very rarely. */ public static <E> SetView<E> intersection( final Set<E> set1, final Set<?> set2) { checkNotNull(set1, "set1"); checkNotNull(set2, "set2"); final Predicate<Object> inSet2 = Predicates.in(set2); return new SetView<E>() { @Override public Iterator<E> iterator() { return Iterators.filter(set1.iterator(), inSet2); } @Override public int size() { return Iterators.size(iterator()); } @Override public boolean isEmpty() { return !iterator().hasNext(); } @Override public boolean contains(Object object) { return set1.contains(object) && set2.contains(object); } @Override public boolean containsAll(Collection<?> collection) { return set1.containsAll(collection) && set2.containsAll(collection); } }; } /** * Returns an unmodifiable <b>view</b> of the difference of two sets. The * returned set contains all elements that are contained by {@code set1} and * not contained by {@code set2}. {@code set2} may also contain elements not * present in {@code set1}; these are simply ignored. The iteration order of * the returned set matches that of {@code set1}. * * <p>Results are undefined if {@code set1} and {@code set2} are sets based * on different equivalence relations (as {@code HashSet}, {@code TreeSet}, * and the keySet of an {@code IdentityHashMap} all are). */ public static <E> SetView<E> difference( final Set<E> set1, final Set<?> set2) { checkNotNull(set1, "set1"); checkNotNull(set2, "set2"); final Predicate<Object> notInSet2 = Predicates.not(Predicates.in(set2)); return new SetView<E>() { @Override public Iterator<E> iterator() { return Iterators.filter(set1.iterator(), notInSet2); } @Override public int size() { return Iterators.size(iterator()); } @Override public boolean isEmpty() { return set2.containsAll(set1); } @Override public boolean contains(Object element) { return set1.contains(element) && !set2.contains(element); } }; } /** * Returns an unmodifiable <b>view</b> of the symmetric difference of two * sets. The returned set contains all elements that are contained in either * {@code set1} or {@code set2} but not in both. The iteration order of the * returned set is undefined. * * <p>Results are undefined if {@code set1} and {@code set2} are sets based * on different equivalence relations (as {@code HashSet}, {@code TreeSet}, * and the keySet of an {@code IdentityHashMap} all are). * * @since 3.0 */ public static <E> SetView<E> symmetricDifference( Set<? extends E> set1, Set<? extends E> set2) { checkNotNull(set1, "set1"); checkNotNull(set2, "set2"); // TODO(kevinb): Replace this with a more efficient implementation return difference(union(set1, set2), intersection(set1, set2)); } /** * Returns the elements of {@code unfiltered} that satisfy a predicate. The * returned set is a live view of {@code unfiltered}; changes to one affect * the other. * * <p>The resulting set's iterator does not support {@code remove()}, but all * other set methods are supported. When given an element that doesn't satisfy * the predicate, the set's {@code add()} and {@code addAll()} methods throw * an {@link IllegalArgumentException}. When methods such as {@code * removeAll()} and {@code clear()} are called on the filtered set, only * elements that satisfy the filter will be removed from the underlying set. * * <p>The returned set isn't threadsafe or serializable, even if * {@code unfiltered} is. * * <p>Many of the filtered set's methods, such as {@code size()}, iterate * across every element in the underlying set and determine which elements * satisfy the filter. When a live view is <i>not</i> needed, it may be faster * to copy {@code Iterables.filter(unfiltered, predicate)} and use the copy. * * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, * as documented at {@link Predicate#apply}. Do not provide a predicate such * as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent * with equals. (See {@link Iterables#filter(Iterable, Class)} for related * functionality.) */ // TODO(kevinb): how to omit that last sentence when building GWT javadoc? public static <E> Set<E> filter( Set<E> unfiltered, Predicate<? super E> predicate) { if (unfiltered instanceof SortedSet) { return filter((SortedSet<E>) unfiltered, predicate); } if (unfiltered instanceof FilteredSet) { // Support clear(), removeAll(), and retainAll() when filtering a filtered // collection. FilteredSet<E> filtered = (FilteredSet<E>) unfiltered; Predicate<E> combinedPredicate = Predicates.<E>and(filtered.predicate, predicate); return new FilteredSet<E>( (Set<E>) filtered.unfiltered, combinedPredicate); } return new FilteredSet<E>( checkNotNull(unfiltered), checkNotNull(predicate)); } private static class FilteredSet<E> extends FilteredCollection<E> implements Set<E> { FilteredSet(Set<E> unfiltered, Predicate<? super E> predicate) { super(unfiltered, predicate); } @Override public boolean equals(@Nullable Object object) { return equalsImpl(this, object); } @Override public int hashCode() { return hashCodeImpl(this); } } /** * Returns the elements of a {@code SortedSet}, {@code unfiltered}, that * satisfy a predicate. The returned set is a live view of {@code unfiltered}; * changes to one affect the other. * * <p>The resulting set's iterator does not support {@code remove()}, but all * other set methods are supported. When given an element that doesn't satisfy * the predicate, the set's {@code add()} and {@code addAll()} methods throw * an {@link IllegalArgumentException}. When methods such as * {@code removeAll()} and {@code clear()} are called on the filtered set, * only elements that satisfy the filter will be removed from the underlying * set. * * <p>The returned set isn't threadsafe or serializable, even if * {@code unfiltered} is. * * <p>Many of the filtered set's methods, such as {@code size()}, iterate across * every element in the underlying set and determine which elements satisfy * the filter. When a live view is <i>not</i> needed, it may be faster to copy * {@code Iterables.filter(unfiltered, predicate)} and use the copy. * * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, * as documented at {@link Predicate#apply}. Do not provide a predicate such as * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with * equals. (See {@link Iterables#filter(Iterable, Class)} for related * functionality.) * * @since 11.0 */ public static <E> SortedSet<E> filter( SortedSet<E> unfiltered, Predicate<? super E> predicate) { return Platform.setsFilterSortedSet(unfiltered, predicate); } static <E> SortedSet<E> filterSortedIgnoreNavigable( SortedSet<E> unfiltered, Predicate<? super E> predicate) { if (unfiltered instanceof FilteredSet) { // Support clear(), removeAll(), and retainAll() when filtering a filtered // collection. FilteredSet<E> filtered = (FilteredSet<E>) unfiltered; Predicate<E> combinedPredicate = Predicates.<E>and(filtered.predicate, predicate); return new FilteredSortedSet<E>( (SortedSet<E>) filtered.unfiltered, combinedPredicate); } return new FilteredSortedSet<E>( checkNotNull(unfiltered), checkNotNull(predicate)); } private static class FilteredSortedSet<E> extends FilteredSet<E> implements SortedSet<E> { FilteredSortedSet(SortedSet<E> unfiltered, Predicate<? super E> predicate) { super(unfiltered, predicate); } @Override public Comparator<? super E> comparator() { return ((SortedSet<E>) unfiltered).comparator(); } @Override public SortedSet<E> subSet(E fromElement, E toElement) { return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).subSet(fromElement, toElement), predicate); } @Override public SortedSet<E> headSet(E toElement) { return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).headSet(toElement), predicate); } @Override public SortedSet<E> tailSet(E fromElement) { return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).tailSet(fromElement), predicate); } @Override public E first() { return iterator().next(); } @Override public E last() { SortedSet<E> sortedUnfiltered = (SortedSet<E>) unfiltered; while (true) { E element = sortedUnfiltered.last(); if (predicate.apply(element)) { return element; } sortedUnfiltered = sortedUnfiltered.headSet(element); } } } /** * Returns every possible list that can be formed by choosing one element * from each of the given sets in order; the "n-ary * <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian * product</a>" of the sets. For example: <pre> {@code * * Sets.cartesianProduct(ImmutableList.of( * ImmutableSet.of(1, 2), * ImmutableSet.of("A", "B", "C")))}</pre> * * returns a set containing six lists: * * <ul> * <li>{@code ImmutableList.of(1, "A")} * <li>{@code ImmutableList.of(1, "B")} * <li>{@code ImmutableList.of(1, "C")} * <li>{@code ImmutableList.of(2, "A")} * <li>{@code ImmutableList.of(2, "B")} * <li>{@code ImmutableList.of(2, "C")} * </ul> * * The result is guaranteed to be in the "traditional", lexicographical * order for Cartesian products that you would get from nesting for loops: * <pre> {@code * * for (B b0 : sets.get(0)) { * for (B b1 : sets.get(1)) { * ... * ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...); * // operate on tuple * } * }}</pre> * * Note that if any input set is empty, the Cartesian product will also be * empty. If no sets at all are provided (an empty list), the resulting * Cartesian product has one element, an empty list (counter-intuitive, but * mathematically consistent). * * <p><i>Performance notes:</i> while the cartesian product of sets of size * {@code m, n, p} is a set of size {@code m x n x p}, its actual memory * consumption is much smaller. When the cartesian set is constructed, the * input sets are merely copied. Only as the resulting set is iterated are the * individual lists created, and these are not retained after iteration. * * @param sets the sets to choose elements from, in the order that * the elements chosen from those sets should appear in the resulting * lists * @param <B> any common base class shared by all axes (often just {@link * Object}) * @return the Cartesian product, as an immutable set containing immutable * lists * @throws NullPointerException if {@code sets}, any one of the {@code sets}, * or any element of a provided set is null * @since 2.0 */ public static <B> Set<List<B>> cartesianProduct( List<? extends Set<? extends B>> sets) { return CartesianSet.create(sets); } /** * Returns every possible list that can be formed by choosing one element * from each of the given sets in order; the "n-ary * <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian * product</a>" of the sets. For example: <pre> {@code * * Sets.cartesianProduct( * ImmutableSet.of(1, 2), * ImmutableSet.of("A", "B", "C"))}</pre> * * returns a set containing six lists: * * <ul> * <li>{@code ImmutableList.of(1, "A")} * <li>{@code ImmutableList.of(1, "B")} * <li>{@code ImmutableList.of(1, "C")} * <li>{@code ImmutableList.of(2, "A")} * <li>{@code ImmutableList.of(2, "B")} * <li>{@code ImmutableList.of(2, "C")} * </ul> * * The result is guaranteed to be in the "traditional", lexicographical * order for Cartesian products that you would get from nesting for loops: * <pre> {@code * * for (B b0 : sets.get(0)) { * for (B b1 : sets.get(1)) { * ... * ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...); * // operate on tuple * } * }}</pre> * * Note that if any input set is empty, the Cartesian product will also be * empty. If no sets at all are provided (an empty list), the resulting * Cartesian product has one element, an empty list (counter-intuitive, but * mathematically consistent). * * <p><i>Performance notes:</i> while the cartesian product of sets of size * {@code m, n, p} is a set of size {@code m x n x p}, its actual memory * consumption is much smaller. When the cartesian set is constructed, the * input sets are merely copied. Only as the resulting set is iterated are the * individual lists created, and these are not retained after iteration. * * @param sets the sets to choose elements from, in the order that * the elements chosen from those sets should appear in the resulting * lists * @param <B> any common base class shared by all axes (often just {@link * Object}) * @return the Cartesian product, as an immutable set containing immutable * lists * @throws NullPointerException if {@code sets}, any one of the {@code sets}, * or any element of a provided set is null * @since 2.0 */ public static <B> Set<List<B>> cartesianProduct( Set<? extends B>... sets) { return cartesianProduct(Arrays.asList(sets)); } private static final class CartesianSet<E> extends ForwardingCollection<List<E>> implements Set<List<E>> { private transient final ImmutableList<ImmutableSet<E>> axes; private transient final CartesianList<E> delegate; static <E> Set<List<E>> create(List<? extends Set<? extends E>> sets) { ImmutableList.Builder<ImmutableSet<E>> axesBuilder = new ImmutableList.Builder<ImmutableSet<E>>(sets.size()); for (Set<? extends E> set : sets) { ImmutableSet<E> copy = ImmutableSet.copyOf(set); if (copy.isEmpty()) { return ImmutableSet.of(); } axesBuilder.add(copy); } final ImmutableList<ImmutableSet<E>> axes = axesBuilder.build(); ImmutableList<List<E>> listAxes = new ImmutableList<List<E>>() { @Override public int size() { return axes.size(); } @Override public List<E> get(int index) { return axes.get(index).asList(); } @Override boolean isPartialView() { return true; } }; return new CartesianSet<E>(axes, new CartesianList<E>(listAxes)); } private CartesianSet( ImmutableList<ImmutableSet<E>> axes, CartesianList<E> delegate) { this.axes = axes; this.delegate = delegate; } @Override protected Collection<List<E>> delegate() { return delegate; } @Override public boolean equals(@Nullable Object object) { // Warning: this is broken if size() == 0, so it is critical that we // substitute an empty ImmutableSet to the user in place of this if (object instanceof CartesianSet) { CartesianSet<?> that = (CartesianSet<?>) object; return this.axes.equals(that.axes); } return super.equals(object); } @Override public int hashCode() { // Warning: this is broken if size() == 0, so it is critical that we // substitute an empty ImmutableSet to the user in place of this // It's a weird formula, but tests prove it works. int adjust = size() - 1; for (int i = 0; i < axes.size(); i++) { adjust *= 31; adjust = ~~adjust; // in GWT, we have to deal with integer overflow carefully } int hash = 1; for (Set<E> axis : axes) { hash = 31 * hash + (size() / axis.size() * axis.hashCode()); hash = ~~hash; } hash += adjust; return ~~hash; } } /** * Returns the set of all possible subsets of {@code set}. For example, * {@code powerSet(ImmutableSet.of(1, 2))} returns the set {@code {{}, * {1}, {2}, {1, 2}}}. * * <p>Elements appear in these subsets in the same iteration order as they * appeared in the input set. The order in which these subsets appear in the * outer set is undefined. Note that the power set of the empty set is not the * empty set, but a one-element set containing the empty set. * * <p>The returned set and its constituent sets use {@code equals} to decide * whether two elements are identical, even if the input set uses a different * concept of equivalence. * * <p><i>Performance notes:</i> while the power set of a set with size {@code * n} is of size {@code 2^n}, its memory usage is only {@code O(n)}. When the * power set is constructed, the input set is merely copied. Only as the * power set is iterated are the individual subsets created, and these subsets * themselves occupy only a few bytes of memory regardless of their size. * * @param set the set of elements to construct a power set from * @return the power set, as an immutable set of immutable sets * @throws IllegalArgumentException if {@code set} has more than 30 unique * elements (causing the power set size to exceed the {@code int} range) * @throws NullPointerException if {@code set} is or contains {@code null} * @see <a href="http://en.wikipedia.org/wiki/Power_set">Power set article at * Wikipedia</a> * @since 4.0 */ @GwtCompatible(serializable = false) public static <E> Set<Set<E>> powerSet(Set<E> set) { ImmutableSet<E> input = ImmutableSet.copyOf(set); checkArgument(input.size() <= 30, "Too many elements to create power set: %s > 30", input.size()); return new PowerSet<E>(input); } private static final class PowerSet<E> extends AbstractSet<Set<E>> { final ImmutableSet<E> inputSet; final ImmutableList<E> inputList; final int powerSetSize; PowerSet(ImmutableSet<E> input) { this.inputSet = input; this.inputList = input.asList(); this.powerSetSize = 1 << input.size(); } @Override public int size() { return powerSetSize; } @Override public boolean isEmpty() { return false; } @Override public Iterator<Set<E>> iterator() { return new AbstractIndexedListIterator<Set<E>>(powerSetSize) { @Override protected Set<E> get(final int setBits) { return new AbstractSet<E>() { @Override public int size() { return Integer.bitCount(setBits); } @Override public Iterator<E> iterator() { return new BitFilteredSetIterator<E>(inputList, setBits); } }; } }; } private static final class BitFilteredSetIterator<E> extends UnmodifiableIterator<E> { final ImmutableList<E> input; int remainingSetBits; BitFilteredSetIterator(ImmutableList<E> input, int allSetBits) { this.input = input; this.remainingSetBits = allSetBits; } @Override public boolean hasNext() { return remainingSetBits != 0; } @Override public E next() { int index = Integer.numberOfTrailingZeros(remainingSetBits); if (index == 32) { throw new NoSuchElementException(); } int currentElementMask = 1 << index; remainingSetBits &= ~currentElementMask; return input.get(index); } } @Override public boolean contains(@Nullable Object obj) { if (obj instanceof Set) { Set<?> set = (Set<?>) obj; return inputSet.containsAll(set); } return false; } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof PowerSet) { PowerSet<?> that = (PowerSet<?>) obj; return inputSet.equals(that.inputSet); } return super.equals(obj); } @Override public int hashCode() { /* * The sum of the sums of the hash codes in each subset is just the sum of * each input element's hash code times the number of sets that element * appears in. Each element appears in exactly half of the 2^n sets, so: */ return inputSet.hashCode() << (inputSet.size() - 1); } @Override public String toString() { return "powerSet(" + inputSet + ")"; } } /** * An implementation for {@link Set#hashCode()}. */ static int hashCodeImpl(Set<?> s) { int hashCode = 0; for (Object o : s) { hashCode += o != null ? o.hashCode() : 0; hashCode = ~~hashCode; // Needed to deal with unusual integer overflow in GWT. } return hashCode; } /** * An implementation for {@link Set#equals(Object)}. */ static boolean equalsImpl(Set<?> s, @Nullable Object object){ if (s == object) { return true; } if (object instanceof Set) { Set<?> o = (Set<?>) object; try { return s.size() == o.size() && s.containsAll(o); } catch (NullPointerException ignored) { return false; } catch (ClassCastException ignored) { return false; } } return false; } /** * Remove each element in an iterable from a set. */ static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) { boolean changed = false; while (iterator.hasNext()) { changed |= set.remove(iterator.next()); } return changed; } static boolean removeAllImpl(Set<?> set, Collection<?> collection) { checkNotNull(collection); // for GWT if (collection instanceof Multiset) { collection = ((Multiset<?>) collection).elementSet(); } /* * AbstractSet.removeAll(List) has quadratic behavior if the list size * is just less than the set's size. We augment the test by * assuming that sets have fast contains() performance, and other * collections don't. See * http://code.google.com/p/guava-libraries/issues/detail?id=1013 */ if (collection instanceof Set && collection.size() > set.size()) { return Iterators.removeAll(set.iterator(), collection); } else { return removeAllImpl(set, collection.iterator()); } } }
[ "tyskin@gmail.com" ]
tyskin@gmail.com
e48215bc8fe1b76e3436b5bf5c057acd9b06f1e9
005e5b7d4498f8972560dea3d3a25d87fde8da50
/EthanCohenFinal/src/game/GameEvent.java
121b689f6396979516953f17ece40a4a8c63610a
[]
no_license
EDCohen8/DePaulSE350Final
e6ebab9703b1ea0ab79f15384251752422cc4b8f
50360eba0160d4ee686c46c9cc8b355b92ea58fe
refs/heads/master
2021-08-18T21:50:28.094384
2017-11-24T01:34:44
2017-11-24T01:34:44
110,628,112
0
0
null
null
null
null
UTF-8
Java
false
false
276
java
package game; import javafx.collections.ObservableList; import javafx.scene.Node; //interface that toggles gameover or youwin pictures public interface GameEvent { public void gameOver(ObservableList<Node> sceneGraph); public void youWin(ObservableList<Node> sceneGraph); }
[ "ethan.cohen1997@gmail.com" ]
ethan.cohen1997@gmail.com
2237b1a068bcf5a0127c1c76ac57a4edebf8b61a
f147f93edfca82151f6b4c0e36fba7525eb5a97f
/app/src/main/java/it/veronica/coursemanagement/adapters/ReservationListAdapter.java
7272bc62c73dbe9a6faca511282862ca26eca355
[]
no_license
veronicaDesantis/IUM_Android-
d5b67e00d55f7340c62a3cdcf6f2d604d6e81c3a
4b6325b84e582166f1664150e188b0d0e484b9f5
refs/heads/master
2023-06-06T00:48:25.469135
2021-07-01T06:49:30
2021-07-01T06:49:30
372,894,655
0
0
null
null
null
null
UTF-8
Java
false
false
3,135
java
package it.veronica.coursemanagement.adapters; import android.app.AlertDialog; import android.content.Context; import android.icu.text.SimpleDateFormat; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.RequiresApi; import com.example.coursemanagement.R; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import it.veronica.coursemanagement.model.Disponibility; import it.veronica.coursemanagement.model.Reservation; public class ReservationListAdapter extends ArrayAdapter<Reservation> { private AlertDialog.Builder dialogBuilder; private AlertDialog dialog; private Context myContext; public ReservationListAdapter(Context context, ArrayList<Reservation> reservations) { super(context, 0, reservations); myContext = context; } @RequiresApi(api = Build.VERSION_CODES.M) @Override public View getView(int position, View convertView, ViewGroup parent) { // Get the data item for this position Reservation reservation = getItem(position); // Check if an existing view is being reused, otherwise inflate the view if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_reservation, parent, false); } // Lookup view for data population TextView date = convertView.findViewById(R.id.date); TextView slot = convertView.findViewById(R.id.slot); date.setText(reservation.getDisponibility().getDatetime()); slot.setText(reservation.getDisponibility().getSlotTime()); TextView course = convertView.findViewById(R.id.course); course.setText(reservation.getDisponibility().getCourse().getTitle()); TextView status = convertView.findViewById(R.id.status); Date currentTime = Calendar.getInstance().getTime(); SimpleDateFormat dateFormat2 = null; Date reservationTime = null; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { dateFormat2 = new SimpleDateFormat("dd/MM/yyyy hh:mm"); try { reservationTime = dateFormat2.parse(reservation.getDisponibility().getDatetime() + " " + reservation.getDisponibility().getStartTime()); } catch (ParseException e) { } } if (reservationTime.getTime() <= currentTime.getTime() && currentTime.getDate() == currentTime.getDate()) { status.setText("Effettuata"); reservation.setEditable(false); } else if (reservation.getDeleted() == 1) { status.setText("Disdetta"); reservation.setEditable(false); } else { status.setText("Attiva"); reservation.setEditable(true); } // Return the completed view to render on screen return convertView; } }
[ "veronica.desantis@hrcsrl.it" ]
veronica.desantis@hrcsrl.it
b2d74b2b1275a80da38a14c17d26e9d98f7fadad
0f1a86ae8e5553f645f2df195dd60e94a4b7ebe5
/src/main/java/org/maxwe/epub/parser/constant/XmlLabelName.java
80a64ace93a43e7b2ec6bb241dc61f5b477e2b2e
[ "MIT" ]
permissive
maxwe/maxwe-epub-parser
f9d72201acfd8b5e64a0036d1f8aa446cffc705f
9db8cb3598358f6e71c1a357b7e8b37f90a44e3b
refs/heads/master
2021-05-16T02:29:54.267545
2017-03-22T09:57:26
2017-03-22T09:57:26
41,722,746
2
0
null
2015-12-17T03:26:29
2015-09-01T07:07:03
HTML
UTF-8
Java
false
false
1,287
java
package org.maxwe.epub.parser.constant; /** * Created by Pengwei Ding on 2015-08-28 23:07. * Email: www.dingpengwei@foxmail.com www.dingpegnwei@gmail.com * Description: 枚举EPub标准中XML文件中的标签名称 */ public enum XmlLabelName { ROOTFILE("rootfile"), PACKAGE("package"), UNIQUE_IDENTIFIER("unique-identifier"), VERSION("version"), METADATA("metadata"), MANIFEST("manifest"), SPINE("spine"), GUIDE("guide"), DC_IDENTIFIER("dc:identifier"), DC_TITLE("dc:title"), DC_LANGUAGE("dc:language"), DC_CREATOR("dc:creator"), DC_PUBLISHER("dc:publisher"), DC_DATE("dc:date"), ITEM("item"), HREF("href"), MEDIA_TYPE("media-type"), ID("id"), REFERENCE("reference"), IDREF("idref"), TITLE("title"), TOC("toc"), TYPE("type"), ITEMREF("itemref"), META("meta"), NAVPOINT("navPoint"), PLAYORDER("playOrder"), NAVLABEL("navLabel"), TEXT("text"), NAVMAP("navMap"), CONTENT("content"), NCX("ncx"), SRC("src"), PROPERTIES("properties"), temp("temp"); private String value; XmlLabelName(String value){ this.value = value; } @Override public String toString() { return this.value; } }
[ "www.dingpengwei@gmail.com" ]
www.dingpengwei@gmail.com
5a0fb50958f17f6eb9b1ba275d5572fb6586e549
de56b7409521bec01709042fb6ba8d7b49c066bc
/JUNGOL/src/LanguageCoder/String237.java
d1c34e447bed6f47933a53a769abbced87803bca
[]
no_license
hodurie/Algorithm
40595c836febef815eff80585765a21a8cc299f1
f0a72afd65d078661f3e8921de61d8c61ac06d89
refs/heads/master
2023-07-26T04:29:59.181987
2021-09-06T11:44:39
2021-09-06T11:44:39
264,898,915
0
0
null
null
null
null
UTF-8
Java
false
false
605
java
package LanguageCoder; import java.util.Scanner; public class String237 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String a = sc.next(); double b = sc.nextDouble(); b = Math.round(b * 1000) / 1000.0; String c = sc.next(); String txtAll = a + b + c; int N = txtAll.length(); for (int i = 0; i < N; i++) { if (N % 2 == 0) { if (i == N / 2) { System.out.println(); } System.out.print(txtAll.charAt(i)); } else { if (i == (N+1)/2) { System.out.println(); } System.out.print(txtAll.charAt(i)); } } } }
[ "hodurie@gmail.com" ]
hodurie@gmail.com
163ca6b1e7156e9e0fe08ade251d6176388d67f0
0478f4562764822697b20ee57cb582a216c00d8a
/src/main/java/net/robert/kitpvp/lobby/event/PlayerJoinListener.java
dfe06da04f03d053dc98531dc4d11aa2a144ef55
[]
no_license
Roby09/KitPvPDDG
ac9a8c1bc784949418bd84855fc3beb5d8d7d233
80e473dc11cc2fb76793973f4a6564a6a640c87c
refs/heads/master
2022-11-12T09:49:39.923304
2020-07-01T14:19:44
2020-07-01T14:19:44
276,396,562
0
1
null
null
null
null
UTF-8
Java
false
false
2,571
java
package net.robert.kitpvp.lobby.event; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import net.robert.kitpvp.KitPVP; import net.robert.kitpvp.game.PlayerState; import net.robert.kitpvp.profile.Profile; import net.robert.kitpvp.profile.ProfileLoader; import net.robert.kitpvp.scoreboard.GameScoreboard; public class PlayerJoinListener implements Listener { private KitPVP kitpvp; public PlayerJoinListener(KitPVP kitpvp) { this.kitpvp = kitpvp; } @SuppressWarnings("deprecation") @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { int maxPlayers = kitpvp.getConf().getInt("Lobby.maxPlayers") -1; if(maxPlayers == Bukkit.getServer().getOnlinePlayers().size()) { event.getPlayer().kickPlayer(ChatColor.RED + "De game is helaas al vol."); event.setJoinMessage(""); return; } event.setJoinMessage(ChatColor.GREEN + "+ " + event.getPlayer().getName() + ChatColor.GRAY + " (" + Bukkit.getServer().getOnlinePlayers().size() + "/" + maxPlayers + ")"); event.getPlayer().teleport(kitpvp.getLobby().getSpawn()); event.getPlayer().setFoodLevel(20); event.getPlayer().setHealth(event.getPlayer().getMaxHealth()); event.getPlayer().setGameMode(GameMode.SURVIVAL); event.getPlayer().getInventory().clear(); kitpvp.setPlayerState(event.getPlayer(), PlayerState.LOBBY); final Profile profile = new Profile(kitpvp, event.getPlayer()); kitpvp.getProfiles().put(event.getPlayer().getUniqueId(), profile); new ProfileLoader(profile).runTaskAsynchronously(kitpvp); setupScoreboard(event.getPlayer(), profile); } public void setupScoreboard(Player player, Profile profile) { GameScoreboard board = new GameScoreboard("KitPvP"); board.addLine(ChatColor.GREEN + "" + ChatColor.BOLD + "Kills"); board.addLine(ChatColor.GRAY + String.valueOf(profile.getKills())); board.addBlankLine(); board.addLine(ChatColor.RED + "" + ChatColor.BOLD + "Deaths"); board.addLine(ChatColor.GRAY + String.valueOf(profile.getDeaths())); board.addBlankLine(); board.addLine(ChatColor.AQUA + "" + ChatColor.BOLD + "K/D"); double roundOff = Math.round(profile.getKD() * 100.0) / 100.0; board.addLine(ChatColor.GRAY + String.valueOf(roundOff)); board.addBlankLine(); kitpvp.getScoreboardManager().setScoreboard(player, board); } }
[ "Robert@192.168.178.21" ]
Robert@192.168.178.21
11b3f18cf164125bd1d026b61de163038ee016c3
ddb04518f7641803e392b120561114aff71892b8
/android/app/src/main/java/com/webjumptest/MainActivity.java
fd68e322ee3959c59915ea4442c3b376866f9d38
[]
no_license
haaley/webjump
5df1173c28854437c72a5e6e46ef1a31ed180794
d9e5224be41c5099ad3032a211670a0b78993f2f
refs/heads/master
2023-03-16T22:11:41.378852
2021-03-15T01:45:59
2021-03-15T01:45:59
347,417,555
0
0
null
2021-03-15T01:36:27
2021-03-13T16:14:59
Java
UTF-8
Java
false
false
349
java
package com.webjumptest; import com.facebook.react.ReactActivity; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ @Override protected String getMainComponentName() { return "webjumptest"; } }
[ "haaley_watch@hotmail.com" ]
haaley_watch@hotmail.com
6788303f5b847018bf47deb7320090c6b76010a9
73de24e2de92b2cf26006d08ebc14e6f2f9fba95
/src/main/java/com/study/base/lock/synchronizdpackage/synchr/sync004/DirtyRead.java
42670c6cd10fc18eb6af2a5d42af7b5653ecc174
[]
no_license
kaiminRyan/javaBase
168739ca443bec5c213bcb4d92d0709ebf983402
ded454c6ad969f47422857cb116c3b0906b2ef48
refs/heads/master
2021-01-19T15:18:37.776998
2017-08-22T14:02:31
2017-08-22T14:02:31
100,959,101
0
0
null
null
null
null
UTF-8
Java
false
false
1,073
java
package com.study.base.lock.synchronizdpackage.synchr.sync004; /** * 业务整体需要使用完整的synchronized,保持业务的原子性。 * @author kaimin * */ public class DirtyRead { private String username = "kaimin"; private String password = "123"; public synchronized void setValue(String username, String password){ this.username = username; try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } this.password = password; System.out.println("setValue最终结果:username = " + username + " , password = " + password); } public void getValue(){ System.out.println("getValue方法得到:username = " + this.username + " , password = " + this.password); } public static void main(String[] args) throws Exception{ final DirtyRead dr = new DirtyRead(); Thread t1 = new Thread(new Runnable() { public void run() { dr.setValue("z3", "456"); } }); t1.start(); Thread.sleep(1000); dr.getValue(); } }
[ "ruankaimin3238@tops001.com" ]
ruankaimin3238@tops001.com
f7d48561bccea0888453de3cb787b732c8dc36b3
5cc30c2d8cfc57649bb81c7d480ec884b210add3
/src/test/java/FindMeeting.java
d2099ff364b8a4cab3918be6559da9deb07776a8
[]
no_license
renajing/techchallenge
48376b3f7b08c79adebb53d2ba86abcaf5bbdea7
cedbe4fbd6f7d7924ed4fbd1e50c9d89ea5b1488
refs/heads/master
2022-08-08T12:30:05.808078
2018-06-27T07:08:36
2018-06-27T07:08:36
138,837,603
0
0
null
null
null
null
UTF-8
Java
false
false
796
java
import org.openqa.selenium.By; import org.openqa.selenium.WebElement; /** * Created by renajing on 6/26/18. */ public class FindMeeting extends Page { private By title = By.xpath("//title[contains(text(),'Find A Meeting: Get Schedules & Times Near You | Weight Watchers')]"); private By meetingSearch = By.id("meetingSearch"); private By submitSearch = By.className("form-blue-pill__btn"); public FindMeeting assertTitle(){ driver.findElement(title); return this; } public MeetingPage search(String input){ WebElement searchBar = driver.findElement(meetingSearch); searchBar.sendKeys(input); WebElement submitButton = driver.findElement(submitSearch); submitButton.click(); return new MeetingPage(); } }
[ "rqjing@ucdavis.edu" ]
rqjing@ucdavis.edu
6f50b2a90ecc1b947ee416264ca79ea1e05db16b
7f3c2c847565674e1e29432678206e86e945431a
/GestorTareasApp/src/com/example/gestortareasapp/Prueba.java
cbbddc8d73b6ffa6e99eb9f55f7462068c37cd23
[]
no_license
JosueDx/GestorTareasMovil
78982ef4b3324132298f393f3d170fe674c92bd2
ccb4fd127eb66633c828b3cb99b2029d1af324a9
refs/heads/master
2021-01-10T16:37:18.259913
2016-02-23T00:15:08
2016-02-23T00:15:08
46,815,900
1
0
null
null
null
null
UTF-8
Java
false
false
968
java
package com.example.gestortareasapp; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class Prueba extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_prueba); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.prueba, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
[ "josuepambeer@gmail.com" ]
josuepambeer@gmail.com
15be958912f5f34261ea03ccc0719c2843c80a05
ef23d9b833a84ad79a9df816bd3fd1321b09851e
/L2J_SunriseProject_Data/dist/game/data/scripts/events/GiftOfVitality/GiftOfVitality.java
2451802f461ed60af20a20b5f11ed308521d4a38
[]
no_license
nascimentolh/JBlueHeart-Source
c05c07137a7a4baf5fe8a793375f1700618ef12c
4179e6a6dbd0f74d614d7cc1ab7eb90ff41af218
refs/heads/master
2022-05-28T22:05:06.858469
2020-04-26T15:22:17
2020-04-26T15:22:17
259,045,356
1
0
null
null
null
null
UTF-8
Java
false
false
4,926
java
/* * Copyright (C) 2004-2015 L2J DataPack * * This file is part of L2J DataPack. * * L2J DataPack is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * L2J DataPack is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package events.GiftOfVitality; import l2r.gameserver.model.actor.L2Npc; import l2r.gameserver.model.actor.instance.L2PcInstance; import l2r.gameserver.model.event.LongTimeEvent; import l2r.gameserver.model.holders.SkillHolder; import l2r.gameserver.network.SystemMessageId; import l2r.gameserver.network.serverpackets.SystemMessage; /** * Gift of Vitality event AI. * @author Gnacik, Adry_85 */ public final class GiftOfVitality extends LongTimeEvent { // NPC private static final int STEVE_SHYAGEL = 4306; // Skills private static final SkillHolder GIFT_OF_VITALITY = new SkillHolder(23179, 1); private static final SkillHolder JOY_OF_VITALITY = new SkillHolder(23180, 1); private static SkillHolder[] FIGHTER_SKILLS = { new SkillHolder(5627, 1), // Wind Walk new SkillHolder(5628, 1), // Shield new SkillHolder(5637, 1), // Magic Barrier new SkillHolder(5629, 1), // Bless the Body new SkillHolder(5630, 1), // Vampiric Rage new SkillHolder(5631, 1), // Regeneration new SkillHolder(5632, 1), // Haste }; private static SkillHolder[] MAGE_SKILLS = { new SkillHolder(5627, 1), // Wind Walk new SkillHolder(5628, 1), // Shield new SkillHolder(5637, 1), // Magic Barrier new SkillHolder(5633, 1), // Bless the Soul new SkillHolder(5634, 1), // Acumen new SkillHolder(5635, 1), // Concentration new SkillHolder(5636, 1), // Empower }; private static SkillHolder[] SERVITOR_SKILLS = { new SkillHolder(5627, 1), // Wind Walk new SkillHolder(5628, 1), // Shield new SkillHolder(5637, 1), // Magic Barrier new SkillHolder(5629, 1), // Bless the Body new SkillHolder(5633, 1), // Bless the Soul new SkillHolder(5630, 1), // Vampiric Rage new SkillHolder(5634, 1), // Acumen new SkillHolder(5631, 1), // Regeneration new SkillHolder(5635, 1), // Concentration new SkillHolder(5632, 1), // Haste new SkillHolder(5636, 1), // Empower }; // Misc private static final int HOURS = 5; // Reuse between buffs private static final int MIN_LEVEL = 75; private static final String REUSE = GiftOfVitality.class.getSimpleName() + "_reuse"; public GiftOfVitality() { super(GiftOfVitality.class.getSimpleName(), "events"); addStartNpc(STEVE_SHYAGEL); addFirstTalkId(STEVE_SHYAGEL); addTalkId(STEVE_SHYAGEL); } @Override public String onAdvEvent(String event, L2Npc npc, L2PcInstance player) { String htmltext = event; switch (event) { case "vitality": { final long reuse = player.getVariables().getLong(REUSE, 0); if (reuse > System.currentTimeMillis()) { long remainingTime = (reuse - System.currentTimeMillis()) / 1000; int hours = (int) (remainingTime / 3600); int minutes = (int) ((remainingTime % 3600) / 60); SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.AVAILABLE_AFTER_S1_S2_HOURS_S3_MINUTES); sm.addSkillName(23179); sm.addInt(hours); sm.addInt(minutes); player.sendPacket(sm); htmltext = "4306-notime.htm"; } else { player.doCast(GIFT_OF_VITALITY.getSkill()); player.doSimultaneousCast(JOY_OF_VITALITY.getSkill()); player.getVariables().set(REUSE, System.currentTimeMillis() + (HOURS * 3600000)); htmltext = "4306-okvitality.htm"; } break; } case "memories_player": { if (player.getLevel() <= MIN_LEVEL) { htmltext = "4306-nolevel.htm"; } else { final SkillHolder[] skills = (player.isMageClass()) ? MAGE_SKILLS : FIGHTER_SKILLS; npc.setTarget(player); for (SkillHolder sk : skills) { npc.doCast(sk.getSkill()); } htmltext = "4306-okbuff.htm"; } break; } case "memories_summon": { if (player.getLevel() <= MIN_LEVEL) { htmltext = "4306-nolevel.htm"; } else if (!player.hasServitor()) { htmltext = "4306-nosummon.htm"; } else { npc.setTarget(player.getSummon()); for (SkillHolder sk : SERVITOR_SKILLS) { npc.doCast(sk.getSkill()); } htmltext = "4306-okbuff.htm"; } break; } } return htmltext; } @Override public String onFirstTalk(L2Npc npc, L2PcInstance player) { return "4306.htm"; } }
[ "luizh.nnh@gmail.com" ]
luizh.nnh@gmail.com
844a1a5caa52742624ad3e0d34e7ebddc5726095
24e1b9c46396b7f518f88533df5e5f79c727e530
/account-service/src/main/java/com/online/taxi/dao/DriverInfoDao.java
49932d4bc87144d4a6d41f5a3d0e06e4341c03d7
[]
no_license
over-space/online-taxi
af125b3c4eb5552e7b1004d13d6ecee24df313a6
4c8ee20b42b26f0999b5bb39676778f2e1217a58
refs/heads/master
2023-01-23T00:03:57.927811
2020-11-23T02:11:20
2020-11-23T02:11:20
315,176,452
2
0
null
null
null
null
UTF-8
Java
false
false
1,796
java
package com.online.taxi.dao; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Repository; import com.online.taxi.entity.DriverInfo; import com.online.taxi.mapper.DriverInfoMapper; import java.util.List; /** * 司机端 * @date 2018/08/08 **/ @Repository @RequiredArgsConstructor public class DriverInfoDao { @NonNull private DriverInfoMapper driverInfoMapper; public int deleteByPrimaryKey(Integer id) { return driverInfoMapper.deleteByPrimaryKey(id); } public int insert(DriverInfo record) { return driverInfoMapper.insert(record); } public int insertSelective(DriverInfo record) { return driverInfoMapper.insertSelective(record); } public DriverInfo selectByPrimaryKey(Integer id) { return driverInfoMapper.selectByPrimaryKey(id); } public List<DriverInfo> selectByPrimaryKeyList() { return driverInfoMapper.selectByPrimaryKeyList(); } public int updateByPrimaryKeySelective(DriverInfo record) { return driverInfoMapper.updateByPrimaryKeySelective(record); } public int updateByPrimaryKey(DriverInfo record) { return driverInfoMapper.updateByPrimaryKey(record); } public int updateCarIdById(DriverInfo record) { return driverInfoMapper.updateCarIdById(record); } public DriverInfo queryDriverInfoByPhoneNum(String phoneNum) { return driverInfoMapper.queryDriverInfoByPhoneNum(phoneNum); } public int updateDriverInfoByPhoneNum(DriverInfo driverInfo) { return driverInfoMapper.updateDriverInfoByPhoneNum(driverInfo); } public DriverInfo queryDriverInfoByCarId(Integer carId){ return driverInfoMapper.queryDriverInfoByCarId(carId); } }
[ "lifang@jingkunsystem.com" ]
lifang@jingkunsystem.com
658f902f02aea875c140465e431e90cc8e6d0b44
a4d4d49dabcced4dc52cb403a2b217fca37a15a9
/konakart/hst-client/src/main/java/org/onehippo/forge/konakart/site/service/KKOrderService.java
ece529f4ca2b57428b346a8833349c59cf0a0845
[ "Apache-2.0" ]
permissive
jmirc/Hippo-CMS-Konakart
04488fc6b14f5e64fa68ac0eff808c165e86817e
77b286afc4b87b53450d50f4035e50c9a8733a4d
refs/heads/master
2022-06-27T20:33:36.028524
2017-06-13T11:08:39
2017-06-13T11:08:39
4,908,338
5
9
null
2022-06-20T23:19:10
2012-07-05T14:39:31
Java
UTF-8
Java
false
false
877
java
package org.onehippo.forge.konakart.site.service; import com.konakart.appif.BasketIf; import com.konakart.appif.OrderIf; import org.hippoecm.hst.core.component.HstRequest; import javax.annotation.Nonnull; import javax.annotation.Nullable; public interface KKOrderService { /** * Populate checkout order with a temporary order created before the checkout process really * begins. If the customer hasn't registered or logged in yet, we use the default customer to * create the order. * <p/> * With this temporary order we can give the customer useful information on shipping costs and * discounts without him having to login. * * @param request the hst request * @param custId the customer Id * @param items the basket's items */ @Nullable OrderIf createTempOrder(@Nonnull HstRequest request, int custId, final BasketIf[] items); }
[ "jerome.mirc@gmail.com" ]
jerome.mirc@gmail.com
3ce4a3137c855124657611d62628957a9fffb7af
fdb2cbbd581af365ba381f59cee490c1b4b3b37c
/java/src/java8/com/java8/adv/jls14/point/Point.java
69774a6e07440a502dfed9f4b808cf0bc40cc9cf
[]
no_license
vuquangtin/frameworks
afbb6a024d7b5a77af1e1d4c204f929a9882bd37
b43f2f188fa5ee6fc692e0eeba839acb1c6a2c4d
refs/heads/master
2022-12-16T11:11:56.787032
2020-08-28T03:39:54
2020-08-28T03:39:54
233,235,428
0
1
null
2022-12-16T10:32:07
2020-01-11T13:23:36
Java
UTF-8
Java
false
false
422
java
package com.java8.adv.jls14.point; /** * * * @author EMAIL:vuquangtin@gmail.com , tel:0377443333 * @version 1.0.0 * @see <a href="https://github.com/vuquangtin/frameworks">https://github.com/ * vuquangtin/frameworks</a> * */ public class Point { protected int x, y; public void move(int dx, int dy) { x += dx; y += dy; } public int getX() { return x; } public int getY() { return y; } }
[ "tinvuquang@admicro.vn" ]
tinvuquang@admicro.vn
8db051db36deff3fb658fcfd3459cfbedf3a7185
69a4f2d51ebeea36c4d8192e25cfb5f3f77bef5e
/methods/Method_34493.java
c48df17917fd8b3356c952877460cba07818e134
[]
no_license
P79N6A/icse_20_user_study
5b9c42c6384502fdc9588430899f257761f1f506
8a3676bc96059ea2c4f6d209016f5088a5628f3c
refs/heads/master
2020-06-24T08:25:22.606717
2019-07-25T15:31:16
2019-07-25T15:31:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
77
java
public boolean hasDefaultProperties(){ return defaultProperties != null; }
[ "sonnguyen@utdallas.edu" ]
sonnguyen@utdallas.edu
6e79ba35c4829b6b42ca749b799c19e67c12f2db
bf2966abae57885c29e70852243a22abc8ba8eb0
/aws-java-sdk-signer/src/main/java/com/amazonaws/services/signer/model/RevokeSignatureRequest.java
5ed5cc98e661f797ea6b4a4359a0cb8d40cc2dc5
[ "Apache-2.0" ]
permissive
kmbotts/aws-sdk-java
ae20b3244131d52b9687eb026b9c620da8b49935
388f6427e00fb1c2f211abda5bad3a75d29eef62
refs/heads/master
2021-12-23T14:39:26.369661
2021-07-26T20:09:07
2021-07-26T20:09:07
246,296,939
0
0
Apache-2.0
2020-03-10T12:37:34
2020-03-10T12:37:33
null
UTF-8
Java
false
false
6,191
java
/* * Copyright 2016-2021 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.signer.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/signer-2017-08-25/RevokeSignature" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class RevokeSignatureRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * ID of the signing job to be revoked. * </p> */ private String jobId; /** * <p> * AWS account ID of the job owner. * </p> */ private String jobOwner; /** * <p> * The reason for revoking the signing job. * </p> */ private String reason; /** * <p> * ID of the signing job to be revoked. * </p> * * @param jobId * ID of the signing job to be revoked. */ public void setJobId(String jobId) { this.jobId = jobId; } /** * <p> * ID of the signing job to be revoked. * </p> * * @return ID of the signing job to be revoked. */ public String getJobId() { return this.jobId; } /** * <p> * ID of the signing job to be revoked. * </p> * * @param jobId * ID of the signing job to be revoked. * @return Returns a reference to this object so that method calls can be chained together. */ public RevokeSignatureRequest withJobId(String jobId) { setJobId(jobId); return this; } /** * <p> * AWS account ID of the job owner. * </p> * * @param jobOwner * AWS account ID of the job owner. */ public void setJobOwner(String jobOwner) { this.jobOwner = jobOwner; } /** * <p> * AWS account ID of the job owner. * </p> * * @return AWS account ID of the job owner. */ public String getJobOwner() { return this.jobOwner; } /** * <p> * AWS account ID of the job owner. * </p> * * @param jobOwner * AWS account ID of the job owner. * @return Returns a reference to this object so that method calls can be chained together. */ public RevokeSignatureRequest withJobOwner(String jobOwner) { setJobOwner(jobOwner); return this; } /** * <p> * The reason for revoking the signing job. * </p> * * @param reason * The reason for revoking the signing job. */ public void setReason(String reason) { this.reason = reason; } /** * <p> * The reason for revoking the signing job. * </p> * * @return The reason for revoking the signing job. */ public String getReason() { return this.reason; } /** * <p> * The reason for revoking the signing job. * </p> * * @param reason * The reason for revoking the signing job. * @return Returns a reference to this object so that method calls can be chained together. */ public RevokeSignatureRequest withReason(String reason) { setReason(reason); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getJobId() != null) sb.append("JobId: ").append(getJobId()).append(","); if (getJobOwner() != null) sb.append("JobOwner: ").append(getJobOwner()).append(","); if (getReason() != null) sb.append("Reason: ").append(getReason()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof RevokeSignatureRequest == false) return false; RevokeSignatureRequest other = (RevokeSignatureRequest) obj; if (other.getJobId() == null ^ this.getJobId() == null) return false; if (other.getJobId() != null && other.getJobId().equals(this.getJobId()) == false) return false; if (other.getJobOwner() == null ^ this.getJobOwner() == null) return false; if (other.getJobOwner() != null && other.getJobOwner().equals(this.getJobOwner()) == false) return false; if (other.getReason() == null ^ this.getReason() == null) return false; if (other.getReason() != null && other.getReason().equals(this.getReason()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getJobId() == null) ? 0 : getJobId().hashCode()); hashCode = prime * hashCode + ((getJobOwner() == null) ? 0 : getJobOwner().hashCode()); hashCode = prime * hashCode + ((getReason() == null) ? 0 : getReason().hashCode()); return hashCode; } @Override public RevokeSignatureRequest clone() { return (RevokeSignatureRequest) super.clone(); } }
[ "" ]
1e4239eeac2714852bbda35640e8c3a337cafb99
ccbfa62c4ed327d9cb13dbfdceb5f5d70464d914
/src/main/java/com/case4/model/BillDetail.java
a59ed81b1c8686c22b6c20ec50d0e700b2e3d30b
[]
no_license
duyhai97/CaseModule4
a1a6513747e14e095e56a1c8cb5e539c36e71a21
8a2236ac319549477dcbce1b444e40ce13de5229
refs/heads/master
2023-06-07T13:26:15.515303
2021-07-12T01:36:09
2021-07-12T01:36:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
455
java
package com.case4.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @Data @AllArgsConstructor @NoArgsConstructor @Table @Entity public class BillDetail { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne private Product product; @ManyToOne private Bill bill; private int quantity; private double total; }
[ "79962575+duyhai97@users.noreply.github.com" ]
79962575+duyhai97@users.noreply.github.com
01286870ed21efd8cb13ca4d83823c31f4b53cbc
5322b085d07ee7f31170e3197a720c0e83a008f2
/src/test/java/com/tony/domain/NewsTest.java
8590cbb33ceab3adf0d3d7b552d0fb1a5e1c34f5
[]
no_license
vuha0710/fireapp-cafe
7781da7d54505258270d7f957773a1b1077a4066
394aee80c23a33ff7003741a1ee4044de7e0cf6e
refs/heads/master
2023-04-04T22:48:56.566975
2021-04-03T15:45:02
2021-04-03T15:45:02
352,894,337
0
0
null
null
null
null
UTF-8
Java
false
false
612
java
package com.tony.domain; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import com.tony.web.rest.TestUtil; public class NewsTest { @Test public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(News.class); News news1 = new News(); news1.setId(1L); News news2 = new News(); news2.setId(news1.getId()); assertThat(news1).isEqualTo(news2); news2.setId(2L); assertThat(news1).isNotEqualTo(news2); news1.setId(null); assertThat(news1).isNotEqualTo(news2); } }
[ "vu.ha@tokoin.io" ]
vu.ha@tokoin.io
10271c6ba7a704bb11e2d9b79f806abb8d4338c1
aefdabdcb0debcc54ea5d9b3cdd22f4c3c94057b
/src/main/java/com/multithreading/ThreeThreadPrintingProblem.java
5bce9b3099f89c3603e05df0a47daf68e750fd4e
[]
no_license
subrata304/Multithreading
62c9338ae00f83336431dc99e15a1eaa4ee482fc
db01396eff21fb2f6845b18c0eecfdde42245695
refs/heads/master
2021-07-08T07:53:41.767441
2019-06-11T21:19:50
2019-06-11T21:19:50
191,452,245
0
0
null
null
null
null
UTF-8
Java
false
false
1,207
java
package com.multithreading; import java.util.concurrent.atomic.AtomicInteger; public class ThreeThreadPrintingProblem { Object monitor = new Object(); AtomicInteger number = new AtomicInteger(1); public static void main(String[] args) { ThreeThreadPrintingProblem tnp = new ThreeThreadPrintingProblem(); Thread t1 = new Thread(tnp.new Printer(0, 3)); Thread t2 = new Thread(tnp.new Printer(1, 3)); Thread t3 = new Thread(tnp.new Printer(2, 3)); t1.start(); t2.start(); t3.start(); } class Printer implements Runnable { int threadId; int numOfThreads; public Printer(int id, int nubOfThreads) { threadId = id; this.numOfThreads = nubOfThreads; } public void run() { print(); } private void print() { try { while (true) { Thread.sleep(1000l); synchronized (monitor) { if (number.get() % numOfThreads != threadId) { monitor.wait(); } else { System.out.println("ThreadId [" + threadId + "] printing -->" + number.getAndIncrement()); monitor.notifyAll(); } } } } catch (InterruptedException e) { e.printStackTrace(); } } } }
[ "subrata.kundu30@gmail.com" ]
subrata.kundu30@gmail.com
59a7feeb5374ccde4e02ede23bfdc1a336420d11
3b9b510ab7f851e6d65b3973dfefd9c264b5fc4b
/src/main/java/com/springjwt/apijwt/service/KeyServiceImpl.java
a9137ffc4852bac6448f15d63cddb1fba0a6bc0b
[]
no_license
suranjanabasu/api_mysql_dynamodb
a7d39b0851797836e75e0f5b550448ddc289c8bd
0f1f57c036e4d03da20ba84f0f2a5bd840230a47
refs/heads/master
2021-07-15T07:02:46.693145
2020-09-24T20:45:37
2020-09-24T20:45:37
197,410,732
0
0
null
2020-09-24T20:46:18
2019-07-17T14:57:12
Java
UTF-8
Java
false
false
1,243
java
package com.springjwt.apijwt.service; import com.springjwt.apijwt.dynamodbrepositories.ApiKeysRepository; import com.springjwt.apijwt.pojo.UserInfo; import com.springjwt.apijwt.rdsentities.User; import com.springjwt.apijwt.rdsrepositories.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @Service public class KeyServiceImpl implements KeysService{ @Autowired private UserRepository userRepository; @Autowired ApiKeysRepository apiKeysRepository; public String createApiKeys(UserInfo userInfo) { //Retrieve the data from mysql using the mageId User user = userRepository.findByUid(userInfo.getMageId()); String key = apiKeysRepository.createApiKey(user); if (!StringUtils.isEmpty(key)) { //Add the key to user user.setApiKey(key); userRepository.save(user); } return key; } @Override public String getKey(String mageId) { User user = userRepository.findByUid(mageId); if (!StringUtils.isEmpty(user)) { return user.getApiKey(); } return ""; } }
[ "surbasu@suranjanas-mbp.corp.adobe.com" ]
surbasu@suranjanas-mbp.corp.adobe.com
1c8a541e26017fa4ac5e68a29289506ed20a39c0
3892a26c0251dec336ac12513def7be711f5f9d2
/quanyingwang/src/main/java/com/quanying/app/wxapi/WXEntryActivity.java
c3f1857f2598e59538da950bc2ed7bd2a2b31a03
[]
no_license
RedWolfChao/lihong
104a9b880fd1172735591067dbc2c223b42d83ba
b8529b6603b4a14970c2fdf863f5d4f28b2274b9
refs/heads/master
2020-04-27T15:18:04.885281
2019-03-08T00:18:12
2019-03-08T00:18:12
174,440,509
0
0
null
2019-03-08T00:19:53
2019-03-08T00:19:52
null
UTF-8
Java
false
false
1,676
java
package com.quanying.app.wxapi; import android.content.Intent; import android.widget.Toast; import cn.sharesdk.wechat.utils.WXAppExtendObject; import cn.sharesdk.wechat.utils.WXMediaMessage; import cn.sharesdk.wechat.utils.WechatHandlerActivity; /** 微信客户端回调activity示例 */ public class WXEntryActivity extends WechatHandlerActivity { /** * 处理微信发出的向第三方应用请求app message * <p> * 在微信客户端中的聊天页面有“添加工具”,可以将本应用的图标添加到其中 * 此后点击图标,下面的代码会被执行。Demo仅仅只是打开自己而已,但你可 * 做点其他的事情,包括根本不打开任何页面 */ public void onGetMessageFromWXReq(WXMediaMessage msg) { Intent iLaunchMyself = getPackageManager().getLaunchIntentForPackage(getPackageName()); startActivity(iLaunchMyself); } /** * 处理微信向第三方应用发起的消息 * <p> * 此处用来接收从微信发送过来的消息,比方说本demo在wechatpage里面分享 * 应用时可以不分享应用文件,而分享一段应用的自定义信息。接受方的微信 * 客户端会通过这个方法,将这个信息发送回接收方手机上的本demo中,当作 * 回调。 * <p> * 本Demo只是将信息展示出来,但你可做点其他的事情,而不仅仅只是Toast */ public void onShowMessageFromWXReq(WXMediaMessage msg) { if (msg != null && msg.mediaObject != null && (msg.mediaObject instanceof WXAppExtendObject)) { WXAppExtendObject obj = (WXAppExtendObject) msg.mediaObject; Toast.makeText(this, obj.extInfo, Toast.LENGTH_SHORT).show(); } } }
[ "1981812120@qq.com" ]
1981812120@qq.com
62450443da59b6c5947a44ee641034b78816a6fd
995f73d30450a6dce6bc7145d89344b4ad6e0622
/MATE-20_EMUI_11.0.0/src/main/java/ohos/agp/components/$$Lambda$RelativeLayout$LayoutParams$1$v9GytlBpnBUrgN64EBKLrJ2_MQ.java
de1db65b8dcbabb81c43fe2cfe8927d454e608d7
[]
no_license
morningblu/HWFramework
0ceb02cbe42585d0169d9b6c4964a41b436039f5
672bb34094b8780806a10ba9b1d21036fd808b8e
refs/heads/master
2023-07-29T05:26:14.603817
2021-09-03T05:23:34
2021-09-03T05:23:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
897
java
package ohos.agp.components; import java.util.function.BiConsumer; import ohos.agp.components.RelativeLayout; /* renamed from: ohos.agp.components.-$$Lambda$RelativeLayout$LayoutParams$1$v9GytlBpnBUrgN64EBKLrJ2_-MQ reason: invalid class name */ /* compiled from: lambda */ public final /* synthetic */ class $$Lambda$RelativeLayout$LayoutParams$1$v9GytlBpnBUrgN64EBKLrJ2_MQ implements BiConsumer { public static final /* synthetic */ $$Lambda$RelativeLayout$LayoutParams$1$v9GytlBpnBUrgN64EBKLrJ2_MQ INSTANCE = new $$Lambda$RelativeLayout$LayoutParams$1$v9GytlBpnBUrgN64EBKLrJ2_MQ(); private /* synthetic */ $$Lambda$RelativeLayout$LayoutParams$1$v9GytlBpnBUrgN64EBKLrJ2_MQ() { } @Override // java.util.function.BiConsumer public final void accept(Object obj, Object obj2) { ((RelativeLayout.LayoutParams) obj).addRule(8, ((Attr) obj2).getIntegerValue()); } }
[ "dstmath@163.com" ]
dstmath@163.com
579839627e62bcdb51c3ca8121de4a96f7cb60bf
afd49cfe43b14892d6fd3e6cfd844abd7e357bd3
/src/main/java/com/king/bookstore/utils/DateUtils.java
26ac0b8765aeb7ec8f134687350d25b9cbae8422
[]
no_license
15116303251/bookstore
e7420cf62b7cb15b97c2bb13ed654b650c187804
5c0f82d44fa136aa499a4c27b364e3d5c2d2dc3b
refs/heads/master
2021-10-25T23:41:26.004923
2018-06-08T12:58:36
2018-06-08T12:58:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,132
java
package com.king.bookstore.utils; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateUtils { public static String DateToString(Date date){ SimpleDateFormat sdf = new SimpleDateFormat( " yyyy-MM-dd" ); return sdf.format(date); } /** * 比较日期大小 * @param DATE1 * @param DATE2 * @return */ public static int compare_date(String DATE1, String DATE2) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { Date dt1 = df.parse(DATE1); Date dt2 = df.parse(DATE2); if (dt1.getTime() > dt2.getTime()) { System.out.println("dt1 在dt2前"); return 1; } else if (dt1.getTime() < dt2.getTime()) { System.out.println("dt1在dt2后"); return -1; } else { return 0; } } catch (Exception exception) { exception.printStackTrace(); } return 0; } /** * 两个日期之间相差的天数 * @param smdate * @param bdate * @return */ public static int daysBetween(String smdate,String bdate){ SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); Calendar cal = Calendar.getInstance(); long time1 = 0; long time2 = 0; try{ cal.setTime(sdf.parse(smdate)); time1 = cal.getTimeInMillis(); cal.setTime(sdf.parse(bdate)); time2 = cal.getTimeInMillis(); }catch(Exception e){ e.printStackTrace(); } long between_days=(time2-time1)/(1000*3600*24); return Integer.parseInt(String.valueOf(between_days)); } /** * 获取系统的当前时间 * @return */ public static String getCurrentTime(){ Date day=new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); return df.format(day); } }
[ "2315945029@qq.com" ]
2315945029@qq.com
04ea39b3b8a43795edb55a729796198354327ced
4aa046cb37727ae2a59df296fff656cbccf8efe2
/app/src/main/java/cn/goldlone/safe/help/ScreenObserver.java
6947cc16dd2113100ab20e914f6cff3db1f7483c
[]
no_license
goldlone/safe
4c63d7564f744d62909a1abd75fc4974d3975883
5eb74b7af2041c94f93e85b46e3ffb8138f8e59d
refs/heads/master
2020-03-08T01:50:25.001689
2018-04-08T11:24:19
2018-04-08T11:24:19
127,842,060
0
0
null
null
null
null
UTF-8
Java
false
false
2,846
java
package cn.goldlone.safe.help; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.PowerManager; import android.util.Log; import java.lang.reflect.Method; /** * * @author zhangyg * */ public class ScreenObserver { private static String TAG = "ScreenObserver"; private Context mContext; private ScreenBroadcastReceiver mScreenReceiver; private ScreenStateListener mScreenStateListener; private static Method mReflectScreenState; public ScreenObserver(Context context){ mContext = context; mScreenReceiver = new ScreenBroadcastReceiver(); try { mReflectScreenState = PowerManager.class.getMethod("isScreenOn", new Class[] {}); } catch (NoSuchMethodException nsme) { Log.d(TAG, "API < 7," + nsme); } } /** * screen状态广播接收者 * @author zhangyg * */ private class ScreenBroadcastReceiver extends BroadcastReceiver { private String action = null; @Override public void onReceive(Context context, Intent intent) { action = intent.getAction(); if(Intent.ACTION_SCREEN_ON.equals(action)){ mScreenStateListener.onScreenOn(); }else if(Intent.ACTION_SCREEN_OFF.equals(action)){ mScreenStateListener.onScreenOff(); } } } /** * 请求screen状态更新 * @param listener */ public void requestScreenStateUpdate(ScreenStateListener listener) { mScreenStateListener = listener; startScreenBroadcastReceiver(); firstGetScreenState(); } /** * 第一次请求screen状态 */ private void firstGetScreenState(){ PowerManager manager = (PowerManager) mContext .getSystemService(Activity.POWER_SERVICE); if (isScreenOn(manager)) { if (mScreenStateListener != null) { mScreenStateListener.onScreenOn(); } } else { if (mScreenStateListener != null) { mScreenStateListener.onScreenOff(); } } } /** * 停止screen状态更新 */ public void stopScreenStateUpdate(){ mContext.unregisterReceiver(mScreenReceiver); } /** * 启动screen状态广播接收器 */ private void startScreenBroadcastReceiver(){ IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); mContext.registerReceiver(mScreenReceiver, filter); } /** * screen是否打开状态 * @param pm * @return */ private static boolean isScreenOn(PowerManager pm) { boolean screenState; try { screenState = (Boolean) mReflectScreenState.invoke(pm); } catch (Exception e) { screenState = false; } return screenState; } public interface ScreenStateListener { public void onScreenOn(); public void onScreenOff(); } }
[ "857353825@qq.com" ]
857353825@qq.com
b7ffa97e7ea468d3cb6884737e9c7a5e1b3a6841
9eef100f21d5b64ec9211121d23fae87575ea6f1
/UCU-BSACalc/gen/com/edu/ucuccs/ucu_bsacalc/BuildConfig.java
9a87ac4ea3d06d5af0d033c372e23778095b0a3b
[]
no_license
jaysoncallorina/UCU-BSACalculator
3494a3394af1f3d20ece1552462cf9482f3115ae
c69fb846e80dfb918ca842d905288d59a0addd5f
refs/heads/master
2016-09-05T11:40:14.531965
2014-09-30T08:58:01
2014-09-30T08:58:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
168
java
/** Automatically generated file. DO NOT MODIFY */ package com.edu.ucuccs.ucu_bsacalc; public final class BuildConfig { public final static boolean DEBUG = true; }
[ "callorinajay05@gmail.com" ]
callorinajay05@gmail.com
a3321c43c386a0ddb3ddc5efa75ecd8e69944f81
6c061c838aabbc85fd8df46fc65f6bca1f6a61c9
/app/src/main/java/com/mbakshi/decodeframe/FrameResources/Util/PositionHolder.java
a0c5d4473c3a9b89ff30d9345fd54c2e2460fb8a
[]
no_license
Morphinity/FrameDecoder
7390aa25dfad98b9068b4ce154a78c953eed6350
80d830acf7dac714f663b5b10b8e32fe6ae5a8ea
refs/heads/master
2021-01-10T16:24:38.887173
2015-11-09T10:39:44
2015-11-09T10:39:44
45,831,320
1
0
null
null
null
null
UTF-8
Java
false
false
161
java
package com.mbakshi.decodeframe.FrameResources.Util; /** * Created by mbakshi on 20/08/15. */ public final class PositionHolder { public long position; }
[ "mbakshi@adobe.com" ]
mbakshi@adobe.com
7902b5ac39cafb14f6af129211d0e29f479a8245
5adb9848b978e3754df65e55c22af20a0c54f84c
/src/main/java/com/netthreads/libgdx/scene/transition/MoveInLTransitionScene.java
dcdf9a1f00297958a6cc2d183750e484750230d1
[ "Apache-2.0" ]
permissive
alistairrutherford/netthreads-libgdx
c8ce08b01eba4379ed8de99b40a64b271c577f14
c7bb502992a6097712b26e8a05d704a3b81d0e21
refs/heads/master
2020-05-17T15:24:58.832747
2016-11-27T10:51:52
2016-11-27T10:51:52
8,676,644
23
12
null
null
null
null
UTF-8
Java
false
false
3,910
java
/* * ----------------------------------------------------------------------- * Copyright 2012 - Alistair Rutherford - www.netthreads.co.uk * ----------------------------------------------------------------------- * * 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.netthreads.libgdx.scene.transition; import aurelienribon.tweenengine.Timeline; import aurelienribon.tweenengine.Tween; import aurelienribon.tweenengine.TweenCallback; import aurelienribon.tweenengine.TweenEquation; import com.badlogic.gdx.utils.Pool; import com.netthreads.libgdx.action.TimelineAction; import com.netthreads.libgdx.scene.Scene; import com.netthreads.libgdx.tween.GroupAccessor; /** * Transition: Move in from left. * */ public class MoveInLTransitionScene extends TransitionScene { private static final int DEFAULT_INITIAL_POOL_SIZE = 4; private static Pool<MoveInLTransitionScene> _pool = new Pool<MoveInLTransitionScene>(DEFAULT_INITIAL_POOL_SIZE) { @Override protected MoveInLTransitionScene newObject() { MoveInLTransitionScene transitionScene = new MoveInLTransitionScene(); return transitionScene; } }; /** * Create transition. * * @param inScene * The incoming scene. * @param outScene * The outgoing scene. * @param durationMillis * The duration of transition. * @param easeEquation * The easing type. */ public static MoveInLTransitionScene $(Scene inScene, Scene outScene, int durationMillis, TweenEquation easeEquation) { MoveInLTransitionScene transitionScene = _pool.obtain(); transitionScene.setInScene(inScene); transitionScene.setInSceneRoot(inScene.getRoot()); transitionScene.setOutScene(outScene); transitionScene.setOutSceneRoot(outScene.getRoot()); transitionScene.setDurationMillis(durationMillis); transitionScene.setEaseEquation(easeEquation); return transitionScene; } /** * On entry build easing TimeLines. * */ @Override public void enter() { super.enter(); // In Scene TimeLine. Timeline inTimeline = Timeline.createSequence() .beginSequence() .push(Tween.to(getInSceneRoot(), GroupAccessor.POSITION_XY, 0).target(-getInScene().getWidth(), 0).ease(getEaseEquation())) .push(Tween.to(getInSceneRoot(), GroupAccessor.POSITION_XY, getDurationMillis()).target(0, 0).ease(getEaseEquation())) .end() .start(); // In Scene TimeLine Action. TimelineAction inTimelineAction = TimelineAction.$(inTimeline); getInSceneRoot().addAction(inTimelineAction); // Out Scene TimeLine. Timeline outTimeline = Timeline.createSequence() .beginSequence() .push(Tween.to(getOutSceneRoot(), GroupAccessor.POSITION_XY, 0).target(0, 0).ease(getEaseEquation())) .push(Tween.to(getOutSceneRoot(), GroupAccessor.POSITION_XY, getDurationMillis()).target(getOutScene().getWidth(), 0).ease(getEaseEquation())) .setCallbackTriggers(TweenCallback.COMPLETE) .setCallback(this) .end() .start(); // Out Scene TimeLine Action. TimelineAction outTimelineAction = TimelineAction.$(outTimeline); getOutSceneRoot().addAction(outTimelineAction); } /** * On exit tidy up. * */ @Override public void exit() { super.exit(); _pool.free(this); } }
[ "alistair.rutherford@gmail.com" ]
alistair.rutherford@gmail.com
013dbd6e199c0af3732f31538eecdd159ab2bb5e
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/10/10_68f2c7def5c1c70049cfebbed6be597b005e30fd/Database/10_68f2c7def5c1c70049cfebbed6be597b005e30fd_Database_t.java
cf0ff3f239155961bb8ec3a407a7e1d15108d3e9
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
16,117
java
package ro.undef.patois; import android.app.Activity; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.TreeMap; public class Database { private final static String TAG = "Database"; private static final String DATABASE_NAME = "patois.db"; private static final int DATABASE_VERSION = 1; private static final String PREFERENCES_NAME = "patois.prefs"; private final Activity mActivity; private DatabaseHelper mDbHelper; private SQLiteDatabase mDb; private SharedPreferences mPrefs; private TreeMap<Long, Language> mLanguagesCache; private static class DatabaseHelper extends SQLiteOpenHelper { private Context mCtx; DatabaseHelper(Context ctx) { super(ctx, DATABASE_NAME, null, DATABASE_VERSION); mCtx = ctx; } @Override public void onCreate(SQLiteDatabase db) { for (String statement : readStatementsFromAsset("sql/patois.sql")) db.execSQL(statement); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // When we'll have a new version of the database, implement this // method. } private ArrayList<String> readStatementsFromAsset(String fileName) { try { BufferedReader in = new BufferedReader( new InputStreamReader(mCtx.getAssets().open(fileName)), 4096); try { String eol = System.getProperty("line.separator"); ArrayList<String> schema = new ArrayList<String>(); StringBuffer statement = new StringBuffer(""); String line; while ((line = in.readLine()) != null) { String trimmed = line.trim(); // Ignore comments. if (trimmed.startsWith("--")) continue; // Empty lines terminate statements. if (trimmed.length() == 0) { if (statement.length() != 0) schema.add(statement.toString()); statement.setLength(0); continue; } statement.append(line); statement.append(eol); // readLine() strips the EOL characters. } if (statement.length() != 0) schema.add(statement.toString()); return schema; } finally { in.close(); } } catch (java.io.IOException e) { throw new RuntimeException("Could not read asset file: " + fileName, e); } } } Database(Activity activity) { mActivity = activity; mDbHelper = new DatabaseHelper(mActivity); mDb = mDbHelper.getWritableDatabase(); mPrefs = mActivity.getSharedPreferences(PREFERENCES_NAME, 0); mLanguagesCache = new TreeMap<Long, Language>(); } public void close() { mDbHelper.close(); mLanguagesCache.clear(); } public static final int LANGUAGES_ID_COLUMN = 0; public static final int LANGUAGES_CODE_COLUMN = 1; public static final int LANGUAGES_NAME_COLUMN = 2; public Cursor getLanguagesCursor() { Cursor cursor = mDb.query("languages", new String[] { "_id", "code", "name" }, null, null, null, null, null); mActivity.startManagingCursor(cursor); return cursor; } public ArrayList<Language> getLanguages() { ArrayList<Language> languages = new ArrayList<Language>(); Cursor cursor = mDb.query("languages", new String[] { "_id", "code", "name", "num_words" }, null, null, null, null, null); try { while (cursor.moveToNext()) { Language language = new Language(cursor.getLong(0), cursor.getString(1), cursor.getString(2), cursor.getLong(3)); mLanguagesCache.put(language.getId(), language); languages.add(language); } } finally { cursor.close(); } return languages; } public Language getLanguage(long id) { Language language = mLanguagesCache.get(id); if (language != null) return language; Cursor cursor = mDb.query("languages", new String[] { "code", "name", "num_words" }, "_id = ?", new String[] { Long.toString(id) }, null, null, null); try { if (cursor.getCount() != 1) return null; cursor.moveToFirst(); language = new Language(id, cursor.getString(0), cursor.getString(1), cursor.getLong(2)); mLanguagesCache.put(id, language); return language; } finally { cursor.close(); } } public boolean insertLanguage(Language language) { mLanguagesCache.put(language.getId(), language); ContentValues values = new ContentValues(); values.put("code", language.getCode()); values.put("name", language.getName()); long id = mDb.insert("languages", null, values); language.setId(id); return id != -1; } public boolean updateLanguage(Language language) { mLanguagesCache.put(language.getId(), language); ContentValues values = new ContentValues(); values.put("code", language.getCode()); values.put("name", language.getName()); return mDb.update("languages", values, "_id = ?", new String[] { language.getIdString() }) == 1; } public boolean deleteLanguage(Language language) { mLanguagesCache.remove(language.getId()); return mDb.delete("languages", "_id = ?", new String[] { language.getIdString() }) == 1; } public void clearLanguagesCache() { mLanguagesCache.clear(); } private static final String ACTIVE_LANGUAGE_PREF = "active_language"; private static final String SORT_ORDER_PREF = "sort_order"; public Language getActiveLanguage() { long id = mPrefs.getLong(ACTIVE_LANGUAGE_PREF, -1); if (id == -1) return null; return getLanguage(id); } public void setActiveLanguageId(long id) { SharedPreferences.Editor editor = mPrefs.edit(); editor.putLong(ACTIVE_LANGUAGE_PREF, id); editor.commit(); } public static final int SORT_ORDER_BY_NAME = 0; public static final int SORT_ORDER_BY_SCORE = 1; public static final int SORT_ORDER_NEWEST_FIRST = 2; public static final int SORT_ORDER_OLDEST_FIRST = 3; public int getSortOrder() { return mPrefs.getInt(SORT_ORDER_PREF, 0); } public void setSortOrder(int order) { SharedPreferences.Editor editor = mPrefs.edit(); editor.putInt(SORT_ORDER_PREF, order); editor.commit(); } public static final String BROWSE_WORDS_NAME_COLUMN = "display_name"; public static final String BROWSE_WORDS_SCORE_COLUMN = "score"; public static final String BROWSE_WORDS_TRANSLATIONS_COLUMN = "display_translations"; public Cursor getBrowseWordsCursor(Language language, String filter) { String pattern = "%" + filter + "%"; String sortCriteria = "_id"; switch (getSortOrder()) { case SORT_ORDER_BY_NAME: sortCriteria = "sort_name ASC"; break; case SORT_ORDER_BY_SCORE: sortCriteria = "sort_score DESC, sort_name ASC"; break; case SORT_ORDER_NEWEST_FIRST: sortCriteria = "timestamp DESC"; break; case SORT_ORDER_OLDEST_FIRST: sortCriteria = "timestamp ASC"; break; } Cursor cursor = mDb.rawQuery( "SELECT " + " t.word_id1 AS _id, " + // Simple escaping for BrowseWordsActivity.applyWordMarkup(). " replace(w1.name, '.', '..') AS display_name, " + " group_concat( " + " replace(w2.name, '.', '..') || ' .c(' || " + " replace(l.code, '.', '..') || ').C', ' ') AS display_translations, " + " lower(w1.name) AS sort_name, " + " w1.timestamp AS timestamp, " + " w1.score AS score, " + " w1.score AS sort_score " + " FROM " + " translations AS t, " + " words AS w1, " + " words AS w2, " + " languages AS l " + " WHERE " + " w1.language_id = ? AND " + " ((w1.name LIKE ?) OR (w2.name LIKE ?)) AND " + " t.word_id1 = w1._id AND " + " t.word_id2 = w2._id AND " + " w2.language_id = l._id " + " GROUP BY (t.word_id1) " + "UNION " + "SELECT " + " w._id AS _id, " + " '.u' || replace(w.name, '.', '..') || '.U' AS display_name, " + " '.c.0.C' AS display_translations, " + " lower(w.name) AS sort_name, " + " w.timestamp AS timestamp, " + " w.score AS score, " + " 2147483647 AS sort_score " + " FROM " + " words AS w " + " WHERE " + " w.language_id = ? AND " + " w.name LIKE ? AND " + " w.num_translations == 0 " + "ORDER BY " + sortCriteria, new String[] { language.getIdString(), pattern, pattern, language.getIdString(), pattern, }); mActivity.startManagingCursor(cursor); return cursor; } public static final String WORDS_NAME_COLUMN = "name"; public static final int WORDS_NAME_COLUMN_ID = 1; public Cursor getWordsCursor(Language language, String filter, Word mainWord) { // We want to avoid suggesting the main word as a translation of // itself, so we have to explicitly filter it out here. Cursor cursor = mDb.query("words", new String[] { "_id", "name" }, "(language_id = ?) AND (name LIKE ?) AND (_id != ?)", new String[] { language.getIdString(), "%" + filter + "%", mainWord.getIdString(), }, null, null, null); mActivity.startManagingCursor(cursor); return cursor; } public ArrayList<Word.Score> getWordScores(Language language) { ArrayList<Word.Score> scores = new ArrayList<Word.Score>(); Cursor cursor = mDb.query("words", new String[] { "_id", "score" }, "(language_id = ?) AND (num_translations > 0)", new String[] { language.getIdString() }, null, null, null); try { while (cursor.moveToNext()) scores.add(new Word.Score(cursor.getLong(0), cursor.getInt(1))); } finally { cursor.close(); } return scores; } public Word getWord(long id) { Cursor cursor = mDb.query("words", new String[] { "name", "language_id", "score" }, "_id = ?", new String[] { Long.toString(id) }, null, null, null); try { if (cursor.getCount() != 1) return null; cursor.moveToFirst(); return new Word(id, cursor.getString(0), getLanguage(cursor.getLong(1)), cursor.getInt(2)); } finally { cursor.close(); } } public boolean insertWord(Word word) { ContentValues values = new ContentValues(); values.put("name", word.getName()); values.put("language_id", word.getLanguage().getId()); values.put("score", word.getScore()); long id = mDb.insert("words", null, values); word.setId(id); return id != -1; } public boolean updateWord(Word word) { ContentValues values = new ContentValues(); values.put("name", word.getName()); values.put("language_id", word.getLanguage().getId()); values.put("score", word.getScore()); return mDb.update("words", values, "_id = ?", new String[] { word.getIdString() }) == 1; } public boolean deleteWord(Word word) { return mDb.delete("words", "_id = ?", new String[] { word.getIdString() }) == 1; } public boolean deleteWordById(long id) { return mDb.delete("words", "_id = ?", new String[] { Long.toString(id) }) == 1; } public ArrayList<Word> getTranslations(Word word) { ArrayList<Word> translations = new ArrayList<Word>(); Cursor cursor = mDb.query("translations", new String[] { "word_id2" }, "word_id1 = ?", new String[] { word.getIdString() }, null, null, null); try { while (cursor.moveToNext()) translations.add(getWord(cursor.getLong(0))); } finally { cursor.close(); } return translations; } public void insertTranslation(Word word1, Word word2) { ContentValues values = new ContentValues(); values.put("word_id1", word1.getId()); values.put("word_id2", word2.getId()); mDb.insert("translations", null, values); values.clear(); values.put("word_id1", word2.getId()); values.put("word_id2", word1.getId()); mDb.insert("translations", null, values); } public void deleteTranslation(Word word1, Word word2) { mDb.delete("translations", "(word_id1 = ? AND word_id2 = ?) OR (word_id1 = ? AND word_id2 = ?)", new String[] { word1.getIdString(), word2.getIdString(), word2.getIdString(), word1.getIdString(), }); } public void insertPracticeLogEntry(Word word, int direction, boolean successful) { ContentValues values = new ContentValues(); values.put("word_id", word.getId()); values.put("direction", direction); values.put("successful", successful); mDb.insert("practice_log", null, values); } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
4bbe19a569d15e7041ba934e3cfe32f54d7fd58e
e4e67996ea8614bd00a7b488e80bbebe9ec27e2e
/src/main/java/org/b3log/solo/wechat/HandleType.java
838a2a659fae89316dd18307816fff317deb03f6
[ "Apache-2.0" ]
permissive
likeaboy/solo
fe0f94ebc1ea7bcfd6846689438829a5041181bf
21112b88b9911b8b0f3ec2da70cafbf58aceec7a
refs/heads/master
2021-01-22T19:41:27.840990
2017-09-12T14:29:39
2017-09-12T14:29:39
102,421,236
0
0
null
2017-09-05T01:57:21
2017-09-05T01:57:21
null
UTF-8
Java
false
false
273
java
package org.b3log.solo.wechat; /** * 处理方式 * @author Rocky.Wang * */ public enum HandleType { //返回menu菜单 RETURN_MENU, //返回图文消息列表 RETURN_NEWS, //返回超链接列表 RETURN_LIST, //返回MenuItem中的name信息 RETURN_PLAIN; }
[ "jrocky.wang@gmail.com" ]
jrocky.wang@gmail.com
3f4f72f4b0ce704bb6f9a419be4a1cb22d9265b8
91bb487a414fd20d409d406b70ed770d9ece32b4
/albedo-boot-common/albedo-boot-util/src/main/java/com/albedo/java/util/base/Reflections.java
6a5108b53b837fec6237941ad6f366c398c8dc7d
[ "Apache-2.0" ]
permissive
ch123iu/albedo-boot
8528b499eb8fa742dd41a0c9d5b87be5ccdff592
ac43509a85d02e9d5908e974b2847039d57c1352
refs/heads/master
2020-12-02T21:20:00.755210
2017-07-05T05:35:27
2017-07-05T05:35:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
37,783
java
package com.albedo.java.util.base; import com.albedo.java.util.PublicUtil; import com.albedo.java.util.StringUtil; import com.albedo.java.util.config.SystemConfig; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import javassist.*; import javassist.bytecode.CodeAttribute; import javassist.bytecode.LocalVariableAttribute; import javassist.bytecode.MethodInfo; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.lang3.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.framework.AdvisedSupport; import org.springframework.beans.DirectFieldAccessor; import org.springframework.util.Assert; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.lang.reflect.Modifier; import java.util.*; /** * @author lijie version 2013-12-26 下午2:43:53 */ @SuppressWarnings("rawtypes") public class Reflections { private static final String SETTER_PREFIX = "set"; private static final String GETTER_PREFIX = "get"; private static final String CGLIB_CLASS_SEPARATOR = "$$"; private static final String ADVISED_FIELD_NAME = "advised"; private static final String CLASS_JDK_DYNAMIC_AOP_PROXY = "org.springframework.aop.framework.JdkDynamicAopProxy"; public static String classPackge = SystemConfig.get("system.base.class.path"); private static Logger logger = LoggerFactory.getLogger(Reflections.class); public static boolean checkClassIsBase(String className) { if (PublicUtil.isNotEmpty(className) && PublicUtil.isNotEmpty(classPackge)) { String[] strs = classPackge.split(","); for (String item : strs) { if (className.contains(item)) { return true; } } } return false; } /** * 调用Getter方法. 支持多级,如:对象名.对象名.方法 */ public static Object invokeGetter(Object obj, String propertyName) { if (obj instanceof Map) { return ((Map) obj).get(propertyName); } Object object = obj; for (String name : StringUtil.split(propertyName, ".")) { object = invokeMethod(object, PublicUtil.toAppendStr(GETTER_PREFIX, StringUtil.capitalize(name)), new Class[]{}, new Object[]{}); } return object; } /** * 调用Setter方法, 仅匹配方法名。 支持多级,如:对象名.对象名.方法 */ public static void invokeSetter(Object obj, String propertyName, Object value) { Object object = obj; String[] names = StringUtil.split(propertyName, "."); for (int i = 0; i < names.length; i++) { if (i < names.length - 1) { object = invokeMethod(object, PublicUtil.toAppendStr(GETTER_PREFIX, StringUtil.capitalize(names[i])), new Class[]{}, new Object[]{}); } else { invokeMethodByName(object, PublicUtil.toAppendStr(SETTER_PREFIX, StringUtil.capitalize(names[i])), new Object[]{value}); } } } /** * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数. */ public static Object getFieldValue(final Object obj, final String fieldName) { if (obj instanceof Map) { return ((Map) obj).get(fieldName); } Field field = getAccessibleField(obj, fieldName); if (field == null) { throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]"); } Object result = null; try { result = field.get(obj); } catch (IllegalAccessException e) { logger.error("不可能抛出的异常{}", e.getMessage()); } return result; } /** * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数. */ public static void setFieldValue(final Object obj, final String fieldName, final Object value) { Field field = getAccessibleField(obj, fieldName); if (field == null) { throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]"); } try { field.set(obj, value); } catch (IllegalAccessException e) { logger.error("不可能抛出的异常:{}", e.getMessage()); } } /** * 直接设置对象属性值, 经过setter函数. PropertyUtil操作 自动判断值类型(仅包含基础类型) * * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */ public static void setProperty(final Object obj, final PropertyDescriptor p, final Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { String typeName = p.getPropertyType().getName(); if (typeName.contains("int") || typeName.contains("Integer")) { PropertyUtils.setProperty(obj, p.getName(), Integer.parseInt(PublicUtil.toStrString(value))); } else if (typeName.contains("float") || typeName.contains("Float")) { PropertyUtils.setProperty(obj, p.getName(), Float.parseFloat(PublicUtil.toStrString(value))); } else if (typeName.contains("double") || typeName.contains("Double")) { PropertyUtils.setProperty(obj, p.getName(), Double.parseDouble(PublicUtil.toStrString(value))); } else if (typeName.contains("long") || typeName.contains("Long")) { PropertyUtils.setProperty(obj, p.getName(), Long.parseLong(PublicUtil.toStrString(value))); } else { PropertyUtils.setProperty(obj, p.getName(), value); } } /** * 直接设置对象属性值, 经过setter函数. PropertyUtil操作 自动判断值类型(仅包含基础类型) * * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */ public static void setProperty(final Object obj, final String propertyName, final Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (PublicUtil.isNotEmpty(value)) { PropertyDescriptor p = PropertyUtils.getPropertyDescriptor(obj, propertyName); setProperty(obj, p, value); } } /** * 直接调用对象方法, 无视private/protected修饰符. * 用于一次性调用的情况,否则应使用getAccessibleMethod()函数获得Method后反复调用. 同时匹配方法名+参数类型, */ public static Object invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes, final Object[] args) { Method method = getAccessibleMethod(obj, methodName, parameterTypes); if (method == null) { throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]"); } try { return method.invoke(obj, args); } catch (Exception e) { throw convertReflectionExceptionToUnchecked(e); } } /** * 直接调用对象方法, 无视private/protected修饰符, * 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用. * 只匹配函数名,如果有多个同名函数调用第一个。 */ public static Object invokeMethodByName(final Object obj, final String methodName, final Object[] args) { Method method = getAccessibleMethodByName(obj, methodName); if (method == null) { throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]"); } try { return method.invoke(obj, args); } catch (Exception e) { throw convertReflectionExceptionToUnchecked(e); } } /** * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问. 如向上转型到Object仍无法找到, 返回null. */ public static Field getAccessibleField(final Object obj, final String fieldName) { Validate.notNull(obj, "object can't be null"); Validate.notBlank(fieldName, "fieldName can't be blank"); for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass .getSuperclass()) { try { Field field = superClass.getDeclaredField(fieldName); makeAccessible(field); return field; } catch (NoSuchFieldException e) {// NOSONAR // Field不在当前类定义,继续向上转型 continue;// new add } } return null; } /** * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. 如向上转型到Object仍无法找到, 返回null. * 匹配函数名+参数类型。 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, * Object... args) */ public static Method getAccessibleMethod(final Object obj, final String methodName, final Class<?>... parameterTypes) { Validate.notNull(obj, "object can't be null"); Validate.notBlank(methodName, "methodName can't be blank"); for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType .getSuperclass()) { try { Method method = searchType.getDeclaredMethod(methodName, parameterTypes); makeAccessible(method); return method; } catch (NoSuchMethodException e) { // Method不在当前类定义,继续向上转型 continue;// new add } } return null; } public static Method getAccessibleMethodByName(final Object obj, final String methodName) { return getAccessibleMethodClazzByName(Reflections.getTargetClass(obj), methodName); } /** * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. 如向上转型到Object仍无法找到, 返回null. 只匹配函数名。 * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... * args) */ public static Method getAccessibleMethodClazzByName(final Class<?> clazz, final String methodName) { Validate.notNull(clazz, "object can't be null"); Validate.notBlank(methodName, "methodName can't be blank"); for (Class<?> searchType = clazz; searchType != Object.class; searchType = searchType .getSuperclass()) { Method[] methods = searchType.getDeclaredMethods(); for (Method method : methods) { if (method.getName().equals(methodName)) { makeAccessible(method); return method; } } } return null; } /** * 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。 */ public static void makeAccessible(Method method) { if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) { method.setAccessible(true); } } /** * 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。 */ public static void makeAccessible(Field field) { if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) { field.setAccessible(true); } } /** * 通过反射, 获得Class定义中声明的泛型参数的类型, 注意泛型必须定义在父类处 如无法找到, 返回Object.class. eg. * public UserDao extends HibernateDao<User> * * @param clazz The class to introspect * @return the first generic declaration, or Object.class if cannot be * determined */ @SuppressWarnings("unchecked") public static <T> Class<T> getClassGenricType(final Class clazz) { return getClassGenricType(clazz, 0); } /** * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. 如无法找到, 返回Object.class. 如public UserDao * extends HibernateDao<User,Long> * * @param clazz clazz The class to introspect * @param index the Index of the generic ddeclaration,start from 0. * @return the index generic declaration, or Object.class if cannot be * determined */ public static Class getClassGenricType(final Class clazz, final int index) { Type genType = clazz.getGenericSuperclass(); if (!(genType instanceof ParameterizedType)) { logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType"); return Object.class; } Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); if (index >= params.length || index < 0) { logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " + params.length); return Object.class; } if (!(params[index] instanceof Class)) { logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter"); return Object.class; } return (Class) params[index]; } public static Class<?> getUserClass(Object instance) { Assert.notNull(instance, "Instance must not be null"); Class clazz = instance.getClass(); if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) { Class<?> superClass = clazz.getSuperclass(); if (superClass != null && !Object.class.equals(superClass)) { return superClass; } } return clazz; } /** * 将反射时的checked exception转换为unchecked exception. */ public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) { if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException || e instanceof NoSuchMethodException) { return new IllegalArgumentException(e); } else if (e instanceof InvocationTargetException) { return new RuntimeException(((InvocationTargetException) e).getTargetException()); } else if (e instanceof RuntimeException) { return (RuntimeException) e; } return new RuntimeException("Unexpected Checked Exception.", e); } /** * 获取对象属性所包含的指定注解(含get方法) * * @param cls * @param pName * @param annotationClass * @return */ public static <T extends Annotation> T getAnnotationByClazz(Class<?> cls, String pName, Class<T> annotationClass) { try { Object obj = cls.newInstance(); return getAnnotation(obj, pName, annotationClass); } catch (Exception e) { logger.error(e.getMessage()); } return null; } /** * 获取对象属性所包含的指定注解(含get方法) * * @param obj * @param pName * @param annotationClass * @return */ public static <T extends Annotation> T getAnnotation(Object obj, String pName, Class<T> annotationClass) { if (annotationClass == null || obj == null) throw new NullPointerException(); T an = null; Class<?> temp = obj.getClass(); while (an == null && checkClassIsBase(temp.toString())) { try { an = temp.getDeclaredField(pName).getAnnotation(annotationClass); } catch (Exception e) { // logger.debug(e.getMessage()); } try { if (an == null) an = temp.getDeclaredMethod(PublicUtil.toAppendStr(GETTER_PREFIX, StringUtil.capitalize(pName))) .getAnnotation(annotationClass); } catch (Exception e) { // logger.debug(e.getMessage()); } temp = temp.getSuperclass(); } return an; } /** * 创建对象,注入指定属性值 * * @param cls * @param fields * @param value * @param <T> * @return */ @SuppressWarnings("unchecked") public static <T> T createObj(Class<T> cls, List<String> fields, Object... value) { Object obj = null; try { obj = updateObj(cls.newInstance(), fields, value); } catch (Exception e) { e.printStackTrace(); } return (T) obj; } /** * 更新对象,注入指定属性值 * * @param obj * @param fields * @param value * @return */ @SuppressWarnings("unchecked") public static <T> T updateObj(Object obj, List<String> fields, Object... value) { try { if (obj != null) { if (PublicUtil.isNotEmpty(fields) && PublicUtil.isNotEmpty(value) && value.length == fields.size()) { for (int i = 0; i < fields.size(); i++) { setFieldValue(obj, fields.get(i), value[i]); } } else { logger.warn("obj {} fields {} value {}", obj, fields, value); } } else { logger.warn("obj is null"); } } catch (Exception e) { e.printStackTrace(); } return (T) obj; } /** * 获取对象属性所包含的指定注解(含get方法) * * @param objClass * @param pName * @param annotationClass * @return */ public static <T extends Annotation> T getClassAnnotation(Class<?> objClass, String pName, Class<T> annotationClass) { if (annotationClass == null || objClass == null) throw new NullPointerException(); T an = null; Class<?> temp = objClass; while (an == null && !temp.toString().contains("java.lang.Object")) { try { an = temp.getDeclaredField(pName).getAnnotation(annotationClass); } catch (Exception e) { // logger.debug(e.getMessage()); } try { if (an == null) an = temp.getDeclaredMethod(PublicUtil.toAppendStr(GETTER_PREFIX, StringUtil.capitalize(pName))) .getAnnotation(annotationClass); } catch (Exception e) { // logger.debug(e.getMessage()); } temp = temp.getSuperclass(); } return an; } /** * 获取方法的参数名称 * * @param className * @param methodName * @return */ public static List<String> getMethodParameterList(String className, String methodName) { try { ClassPool pool = ClassPool.getDefault(); ClassClassPath classPath = new ClassClassPath(Reflections.class); pool.insertClassPath(classPath); CtClass cc = pool.get(className); CtMethod cm = cc.getDeclaredMethod(methodName); // 使用javaassist的反射方法获取方法的参数名 MethodInfo methodInfo = cm.getMethodInfo(); CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute .getAttribute(LocalVariableAttribute.tag); if (attr == null) { // exception } String[] paramNames = new String[cm.getParameterTypes().length]; int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1; for (int i = 0; i < paramNames.length; i++) { paramNames[i] = attr.variableName(i + pos); System.out.println(attr.getName()); } List<String> rs = Lists.newArrayList(paramNames); return rs; } catch (NotFoundException e) { logger.error(e.getMessage()); throw new RuntimeException(e); } } /** * 获取方法的参数名称 * * @param clazz * @param methodName * @return */ public static List<String> getMethodParameterList(Class<?> clazz, String methodName) { return getMethodParameterList(clazz.getName(), methodName); } /** * 获取方法的参数名称和类型 * * @param clazz * @param methodName * @return */ public static List<Map<String, Object>> getMethodParameter(Class<?> clazz, String methodName) { return getMethodParameter(clazz.getName(), methodName); } /** * 获取方法的参数名称和类型 * * @param className * @param methodName * @return */ public static List<Map<String, Object>> getMethodParameter(String className, String methodName) { try { List<Map<String, Object>> rs = Lists.newArrayList(); ClassPool pool = ClassPool.getDefault(); ClassClassPath classPath = new ClassClassPath(Reflections.class); pool.insertClassPath(classPath); CtClass cc = pool.get(className); CtMethod cm = cc.getDeclaredMethod(methodName); // 使用javaassist的反射方法获取方法的参数名 MethodInfo methodInfo = cm.getMethodInfo(); CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute .getAttribute(LocalVariableAttribute.tag); if (attr == null) { // exception } Class clazz = Class.forName(className); Method[] methods = clazz.getDeclaredMethods(); Class[] params = null; for (Method method : methods) { if (method.getName().equals(methodName) && method.getParameterTypes().length == cm.getParameterTypes().length) { params = method.getParameterTypes(); } } if (params != null) { String[] paramNames = new String[cm.getParameterTypes().length]; int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1; Map<String, Object> map = null; for (int i = 0; i < paramNames.length; i++) { map = Maps.newHashMap(); map.put("name", attr.variableName(i + pos)); map.put("type", params[i]); rs.add(map); } } return rs; } catch (Exception e) { logger.error(e.getMessage()); throw new RuntimeException(e); } } /** * 是否为基础类型 @Title: isWrapClass @Description: * TODO(这里用一句话描述这个方法的作用) @param @param clz @param @return 设定文件 @return * boolean 返回类型 @throws */ public static boolean isWrapClass(Class clz) { try { return ((Class) clz.getField("TYPE").get(null)).isPrimitive(); } catch (Exception e) { return false; } } /** * 可获取spring动态代理对象class * * @param candidate * @return */ public static Class getTargetClass(Object candidate) { if (!org.springframework.aop.support.AopUtils.isJdkDynamicProxy(candidate)) { return org.springframework.aop.support.AopUtils.getTargetClass(candidate); } return getTargetClassFromJdkDynamicAopProxy(candidate); } private static Class getTargetClassFromJdkDynamicAopProxy(Object candidate) { try { InvocationHandler invocationHandler = Proxy.getInvocationHandler(candidate); if (!invocationHandler.getClass().getName().equals(CLASS_JDK_DYNAMIC_AOP_PROXY)) { // 在目前的spring版本,这处永远不会执行,除非以后spring的dynamic proxy实现变掉 logger.warn("the invocationHandler of JdkDynamicProxy isn`t the instance of {}", CLASS_JDK_DYNAMIC_AOP_PROXY); return candidate.getClass(); } AdvisedSupport advised = (AdvisedSupport) new DirectFieldAccessor(invocationHandler) .getPropertyValue(ADVISED_FIELD_NAME); Class targetClass = advised.getTargetClass(); if (Proxy.isProxyClass(targetClass)) { // 目标类还是代理,递归 Object target = advised.getTargetSource().getTarget(); return getTargetClassFromJdkDynamicAopProxy(target); } return targetClass; } catch (Exception e) { logger.info("get target class from {}", CLASS_JDK_DYNAMIC_AOP_PROXY, e); return candidate.getClass(); } } public static PropertyDescriptor[] getPropertiesDescriptor(Object obj) { return getPropertiesDescriptor(obj, Object.class); } /** * 内省class * * @param obj 内省对象 * @param clazz 内省最高层级 * @return */ public static PropertyDescriptor[] getPropertiesDescriptor(Object obj, Class<?> clazz) { BeanInfo beanInfo = null; Class<?> objClass = null; if (obj instanceof Class<?>) { objClass = (Class<?>) obj; } else { objClass = obj.getClass(); } try { beanInfo = Introspector.getBeanInfo(objClass, clazz); } catch (IntrospectionException e) { e.printStackTrace(); } return beanInfo.getPropertyDescriptors(); } public static Object getFieldValue(Object obj, Field field) { field.setAccessible(true); Object value = null; try { value = field.get(obj); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return value; } /** * 获取字段泛型 * * @param field 指定字段 * @param index 第几个泛型 * @return */ public static Class<?> getGenericClass(Field field, int index) { Type type = field.getGenericType(); if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Type[] types = parameterizedType.getActualTypeArguments(); return (Class<?>) types[index]; } return null; } /** * 在目标clazz中获取类型为fieldClass的字段 * * @param clazz * @param fieldClass * @return * @throws NoSuchFieldException */ public static Field[] getDeclaredFieldByType(Class<?> clazz, Class<?> fieldClass) throws NoSuchFieldException { Field[] fields = clazz.getDeclaredFields(); List<Field> listResult = new ArrayList<Field>(); for (Field field : fields) { if (fieldClass.isAssignableFrom(field.getClass())) { listResult.add(field); } } if (listResult == null || listResult.size() == 0) { throw new NoSuchFieldException(); } else { Field[] rt = new Field[listResult.size()]; return listResult.toArray(rt); } } /** * 在目标clazz中获取类型为fieldClass<E extent genericeType>的字段 * * @param clazz * @param fieldClass * @param genericType * @return * @throws NoSuchFieldException */ public static Field[] getDeclaredFieldByType(Class<?> clazz, Class<?> fieldClass, Class<?> genericType) throws NoSuchFieldException { Field[] fields = clazz.getDeclaredFields(); List<Field> listResult = new ArrayList<Field>(); for (Field field : fields) { if (fieldClass.isAssignableFrom(field.getType())) { Type type = field.getGenericType(); if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Class<?> genericClass = (Class<?>) parameterizedType .getActualTypeArguments()[0]; if (genericClass == genericType) { listResult.add(field); } } } } if (listResult == null || listResult.size() == 0) { throw new NoSuchFieldException(); } else { Field[] rt = new Field[listResult.size()]; return listResult.toArray(rt); } } /** * 获取class上的注解 * * @param clazz * @param annotationClass * @return */ public static <T extends Annotation> T getAnnotation(Class<?> clazz, Class<T> annotationClass) { return clazz.getAnnotation(annotationClass); } public static boolean hasAnnotation(Class<?> clazz, Class<? extends Annotation> annotationClass) { return clazz.isAnnotationPresent(annotationClass); } /** * Attempt to find a {@link Method} on the supplied class with the supplied * name and no parameters. Searches all superclasses up to {@code Object}. * <p> * Returns {@code null} if no {@link Method} can be found. * * @param clazz the class to introspect * @param name the name of the method * @return the Method object, or {@code null} if none found */ public static Method getMethod(Class<?> clazz, String name) { return getMethod(clazz, name, new Class<?>[0]); } /** * Attempt to find a {@link Method} on the supplied class with the supplied * name and parameter types. Searches all superclasses up to {@code Object}. * <p> * Returns {@code null} if no {@link Method} can be found. * * @param clazz the class to introspect * @param name the name of the method * @param paramTypes the parameter types of the method (may be {@code null} to * indicate any signature) * @return the Method object, or {@code null} if none found */ public static Method getMethod(Class<?> clazz, String name, Class<?>... paramTypes) { Assert.notNull(clazz, "Class must not be null"); Assert.notNull(name, "Method name must not be null"); Class<?> searchType = clazz; while (searchType != null) { Method[] methods = (searchType.isInterface() ? searchType .getMethods() : searchType.getDeclaredMethods()); for (Method method : methods) { if (name.equals(method.getName()) && (paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) { return method; } } searchType = searchType.getSuperclass(); } return null; } /** * Invoke the specified {@link Method} against the supplied target object * with the supplied arguments. The target object can be {@code null} when * invoking a static {@link Method}. * <p> * Thrown exceptions are handled via a call to * {@link #handleReflectionException}. * * @param method the method to invoke * @param target the target object to invoke the method on * @param args the invocation arguments (may be {@code null}) * @return the invocation result, if any */ public static Object invokeMethod(Method method, Object target, Object... args) { try { return method.invoke(target, args); } catch (Exception ex) { handleReflectionException(ex); } throw new IllegalStateException("Should never get here"); } /** * Handle the given reflection exception. Should only be called if no * checked exception is expected to be thrown by the target method. * <p> * Throws the underlying RuntimeException or Error in case of an * InvocationTargetException with such a root cause. Throws an * IllegalStateException with an appropriate message else. * * @param ex the reflection exception to handle */ public static void handleReflectionException(Exception ex) { if (ex instanceof NoSuchMethodException) { throw new IllegalStateException("没有找到指定名称的method: " + ex.getMessage()); } if (ex instanceof IllegalAccessException) { throw new IllegalStateException("无权访问指定的method: " + ex.getMessage()); } if (ex instanceof InvocationTargetException) { handleInvocationTargetException((InvocationTargetException) ex); } if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } throw new UndeclaredThrowableException(ex); } public static void handleInvocationTargetException( InvocationTargetException ex) { rethrowRuntimeException(ex.getTargetException()); } /** * Rethrow the given {@link Throwable exception}, which is presumably the * <em>target exception</em> of an {@link InvocationTargetException}. Should * only be called if no checked exception is expected to be thrown by the * target method. * <p> * Rethrows the underlying exception cast to an {@link RuntimeException} or * {@link Error} if appropriate; otherwise, throws an * {@link IllegalStateException}. * * @param ex the exception to rethrow * @throws RuntimeException the rethrown exception */ public static void rethrowRuntimeException(Throwable ex) { if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } if (ex instanceof Error) { throw (Error) ex; } throw new UndeclaredThrowableException(ex); } // Bean --> Map 1: 利用Introspector和PropertyDescriptor 将Bean --> Map public static Map<String, ? extends Object> bean2Map(Object obj) { if (obj == null) { return null; } Map<String, Object> map = new HashMap<>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); // 过滤class属性 if (!key.equals("class")) { // 得到property对应的getter方法 Method getter = property.getReadMethod(); Object value = getter.invoke(obj); map.put(key, value); } } } catch (Exception e) { logger.error("=============Bean转Map异常================{}", e); } return map; } // Map --> Bean 1: 利用Introspector,PropertyDescriptor实现 Map --> Bean public static void map2Bean(Map<String, Object> map, Object obj) { try { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (map.containsKey(key)) { Object value = map.get(key); if (value != null) { value = ConvertUtils.convert(value, property.getPropertyType());//类型转换,引用类型需要在监听器里面注册转换 } // 得到property对应的setter方法 Method setter = property.getWriteMethod(); setter.invoke(obj, value); } } } catch (Exception e) { logger.error("=============Map转Bean异常================{}", e); } return; } public static void main(String[] args) { System.out.println(getMethodParameter("com.albedo.java.modules.sys.controller.AreaController", "findTreeData")); } }
[ "837158334@qq.com" ]
837158334@qq.com
408c468095d8d6811ba8a069f70dde3c3c818d16
99cf7d5b4d1ec08c514648287ca637a75c962467
/app/src/main/java/com/whoisconnected/util/PlaceHolder.java
9893c28bc776e0991f10362e46e19ccc0d8c5d08
[]
no_license
Pramod-sj/Who-sConnected
661996780109705aa99524a00d79467cd6cffbc7
aaf701650fbd21dafbef9f9212c4615c6dd9fed3
refs/heads/master
2022-02-14T19:38:22.827014
2019-09-14T13:03:06
2019-09-14T13:03:06
208,441,123
0
0
null
null
null
null
UTF-8
Java
false
false
2,806
java
package com.whoisconnected.util; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.Nullable; import com.whoisconnected.R; public class PlaceHolder extends FrameLayout { String placeHolderMessage,placeHolderTitle; Drawable placeHolderImage; ImageView placeHolderImageView; TextView placeHolderTextView,placeHolderDescTextView; Context context; public PlaceHolder(Context context, @Nullable AttributeSet attrs) { super(context, attrs); this.context=context; TypedArray attributes=context.obtainStyledAttributes(attrs, R.styleable.PlaceHolder,0,0); placeHolderTitle=attributes.getString(R.styleable.PlaceHolder_setPlaceHolderTitle); placeHolderImage=attributes.getDrawable(R.styleable.PlaceHolder_setPlaceHolderImage); placeHolderMessage=attributes.getString(R.styleable.PlaceHolder_setPlaceHolderMessage); View view=LayoutInflater.from(context).inflate(R.layout.placeholder,this); placeHolderImageView=view.findViewById(R.id.placeholderimage); placeHolderTextView=view.findViewById(R.id.placeHolderTextView); placeHolderDescTextView=view.findViewById(R.id.placeHolderDescTextView); if(placeHolderImage!=null) { placeHolderImageView.setImageDrawable(placeHolderImage); } placeHolderDescTextView.setText(placeHolderMessage); placeHolderTextView.setText(placeHolderTitle); attributes.recycle(); } public void setPlaceHolder(Drawable placeHolderImage,String title,String placeHolderMessage) { placeHolderImageView.setImageDrawable(placeHolderImage); placeHolderTextView.setText(title); placeHolderDescTextView.setText(placeHolderMessage); } public void showPlaceHolder(Drawable placeHolderImage,String title,String placeHolderMessage) { placeHolderImageView.setImageDrawable(placeHolderImage); placeHolderTextView.setText(title); placeHolderDescTextView.setText(placeHolderMessage); this.setVisibility(VISIBLE); } public void showPlaceHolder(int placeholdlerImageId,String title,String placeHolderMessage) { placeHolderImageView.setImageResource(placeholdlerImageId); placeHolderTextView.setText(title); placeHolderDescTextView.setText(placeHolderMessage); this.setVisibility(VISIBLE); } public void showPlaceHolder() { this.setVisibility(VISIBLE); } public void hidePlaceHolder(){ this.setVisibility(GONE); } }
[ "pramodsinghjantwal@gmail.com" ]
pramodsinghjantwal@gmail.com
0c1688e4888f0e33ed02cf3c6e614cef48e402f2
0ca9a0873d99f0d69b78ed20292180f513a20d22
/src/main/java/com/google/common/collect/ForwardingListMultimap.java
42060772b410968277cd7f0c48ae6922b17d92cb
[]
no_license
Eliminater74/com.google.android.tvlauncher
44361fbbba097777b99d7eddd6e03d4bbe5f4d60
e8284f9970d77a05042a57e9c2173856af7c4246
refs/heads/master
2021-01-14T23:34:04.338366
2020-02-24T16:39:53
2020-02-24T16:39:53
242,788,539
1
0
null
null
null
null
UTF-8
Java
false
false
1,466
java
package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.List; import org.checkerframework.checker.nullness.compatqual.NullableDecl; @GwtCompatible public abstract class ForwardingListMultimap<K, V> extends ForwardingMultimap<K, V> implements ListMultimap<K, V> { /* access modifiers changed from: protected */ public abstract ListMultimap<K, V> delegate(); protected ForwardingListMultimap() { } public List<V> get(@NullableDecl K key) { return delegate().get((Object) key); } @CanIgnoreReturnValue public List<V> removeAll(@NullableDecl Object key) { return delegate().removeAll(key); } /* JADX DEBUG: Failed to find minimal casts for resolve overloaded methods, cast all args instead method: com.google.common.collect.ListMultimap.replaceValues(java.lang.Object, java.lang.Iterable):java.util.List<V> arg types: [K, java.lang.Iterable<? extends V>] candidates: com.google.common.collect.Multimap.replaceValues(java.lang.Object, java.lang.Iterable):java.util.Collection<V> com.google.common.collect.ListMultimap.replaceValues(java.lang.Object, java.lang.Iterable):java.util.List<V> */ @CanIgnoreReturnValue public List<V> replaceValues(K key, Iterable<? extends V> values) { return delegate().replaceValues((Object) key, (Iterable) values); } }
[ "eliminater74@gmail.com" ]
eliminater74@gmail.com
d1db4f2a73b338bb4d7899c11170b610332ffeb1
355cf485e3b6233c849bc986c661ac520153cbbb
/src/main/java/br/com/hfn/integracaogoogleassitente/google/api/v1/Card.java
57dc692172e3da991d0c3e63c13661be04333e46
[]
no_license
helenofn/integracao-google-assistente
52dee5825565ab8369bfcf4ffb971ba87316601f
0b344403eb21c0c7d3e4974a661067f2674b3af4
refs/heads/main
2023-08-07T14:16:03.932105
2021-09-15T23:58:09
2021-09-15T23:58:09
406,083,263
0
0
null
null
null
null
UTF-8
Java
false
false
1,169
java
package br.com.hfn.integracaogoogleassitente.google.api.v1; import com.fasterxml.jackson.annotation.JsonProperty; /** * A basic card. * * A basic card for displaying some information, e.g. an image and/or text. */ @lombok.Data @lombok.AllArgsConstructor @lombok.NoArgsConstructor public class Card { @lombok.Getter(onMethod_ = {@JsonProperty("button")}) @lombok.Setter(onMethod_ = {@JsonProperty("button")}) private Link button; @lombok.Getter(onMethod_ = {@JsonProperty("image")}) @lombok.Setter(onMethod_ = {@JsonProperty("image")}) private Image image; @lombok.Getter(onMethod_ = {@JsonProperty("imageFill")}) @lombok.Setter(onMethod_ = {@JsonProperty("imageFill")}) private ImageFill imageFill; @lombok.Getter(onMethod_ = {@JsonProperty("subtitle")}) @lombok.Setter(onMethod_ = {@JsonProperty("subtitle")}) private String subtitle; @lombok.Getter(onMethod_ = {@JsonProperty("text")}) @lombok.Setter(onMethod_ = {@JsonProperty("text")}) private String text; @lombok.Getter(onMethod_ = {@JsonProperty("title")}) @lombok.Setter(onMethod_ = {@JsonProperty("title")}) private String title; }
[ "heleno.freitas@gmail.com" ]
heleno.freitas@gmail.com
6f8e54c2fde0606a676047017151daaec1fee0e3
11dab87301876d8bf2d00fc86490fade7c3c9086
/src/org/ramadda/plugins/incident/LocationTypeHandler.java
8f8da2548f11c3424bd4dc0c7199260707553b26
[ "Apache-2.0" ]
permissive
geodesystems/ramadda
c9af6f72fc2645f5ff76b5470edbfd7e41f2a4f7
9c279e310efda34258ea3477355c845c19097d66
refs/heads/master
2023-08-16T15:42:29.367654
2023-08-16T14:14:53
2023-08-16T14:14:53
39,629,064
16
5
Apache-2.0
2018-12-27T00:43:14
2015-07-24T11:26:13
Java
UTF-8
Java
false
false
3,877
java
/** Copyright (c) 2008-2023 Geode Systems LLC SPDX-License-Identifier: Apache-2.0 */ package org.ramadda.plugins.incident; import org.ramadda.repository.*; import org.ramadda.repository.type.*; import org.ramadda.util.HtmlUtils; import org.ramadda.util.Utils; import org.ramadda.util.geo.GeoUtils; import org.ramadda.util.geo.Place; import org.w3c.dom.*; import ucar.unidata.util.StringUtil; import java.io.File; import java.util.Date; import java.util.Hashtable; import java.util.List; /** * * */ public class LocationTypeHandler extends ExtensibleGroupTypeHandler { /** * _more_ * * @param repository _more_ * @param entryNode _more_ * * @throws Exception _more_ */ public LocationTypeHandler(Repository repository, Element entryNode) throws Exception { super(repository, entryNode); } /** * _more_ * * @param entry _more_ * * @return _more_ */ @Override public String getEntryName(Entry entry) { String name = super.getEntryName(entry); if ( !Utils.stringDefined(name)) { name = entry.getStringValue(0, ""); } // System.err.println("NAME:" + name); return name; } /** * _more_ * * @param request _more_ * @param entry _more_ * @param parent _more_ * @param newEntry _more_ * * @throws Exception _more_ */ @Override public void initializeEntryFromForm(Request request, Entry entry, Entry parent, boolean newEntry) throws Exception { super.initializeEntryFromForm(request, entry, parent, newEntry); georeferenceEntry(request, entry); } /** * _more_ * * @param request _more_ * @param entry _more_ * @param node _more_ * @param files _more_ * * @throws Exception _more_ */ @Override public void initializeEntryFromXml(Request request, Entry entry, Element node, Hashtable<String, File> files) throws Exception { initializeEntryFromXml(request, entry, node, files); georeferenceEntry(request, entry); } /** * * @param request _more_ * @param entry _more_ */ private void georeferenceEntry(Request request, Entry entry) { if (entry.isGeoreferenced()) { return; } //TODO: if the entry has a location then don't do this? String address = entry.getStringValue(0, (String) null); String city = entry.getStringValue(1, (String) null); String state = entry.getStringValue(2, (String) null); if ( !Utils.stringDefined(address)) { return; } String fullAddress = address + "," + city + "," + state; Place place = GeoUtils.getLocationFromAddress(fullAddress,null); if (place == null) { System.err.println("no geo for address:" + fullAddress); } else { System.err.println("got geo for address:" + fullAddress); entry.setLatitude(place.getLatitude()); entry.setLongitude(place.getLongitude()); } } /** * _more_ * * @param request _more_ * @param entry _more_ * * @return _more_ * * @throws Exception _more_ */ @Override public String getEntryIconUrl(Request request, Entry entry) throws Exception { double depth = entry.getDoubleValue(4, 0.0); if (depth == 0) { return getIconUrl("/incident/flag_green.png"); } if (depth <= 2) { return getIconUrl("/incident/flag_blue.png"); } return getIconUrl("/incident/flag_red.png"); } }
[ "jeff.mcwhirter@gmail.com" ]
jeff.mcwhirter@gmail.com
fad0af332472452ff280e2dc1dd7045ce9ec9680
d5d0a8352fc5025e326782f98fa2dc4771a864ec
/Exshop/src/main/java/com/swcodingschool/Exshop/service/ExshopService.java
de5e8e1608437fc73500e4354fb3b92f11c7d87b
[]
no_license
55310/java2012
73f5f663797e96406e3b8a2f2487b49cdfa25581
3b34d99a9b237414953f44a8f30748e2a36910f7
refs/heads/main
2023-03-06T17:13:16.466561
2021-02-24T07:56:38
2021-02-24T07:56:38
325,197,097
0
0
null
null
null
null
UTF-8
Java
false
false
1,038
java
package com.swcodingschool.Exshop.service; import com.swcodingschool.Exshop.dto.PageRequestDTO; import com.swcodingschool.Exshop.dto.PageResultDTO; import com.swcodingschool.Exshop.dto.ExshopDTO; import com.swcodingschool.Exshop.entity.Exshop; public interface ExshopService { Long register(ExshopDTO pnum); PageResultDTO<ExshopDTO, Exshop> getList(PageRequestDTO requestDTO); ExshopDTO read(Long pnum); default Exshop dtoToEntity(ExshopDTO dto) { Exshop entity = Exshop.builder() .pnum(dto.getPnum()) .pname(dto.getPname()) .pprice(dto.getPprice()) .pdes(dto.getPdes()) .build(); return entity; } default ExshopDTO entityToDto(Exshop entity) { ExshopDTO dto = ExshopDTO.builder() .pnum(entity.getPnum()) .pname(entity.getPname()) .pprice(entity.getPprice()) .pdes(entity.getPdes()) .build(); return dto; } }
[ "76715532+55310@users.noreply.github.com" ]
76715532+55310@users.noreply.github.com
91a2d0cbdd5ccf597309de52406370a8583e0afa
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_aea4bb9c30d8e824fdca7f645d03d49d509c63e3/ModelEditorPartListener/2_aea4bb9c30d8e824fdca7f645d03d49d509c63e3_ModelEditorPartListener_t.java
e245c97871082e8131fc42ebb6db7ee1506da187
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
1,920
java
/******************************************************************************* * Copyright (c) 2010-2012, Zoltan Ujhelyi, Abel Hegedus, Tamas Szabo, Istvan Rath and Daniel Varro * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Zoltan Ujhelyi, Abel Hegedus, Tamas Szabo - initial API and implementation *******************************************************************************/ package org.eclipse.viatra2.emf.incquery.validation.runtime; import java.util.Set; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.viatra2.emf.incquery.runtime.api.IPatternMatch; /** * The PartListener is used to observe EditorPart close actions. * * @author Tamas Szabo * */ public class ModelEditorPartListener implements IPartListener { @Override public void partActivated(IWorkbenchPart part) { } @Override public void partBroughtToTop(IWorkbenchPart part) { } @Override public void partClosed(IWorkbenchPart part) { if (part instanceof IEditorPart) { IEditorPart closedEditor = (IEditorPart) part; Set<ConstraintAdapter<IPatternMatch>> adapters = ValidationUtil.getAdapterMap().remove(closedEditor); if (adapters != null) { for (ConstraintAdapter<IPatternMatch> adapter : adapters) { adapter.dispose(); } } closedEditor.getEditorSite().getPage().removePartListener(ValidationUtil.editorPartListener); } } @Override public void partDeactivated(IWorkbenchPart part) { } @Override public void partOpened(IWorkbenchPart part) { } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
7b4781e4a72e96c252397b5a36dda9f36416764f
c89624d87836501a73b3ad7aae2d6ac6499ff343
/src/main/java/com/autobook/config/Configuration.java
ffb366c3e1b853902cd20d25a0acffca80273e00
[ "Apache-2.0" ]
permissive
xiaduobao/AirLine-BugFixer
56cec8b27b1e352dc555cca08dea3fe9e7fff154
7fb7b6e41cfedbd0a22e722bb1d1cc325a47f2e1
refs/heads/master
2020-03-10T00:29:46.937035
2018-04-16T06:46:45
2018-04-16T06:46:45
129,083,104
0
0
null
null
null
null
UTF-8
Java
false
false
673
java
package com.autobook.config; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * Created by jiabaowang on 2018/4/12. */ public class Configuration { private static Properties properties ; static { InputStream inputStream = Configuration.class.getClassLoader().getResourceAsStream("config.properties"); properties = new Properties(); try { properties.load(inputStream); } catch (IOException e) { throw new RuntimeException("加载配置出错"); } } public static String valueOf(String key){ return properties.getProperty(key); } }
[ "jiabaowang@Ctrip.com" ]
jiabaowang@Ctrip.com
d911a795b57b1d3950ea3b2a1e98f9eea758ce98
f9eb1be79bff61a30e742b7870526262df0f3de9
/build/generated/source/r/debug/com/xdandroid/hellodaemon/R.java
d043b954a1989ccc1117f2f5d2a6bc3cf5f012f4
[]
no_license
chengyiqingqing/toutiaoDemo
1951a9cba0abbcff8bca17ea3b884969fc990fef
0f5fcffd62b80f2e8689364a8a6f0d8ded1c91be
refs/heads/master
2022-12-08T18:43:14.659850
2020-08-28T11:01:08
2020-08-28T11:01:08
291,024,368
1
0
null
null
null
null
UTF-8
Java
false
false
330
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.xdandroid.hellodaemon; public final class R { public static final class string { public static final int app_name = 0x7f08002c; } }
[ "sww1@meitu.com" ]
sww1@meitu.com
5183470a6f2f981ee5ec12e3b8b97f74e7b43bf7
daf2da00f5c5000ab63697a16a2af9027bfdb521
/Extra/Security-Components/authorisation/XACML_PAP_PDP/XACML_PDP_SunXACML/src/com/sun/xacml/simplepdp/SamplePolicyBuilder.java
113dd43214315eb4596c8e935f344216251fb403
[ "Apache-2.0" ]
permissive
fed4iot/VirIoT
b4b781ca419faaf50858118b1bc8c80cea6c011a
0301a908554f31748985b82b9f310ce9b9af1f9b
refs/heads/master
2023-01-29T06:41:27.379050
2023-01-25T08:56:51
2023-01-25T08:56:51
242,765,526
12
11
NOASSERTION
2021-12-07T18:53:03
2020-02-24T15:02:23
C
UTF-8
Java
false
false
13,456
java
package com.sun.xacml.simplepdp; /* * @(#)SamplePolicyBuilder.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ import com.sun.xacml.Indenter; import com.sun.xacml.Policy; import com.sun.xacml.Rule; import com.sun.xacml.Target; import com.sun.xacml.TargetMatch; import com.sun.xacml.UnknownIdentifierException; import com.sun.xacml.attr.AnyURIAttribute; import com.sun.xacml.attr.AttributeDesignator; import com.sun.xacml.attr.AttributeValue; import com.sun.xacml.attr.StringAttribute; import com.sun.xacml.combine.CombiningAlgFactory; import com.sun.xacml.combine.OrderedPermitOverridesRuleAlg; import com.sun.xacml.combine.RuleCombiningAlgorithm; import com.sun.xacml.cond.Apply; import com.sun.xacml.cond.Function; import com.sun.xacml.cond.FunctionFactory; import com.sun.xacml.ctx.Result; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; /** * This is an example program that shows how to build and generate an XACML * Policy. This doesn't show all the available features, but it provides a * good sample of commonly used functionality. Note that there's a fair amount * of duplicate code in this class, since verbosity (in this case) makes the * code a little easier to understand. An equivalent Polict to that generated * here is found in the policy directory as generated.xml. The generated * request can be used with this policy. * * @since 1.1 * @author seth proctor */ public class SamplePolicyBuilder { /** * Simple helper routine that creates a TargetMatch instance. * * @param type the type of match * @param functionId the matching function identifier * @param designator the AttributeDesignator used in this match * @param value the AttributeValue used in this match * * @return the matching element */ public static TargetMatch createTargetMatch(int type, String functionId, AttributeDesignator designator, AttributeValue value) { try { // get the factory that handles Target functions and get an // instance of the right function FunctionFactory factory = FunctionFactory.getTargetInstance(); Function function = factory.createFunction(functionId); // create the TargetMatch return new TargetMatch(type, function, designator, value); } catch (Exception e) { // note that in this example, we should never hit this case, but // in the real world you need to worry about exceptions, especially // from the factory return null; } } /** * Creates the Target used in the Policy. This Target specifies that * the Policy applies to any example.com users who are requesting some * form of access to server.example.com. * * @return the target * * @throws URISyntaxException if there is a problem with any of the URIs */ public static Target createPolicyTarget() throws URISyntaxException { List subjects = new ArrayList(); List resources = new ArrayList(); // create the Subject section List subject = new ArrayList(); String subjectMatchId = "urn:oasis:names:tc:xacml:1.0:function:rfc822Name-match"; URI subjectDesignatorType = new URI("urn:oasis:names:tc:xacml:1.0:data-type:rfc822Name"); URI subjectDesignatorId = new URI("urn:oasis:names:tc:xacml:1.0:subject:subject-id"); AttributeDesignator subjectDesignator = new AttributeDesignator(AttributeDesignator.SUBJECT_TARGET, subjectDesignatorType, subjectDesignatorId, false); StringAttribute subjectValue = new StringAttribute("users.example.com"); subject.add(createTargetMatch(TargetMatch.SUBJECT, subjectMatchId, subjectDesignator, subjectValue)); // create the Resource section List resource = new ArrayList(); String resourceMatchId = "urn:oasis:names:tc:xacml:1.0:function:anyURI-equal"; URI resourceDesignatorType = new URI("http://www.w3.org/2001/XMLSchema#anyURI"); URI resourceDesignatorId = new URI("urn:oasis:names:tc:xacml:1.0:resource:resource-id"); AttributeDesignator resourceDesignator = new AttributeDesignator(AttributeDesignator.RESOURCE_TARGET, resourceDesignatorType, resourceDesignatorId, false); AnyURIAttribute resourceValue = new AnyURIAttribute(new URI("http://server.example.com/")); resource.add(createTargetMatch(TargetMatch.RESOURCE, resourceMatchId, resourceDesignator, resourceValue)); // put the Subject and Resource sections into their lists subjects.add(subject); resources.add(resource); // create & return the new Target return new Target(subjects, resources, null); } /** * Creates the Target used in the Condition. This Target specifies that * the Condition applies to anyone taking the action commit. * * @return the target * * @throws URISyntaxException if there is a problem with any of the URIs */ public static Target createRuleTarget() throws URISyntaxException { List actions = new ArrayList(); // create the Action section List action = new ArrayList(); String actionMatchId = "urn:oasis:names:tc:xacml:1.0:function:string-equal"; URI actionDesignatorType = new URI("http://www.w3.org/2001/XMLSchema#string"); URI actionDesignatorId = new URI("urn:oasis:names:tc:xacml:1.0:action:action-id"); AttributeDesignator actionDesignator = new AttributeDesignator(AttributeDesignator.ACTION_TARGET, actionDesignatorType, actionDesignatorId, false); StringAttribute actionValue = new StringAttribute("commit"); action.add(createTargetMatch(TargetMatch.ACTION, actionMatchId, actionDesignator, actionValue)); // put the Action section in the Actions list actions.add(action); // create & return the new Target return new Target(null, null, actions); } /** * Creates the Condition used in the Rule. Note that a Condition is just a * special kind of Apply. * * @return the condition * * @throws URISyntaxException if there is a problem with any of the URIs */ public static Apply createRuleCondition() throws URISyntaxException { List conditionArgs = new ArrayList(); // get the function that the condition uses FunctionFactory factory = FunctionFactory.getConditionInstance(); Function conditionFunction = null; try { conditionFunction = factory.createFunction("urn:oasis:names:tc:xacml:1.0:function:" + "string-equal"); } catch (Exception e) { // see comment in createTargetMatch() return null; } // now create the apply section that gets the designator value List applyArgs = new ArrayList(); factory = FunctionFactory.getGeneralInstance(); Function applyFunction = null; try { applyFunction = factory.createFunction("urn:oasis:names:tc:xacml:1.0:function:" + "string-one-and-only"); } catch (Exception e) { // see comment in createTargetMatch() return null; } URI designatorType = new URI("http://www.w3.org/2001/XMLSchema#string"); URI designatorId = new URI("group"); URI designatorIssuer = new URI("admin@users.example.com"); AttributeDesignator designator = new AttributeDesignator(AttributeDesignator.SUBJECT_TARGET, designatorType, designatorId, false, designatorIssuer); applyArgs.add(designator); Apply apply = new Apply(applyFunction, applyArgs, false); // add the new apply element to the list of inputs to the condition conditionArgs.add(apply); // create an AttributeValue and add it to the input list StringAttribute value = new StringAttribute("developers"); conditionArgs.add(value); // finally, create & return our Condition return new Apply(conditionFunction, conditionArgs, true); } /** * Creates the Rule used in the Policy. * * @return the rule * * @throws URISyntaxException if there is a problem with any of the URIs */ public static Rule createRule() throws URISyntaxException { // define the identifier for the rule URI ruleId = new URI("CommitRule"); // define the effect for the Rule int effect = Result.DECISION_PERMIT; // get the Target for the rule Target target = createRuleTarget(); // get the Condition for the rule Apply condition = createRuleCondition(); return new Rule(ruleId, effect, null, target, condition); } /** * Command-line routine that bundles together all the information needed * to create a Policy and then encodes the Policy, printing to standard * out. */ public static void main(String [] args) throws Exception { // define the identifier for the policy URI policyId = new URI("GeneratedPolicy"); // get the combining algorithm for the policy URI combiningAlgId = new URI(OrderedPermitOverridesRuleAlg.algId); CombiningAlgFactory factory = CombiningAlgFactory.getInstance(); RuleCombiningAlgorithm combiningAlg = (RuleCombiningAlgorithm)(factory.createAlgorithm(combiningAlgId)); // add a description for the policy String description = "This policy applies to any accounts at users.example.com " + "accessing server.example.com. The one Rule applies to the " + "specific action of doing a CVS commit, but other Rules could " + "be defined that handled other actions. In this case, only " + "certain groups of people are allowed to commit. There is a " + "final fall-through rule that always returns Deny."; // create the target for the policy Target policyTarget = createPolicyTarget(); // create the commit rule Rule commitRule = createRule(); // create the default, fall-through rule Rule defaultRule = new Rule(new URI("FinalRule"), Result.DECISION_DENY, null, null, null); // create a list for the rules and add our rules in order List ruleList = new ArrayList(); ruleList.add(commitRule); ruleList.add(defaultRule); // create the policy Policy policy = new Policy(policyId, combiningAlg, description, policyTarget, ruleList); // finally, encode the policy and print it to standard out policy.encode(System.out, new Indenter()); } }
[ "jasanchez@odins.es" ]
jasanchez@odins.es
98f8b73985ea1e3c5d1dc607c771a8692d0e8cf3
96850c7e51bbda9d35cbcf045f09f179c942a0d4
/chapter6-multiple-database-config/src/main/java/com/multi/database/dao/entity/SalaryPK.java
c96cf13db9be42716d1d9fa397da289037d1395f
[ "MIT" ]
permissive
kodluyoruz-java-101-31102020-ders-proje/chapter6-multiple-database-config-sample
362c0135ef6547bbaf2be157597054fd37df5af8
fc1d20a8e0b6bd22b72b68c273e104ef5fe2d87f
refs/heads/main
2023-01-31T18:23:59.969743
2020-12-13T14:09:03
2020-12-13T14:09:03
321,079,573
1
0
null
null
null
null
UTF-8
Java
false
false
1,474
java
package com.multi.database.dao.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Embeddable public class SalaryPK implements Serializable{ private static final long serialVersionUID = -217841440401282648L; @Column(name = "emp_no") private Long empNo; @Column(name = "from_date") @Temporal(TemporalType.DATE) private Date fromDate; public Long getEmpNo() { return empNo; } public void setEmpNo(Long empNo) { this.empNo = empNo; } public Date getFromDate() { return fromDate; } public void setFromDate(Date fromDate) { this.fromDate = fromDate; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((empNo == null) ? 0 : empNo.hashCode()); result = prime * result + ((fromDate == null) ? 0 : fromDate.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SalaryPK other = (SalaryPK) obj; if (empNo == null) { if (other.empNo != null) return false; } else if (!empNo.equals(other.empNo)) return false; if (fromDate == null) { if (other.fromDate != null) return false; } else if (!fromDate.equals(other.fromDate)) return false; return true; } }
[ "batuhan.duzgun@sahibinden.com" ]
batuhan.duzgun@sahibinden.com
eb4095cc0663ec6355cb08f4fae636075a80ca3d
6af6feb0c20984a9358a37540f79096de3018115
/core/src/main/java/com/alibaba/alink/operator/common/dataproc/vector/VectorMinMaxScalerModelInfoBatchOp.java
0f26b85d1b7d98c09ddf6f1f6091f448bc4913a5
[ "Apache-2.0" ]
permissive
Vipamp/Alink
613c833d67e81ad688abd6d631b6297640e3b2a3
2b5d0ae81c7cf90fe3b68cc5ba39d4b6c9b57ef8
refs/heads/mylearn
2021-07-21T13:45:27.206365
2020-10-29T09:44:41
2020-10-29T09:44:41
224,653,808
0
0
Apache-2.0
2020-07-14T05:07:16
2019-11-28T12:56:51
Java
UTF-8
Java
false
false
706
java
package com.alibaba.alink.operator.common.dataproc.vector; import com.alibaba.alink.common.lazy.ExtractModelInfoBatchOp; import org.apache.flink.ml.api.misc.param.Params; import org.apache.flink.types.Row; import java.util.List; public class VectorMinMaxScalerModelInfoBatchOp extends ExtractModelInfoBatchOp<VectorMinMaxScalerModelInfo, VectorMinMaxScalerModelInfoBatchOp> { public VectorMinMaxScalerModelInfoBatchOp() { this(null); } public VectorMinMaxScalerModelInfoBatchOp(Params params) { super(params); } @Override protected VectorMinMaxScalerModelInfo createModelInfo(List<Row> rows) { return new VectorMinMaxScalerModelInfo(rows); } }
[ "hongfan.hf@alibaba-inc.com" ]
hongfan.hf@alibaba-inc.com
aca01bcda20fb76adb02fcf40ef169743014d5de
1b942a9ab261634824c0ecf4c334730e6fa18983
/src/main/java/Listener/MyContextListener.java
d3d100277da9ef8511a38205f8cae438c469f7b5
[]
no_license
zaqmk55/eshop
e00c55bdfefd4c376feba9d07d49c8c66863afc6
7289363cc03d20943dfe3320b35936e64b9f17f5
refs/heads/master
2020-03-31T21:01:30.273496
2018-10-11T09:09:35
2018-10-11T09:09:35
152,564,307
0
0
null
null
null
null
UTF-8
Java
false
false
1,563
java
package Listener; /** * Created by xiaohuang on 2018/9/28. */ import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import java.io.*; @WebListener() public class MyContextListener implements ServletContextListener{ public void contextInitialized(ServletContextEvent sce) { Integer online = 0; sce.getServletContext().setAttribute("online",online); File file = new File("D:\\history.txt"); try { Reader reader = new FileReader(file); int history=reader.read(); sce.getServletContext().setAttribute("history",history); reader.close(); } catch (IOException e) { e.printStackTrace(); } /* This method is called when the servlet context is initialized(when the Web application is deployed). You can initialize servlet context related data here. */ } public void contextDestroyed(ServletContextEvent sce) { /* This method is invoked when the Servlet Context (the Web application) is undeployed or Application Server shuts down. */ Object history = sce.getServletContext().getAttribute("history"); File file=new File("D:\\history.txt"); try { Writer writer = new FileWriter(file); writer.write(history.toString()); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
[ "a519638047@qq.com" ]
a519638047@qq.com
f53d7236ed1bd0f859f0b0df28f3fafd8b484e10
4cc3d9ea911532c9899d119babd85aa084e8c267
/person-parent/person-domain/src/main/java/com/xzhang/model/WdBuyer.java
cf6aef3b5abebcbbe2080b975c2724a9551489b5
[]
no_license
chouxiang/mybatis-test
421584ceacd0f641568c9772fbf8877502b5aab9
0e927bfda2aa7ab645a3111ba39e28a9246bdbe3
refs/heads/master
2021-01-24T09:37:21.450657
2016-11-12T09:56:51
2016-11-12T09:56:51
69,308,127
0
2
null
null
null
null
UTF-8
Java
false
false
1,881
java
package com.xzhang.model; import java.io.Serializable; import java.util.Date; /** * @Title: WdBuyer.java * @Package: com.xzhang.model * @Description: 登录验证表:wd_buyer * ******************************************************** * Date Author Changes * 2016年10月20日 zx 创建 ******************************************************** */ public class WdBuyer implements Serializable { private static final long serialVersionUID = 1L; /**是否禁止登录:0禁用*/ public static final String STATUS_NO = "0"; /**是否禁止登录:1启用*/ public static final String STATUS_YES = "1"; private String id; private String firstname;//姓名 private String mobile;//手机号 private String password;//密码(密码初次添加的时候是发送随机的8位数字,并通过MD5加密保存) private Date createtime;//创建时间 private String email;//邮箱必填,并通过数据字典加载后面的@qq.com、@163.com等等 private String status = WdBuyer.STATUS_YES;//状态 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getCreatetime() { return createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
[ "15755363350@139.com" ]
15755363350@139.com
65ed9794fde07f226e08d8afed0b39ee865e73be
14ae3aa0bd3fa281b2097f6c8627a3ed1d2f7633
/Codes/Python/csm/Auto.java
768205228bd49466fddc87849857a3e5fe7b9de8
[]
no_license
ashutoshe/Coding
c8d4610629b2b3af9a6596247ee8365fab2a5f4a
f67d1dfe2f4f4fea1d25bcce7b50b29bc4c7accd
refs/heads/master
2021-05-11T01:54:04.972900
2019-11-09T10:53:21
2019-11-09T10:53:21
118,340,798
0
0
null
null
null
null
UTF-8
Java
false
false
841
java
import java.util.*; import java.io.*; class Auto { public static void main(String[]args) throws IOException { int i,m,M,j,n; double num[]; double sum=0,sim,sig,z; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter number of elements"); n=Integer.parseInt(br.readLine()); System.out.println("Enter values of i and m"); i=Integer.parseInt(br.readLine()); m=Integer.parseInt(br.readLine()); M=((n-i)/m)-1; System.out.println("M="+M); num=new double[n]; for(j=0;j<n;j++) //num[j]=((int)(Math.random()*100+1))/100.0; num[j]=Double.parseDouble(br.readLine()); for(j=0;j<=M;j++) sum+=num[i-1+j*m]*num[i-1+(j+1)*m]; sim=(sum/(M+1.0))-0.25; sig=Math.sqrt(13.0*M+7.0)/(12.0*(M+1.0)); z=sim/sig; System.out.println("sim="+sim+" sig="+sig+" z="+z); } }
[ "ashutosheeeee@gmail.com" ]
ashutosheeeee@gmail.com
3304781efef533d6b0238b5c32d3a0e117e6be71
3e570cf2cf76daa78d48a3b54c4f185ac18e868d
/src/main/java/com/example/demo/domain/object/User.java
db960761efe248ed215c979e1b0257b2a4b8cd11
[]
no_license
zkousei/spring-boot-restAPI-sample
6cfd62cdec75bc8772ce4dddc5c04bee5f446d87
87188a53e7b85bd2db2adfb6e5fd03063ef9a25d
refs/heads/master
2022-11-21T14:03:34.358471
2020-07-19T15:15:05
2020-07-19T15:15:05
279,134,339
0
0
null
null
null
null
UTF-8
Java
false
false
169
java
package com.example.demo.domain.object; import lombok.Data; @Data public class User { private String userId; private String password; private String authority; }
[ "k.izawa1994@gmail.com" ]
k.izawa1994@gmail.com
5e6cdbe447bf1cee1814b514878a373d4447785c
ded54ca8ce115e79d7b36269234c0817199a5f75
/server/xml/src/main/java/net/ramify/model/event/xml/XmlHistoricEventProvider.java
3fd86fd2b95024904f5ff794b3e5e627968d4609
[]
no_license
ollierob/Ramify
a363014b8947da881963208bf4c5b348d4da98ef
ea4e7c5edb5ec2fc1b96e69ef508ef73e9eb87b8
refs/heads/master
2022-12-10T21:52:52.365600
2021-12-21T17:20:41
2021-12-21T17:20:41
127,625,132
0
0
null
2022-12-09T07:17:44
2018-04-01T11:59:09
Java
UTF-8
Java
false
false
3,886
java
package net.ramify.model.event.xml; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import net.ramify.model.AbstractMappedProvider; import net.ramify.model.date.DateRange; import net.ramify.model.event.EventId; import net.ramify.model.event.historic.HistoricEvent; import net.ramify.model.event.historic.HistoricEventProvider; import net.ramify.model.event.xml.historic.XmlHistoricEvents; import net.ramify.model.place.Place; import net.ramify.model.record.xml.RecordContext; import net.ramify.utils.file.FileTraverseUtils; import net.ramify.utils.file.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlTransient; import java.io.File; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; @XmlTransient class XmlHistoricEventProvider extends AbstractMappedProvider<EventId, HistoricEvent> implements HistoricEventProvider { private static final Logger logger = LoggerFactory.getLogger(XmlHistoricEventProvider.class); XmlHistoricEventProvider(final Map<EventId, HistoricEvent> map) { super(map); } void addAll(final Collection<HistoricEvent> events) { events.forEach(event -> this.put(event.eventId(), event)); } @Nonnull @Override public Set<HistoricEvent> global(final DateRange dateRange) { return this.values() .stream() .filter(HistoricEvent::isGlobal) .filter(event -> event.date().intersects(dateRange)) .collect(Collectors.toSet()); } @Nonnull @Override public Set<HistoricEvent> within(final Place place, final DateRange date) { return this.values() .stream() //.filter(event -> event.region().isParentOf(place)) //FIXME .filter(event -> event.date().intersects(date)) .collect(Collectors.toSet()); } HistoricEventProvider immutableCopy() { return new XmlHistoricEventProvider(this.immutableMap()); } static HistoricEventProvider readRecordsInDirectory( final JAXBContext jaxbContext, final File root, final RecordContext recordContext) throws JAXBException { final var provider = new XmlHistoricEventProvider(Maps.newHashMap()); final var unmarshaller = jaxbContext.createUnmarshaller(); FileTraverseUtils.traverseSubdirectories( root, file -> file.getName().endsWith(".xml") && file.getPath().contains("event"), file -> readRecordsInFile(unmarshaller, file, provider, recordContext)); logger.info("Loaded {} record sets from {}.", provider.size(), root); return provider.immutableCopy(); } private static void readRecordsInFile(final Unmarshaller unmarshaller, final File file, final XmlHistoricEventProvider eventProvider, final RecordContext context) { FileUtils.checkReadableFile(file); Preconditions.checkArgument(file.getName().endsWith(".xml"), "Not an XML file: %s", file); try { logger.info("Reading events from file {}", file); final var unmarshalled = unmarshaller.unmarshal(file); if (!(unmarshalled instanceof XmlHistoricEvents)) return; final var events = (XmlHistoricEvents) unmarshalled; eventProvider.addAll(events.build(context)); } catch (final JAXBException jex) { logger.warn("Could not read events in file " + file + ": " + jex.getMessage()); } catch (final Exception ex) { throw new RuntimeException("Error reading events in file " + file, ex); } } }
[ "oliver.robertshaw@mahifx.com" ]
oliver.robertshaw@mahifx.com
acc74ee88b28e3de94174e8ba62c45d705881480
2a00e8f8c3012b6d59e2d30b4e0185a63caef582
/agent/java/com/chenjw/knife/agent/event/Event.java
e458d624ea34f784d911e40312d3c9258279e767
[]
no_license
donniepeng/knife
f874e4d76532e366ce25e9e428c09988ace65113
e894fe065b6a8679debff0d4f1a485c6db672499
refs/heads/master
2023-09-04T22:38:10.850533
2021-11-23T03:52:19
2021-11-23T03:52:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
77
java
package com.chenjw.knife.agent.event; public abstract class Event { }
[ "chenjw@ubuntu.(none)" ]
chenjw@ubuntu.(none)
95e0d88b7a78a0fe5c67fac67e298a699aec8ed8
4b4b4ef9c39f949bcd8969dadd4f660a67f74b2c
/src/test/java/io/netty/incubator/codec/quic/QuicChannelConnectTest.java
cb1084f51577be90803955dc3840994bc61c0858
[ "Apache-2.0" ]
permissive
kachayev/netty-incubator-codec-quic
3c7401fcf52d76b447bd9e8e1856c51d628e32b7
21fead3cf1a8181830f1c2424066ebc6d0e1ab32
refs/heads/main
2023-01-13T21:32:44.672230
2020-11-27T14:57:54
2020-11-27T14:57:54
311,492,790
0
0
Apache-2.0
2020-11-09T23:39:55
2020-11-09T23:39:55
null
UTF-8
Java
false
false
8,083
java
/* * Copyright 2020 The Netty Project * * The Netty Project 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 io.netty.incubator.codec.quic; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelOption; import io.netty.channel.ConnectTimeoutException; import io.netty.util.concurrent.Future; import org.hamcrest.CoreMatchers; import org.junit.Test; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.nio.channels.AlreadyConnectedException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class QuicChannelConnectTest { @Test public void testConnectTimeout() throws Throwable { // Bind to something so we can use the port to connect too and so can ensure we really timeout. DatagramSocket socket = new DatagramSocket(); Channel channel = QuicTestUtils.newClient(); try { ChannelStateVerifyHandler verifyHandler = new ChannelStateVerifyHandler(); Future<QuicChannel> future = QuicChannel.newBootstrap(channel) .handler(verifyHandler) .streamHandler(new ChannelInboundHandlerAdapter()) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10) .remoteAddress(socket.getLocalSocketAddress()) .connect(); Throwable cause = future.await().cause(); assertThat(cause, CoreMatchers.instanceOf(ConnectTimeoutException.class)); verifyHandler.assertState(); } finally { socket.close(); // Close the parent Datagram channel as well. channel.close().sync(); } } @Test public void testConnectAlreadyConnected() throws Throwable { ChannelActiveVerifyHandler serverQuicChannelHandler = new ChannelActiveVerifyHandler(); ChannelStateVerifyHandler serverQuicStreamHandler = new ChannelStateVerifyHandler(); Channel server = QuicTestUtils.newServer(serverQuicChannelHandler, serverQuicStreamHandler); InetSocketAddress address = (InetSocketAddress) server.localAddress(); Channel channel = QuicTestUtils.newClient(); try { ChannelActiveVerifyHandler clientQuicChannelHandler = new ChannelActiveVerifyHandler(); QuicChannel quicChannel = QuicChannel.newBootstrap(channel) .handler(clientQuicChannelHandler) .streamHandler(new ChannelInboundHandlerAdapter()) .remoteAddress(address) .connect() .get(); // Try to connect again ChannelFuture connectFuture = quicChannel.connect(QuicConnectionAddress.random()); Throwable cause = connectFuture.await().cause(); assertThat(cause, CoreMatchers.instanceOf(AlreadyConnectedException.class)); assertTrue(quicChannel.close().await().isSuccess()); ChannelFuture closeFuture = quicChannel.closeFuture().await(); assertTrue(closeFuture.isSuccess()); clientQuicChannelHandler.assertState(); } finally { serverQuicChannelHandler.assertState(); serverQuicStreamHandler.assertState(); server.close().sync(); // Close the parent Datagram channel as well. channel.close().sync(); } } @Test public void testConnectWithoutTokenValidation() throws Throwable { ChannelActiveVerifyHandler serverQuicChannelHandler = new ChannelActiveVerifyHandler(); ChannelStateVerifyHandler serverQuicStreamHandler = new ChannelStateVerifyHandler(); Channel server = QuicTestUtils.newServer(new QuicTokenHandler() { // Disable token validation @Override public boolean writeToken(ByteBuf out, ByteBuf dcid, InetSocketAddress address) { return false; } @Override public int validateToken(ByteBuf token, InetSocketAddress address) { return 0; } @Override public int maxTokenLength() { return 0; } }, serverQuicChannelHandler, serverQuicStreamHandler); InetSocketAddress address = (InetSocketAddress) server.localAddress(); Channel channel = QuicTestUtils.newClient(); try { ChannelActiveVerifyHandler clientQuicChannelHandler = new ChannelActiveVerifyHandler(); QuicChannel quicChannel = QuicChannel.newBootstrap(channel) .handler(clientQuicChannelHandler) .streamHandler(new ChannelInboundHandlerAdapter()) .remoteAddress(address) .connect() .get(); assertTrue(quicChannel.close().await().isSuccess()); ChannelFuture closeFuture = quicChannel.closeFuture().await(); assertTrue(closeFuture.isSuccess()); clientQuicChannelHandler.assertState(); } finally { serverQuicChannelHandler.assertState(); serverQuicStreamHandler.assertState(); server.close().sync(); // Close the parent Datagram channel as well. channel.close().sync(); } } private static final class ChannelStateVerifyHandler extends ChannelInboundHandlerAdapter { private volatile Throwable cause; @Override public void channelActive(ChannelHandlerContext ctx) { ctx.fireChannelActive(); fail(); } @Override public void channelInactive(ChannelHandlerContext ctx) { ctx.fireChannelInactive(); fail(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { this.cause = cause; } void assertState() throws Throwable { if (cause != null) { throw cause; } } } private static final class ChannelActiveVerifyHandler extends ChannelInboundHandlerAdapter { private final BlockingQueue<Integer> states = new LinkedBlockingQueue<>(); @Override public void channelRegistered(ChannelHandlerContext ctx) { ctx.fireChannelRegistered(); states.add(0); } @Override public void channelUnregistered(ChannelHandlerContext ctx) { ctx.fireChannelUnregistered(); states.add(3); } @Override public void channelActive(ChannelHandlerContext ctx) { ctx.fireChannelActive(); states.add(1); } @Override public void channelInactive(ChannelHandlerContext ctx) { ctx.fireChannelInactive(); states.add(2); } void assertState() throws Throwable { // Check that we receive the different events in the correct order. for (long i = 0; i < 4; i++) { assertEquals(i, (int) states.take()); } assertNull(states.poll()); } } }
[ "noreply@github.com" ]
kachayev.noreply@github.com
354505f8bef258ed59a2d8f98b7873da051a7433
dadabe1a6c0954db5696b14e953e80706f5013e9
/core/src/main/java/org/drdevelopment/webtool/servlet/AssetsServlet.java
100dff0ddec0d6b495b8974fd13c0a9bf1e2bbdd
[ "MIT" ]
permissive
drdevelopment/WebTool
71a72ffdfc80e0e08a7d358b275e413c4424e115
c7f7380c70f517470f75e6dd4361a7976d237d62
refs/heads/master
2020-06-14T13:49:44.689343
2015-10-15T19:38:55
2015-10-15T19:38:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,528
java
package org.drdevelopment.webtool.servlet; import java.io.File; import java.io.IOException; import java.util.List; import javax.activation.MimetypesFileTypeMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.drdevelopment.webtool.repository.UsersRepository; import org.drdevelopment.webtool.template.TemplateEngine; import org.drdevelopment.webtool.util.FileUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AssetsServlet extends HttpServlet { private static final Logger LOGGER = LoggerFactory.getLogger(AssetsServlet.class); private String folder; private TemplateEngine templateEngine; private List<String> dynamicStaticPages; private Boolean hasUsersInSystem = null; public AssetsServlet(String folder) { super(); this.folder = folder; } public AssetsServlet(String folder, List<String> dynamicStaticPages) { super(); this.folder = folder; this.dynamicStaticPages = dynamicStaticPages; } public AssetsServlet(String folder, TemplateEngine templateEngine, List<String> dynamicStaticPages) { super(); this.folder = folder; this.templateEngine = templateEngine; this.dynamicStaticPages = dynamicStaticPages; } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setStatus(HttpServletResponse.SC_OK); String uri = withoutParameters(request.getRequestURI()); // LOGGER.info(uri); if (!hasUsers()) { LOGGER.debug("No users in the system, so, first create a new user."); response.sendRedirect("/setup/index.html"); return; } String param = getDynamicPage(uri); if (param != null) { uri = uri.substring(0, uri.length() - param.length()) + "/"; } String fileExtension = getFileExtension(uri); if (fileExtension == null || fileExtension.isEmpty()) { String newUri = ""; if (uri.endsWith("/") || uri.endsWith("\\")) { newUri = uri + "index.html"; } else { newUri = uri + "/index.html"; } LOGGER.warn("Could not find extension in uri {} and will be redirected to {}.", uri, newUri); uri = newUri; fileExtension = getFileExtension(uri); if (param == null) { response.sendRedirect(request.getContextPath() + uri); return; } } String fullUri = getFullUri(folder, uri); String contentType = getContentType(fileExtension); response.setContentType(contentType + "; charset=utf-8"); // LOGGER.debug("Request uri is {} and converted to {}.", uri, fullUri); if (FileExtenstionMediaType.IMAGE.isMediaType(fileExtension)) { ImageServlet.getImage(request, response, folder); } else if (isTemplateText(fileExtension)) { readTemplate(response, fullUri, param); } else if (isReadableText(fileExtension)) { readText(response, fullUri, param); } else if (isBinary(fileExtension)) { readBinary(response, fullUri); } else { LOGGER.error("Could not find resource uri {} which is mapped to file {}.", uri, fullUri); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } private String getDynamicPage(String uri) { String param = null; if (dynamicStaticPages != null) { for (String dynamicStaticPage : dynamicStaticPages) { if (uri.toLowerCase().startsWith(dynamicStaticPage.toLowerCase()) && !uri.toLowerCase().endsWith("index.html")) { param = uri.substring(dynamicStaticPage.length()); } } } return param; } private void readBinary(HttpServletResponse response, String uri) { try { if (FileUtil.isResourceExists(uri)) { response.getOutputStream().write(FileUtil.readBytesFromResource(uri)); } else if (FileUtil.isFileExists(uri)) { response.getOutputStream().write(FileUtil.readBytes(uri)); } else { LOGGER.error("Can not find file or resource with uri {}.", uri); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } catch(IOException e) { LOGGER.debug("Could not find resource with uri {}", uri); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } private void readText(HttpServletResponse response, String uri, String param) { // check if there is a template. If so, parse this one first, else try to locate the none-template. try { String source = readTemplate(response, uri, param); // + ".template"); if (source != null) { response.getWriter().println(source); } else { if (FileUtil.isResourceExists(uri)) { response.getWriter().println(FileUtil.readLinesWithCarriageReturnFromResource(uri)); } else if (FileUtil.isFileExists(uri)) { response.getWriter().println(FileUtil.readFile(uri)); } else { LOGGER.error("Can not find file or resource with uri {}.", uri); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } } catch(IOException e) { LOGGER.debug("Could not find resource with uri {}", uri); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } private String readTemplate(HttpServletResponse response, String uri, String param) { String source = null; if (templateEngine != null) { source = templateEngine.get(uri, param); } return source; } private static String getFullUri(String folder, String uri) { String osUri = null; String osFolder = null; if (File.separatorChar == '\\') { osUri = uri.replace("/", File.separator); osFolder = folder.replace("/", File.separator); } else { osUri = uri.replace("\\", File.separator); osFolder = folder.replace("\\", File.separator); } String newUrl = osFolder + (osUri != null && (osUri.startsWith(File.separator)) ? "" : File.separator) + osUri; return newUrl; } private static String withoutParameters(String uri) { if (uri == null || uri.isEmpty()) { return ""; } else { String newUri = uri; int posDotComma = newUri.indexOf(';'); if (posDotComma > -1) { newUri = newUri.substring(0, posDotComma); } int posQuestionMark = newUri.indexOf('?'); if (posQuestionMark > -1) { newUri = newUri.substring(0, posQuestionMark); } int posQuestionHash = newUri.indexOf('#'); if (posQuestionHash > -1) { newUri = newUri.substring(0, posQuestionHash); } return newUri.trim(); } } private String getFileExtension(String uri) { if (uri != null && !uri.isEmpty()) { int pos = uri.lastIndexOf('.'); if (pos >= 0) { return uri.substring(pos); } } return null; } private static boolean isTemplateText(String fileExtension) { return FileExtenstionMediaType.TEMPLATE.isMediaType(fileExtension); } private static boolean isReadableText(String fileExtension) { return FileExtenstionMediaType.JAVASCRIPT.isMediaType(fileExtension) || FileExtenstionMediaType.HTML.isMediaType(fileExtension) || FileExtenstionMediaType.CSS.isMediaType(fileExtension); } private static boolean isBinary(String fileExtension) { return FileExtenstionMediaType.TTF.isMediaType(fileExtension) || FileExtenstionMediaType.WOFF.isMediaType(fileExtension); } private static String getContentType(String fileExtension) { String contentType = null; if (FileExtenstionMediaType.JAVASCRIPT.isMediaType(fileExtension)) { contentType = "application/javascript"; } else if (FileExtenstionMediaType.CSS.isMediaType(fileExtension)) { contentType = "text/css"; } else if (FileExtenstionMediaType.HTML.isMediaType(fileExtension)) { contentType = "text/html"; } else if (FileExtenstionMediaType.JSON.isMediaType(fileExtension)) { contentType = "application/json"; } else if (FileExtenstionMediaType.WOFF.isMediaType(fileExtension)) { contentType = "application/font-woff2"; } else if (FileExtenstionMediaType.TTF.isMediaType(fileExtension)) { contentType = "application/x-font-ttf"; } else if (FileExtenstionMediaType.EOT.isMediaType(fileExtension)) { contentType = "application/vnd.ms-fontobject"; } else { contentType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(fileExtension); } if (contentType == null || contentType.isEmpty()) { LOGGER.error("Content type for file extension {} could not be defined.", fileExtension); } return contentType; } private boolean hasUsers() { if (hasUsersInSystem == null || !hasUsersInSystem) { hasUsersInSystem = UsersRepository.getUsers().size() > 0; } return hasUsersInSystem; } }
[ "david.righart@gmail.com" ]
david.righart@gmail.com
c16d6adfd8227551e5ed5c82e9164ffe68626ff1
32b4f3b4f15232f82045d2e1d9277bd117228921
/warehouse-commons/src/main/java/com/hys/commons/http/RequestUtil.java
7222afc756aa7c77256ad39aa8ef64f070c55fd4
[]
no_license
lifeng198701/warehouse
3964f4c660c123ef2d7d74af7cdb71b3f65d823c
06f979f5da216d3202a5be6f0afbdff428bfb297
refs/heads/master
2020-04-08T19:58:02.810756
2018-08-31T03:43:22
2018-08-31T03:43:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,236
java
package com.hys.commons.http; import javax.servlet.ServletRequest; import com.hys.commons.string.StringUtil; /** * 取参数,并自动转成基本数据类型如boolean * */ public class RequestUtil { /** * 获取页面输入的String类型参数 * * @param request * ServletRequest的实例 * @param name * 参数名字 * @param defaults * 设定的默认值 * @return String型的输入参数 */ public static String getStringParameter(ServletRequest request, String name, String defaults) { return getStringParameter(request, name, defaults, true); } /** * 获取页面输入的String类型参数 * * @param request * ServletRequest的实例 * @param name * 参数名字 * @param defaults * 设定的默认值 * @param decode * 是否需要解码&#xxx;这种编码 * @return String型的输入参数 */ public static String getStringParameter(ServletRequest request, String name, String defaults, boolean decode) { String str = request.getParameter(name); if (decode) { // 解码 str = StringUtil.decodeNetUnicode(str); } return StringUtil.convertString(str, defaults); } /** * 获取页面输入的int类型参数 * * @param request * ServletRequest的实例 * @param name * 参数名字 * @param defaults * 设定的默认值 * @return int型的输入参数 */ public static int getIntParameter(ServletRequest request, String name, int defaults) { return StringUtil.convertInt(request.getParameter(name), defaults); } /** * 获取页面输入的int类型参数,若无该输入参数,则返回0 * * @param request * ServletRequest的实例 * @param name * 参数名字 * @return int型的输入参数 */ public static int getIntParameter(ServletRequest request, String name) { return getIntParameter(request, name, 0); } /** * 获取页面输入的long类型参数 * * @param request * ServletRequest的实例 * @param name * 参数名字 * @param defaults * 设定的默认值 * @return long型的输入参数 */ public static long getLongParameter(ServletRequest request, String name, long defaults) { return StringUtil.convertLong(request.getParameter(name), defaults); } /** * 获取页面输入的long类型参数,若无该输入参数,则返回0 * * @param request * ServletRequest的实例 * @param name * 参数名字 * @return long型的输入参数 */ public static long getLongParameter(ServletRequest request, String name) { return getLongParameter(request, name, 0); } /** * 获取页面输入的double类型参数 * * @param request * ServletRequest的实例 * @param name * 参数名字 * @param defaults * 设定的默认值 * @return double型的输入参数 */ public static double getDoubleParameter(ServletRequest request, String name, double defaults) { return StringUtil.convertDouble(request.getParameter(name), defaults); } /** * 获取页面输入的double类型参数,若无该参数,则返回0.0 * * @param request * ServletRequest的实例 * @param name * 参数名字 * @return long型的输入参数 */ public static double getDoubleParameter(ServletRequest request, String name) { return getDoubleParameter(request, name, 0.0); } /** * 获取页面输入的short类型参数 * * @param request * ServletRequest的实例 * @param name * 参数名字 * @param defaults * 设定的默认值 * @return short型的输入参数 */ public static short getShortParameter(ServletRequest request, String name, short defaults) { return StringUtil.convertShort(request.getParameter(name), defaults); } /** * 获取页面输入的short类型参数,若无该参数,则返回0 * * @param request * ServletRequest的实例 * @param name * 参数名字 * @return short型的输入参数 */ public static short getShortParameter(ServletRequest request, String name) { return getShortParameter(request, name, (short) 0); } /** * 获取页面输入的float类型参数 * * @param request * ServletRequest的实例 * @param name * 参数名字 * @param defaults * 设定的默认值 * @return float型的输入参数 */ public static float getFloatParameter(ServletRequest request, String name, float defaults) { return StringUtil.convertFloat(request.getParameter(name), defaults); } /** * 获取页面输入的float类型参数,若无该参数,则返回0.0 * * @param request * ServletRequest的实例 * @param name * 参数名字 * @return long型的输入参数 */ public static float getFloatParameter(ServletRequest request, String name) { return getFloatParameter(request, name, (float) 0.0); } /** * 获取boolean 类型的参数 * * @param request * @param name * @param defaults * @return boolean */ public static boolean getBooleanParameter(ServletRequest request, String name, boolean defaults) { return StringUtil.convertBoolean(request.getParameter(name), defaults); } /** * 获取boolean 类型的参数,默认值为false * * @param request * @param name * @return boolean */ public static boolean getBooleanParameter(ServletRequest request, String name) { return getBooleanParameter(request, name, false); } }
[ "2851823541@qq.com" ]
2851823541@qq.com
f5006d6a48fb0a942f78dfac077d9794df83c07a
04d69e746ca8e9c7b5c2b9bd3200196e391be3a1
/common/src/main/java/io/github/flemmli97/tenshilib/client/AnimationManager.java
9ceed17f3ad1326619259023a7a02f965c38d4b0
[]
no_license
Flemmli97/TenshiLib
5aed2a9c620fc1124c9093f612523615724d0f38
d7218b5b0fd5f40941af21033e7216466603add6
refs/heads/1.19
2023-09-05T22:31:17.829124
2023-02-15T12:07:46
2023-02-15T12:07:46
160,566,792
0
2
null
2022-11-05T05:18:30
2018-12-05T19:17:49
Java
UTF-8
Java
false
false
2,221
java
package io.github.flemmli97.tenshilib.client; import com.google.gson.Gson; import com.google.gson.JsonObject; import io.github.flemmli97.tenshilib.client.model.BlockBenchAnimations; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.server.packs.resources.ResourceManagerReloadListener; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; /** * Stores BlockBenchAnimations. The files are read under assets/<modid>/animation/entity and assigned the * id modid:filename without ".json" * Example: an animation ./assets/foo/animation/entity/bar.json has the id foo:bar */ public class AnimationManager implements ResourceManagerReloadListener { private static final Gson gson = new Gson(); private static final AnimationManager instance = new AnimationManager(); public static AnimationManager getInstance() { return instance; } private final Map<ResourceLocation, BlockBenchAnimations> animations = new HashMap<>(); @Override public void onResourceManagerReload(ResourceManager resourceManager) { Map<ResourceLocation, Resource> anims = resourceManager.listResources("animation/entity", s -> s.getPath().endsWith(".json")); for (Map.Entry<ResourceLocation, Resource> res : anims.entrySet()) { try { InputStream input = res.getValue().open(); JsonObject obj = gson.getAdapter(JsonObject.class).read(gson.newJsonReader(new InputStreamReader(input))); ResourceLocation animID = new ResourceLocation(res.getKey().getNamespace(), res.getKey().getPath().replace("animation/entity/", "").replace(".json", "")); BlockBenchAnimations anim = this.getAnimation(animID); anim.reload(obj); } catch (IOException e) { e.fillInStackTrace(); } } } public BlockBenchAnimations getAnimation(ResourceLocation res) { return this.animations.computeIfAbsent(res, r -> new BlockBenchAnimations()); } }
[ "Flemmli97@users.noreply.github.com" ]
Flemmli97@users.noreply.github.com
03b9e21dd808a84a34e73a555fe8adb7bb838a25
37083902c53448534c358d1069b9a6e96420e221
/bigeyepet/pet_net/src/main/java/com/junwu/pet_net/base/EndpointRequest.java
faf8cdc52ea0238f4a71481067e3835e1dea1a23
[]
no_license
JinJiuApp/BigEyeMM
64687c4a86c75a6d544983c8655466960fdd6e60
ff30f0d643ea786c1cc59afe81a7512c464ecca7
refs/heads/master
2021-06-17T06:20:22.745054
2017-06-13T03:27:51
2017-06-13T03:27:51
94,080,793
0
0
null
null
null
null
UTF-8
Java
false
false
1,073
java
/* * * Copyright 2015 TedXiong xiong-wei@hotmail.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.junwu.pet_net.base; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.HashMap; public interface EndpointRequest { @JsonIgnore HashMap<String, String> getHeaders(); @JsonIgnore String getProtocol(); @JsonIgnore String getHost(); @JsonIgnore int getPort(); @JsonIgnore String getPath(); @JsonIgnore boolean isShowJSON(); @JsonIgnore boolean isShowLoading(); }
[ "wujun@yscap.com" ]
wujun@yscap.com
e31f07f627c5e3818c78e5b202a0baa23908872a
3cf99601688f0c1bfe708af0573448693ab5ac44
/src/main/java/local/apichlkostner/myminecraftmod/item/ItemTable.java
80040a9ad26f58821c0ed0046026760dad863a09
[]
no_license
immortalcatz/mytestmod
d296ec3214c17c040b11624e54cdc2537accfbf9
a84088fe528581e83cb6ef535ad97f9038ef0ef6
refs/heads/master
2020-04-08T13:54:53.809050
2016-09-04T10:54:29
2016-09-04T10:54:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
668
java
package local.apichlkostner.myminecraftmod.item; import cpw.mods.fml.common.registry.GameRegistry; import local.apichlkostner.myminecraftmod.config.Constants; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; public class ItemTable extends Item implements IItem { public ItemTable() { } @Override public void init() { setUnlocalizedName(Constants.ItemTableName); setTextureName(Constants.ItemTableTexture); setCreativeTab(CreativeTabs.tabAllSearch); GameRegistry.registerItem(this, getUnlocalizedName().substring(5)); } @Override public void registerReceipe() { // no receipe } }
[ "apichlkostner@gmx.de" ]
apichlkostner@gmx.de
c9af18c42cddc52766b39c744c2228b68560b7f8
71f5a811e7d5517abaa37a9dbe413e52d34b491a
/src/main/java/br/edu/infnet/data/IUsuarioRepository.java
7e8c29aadfae0cb32a141453ddcf68bf6d361b6f
[]
no_license
lanzgit/personagem-rpg
8ea3635a5c079edc8fbeb0d018ecd3df629e7a3a
790a111080aca1d56c2aed492282a74f241c8919
refs/heads/master
2023-08-05T02:11:34.714513
2021-09-24T02:28:46
2021-09-24T02:28:46
381,068,861
0
0
null
null
null
null
UTF-8
Java
false
false
550
java
package br.edu.infnet.data; import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import br.edu.infnet.model.domain.Usuario; @Repository public interface IUsuarioRepository extends CrudRepository<Usuario, Integer> { @Query("from Usuario u where u.email = :email and u.senha = :senha") public Usuario autenticacao(String email, String senha); Usuario findById(int id); List<Usuario> findByOrderByNomeAsc(); }
[ "vnvianna@icloud.com" ]
vnvianna@icloud.com
1b907f6bd4060c6d8e6ff4d2c8dce7f47f78c741
2b87826e3b3d87e4e7793c758b0bbcd2894806f4
/src/module5/homework/Room.java
d5bfb5835ff7cb2fde8b7bf75c9ac8ff9c0d1b81
[]
no_license
AlexanderPokidin/MyJavaCore
1cd6f56416aca78bcc80e67602bacba3aa9faa8e
3df553e97142ea76cb2374d61d504405220d64b7
refs/heads/master
2020-07-08T10:24:34.467195
2016-10-10T05:55:56
2016-10-10T05:55:56
66,151,394
0
1
null
2016-10-10T05:55:57
2016-08-20T14:38:36
Java
UTF-8
Java
false
false
2,371
java
package module5.homework; import javax.xml.crypto.Data; public class Room { private long id; private int price; private int persons; private Data dataAvailableFrom; private String hotelName; private String cityName; public Room(long id, int price, int persons, Data dataAvailableFrom, String hotelName, String cityName) { this.id = id; this.price = price; this.persons = persons; this.dataAvailableFrom = dataAvailableFrom; this.hotelName = hotelName; this.cityName = cityName; } @Override public String toString() { return "Room{" + "id=" + id + ", price=" + price + ", persons=" + persons + ", dataAvailableFrom=" + dataAvailableFrom + ", hotelName='" + hotelName + '\'' + ", cityName='" + cityName + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Room room = (Room) o; if (price != room.price) return false; if (persons != room.persons) return false; return cityName.equals(room.cityName); } @Override public int hashCode() { int result = price; result = 31 * result + persons; result = 31 * result + cityName.hashCode(); return result; } public long getId() { return id; } public void setId(long id) { this.id = id; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getPersons() { return persons; } public void setPersons(int persons) { this.persons = persons; } public Data getDataAvailableFrom() { return dataAvailableFrom; } public void setDataAvailableFrom(Data dataAvailableFrom) { this.dataAvailableFrom = dataAvailableFrom; } public String getHotelName() { return hotelName; } public void setHotelName(String hotelName) { this.hotelName = hotelName; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } }
[ "a.pokidin@gmail.com" ]
a.pokidin@gmail.com
f2a179b1287720828df2167ea4ab9fe008c886a7
8b1246f25db826551efcb23ce56575b0db6047c8
/src/DecoratorPattern/Beverage.java
924d92f9c4aede5f9359fde80be8c3cf551fdf3e
[]
no_license
PlumpMath/DesignPattern-387
2e8093348c0b986a537b151677959e1211b90d46
a959cc39012d19e0689d31491af2977a1c1f27ca
refs/heads/master
2021-01-20T09:36:58.540547
2016-11-25T13:30:55
2016-11-25T13:30:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
488
java
package DecoratorPattern; /** * Created by pengshuang on 16/11/24. */ public abstract class Beverage { static int TALL = 1; static int GRANDE = 2; static int VENTI = 3; private int size; public int getSize() { return size; } public void setSize(int size) { this.size = size; } String description = "Unknown Beverage"; public String getDescription() { return description; } public abstract double cost(); }
[ "pengshuang92@163.com" ]
pengshuang92@163.com
75eec93398457d3c60be7f9463cc2140292fcbda
b272ea8c0f5f0fac08d85f507dcb347b1e1f1341
/famous-common/src/main/java/com/noseparte/common/http/HttpAsyncClient.java
1684aa883928f6e59dd8f4da8b786f43a17faec6
[ "MIT" ]
permissive
xuepomh/Almost-Famous
d45fec1eb1513e255c26e9a51b499066273b99e9
ebe944c8e21697ef71d4fdef0ba3ff332f6de452
refs/heads/master
2020-07-27T08:37:42.514212
2020-06-15T05:36:49
2020-06-15T05:36:49
209,032,567
0
0
MIT
2020-06-15T05:36:50
2019-09-17T11:11:29
null
UTF-8
Java
false
false
6,250
java
package com.noseparte.common.http; import org.apache.http.Consts; import org.apache.http.HttpHost; import org.apache.http.auth.AuthSchemeProvider; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.AuthSchemes; import org.apache.http.client.config.RequestConfig; import org.apache.http.config.ConnectionConfig; import org.apache.http.config.Lookup; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.impl.auth.*; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.impl.nio.reactor.IOReactorConfig; import org.apache.http.nio.conn.NoopIOSessionStrategy; import org.apache.http.nio.conn.SchemeIOSessionStrategy; import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOReactorException; import org.apache.http.ssl.SSLContexts; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLContext; import java.nio.charset.CodingErrorAction; public class HttpAsyncClient { private static Logger LOG = LoggerFactory.getLogger(HttpAsyncClient.class); private static int socketTimeout = 500;// 设置等待数据超时时间0.5秒钟 根据业务调整 private static int connectTimeout = 2000;// 连接超时 private static int poolSize = 100;// 连接池最大连接数 private static int maxPerRoute = 100;// 每个主机的并发最多只有1500 private static int connectionRequestTimeout = 3000; //从连接池中后去连接的timeout时间 // http代理相关参数 private String host = ""; private int port = 0; private String username = ""; private String password = ""; // 异步httpclient private CloseableHttpAsyncClient asyncHttpClient; // 异步加代理的httpclient private CloseableHttpAsyncClient proxyAsyncHttpClient; public HttpAsyncClient() { try { this.asyncHttpClient = createAsyncClient(false); // this.proxyAsyncHttpClient = createAsyncClient(true); } catch (Exception e) { e.printStackTrace(); } } public CloseableHttpAsyncClient createAsyncClient(boolean proxy) throws IOReactorException { RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(connectionRequestTimeout) .setConnectTimeout(connectTimeout) .setSocketTimeout(socketTimeout).build(); SSLContext sslcontext = SSLContexts.createDefault(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( username, password); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, credentials); // 设置协议http和https对应的处理socket链接工厂的对象 Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder .<SchemeIOSessionStrategy>create() .register("http", NoopIOSessionStrategy.INSTANCE) .register("https", new SSLIOSessionStrategy(sslcontext)) .build(); // 配置io线程 IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoKeepAlive(false).setTcpNoDelay(true) .setIoThreadCount(Runtime.getRuntime().availableProcessors()) .build(); // 设置连接池大小 ConnectingIOReactor ioReactor; ioReactor = new DefaultConnectingIOReactor(ioReactorConfig); PoolingNHttpClientConnectionManager conMgr = new PoolingNHttpClientConnectionManager( ioReactor, null, sessionStrategyRegistry); if (poolSize > 0) { conMgr.setMaxTotal(poolSize); } if (maxPerRoute > 0) { conMgr.setDefaultMaxPerRoute(maxPerRoute); } else { conMgr.setDefaultMaxPerRoute(10); } ConnectionConfig connectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE) .setCharset(Consts.UTF_8).build(); Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder .<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory()) .register(AuthSchemes.DIGEST, new DigestSchemeFactory()) .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()) .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()) .build(); conMgr.setDefaultConnectionConfig(connectionConfig); if (proxy) { return HttpAsyncClients.custom().setConnectionManager(conMgr) .setDefaultCredentialsProvider(credentialsProvider) .setDefaultAuthSchemeRegistry(authSchemeRegistry) .setProxy(new HttpHost(host, port)) .setDefaultCookieStore(new BasicCookieStore()) .setDefaultRequestConfig(requestConfig).build(); } else { return HttpAsyncClients.custom().setConnectionManager(conMgr) .setDefaultCredentialsProvider(credentialsProvider) .setDefaultAuthSchemeRegistry(authSchemeRegistry) .setDefaultCookieStore(new BasicCookieStore()).build(); } } public CloseableHttpAsyncClient getAsyncHttpClient() { return asyncHttpClient; } public CloseableHttpAsyncClient getProxyAsyncHttpClient() { return proxyAsyncHttpClient; } }
[ "noseparte@aliyun.com" ]
noseparte@aliyun.com
6c292dfb057cb639557a083b23ea5c2e3c12e91f
0e81247e404755acc33205836a15aaa83a589ce5
/kc_project3.1_GitHub/src/main/java/org/kuali/kra/award/contacts/AwardPersonUnitCreditSplitRuleEvent.java
7ea2d836449e8605f11c6520dc1c5600586c1746
[]
no_license
ajeeshg/KC3Remote
e2d88bb8efe6384083a6b3978a405b51e998f361
941646814a7a11237ce4ed1f844941182e357ec9
refs/heads/master
2016-09-10T20:07:05.685013
2012-07-17T15:52:59
2012-07-17T15:52:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,913
java
/* * Copyright 2005-2010 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * 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.kuali.kra.award.contacts; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.kuali.kra.rule.event.KraDocumentEventBase; import org.kuali.rice.kns.document.Document; import org.kuali.rice.kns.rule.BusinessRule; import org.kuali.rice.kns.util.KualiDecimal; /** * This class is used by AwardPersonCreditSplitRule implementers */ public class AwardPersonUnitCreditSplitRuleEvent extends KraDocumentEventBase { private static final Log LOG = LogFactory.getLog(AwardPersonUnitCreditSplitRuleEvent.class); private AwardPerson projectPerson; private Map<String, KualiDecimal> totalsByCreditSplitType; /** * Constructs a AwardPersonCreditSplitRuleEvent * @param description * @param errorPathPrefix * @param document */ public AwardPersonUnitCreditSplitRuleEvent(Document document, AwardPerson projectPerson, Map<String, KualiDecimal> totalsByCreditSplitType) { super("Credit splits invalid", "document.awardList[0].creditSplits.*", document); this.projectPerson = projectPerson; this.totalsByCreditSplitType = totalsByCreditSplitType; } /** * Gets the projectPerson attribute. * @return Returns the projectPerson. */ public AwardPerson getProjectPerson() { return projectPerson; } /** * @see org.kuali.rice.kns.rule.event.KualiDocumentEvent#getRuleInterfaceClass() */ public Class<AwardPersonUnitCreditSplitRule> getRuleInterfaceClass() { return AwardPersonUnitCreditSplitRule.class; } /** * Gets the totalsByCreditSplitType attribute. * @return Returns the totalsByCreditSplitType. */ public Map<String, KualiDecimal> getTotalsByCreditSplitType() { return totalsByCreditSplitType; } /** * @see org.kuali.rice.kns.rule.event.KualiDocumentEvent#invokeRuleMethod(org.kuali.rice.kns.rule.BusinessRule) */ public boolean invokeRuleMethod(BusinessRule rule) { return false; } @Override protected void logEvent() { LOG.info("Logging event"); } }
[ "naira@campusad.msu.edu" ]
naira@campusad.msu.edu
8ce3141670a2001a168b4a67d23cb036e8ffa530
06a097169756908cb3a2807cf7f14d284d002eeb
/rocketmq-streams-script/src/main/java/org/apache/rocketmq/streams/script/function/impl/field/ExtraFieldFunction.java
1de8d0e8f796c094360e4f554f89b6a8727f099c
[ "Apache-2.0" ]
permissive
xstorm1/rocketmq-streams
c058d44f542f3147ce4920ccc5917cac02a84283
a897b47f801457220bb99eb35fb0717cd896a692
refs/heads/main
2023-09-01T11:15:38.423242
2021-09-07T01:37:16
2021-09-07T01:37:16
402,685,883
0
1
Apache-2.0
2021-09-03T07:34:30
2021-09-03T07:34:29
null
UTF-8
Java
false
false
3,129
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rocketmq.streams.script.function.impl.field; import com.alibaba.fastjson.JSONObject; import org.apache.rocketmq.streams.common.context.IMessage; import org.apache.rocketmq.streams.common.utils.StringUtil; import org.apache.rocketmq.streams.script.annotation.Function; import org.apache.rocketmq.streams.script.annotation.FunctionMethod; import org.apache.rocketmq.streams.script.annotation.FunctionParamter; import org.apache.rocketmq.streams.script.context.FunctionContext; import org.apache.rocketmq.streams.script.utils.FunctionUtils; @Function public class ExtraFieldFunction { @FunctionMethod(value = "rename", alias = "rn", comment = "修改字段名称") public String extra(IMessage message, FunctionContext context, @FunctionParamter(value = "string", comment = "代表新字段的名称,不需要引号") String newFieldName, @FunctionParamter(value = "string", comment = "代表旧字段的字段,不需要引号") String oldFieldName) { Object value = FunctionUtils.getValue(message, context, oldFieldName); if (value == null) { return null; } String name = FunctionUtils.getValueString(message, context, newFieldName); if (StringUtil.isEmpty(name)) { name = newFieldName; } message.getMessageBody().remove(oldFieldName); message.getMessageBody().put(name, value); return value.toString(); } /** * 把一个json字段展开到外层数据结构 * * @param channelMessage * @param context * @param expandFieldName */ @FunctionMethod(value = "expandField", comment = "json字段展开到外层数据结") public void expandField(IMessage channelMessage, FunctionContext context, @FunctionParamter(value = "string", comment = "代表字符串的字段名或常量") String expandFieldName) { if (StringUtil.isEmpty(expandFieldName)) { return; } JSONObject jsonObject = channelMessage.getMessageBody().getJSONObject(expandFieldName); if (jsonObject == null) { return; } channelMessage.getMessageBody().remove(expandFieldName); channelMessage.getMessageBody().putAll(jsonObject); } }
[ "chris.yxd@alibaba-inc.com" ]
chris.yxd@alibaba-inc.com
c57af5f1e01ba99bf33298d8c2327d3df5413c5e
a1826c2ed9c12cfc395fb1a14c1a2e1f097155cb
/dm-20170622/src/main/java/com/aliyun/dm20170622/models/GetAccountListResponse.java
1db54905fc753b3623464e3ecde736e75a02771f
[ "Apache-2.0" ]
permissive
aliyun/alibabacloud-java-sdk
83a6036a33c7278bca6f1bafccb0180940d58b0b
008923f156adf2e4f4785a0419f60640273854ec
refs/heads/master
2023-09-01T04:10:33.640756
2023-09-01T02:40:45
2023-09-01T02:40:45
288,968,318
40
45
null
2023-06-13T02:47:13
2020-08-20T09:51:08
Java
UTF-8
Java
false
false
1,356
java
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.dm20170622.models; import com.aliyun.tea.*; public class GetAccountListResponse extends TeaModel { @NameInMap("headers") @Validation(required = true) public java.util.Map<String, String> headers; @NameInMap("statusCode") @Validation(required = true) public Integer statusCode; @NameInMap("body") @Validation(required = true) public GetAccountListResponseBody body; public static GetAccountListResponse build(java.util.Map<String, ?> map) throws Exception { GetAccountListResponse self = new GetAccountListResponse(); return TeaModel.build(map, self); } public GetAccountListResponse setHeaders(java.util.Map<String, String> headers) { this.headers = headers; return this; } public java.util.Map<String, String> getHeaders() { return this.headers; } public GetAccountListResponse setStatusCode(Integer statusCode) { this.statusCode = statusCode; return this; } public Integer getStatusCode() { return this.statusCode; } public GetAccountListResponse setBody(GetAccountListResponseBody body) { this.body = body; return this; } public GetAccountListResponseBody getBody() { return this.body; } }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
3df5a71e9c29531fb5fffa4e632d13b707309f69
02100127e19d2983c9497a5bc44f640240f1f640
/viboot-apilog/src/main/java/indi/viyoung/viboot/apilog/entity/User.java
ac78b7a75e3352ee40af149ef9a5cac899b18a70
[]
no_license
chuaaron/viboot
ea49060be7c7c685d28b0dfc3e5005bb46010409
7efdaebf2fecbeb08181229e3e986c43017786f7
refs/heads/master
2020-08-22T17:17:33.794790
2019-07-17T13:42:05
2019-07-17T13:42:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
638
java
package indi.viyoung.viboot.apilog.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <p> * * </p> * * @author viyoung * @since 2019-01-23 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class User implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; private String password; private String userName; }
[ "yangwei@datatang.com" ]
yangwei@datatang.com
59e2cef62380ff4d03ee5ef95cc47af1873f1915
6f25cd0e51a6652addd74a807d81877974c96727
/src/birdsanctuary/Penguin.java
4f27b8d19db396c434d7e7cea21e9c3c54c68c2f
[]
no_license
avinash7773/BirdSanctuary
bd3643fedf6ca219682c530af47013a0e27ac264
db76482110cd1175a9fa5906716ee42c9ab359a5
refs/heads/master
2023-04-02T05:53:00.025644
2021-04-11T16:37:36
2021-04-11T16:37:36
356,921,367
0
0
null
null
null
null
UTF-8
Java
false
false
377
java
package birdsanctuary; public class Penguin extends Bird implements Swimmable { static int count; public void swim() { System.out.println("penguin can swim"); } public void eat() { System.out.println("penguin can eat"); } public int getCount() { return count; } public void incrementCount() { count++; } public void decrementCount() { count--; } }
[ "javinash228@gmail.com" ]
javinash228@gmail.com
916221cd9b9e712937b90fd3cd8702ddfefa9190
241f4913e43487c7fbee35cc6020e1a21160a1d9
/test/com/kotai/cracking/chapter2/test/LinkedListCycleFinderTest.java
3bd03cb4aa9b7d737456efc67c648cd6d1af34c0
[]
no_license
KotaiVictor/CrackingTheCodeInterview
a8943a8f2b77196fa8b5aeacac621beda917995c
d5f5846f589fb1fb9f88722d8d2cce1231859db2
refs/heads/master
2022-06-17T01:53:27.374491
2022-06-04T12:24:28
2022-06-04T12:24:28
38,383,723
0
1
null
2022-06-04T12:24:29
2015-07-01T17:01:49
Java
UTF-8
Java
false
false
953
java
package com.kotai.cracking.chapter2.test; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import org.junit.Test; import com.kotai.cracking.chapter2.LinkedListCycleFinder; import com.kotai.cracking.samples.TestNode; public class LinkedListCycleFinderTest { private LinkedListCycleFinder finder = new LinkedListCycleFinder(); @Test public void find_cycle_in_a_linked_list() { TestNode<Integer> head = new TestNode<Integer>(10).appendToTail(11).appendToTail(12).appendToTail(13); TestNode<Integer> cycleHead = head.getLast().next = head.next; // 10 -> 11 -> 12 -> 13 -> 11 assertThat(finder.findCycle(head), equalTo(cycleHead)); } @Test public void no_cycle_in_linked_list() { TestNode<Integer> head = new TestNode<Integer>(10).appendToTail(11).appendToTail(12) .appendToTail(13).appendToTail(14); assertThat(finder.findCycle(head), equalTo(null)); } }
[ "kotai.viktor@gmail.com" ]
kotai.viktor@gmail.com
3fbe52c9657bc915838930562af7566305ffb01a
d1e745af2aa33e86b11f0f81373d7cff4923454f
/app/src/main/java/com/anythingintellect/mydeliveries/di/AppComponent.java
be7f48569b64ed8cad411c8c0bc78fb94690c0ba
[]
no_license
SaulRiglez/my-deliveries
91cc83c3bd6902519cd39c9881ed19cd76047095
e5d044a4cac528cccdd1d8c84ecdfc16253c6394
refs/heads/master
2021-04-05T23:50:29.948594
2017-09-05T10:22:32
2017-09-05T10:22:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
311
java
package com.anythingintellect.mydeliveries.di; import javax.inject.Singleton; import dagger.Component; /** * Created by ishan.dhingra on 03/09/17. */ @Component(modules = BaseModule.class) @Singleton public interface AppComponent { ContextComponent plusContextModule(ContextModule contextModule); }
[ "Ishan.Dhingra@snapdeal.com" ]
Ishan.Dhingra@snapdeal.com
b8e88a4bb22513fd3c8762f71fef3f32f56db98c
f6098e21fb8a3368cfc083fdc0546bf585daa520
/app/src/androidTest/java/com/seals/shubham/placementportalvolley/ExampleInstrumentedTest.java
25aab5ed276be1645d4122830a556f8a7659de98
[ "MIT" ]
permissive
ShubhamWorks78/Placement-Portal-Volley
85564bab01354141dc4c335085ca6df9d54d81a8
74573a626467fb8ea3f7cf2b903df9a9230d84c6
refs/heads/master
2021-04-29T10:59:10.252044
2017-01-23T02:07:41
2017-01-23T02:07:41
77,858,731
1
0
null
null
null
null
UTF-8
Java
false
false
782
java
package com.seals.shubham.placementportalvolley; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.seals.shubham.placementportalvolley", appContext.getPackageName()); } }
[ "2014UGEC078@nitjsr.ac.in" ]
2014UGEC078@nitjsr.ac.in
7a961788f762e725035399c4edab0d82a57ed056
8b7a233166064b6f6de4b954590d1f523c7bdedd
/src/main/java/com/vigekoo/modules/sys/entity/SysUserToken.java
e78e3c502fc3a0f4291656deae95a5b5d0a35830
[ "Apache-2.0" ]
permissive
xsc19850920/boot-cms
c1805b232ed5bfe584ef12b4c2d432970817c6ba
9202b02b3660060162aace0195ce507db0659356
refs/heads/master
2020-04-07T09:15:19.809515
2018-06-09T05:58:15
2018-06-09T05:58:15
123,907,204
0
0
null
null
null
null
UTF-8
Java
false
false
1,336
java
package com.vigekoo.modules.sys.entity; import java.io.Serializable; import java.util.Date; /** * @author sxia * @Description: TODO(系统用户Token) * @date 2017-6-23 15:07 */ public class SysUserToken implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String id; //用户ID private String userId; //token private String token; //过期时间 private Date expireTime; //更新时间 private Date updateTime; public String getId() { return id; } public void setId(String id) { this.id = id; } /** * 设置:用户ID */ public void setUserId(String userId) { this.userId = userId; } /** * 获取:用户ID */ public String getUserId() { return userId; } /** * 设置:token */ public void setToken(String token) { this.token = token; } /** * 获取:token */ public String getToken() { return token; } /** * 设置:过期时间 */ public void setExpireTime(Date expireTime) { this.expireTime = expireTime; } /** * 获取:过期时间 */ public Date getExpireTime() { return expireTime; } /** * 设置:更新时间 */ public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } /** * 获取:更新时间 */ public Date getUpdateTime() { return updateTime; } }
[ "xsc19850920@163.com" ]
xsc19850920@163.com
afbdc3a70bdda6949d97bd6365a66e8561ced7a1
7e541f3ddb96c6c59385f0e9d148e95441c70655
/tests/serenity/src/main/java/bla/tm/steps/support/Support_FAQSteps.java
99356b3967638e2dfe30b9aab39496122bb20408
[ "MIT" ]
permissive
csvra01/ticketmaster-api.github.io
14c4c3e5cede8e4186aeb9bd0c473c88d1054e95
01e8d61affa6caf5be87436c6a30db0e8eaecd3c
refs/heads/dev
2021-01-09T06:29:57.985848
2018-03-22T08:26:57
2018-03-22T08:26:57
65,800,210
0
0
MIT
2018-08-21T10:08:13
2016-08-16T08:03:47
JavaScript
UTF-8
Java
false
false
682
java
package bla.tm.steps.support; import bla.tm.pages.site.support.Support_FAQPage; import net.thucydides.core.annotations.Step; import static org.junit.Assert.assertEquals; public class Support_FAQSteps { Support_FAQPage faqPage; @Step public void openPage() { faqPage.open(); } @Step public void maximiseBrowserWindow() { faqPage.maximisePageWindow(); } @Step public void checkIfTitleIsCorrect(){ assertEquals (faqPage.getTitleText(), faqPage.pageHeader); } @Step public void checkGeneralPageElements(boolean disqus, boolean leftMenu){ faqPage.checkGeneralPageElements(disqus, leftMenu); } }
[ "oleksiy_slavutskyy@epam.com" ]
oleksiy_slavutskyy@epam.com