blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
2b37385fbdb0681041bf4f41147105cc5dc7b1ed
20,882,131,054,879
c15e2916bb813d4714986f7e1a989646dc4bc444
/src/g13/ONode.java
7c19271a3cd009826862bff3bccb6823f3a52396
[ "MIT" ]
permissive
AlbertSuarez/Wikipedia-PROP
https://github.com/AlbertSuarez/Wikipedia-PROP
fbf93252c9809a66f5b7f9e43b661c02b7e124d9
845cc511f993111c280a0a138d29547f05d9b8d3
refs/heads/master
2020-12-24T20:33:13.264000
2016-04-25T13:43:01
2016-04-25T13:43:01
57,044,910
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package g13; import wikipedia.domain.Element; /** * Own Node implementation * @author G13.2 */ public class ONode extends Node { /** * The element of Node. */ private Element e; /** * Creates a new ONode. * @param e element of the ONode. */ public ONode(Element e) { this.e = e; } /** * Compares the specified object with this ONode for equality. * @param o object for the comparison. * @return true if this node is equals than o, false alternatively. */ @Override public boolean equals(Object o) { return o instanceof ONode &&((ONode)o).e.equals(this.e); } /** * Returns a hash code value for this Node. * @return The hashCode of ONode. */ @Override public int hashCode() { if (e == null) return 0; return e.getTitle().hashCode(); } /** * Returns a string representation of this Node. * @return The string representation of this Node. */ @Override public String toString() { return e.toString(); } /** * Returns whether this Node is greater than the parameter node. * @param n the node to compare. * @return true if this node is greater than n, false alternatively. */ public int compareTo(Node n) { return (this.toString()).compareTo(((ONode)n).toString()); } /** * Returns the element of implicit ONode. * @return The element of implicit ONode. */ public Element getElement() { return e; } }
UTF-8
Java
1,398
java
ONode.java
Java
[ { "context": "lement;\n\n/**\n * Own Node implementation\n * @author G13.2\n */\npublic class ONode extends Node\n{\n\t/**\n\t * Th", "end": 95, "score": 0.9992057085037231, "start": 90, "tag": "USERNAME", "value": "G13.2" } ]
null
[]
package g13; import wikipedia.domain.Element; /** * Own Node implementation * @author G13.2 */ public class ONode extends Node { /** * The element of Node. */ private Element e; /** * Creates a new ONode. * @param e element of the ONode. */ public ONode(Element e) { this.e = e; } /** * Compares the specified object with this ONode for equality. * @param o object for the comparison. * @return true if this node is equals than o, false alternatively. */ @Override public boolean equals(Object o) { return o instanceof ONode &&((ONode)o).e.equals(this.e); } /** * Returns a hash code value for this Node. * @return The hashCode of ONode. */ @Override public int hashCode() { if (e == null) return 0; return e.getTitle().hashCode(); } /** * Returns a string representation of this Node. * @return The string representation of this Node. */ @Override public String toString() { return e.toString(); } /** * Returns whether this Node is greater than the parameter node. * @param n the node to compare. * @return true if this node is greater than n, false alternatively. */ public int compareTo(Node n) { return (this.toString()).compareTo(((ONode)n).toString()); } /** * Returns the element of implicit ONode. * @return The element of implicit ONode. */ public Element getElement() { return e; } }
1,398
0.653791
0.649499
72
18.416666
19.639635
69
false
false
0
0
0
0
0
0
1.138889
false
false
12
04944846a0fac2d3f365e9501a8023030d0e5e7f
29,283,087,051,033
cf57c9b614b7d769c26a2b1ed5c9b1904e2388f7
/backend/lesson/src/main/java/com/group/lesson/service/impl/UserServiceImpl.java
eb28acb7be0a77f0f4eb34c1bb4b0d0328d1ff17
[]
no_license
zixixiyu/lessonDesign
https://github.com/zixixiyu/lessonDesign
d73e3c482b1fcd3e29826d1e414e5ccdcd43db60
83b66dff3fb949e7db70f2339634f401a5d8a966
refs/heads/main
2023-08-10T19:39:24.445000
2021-09-12T01:29:29
2021-09-12T01:29:29
403,439,848
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.group.lesson.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.group.lesson.entity.User; import com.group.lesson.mapper.UserMapper; import com.group.lesson.service.UserService; import com.group.lesson.vo.UserVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * @Author: hwj * @Date: 2021/9/8 13:19 */ @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Autowired private RedisTemplate<String,String> redisTemplate; @Autowired private HttpServletRequest request; @Override public List<UserVo> getAllUser(Integer pageNum) { QueryWrapper<User> queryWrapper = new QueryWrapper(); queryWrapper.select("username","registryDate","email","mobile"); queryWrapper.last("limit "+(pageNum-1)*10+",10"); List<User> users = userMapper.selectList(queryWrapper); ArrayList<UserVo> userVos = new ArrayList<>(); for (User user:users){ UserVo userVo = new UserVo(); userVo.setEmail(user.getEmail()); userVo.setMobile(user.getMobile()); userVo.setRegistryDate(user.getRegistryDate()); userVo.setUsername(user.getUsername()); userVos.add(userVo); } return userVos; } @Override public Integer getUserNum() { QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(); return userMapper.selectCount(userQueryWrapper); } @Override public Boolean distinctUsername(String username) { QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(); userQueryWrapper.eq("username",username); List<User> users = userMapper.selectList(userQueryWrapper); if (users.isEmpty()){ return Boolean.TRUE; }else { return Boolean.FALSE; } } @Override public Boolean registry(User user) { int insert = userMapper.insert(user); return insert==1?Boolean.TRUE:Boolean.FALSE; } @Override public String login(String username, String password) { String tok = request.getHeader("u-token"); if (tok!=null){ redisTemplate.opsForValue().set(tok,username,60*30); return tok; } QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.eq("username",username).eq("password",password); Integer integer = userMapper.selectCount(wrapper); if (integer==1){ String token = UUID.randomUUID().toString(); redisTemplate.opsForValue().set(token,username,60*30); return token; } return null; } }
UTF-8
Java
2,952
java
UserServiceImpl.java
Java
[ { "context": "util.List;\nimport java.util.UUID;\n\n/**\n * @Author: hwj\n * @Date: 2021/9/8 13:19\n */\n@Service\npublic clas", "end": 577, "score": 0.9996644854545593, "start": 574, "tag": "USERNAME", "value": "hwj" }, { "context": "w QueryWrapper<>();\n wrapper.eq(\"username\",username).eq(\"password\",password);\n Integer integer", "end": 2651, "score": 0.8496313095092773, "start": 2643, "tag": "USERNAME", "value": "username" } ]
null
[]
package com.group.lesson.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.group.lesson.entity.User; import com.group.lesson.mapper.UserMapper; import com.group.lesson.service.UserService; import com.group.lesson.vo.UserVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * @Author: hwj * @Date: 2021/9/8 13:19 */ @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Autowired private RedisTemplate<String,String> redisTemplate; @Autowired private HttpServletRequest request; @Override public List<UserVo> getAllUser(Integer pageNum) { QueryWrapper<User> queryWrapper = new QueryWrapper(); queryWrapper.select("username","registryDate","email","mobile"); queryWrapper.last("limit "+(pageNum-1)*10+",10"); List<User> users = userMapper.selectList(queryWrapper); ArrayList<UserVo> userVos = new ArrayList<>(); for (User user:users){ UserVo userVo = new UserVo(); userVo.setEmail(user.getEmail()); userVo.setMobile(user.getMobile()); userVo.setRegistryDate(user.getRegistryDate()); userVo.setUsername(user.getUsername()); userVos.add(userVo); } return userVos; } @Override public Integer getUserNum() { QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(); return userMapper.selectCount(userQueryWrapper); } @Override public Boolean distinctUsername(String username) { QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(); userQueryWrapper.eq("username",username); List<User> users = userMapper.selectList(userQueryWrapper); if (users.isEmpty()){ return Boolean.TRUE; }else { return Boolean.FALSE; } } @Override public Boolean registry(User user) { int insert = userMapper.insert(user); return insert==1?Boolean.TRUE:Boolean.FALSE; } @Override public String login(String username, String password) { String tok = request.getHeader("u-token"); if (tok!=null){ redisTemplate.opsForValue().set(tok,username,60*30); return tok; } QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.eq("username",username).eq("password",password); Integer integer = userMapper.selectCount(wrapper); if (integer==1){ String token = UUID.randomUUID().toString(); redisTemplate.opsForValue().set(token,username,60*30); return token; } return null; } }
2,952
0.661247
0.652778
90
31.799999
22.39752
72
false
false
0
0
0
0
0
0
0.666667
false
false
12
d811e03f82558feaad193daa20a63d32ef089a8f
12,240,656,828,766
d27622a034c1a2f5c480517f6f04f8933f0f601a
/BookStoreWeb/src/main/java/com/pika/bookstoreweb/BookStoreService.java
f1bc196d10b9daff8426ef443095b2f20e5d103a
[]
no_license
sahil-diwan/SpringBoot-Microservices-BookStore-Application
https://github.com/sahil-diwan/SpringBoot-Microservices-BookStore-Application
66a546058779c282989ced9924c1f5005caf091f
b22f54b86a3a69971bd29789db8005489803cabf
refs/heads/master
2023-05-01T02:41:28.433000
2021-05-17T08:29:23
2021-05-17T08:29:23
367,547,312
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pika.bookstoreweb; import java.util.List; import java.util.Map; public interface BookStoreService { public List<Book> getMyBooks(String author, String category); public Book getBookByBookId(Integer bookId); public BookInfo getBookInfoByBookId(Integer bookId); public void placeOrder(Map<Integer, Book> mycartMap); public void addUserRating(UserRating userRating); public List<UserRating> getMyRatings(String userId); public List<String> getAuthorsList(); public List<String> getCategoryList(); }
UTF-8
Java
525
java
BookStoreService.java
Java
[]
null
[]
package com.pika.bookstoreweb; import java.util.List; import java.util.Map; public interface BookStoreService { public List<Book> getMyBooks(String author, String category); public Book getBookByBookId(Integer bookId); public BookInfo getBookInfoByBookId(Integer bookId); public void placeOrder(Map<Integer, Book> mycartMap); public void addUserRating(UserRating userRating); public List<UserRating> getMyRatings(String userId); public List<String> getAuthorsList(); public List<String> getCategoryList(); }
525
0.794286
0.794286
22
22.863636
22.782162
62
false
false
0
0
0
0
0
0
0.954545
false
false
12
16270268a7b591fc8f00bff1a09e1172644d075a
19,164,144,075,170
3ebf384e0dbd3c3291e3b293f7daf666570ba7e8
/src/main/java/fr/esiea/gl/ihm/PanelRecherche.java
6f02045c497ef4905ee2ea0398019b78853b020c
[ "MIT" ]
permissive
Aktarel/loto-swing
https://github.com/Aktarel/loto-swing
ba8a11a11cc0fd15ff07116e8145f9f4d3768725
bc51227948e339a41120f1274ae1e48e296c2d5a
refs/heads/master
2020-12-31T05:24:15.608000
2016-05-10T07:46:57
2016-05-10T07:46:57
58,372,007
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.esiea.gl.ihm; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import org.joda.time.LocalDate; import com.toedter.calendar.JDateChooser; import fr.esiea.gl.modele.TableModeleTirage; import fr.esiea.gl.modele.Tirage; public class PanelRecherche extends JPanel implements ActionListener{ /** * */ private static final long serialVersionUID = 1L; private GridBagLayout gbl; private GridBagConstraints gbc; private JLabel[] labels; private static final String[] titreLabels = { "Filtrer tirage", "Date n°1:", "Date n°2:" }; private JDateChooser dateChooserBefore, dateChooserSup; private Font f; private JButton buttonMAJ; private ComboChoixDate comboChoixDate; private TableModeleTirage modele; public PanelRecherche(TableModeleTirage modele) { this.modele = modele; config(); } public void config(){ labels = new JLabel[titreLabels.length]; dateChooserBefore = new JDateChooser(); dateChooserSup = new JDateChooser(); dateChooserSup.setEnabled(false); comboChoixDate = new ComboChoixDate(this); buttonMAJ = new JButton("Filtrer!"); buttonMAJ.addActionListener(this); dateChooserBefore.setPreferredSize(new Dimension(120, 20)); dateChooserSup.setPreferredSize(new Dimension(120, 20)); f = new Font("Arial", Font.PLAIN, 14); for (int i = 0; i < titreLabels.length; i++) { labels[i] = new JLabel(titreLabels[i]); labels[i].setFont(f); } labels[0].setFont(new Font("Arial", Font.ITALIC, 18)); gbl = new GridBagLayout(); gbc = new GridBagConstraints(); setLayout(gbl); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 3; gbc.insets = new Insets(10, 10, 10, 10); add(labels[0], gbc); gbc.gridx = 1; gbc.gridy = 2; gbc.gridwidth = 1; gbc.insets = new Insets(20, 10, 20, 10); add(labels[1], gbc); gbc.gridx = 2; gbc.gridy = 2; gbc.gridwidth = 1; gbc.insets = new Insets(20, 10, 20, 10); add(dateChooserBefore, gbc); gbc.gridx = 2; gbc.gridy = 3; gbc.gridwidth = 1; gbc.insets = new Insets(10, 10, 10, 10); add(comboChoixDate, gbc); gbc.gridx = 1; gbc.gridy = 4; gbc.gridwidth = 1; gbc.insets = new Insets(20, 10, 10, 10); add(labels[2], gbc); gbc.gridx = 2; gbc.gridy = 4; gbc.gridwidth = 1; gbc.insets = new Insets(20, 10, 20, 10); add(dateChooserSup, gbc); gbc.gridx = 1; gbc.gridy = 5; gbc.gridwidth = 3; gbc.insets = new Insets(0, 10, 20, 10); add(buttonMAJ, gbc); gbl.setConstraints(this, gbc); } public JDateChooser getDateChooserBefore() { return dateChooserBefore; } public JDateChooser getDateChooserSup() { return dateChooserSup; } public void actionPerformed(ActionEvent e) { if (e.getSource() == buttonMAJ) { LocalDate d = new LocalDate(dateChooserBefore.getDate()); LocalDate d2 = new LocalDate(dateChooserSup.getDate()); List<Tirage> list = new ArrayList<>(); /*Ne pas opérer directement sur modele.getTirages() qui m'a pas l'air threadSafe */ for(Tirage t : modele.getTirages()) list.add(t); switch (comboChoixDate.getSelectedIndex()) { case 1: for(Tirage t : list){ if(!d.isAfter(t.getDateTirage())) modele.supprimerTirage(t); } break; case 2: for(Tirage t : list){ if(!d.isBefore(t.getDateTirage())) modele.supprimerTirage(t); } break; case 3: for(Tirage t : list){ if(!d.isEqual(t.getDateTirage())) modele.supprimerTirage(t); } break; case 4: for(Tirage t : list){ if(!d.isBefore(t.getDateTirage()) || !d2.isAfter(t.getDateTirage())) modele.supprimerTirage(t); } break; case 5: modele.nettoyer(); modele.charger(); break; default: break; } FenetrePrincipale f = (FenetrePrincipale) getTopLevelAncestor(); f.getDataPanel().getPanelInfo().majNombreLigne(modele); } } }
ISO-8859-2
Java
4,142
java
PanelRecherche.java
Java
[]
null
[]
package fr.esiea.gl.ihm; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import org.joda.time.LocalDate; import com.toedter.calendar.JDateChooser; import fr.esiea.gl.modele.TableModeleTirage; import fr.esiea.gl.modele.Tirage; public class PanelRecherche extends JPanel implements ActionListener{ /** * */ private static final long serialVersionUID = 1L; private GridBagLayout gbl; private GridBagConstraints gbc; private JLabel[] labels; private static final String[] titreLabels = { "Filtrer tirage", "Date n°1:", "Date n°2:" }; private JDateChooser dateChooserBefore, dateChooserSup; private Font f; private JButton buttonMAJ; private ComboChoixDate comboChoixDate; private TableModeleTirage modele; public PanelRecherche(TableModeleTirage modele) { this.modele = modele; config(); } public void config(){ labels = new JLabel[titreLabels.length]; dateChooserBefore = new JDateChooser(); dateChooserSup = new JDateChooser(); dateChooserSup.setEnabled(false); comboChoixDate = new ComboChoixDate(this); buttonMAJ = new JButton("Filtrer!"); buttonMAJ.addActionListener(this); dateChooserBefore.setPreferredSize(new Dimension(120, 20)); dateChooserSup.setPreferredSize(new Dimension(120, 20)); f = new Font("Arial", Font.PLAIN, 14); for (int i = 0; i < titreLabels.length; i++) { labels[i] = new JLabel(titreLabels[i]); labels[i].setFont(f); } labels[0].setFont(new Font("Arial", Font.ITALIC, 18)); gbl = new GridBagLayout(); gbc = new GridBagConstraints(); setLayout(gbl); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 3; gbc.insets = new Insets(10, 10, 10, 10); add(labels[0], gbc); gbc.gridx = 1; gbc.gridy = 2; gbc.gridwidth = 1; gbc.insets = new Insets(20, 10, 20, 10); add(labels[1], gbc); gbc.gridx = 2; gbc.gridy = 2; gbc.gridwidth = 1; gbc.insets = new Insets(20, 10, 20, 10); add(dateChooserBefore, gbc); gbc.gridx = 2; gbc.gridy = 3; gbc.gridwidth = 1; gbc.insets = new Insets(10, 10, 10, 10); add(comboChoixDate, gbc); gbc.gridx = 1; gbc.gridy = 4; gbc.gridwidth = 1; gbc.insets = new Insets(20, 10, 10, 10); add(labels[2], gbc); gbc.gridx = 2; gbc.gridy = 4; gbc.gridwidth = 1; gbc.insets = new Insets(20, 10, 20, 10); add(dateChooserSup, gbc); gbc.gridx = 1; gbc.gridy = 5; gbc.gridwidth = 3; gbc.insets = new Insets(0, 10, 20, 10); add(buttonMAJ, gbc); gbl.setConstraints(this, gbc); } public JDateChooser getDateChooserBefore() { return dateChooserBefore; } public JDateChooser getDateChooserSup() { return dateChooserSup; } public void actionPerformed(ActionEvent e) { if (e.getSource() == buttonMAJ) { LocalDate d = new LocalDate(dateChooserBefore.getDate()); LocalDate d2 = new LocalDate(dateChooserSup.getDate()); List<Tirage> list = new ArrayList<>(); /*Ne pas opérer directement sur modele.getTirages() qui m'a pas l'air threadSafe */ for(Tirage t : modele.getTirages()) list.add(t); switch (comboChoixDate.getSelectedIndex()) { case 1: for(Tirage t : list){ if(!d.isAfter(t.getDateTirage())) modele.supprimerTirage(t); } break; case 2: for(Tirage t : list){ if(!d.isBefore(t.getDateTirage())) modele.supprimerTirage(t); } break; case 3: for(Tirage t : list){ if(!d.isEqual(t.getDateTirage())) modele.supprimerTirage(t); } break; case 4: for(Tirage t : list){ if(!d.isBefore(t.getDateTirage()) || !d2.isAfter(t.getDateTirage())) modele.supprimerTirage(t); } break; case 5: modele.nettoyer(); modele.charger(); break; default: break; } FenetrePrincipale f = (FenetrePrincipale) getTopLevelAncestor(); f.getDataPanel().getPanelInfo().majNombreLigne(modele); } } }
4,142
0.6777
0.652331
178
22.25281
18.497742
86
false
false
0
0
0
0
0
0
2.606742
false
false
12
08b0f227b192b6f6babf202dc44e2e7e9c8b125d
2,911,987,893,860
5ed878fc63124f91b14482d6549c4c62ccfdbbd6
/Threads/src/by/epam/javatraining/threads/thirdway/SecondThread.java
b9378e0217dcb6d5d0abeef6aac140bcd0c6b36a
[]
no_license
Kudzko/Repeating
https://github.com/Kudzko/Repeating
140379689f4b2f4cbbef16894b013906cdadc163
7f33cd4b4728ebcb87255c15ea9c5a171098f856
refs/heads/master
2020-04-24T09:28:10.311000
2019-03-31T09:54:13
2019-03-31T09:54:13
171,863,667
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package by.epam.javatraining.threads.thirdway; import java.util.Random; public class SecondThread implements Runnable { private Thread thread; public SecondThread() { thread = new Thread(this); thread.start(); } public Thread getThread() { return thread; } @Override public void run() { for (int i = 0; i < 30; i++){ try { Thread.sleep(new Random().nextInt(100)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Child thread"); } System.out.println("End child thread"); } }
UTF-8
Java
670
java
SecondThread.java
Java
[]
null
[]
package by.epam.javatraining.threads.thirdway; import java.util.Random; public class SecondThread implements Runnable { private Thread thread; public SecondThread() { thread = new Thread(this); thread.start(); } public Thread getThread() { return thread; } @Override public void run() { for (int i = 0; i < 30; i++){ try { Thread.sleep(new Random().nextInt(100)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Child thread"); } System.out.println("End child thread"); } }
670
0.546269
0.537313
29
22.103449
17.585936
56
false
false
0
0
0
0
0
0
0.413793
false
false
12
67d68fb9405d2f5718032421cf6646cadd4c7c40
22,024,592,310,396
8d1c7fba7cd15f8a1e33fd27d11eefd1c67d579f
/src/test/java/com/google/devtools/build/lib/rules/cpp/LinkCommandLineTest.java
bf6816ede4c6bbc77a9aa140480c7f3464c3fb0d
[ "Apache-2.0" ]
permissive
bazelbuild/bazel
https://github.com/bazelbuild/bazel
5896162455f032efc899b8de60aa39b9d2cad4a6
171aae3f9c57b41089e25ec61fc84c35baa3079d
refs/heads/master
2023-08-22T22:52:48.714000
2023-08-22T18:01:53
2023-08-22T18:01:53
20,773,773
20,294
4,383
Apache-2.0
false
2023-09-14T18:38:44
2014-06-12T16:00:38
2023-09-14T16:49:53
2023-09-14T18:38:43
834,634
21,350
3,861
1,797
Java
false
false
// Copyright 2020 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.rules.cpp; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.actions.Artifact.ArtifactExpander; import com.google.devtools.build.lib.actions.Artifact.SpecialArtifact; import com.google.devtools.build.lib.actions.Artifact.TreeFileArtifact; import com.google.devtools.build.lib.actions.ArtifactRoot; import com.google.devtools.build.lib.actions.ArtifactRoot.RootType; import com.google.devtools.build.lib.actions.util.ActionsTestUtil; import com.google.devtools.build.lib.analysis.util.BuildViewTestCase; import com.google.devtools.build.lib.rules.cpp.CcToolchainFeatures.FeatureConfiguration; import com.google.devtools.build.lib.rules.cpp.CcToolchainVariables.LibraryToLinkValue; import com.google.devtools.build.lib.rules.cpp.CcToolchainVariables.SequenceBuilder; import com.google.devtools.build.lib.rules.cpp.CppActionConfigs.CppPlatform; import com.google.devtools.build.lib.rules.cpp.Link.LinkTargetType; import com.google.devtools.build.lib.rules.cpp.Link.LinkingMode; import com.google.devtools.build.lib.testutil.TestUtils; import com.google.devtools.build.lib.util.Pair; import com.google.devtools.build.lib.vfs.FileSystem; import com.google.devtools.build.lib.vfs.Path; import com.google.devtools.build.lib.vfs.PathFragment; import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for {@link LinkCommandLine}. In particular, tests command line emitted subject to the * presence of certain build variables. */ @RunWith(JUnit4.class) public final class LinkCommandLineTest extends BuildViewTestCase { private Artifact scratchArtifact(String s) { Path execRoot = outputBase.getRelative("exec"); String outSegment = "root"; Path outputRoot = execRoot.getRelative(outSegment); ArtifactRoot root = ArtifactRoot.asDerivedRoot(execRoot, RootType.Output, outSegment); try { return ActionsTestUtil.createArtifact( root, scratch.overwriteFile(outputRoot.getRelative(s).toString())); } catch (IOException e) { throw new RuntimeException(e); } } private CcToolchainVariables.Builder getMockBuildVariables() { return getMockBuildVariables(ImmutableList.<String>of()); } private static CcToolchainVariables.Builder getMockBuildVariables( ImmutableList<String> linkstampOutputs) { CcToolchainVariables.Builder result = CcToolchainVariables.builder(); result.addStringVariable(LinkBuildVariables.GENERATE_INTERFACE_LIBRARY.getVariableName(), "no"); result.addStringVariable( LinkBuildVariables.INTERFACE_LIBRARY_INPUT.getVariableName(), "ignored"); result.addStringVariable( LinkBuildVariables.INTERFACE_LIBRARY_OUTPUT.getVariableName(), "ignored"); result.addStringVariable( LinkBuildVariables.INTERFACE_LIBRARY_BUILDER.getVariableName(), "ignored"); result.addStringSequenceVariable( LinkBuildVariables.LINKSTAMP_PATHS.getVariableName(), linkstampOutputs); return result; } private FeatureConfiguration getMockFeatureConfiguration() throws Exception { ImmutableList<CToolchain.Feature> features = new ImmutableList.Builder<CToolchain.Feature>() .addAll( CppActionConfigs.getLegacyFeatures( CppPlatform.LINUX, ImmutableSet.of(), "MOCK_LINKER_TOOL", /* supportsEmbeddedRuntimes= */ true, /* supportsInterfaceSharedLibraries= */ false)) .addAll(CppActionConfigs.getFeaturesToAppearLastInFeaturesList(ImmutableSet.of())) .build(); ImmutableList<CToolchain.ActionConfig> actionConfigs = CppActionConfigs.getLegacyActionConfigs( CppPlatform.LINUX, "MOCK_GCC_TOOL", "MOCK_AR_TOOL", "MOCK_STRIP_TOOL", /* supportsInterfaceSharedLibraries= */ false, /* existingActionConfigNames= */ ImmutableSet.of()); return CcToolchainTestHelper.buildFeatures(features, actionConfigs) .getFeatureConfiguration( ImmutableSet.of( Link.LinkTargetType.EXECUTABLE.getActionName(), Link.LinkTargetType.NODEPS_DYNAMIC_LIBRARY.getActionName(), Link.LinkTargetType.STATIC_LIBRARY.getActionName(), CppActionNames.CPP_COMPILE, CppActionNames.LINKSTAMP_COMPILE, CppRuleClasses.INCLUDES, CppRuleClasses.PREPROCESSOR_DEFINES, CppRuleClasses.INCLUDE_PATHS, CppRuleClasses.PIC)); } private LinkCommandLine.Builder minimalConfiguration(CcToolchainVariables.Builder variables) throws Exception { return new LinkCommandLine.Builder() .setBuildVariables(variables.build()) .setFeatureConfiguration(getMockFeatureConfiguration()); } private LinkCommandLine.Builder minimalConfiguration() throws Exception { return minimalConfiguration(getMockBuildVariables()); } private void assertError(String expectedSubstring, LinkCommandLine.Builder builder) { RuntimeException e = assertThrows(RuntimeException.class, () -> builder.build()); assertThat(e).hasMessageThat().contains(expectedSubstring); } @Test public void testStaticLinkWithBuildInfoHeadersIsError() throws Exception { assertError( "build info headers may only be present", minimalConfiguration() .setLinkTargetType(LinkTargetType.STATIC_LIBRARY) .setLinkingMode(LinkingMode.STATIC) .setBuildInfoHeaderArtifacts( ImmutableList.of(scratchArtifact("FakeBuildInfoHeaderArtifact1")))); } /** * Tests that when linking without linkstamps, the exec command is the same as the link command. */ @Test public void testLinkCommandIsExecCommandWhenNoLinkstamps() throws Exception { LinkCommandLine linkConfig = minimalConfiguration() .setActionName(LinkTargetType.EXECUTABLE.getActionName()) .setLinkTargetType(LinkTargetType.EXECUTABLE) .build(); List<String> rawLinkArgv = linkConfig.getRawLinkArgv(); assertThat(linkConfig.arguments()).isEqualTo(rawLinkArgv); } /** Tests that symbol count output does not appear in argv when it should not. */ @Test public void testSymbolCountsDisabled() throws Exception { LinkCommandLine linkConfig = minimalConfiguration() .forceToolPath("foo/bar/gcc") .setLinkTargetType(LinkTargetType.NODEPS_DYNAMIC_LIBRARY) .setLinkingMode(LinkingMode.STATIC) .build(); List<String> argv = linkConfig.getRawLinkArgv(); for (String arg : argv) { assertThat(arg).doesNotContain("print-symbol-counts"); } } @Test public void testLibrariesToLink() throws Exception { CcToolchainVariables.Builder variables = getMockBuildVariables() .addCustomBuiltVariable( LinkBuildVariables.LIBRARIES_TO_LINK.getVariableName(), new SequenceBuilder() .addValue(LibraryToLinkValue.forStaticLibrary("foo", false)) .addValue(LibraryToLinkValue.forStaticLibrary("bar", true))); LinkCommandLine linkConfig = minimalConfiguration(variables) .forceToolPath("foo/bar/gcc") .setActionName(LinkTargetType.NODEPS_DYNAMIC_LIBRARY.getActionName()) .setLinkTargetType(LinkTargetType.NODEPS_DYNAMIC_LIBRARY) .setLinkingMode(LinkingMode.STATIC) .build(); String commandLine = Joiner.on(" ").join(linkConfig.getRawLinkArgv()); assertThat(commandLine).matches(".*foo -Wl,-whole-archive bar -Wl,-no-whole-archive.*"); } @Test public void testLibrarySearchDirectories() throws Exception { CcToolchainVariables.Builder variables = getMockBuildVariables() .addStringSequenceVariable( LinkBuildVariables.LIBRARY_SEARCH_DIRECTORIES.getVariableName(), ImmutableList.of("foo", "bar")); LinkCommandLine linkConfig = minimalConfiguration(variables) .setActionName(LinkTargetType.NODEPS_DYNAMIC_LIBRARY.getActionName()) .setLinkTargetType(LinkTargetType.NODEPS_DYNAMIC_LIBRARY) .setLinkingMode(LinkingMode.STATIC) .build(); assertThat(linkConfig.getRawLinkArgv()).containsAtLeast("-Lfoo", "-Lbar").inOrder(); } @Test public void testLinkerParamFileForStaticLibrary() throws Exception { CcToolchainVariables.Builder variables = getMockBuildVariables() .addStringVariable( LinkBuildVariables.LINKER_PARAM_FILE.getVariableName(), "foo/bar.param"); LinkCommandLine linkConfig = minimalConfiguration(variables) .setActionName(LinkTargetType.STATIC_LIBRARY.getActionName()) .setLinkTargetType(LinkTargetType.STATIC_LIBRARY) .setLinkingMode(Link.LinkingMode.STATIC) .build(); assertThat(linkConfig.getRawLinkArgv()).contains("@foo/bar.param"); } @Test public void testLinkerParamFileForDynamicLibrary() throws Exception { CcToolchainVariables.Builder variables = getMockBuildVariables() .addStringVariable( LinkBuildVariables.LINKER_PARAM_FILE.getVariableName(), "foo/bar.param"); LinkCommandLine linkConfig = minimalConfiguration(variables) .setActionName(LinkTargetType.NODEPS_DYNAMIC_LIBRARY.getActionName()) .setLinkTargetType(LinkTargetType.NODEPS_DYNAMIC_LIBRARY) .setLinkingMode(Link.LinkingMode.STATIC) .build(); assertThat(linkConfig.getRawLinkArgv()).contains("@foo/bar.param"); } private List<String> basicArgv(LinkTargetType targetType) throws Exception { return basicArgv(targetType, getMockBuildVariables()); } private List<String> basicArgv(LinkTargetType targetType, CcToolchainVariables.Builder variables) throws Exception { LinkCommandLine linkConfig = minimalConfiguration(variables) .setActionName(targetType.getActionName()) .setLinkTargetType(targetType) .setLinkingMode(LinkingMode.STATIC) .build(); return linkConfig.arguments(); } /** Tests that a "--force_pic" configuration applies "-pie" to executable links. */ @Test public void testPicMode() throws Exception { String pieArg = "-pie"; // Disabled: assertThat(basicArgv(LinkTargetType.EXECUTABLE)).doesNotContain(pieArg); assertThat(basicArgv(LinkTargetType.NODEPS_DYNAMIC_LIBRARY)).doesNotContain(pieArg); assertThat(basicArgv(LinkTargetType.STATIC_LIBRARY)).doesNotContain(pieArg); assertThat(basicArgv(LinkTargetType.PIC_STATIC_LIBRARY)).doesNotContain(pieArg); assertThat(basicArgv(LinkTargetType.ALWAYS_LINK_STATIC_LIBRARY)).doesNotContain(pieArg); assertThat(basicArgv(LinkTargetType.ALWAYS_LINK_PIC_STATIC_LIBRARY)).doesNotContain(pieArg); CcToolchainVariables.Builder picVariables = getMockBuildVariables() .addStringVariable(LinkBuildVariables.FORCE_PIC.getVariableName(), ""); // Enabled: useConfiguration("--force_pic"); assertThat(basicArgv(LinkTargetType.EXECUTABLE, picVariables)).contains(pieArg); assertThat(basicArgv(LinkTargetType.NODEPS_DYNAMIC_LIBRARY, picVariables)) .doesNotContain(pieArg); assertThat(basicArgv(LinkTargetType.STATIC_LIBRARY, picVariables)).doesNotContain(pieArg); assertThat(basicArgv(LinkTargetType.PIC_STATIC_LIBRARY, picVariables)).doesNotContain(pieArg); assertThat(basicArgv(LinkTargetType.ALWAYS_LINK_STATIC_LIBRARY, picVariables)) .doesNotContain(pieArg); assertThat(basicArgv(LinkTargetType.ALWAYS_LINK_PIC_STATIC_LIBRARY, picVariables)) .doesNotContain(pieArg); } @Test public void testSplitStaticLinkCommand() throws Exception { useConfiguration("--nostart_end_lib"); Artifact paramFile = scratchArtifact("some/file.params"); LinkCommandLine linkConfig = minimalConfiguration( getMockBuildVariables() .addStringVariable( LinkBuildVariables.OUTPUT_EXECPATH.getVariableName(), "a/FakeOutput") .addStringVariable( LinkBuildVariables.LINKER_PARAM_FILE.getVariableName(), "some/file.params")) .setActionName(LinkTargetType.STATIC_LIBRARY.getActionName()) .setLinkTargetType(LinkTargetType.STATIC_LIBRARY) .forceToolPath("foo/bar/ar") .setParamFile(paramFile) .build(); Pair<List<String>, List<String>> result = linkConfig.splitCommandline(); assertThat(result.first).isEqualTo(Arrays.asList("foo/bar/ar", "@some/file.params")); assertThat(result.second).isEqualTo(Arrays.asList("rcsD", "a/FakeOutput")); } @Test public void testSplitDynamicLinkCommand() throws Exception { useConfiguration("--nostart_end_lib"); Artifact paramFile = scratchArtifact("some/file.params"); LinkCommandLine linkConfig = minimalConfiguration( getMockBuildVariables() .addStringVariable( LinkBuildVariables.OUTPUT_EXECPATH.getVariableName(), "a/FakeOutput") .addStringVariable( LinkBuildVariables.LINKER_PARAM_FILE.getVariableName(), "some/file.params") .addStringSequenceVariable( LinkBuildVariables.USER_LINK_FLAGS.getVariableName(), ImmutableList.of(""))) .setActionName(LinkTargetType.DYNAMIC_LIBRARY.getActionName()) .setLinkTargetType(LinkTargetType.DYNAMIC_LIBRARY) .forceToolPath("foo/bar/linker") .setParamFile(paramFile) .build(); Pair<List<String>, List<String>> result = linkConfig.splitCommandline(); assertThat(result.first).containsExactly("foo/bar/linker", "@some/file.params").inOrder(); assertThat(result.second).containsExactly("-shared", "-o", "a/FakeOutput", "").inOrder(); } @Test public void testStaticLinkCommand() throws Exception { useConfiguration("--nostart_end_lib"); LinkCommandLine linkConfig = minimalConfiguration( getMockBuildVariables() .addStringVariable( LinkBuildVariables.OUTPUT_EXECPATH.getVariableName(), "a/FakeOutput")) .forceToolPath("foo/bar/ar") .setActionName(LinkTargetType.STATIC_LIBRARY.getActionName()) .setLinkTargetType(LinkTargetType.STATIC_LIBRARY) .build(); List<String> result = linkConfig.getRawLinkArgv(); assertThat(result).isEqualTo(Arrays.asList("foo/bar/ar", "rcsD", "a/FakeOutput")); } @Test public void testSplitAlwaysLinkLinkCommand() throws Exception { CcToolchainVariables.Builder variables = CcToolchainVariables.builder() .addStringVariable(CcCommon.SYSROOT_VARIABLE_NAME, "/usr/grte/v1") .addStringVariable(LinkBuildVariables.OUTPUT_EXECPATH.getVariableName(), "a/FakeOutput") .addStringVariable( LinkBuildVariables.LINKER_PARAM_FILE.getVariableName(), "some/file.params") .addCustomBuiltVariable( LinkBuildVariables.LIBRARIES_TO_LINK.getVariableName(), new CcToolchainVariables.SequenceBuilder() .addValue(LibraryToLinkValue.forObjectFile("foo.o", false)) .addValue(LibraryToLinkValue.forObjectFile("bar.o", false))); Artifact paramFile = scratchArtifact("some/file.params"); LinkCommandLine linkConfig = minimalConfiguration(variables) .setActionName(LinkTargetType.ALWAYS_LINK_STATIC_LIBRARY.getActionName()) .setLinkTargetType(LinkTargetType.ALWAYS_LINK_STATIC_LIBRARY) .forceToolPath("foo/bar/ar") .setParamFile(paramFile) .build(); Pair<List<String>, List<String>> result = linkConfig.splitCommandline(); assertThat(result.first).isEqualTo(Arrays.asList("foo/bar/ar", "@some/file.params")); assertThat(result.second).isEqualTo(Arrays.asList("rcsD", "a/FakeOutput", "foo.o", "bar.o")); } private SpecialArtifact createTreeArtifact(String name) { FileSystem fs = scratch.getFileSystem(); Path execRoot = fs.getPath(TestUtils.tmpDir()); PathFragment execPath = PathFragment.create("out").getRelative(name); return ActionsTestUtil.createTreeArtifactWithGeneratingAction( ArtifactRoot.asDerivedRoot(execRoot, RootType.Output, "out"), execPath); } private void verifyArguments( Iterable<String> arguments, Iterable<String> allowedArguments, Iterable<String> disallowedArguments) { assertThat(arguments).containsAtLeastElementsIn(allowedArguments); assertThat(arguments).containsNoneIn(disallowedArguments); } @Test public void testTreeArtifactLink() throws Exception { SpecialArtifact testTreeArtifact = createTreeArtifact("library_directory"); TreeFileArtifact library0 = TreeFileArtifact.createTreeOutput(testTreeArtifact, "library0.o"); TreeFileArtifact library1 = TreeFileArtifact.createTreeOutput(testTreeArtifact, "library1.o"); ArtifactExpander expander = new ArtifactExpander() { @Override public void expand(Artifact artifact, Collection<? super Artifact> output) { if (artifact.equals(testTreeArtifact)) { output.add(library0); output.add(library1); } }; }; Iterable<String> treeArtifactsPaths = ImmutableList.of(testTreeArtifact.getExecPathString()); Iterable<String> treeFileArtifactsPaths = ImmutableList.of(library0.getExecPathString(), library1.getExecPathString()); Artifact paramFile = scratchArtifact("some/file.params"); LinkCommandLine linkConfig = minimalConfiguration( getMockBuildVariables() .addStringVariable( LinkBuildVariables.LINKER_PARAM_FILE.getVariableName(), "some/file.params") .addCustomBuiltVariable( LinkBuildVariables.LIBRARIES_TO_LINK.getVariableName(), new CcToolchainVariables.SequenceBuilder() .addValue( LibraryToLinkValue.forObjectFileGroup( ImmutableList.of(testTreeArtifact), false)))) .forceToolPath("foo/bar/gcc") .setActionName(LinkTargetType.STATIC_LIBRARY.getActionName()) .setLinkTargetType(LinkTargetType.STATIC_LIBRARY) .setLinkingMode(Link.LinkingMode.STATIC) .setParamFile(paramFile) .build(); // Should only reference the tree artifact. verifyArguments(linkConfig.arguments(null), treeArtifactsPaths, treeFileArtifactsPaths); verifyArguments(linkConfig.getRawLinkArgv(null), treeArtifactsPaths, treeFileArtifactsPaths); verifyArguments( linkConfig.paramCmdLine().arguments(null), treeArtifactsPaths, treeFileArtifactsPaths); // Should only reference tree file artifacts. verifyArguments(linkConfig.arguments(expander), treeFileArtifactsPaths, treeArtifactsPaths); verifyArguments( linkConfig.getRawLinkArgv(expander), treeFileArtifactsPaths, treeArtifactsPaths); verifyArguments( linkConfig.paramCmdLine().arguments(expander), treeFileArtifactsPaths, treeArtifactsPaths); } }
UTF-8
Java
20,642
java
LinkCommandLineTest.java
Java
[]
null
[]
// Copyright 2020 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.rules.cpp; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.actions.Artifact.ArtifactExpander; import com.google.devtools.build.lib.actions.Artifact.SpecialArtifact; import com.google.devtools.build.lib.actions.Artifact.TreeFileArtifact; import com.google.devtools.build.lib.actions.ArtifactRoot; import com.google.devtools.build.lib.actions.ArtifactRoot.RootType; import com.google.devtools.build.lib.actions.util.ActionsTestUtil; import com.google.devtools.build.lib.analysis.util.BuildViewTestCase; import com.google.devtools.build.lib.rules.cpp.CcToolchainFeatures.FeatureConfiguration; import com.google.devtools.build.lib.rules.cpp.CcToolchainVariables.LibraryToLinkValue; import com.google.devtools.build.lib.rules.cpp.CcToolchainVariables.SequenceBuilder; import com.google.devtools.build.lib.rules.cpp.CppActionConfigs.CppPlatform; import com.google.devtools.build.lib.rules.cpp.Link.LinkTargetType; import com.google.devtools.build.lib.rules.cpp.Link.LinkingMode; import com.google.devtools.build.lib.testutil.TestUtils; import com.google.devtools.build.lib.util.Pair; import com.google.devtools.build.lib.vfs.FileSystem; import com.google.devtools.build.lib.vfs.Path; import com.google.devtools.build.lib.vfs.PathFragment; import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for {@link LinkCommandLine}. In particular, tests command line emitted subject to the * presence of certain build variables. */ @RunWith(JUnit4.class) public final class LinkCommandLineTest extends BuildViewTestCase { private Artifact scratchArtifact(String s) { Path execRoot = outputBase.getRelative("exec"); String outSegment = "root"; Path outputRoot = execRoot.getRelative(outSegment); ArtifactRoot root = ArtifactRoot.asDerivedRoot(execRoot, RootType.Output, outSegment); try { return ActionsTestUtil.createArtifact( root, scratch.overwriteFile(outputRoot.getRelative(s).toString())); } catch (IOException e) { throw new RuntimeException(e); } } private CcToolchainVariables.Builder getMockBuildVariables() { return getMockBuildVariables(ImmutableList.<String>of()); } private static CcToolchainVariables.Builder getMockBuildVariables( ImmutableList<String> linkstampOutputs) { CcToolchainVariables.Builder result = CcToolchainVariables.builder(); result.addStringVariable(LinkBuildVariables.GENERATE_INTERFACE_LIBRARY.getVariableName(), "no"); result.addStringVariable( LinkBuildVariables.INTERFACE_LIBRARY_INPUT.getVariableName(), "ignored"); result.addStringVariable( LinkBuildVariables.INTERFACE_LIBRARY_OUTPUT.getVariableName(), "ignored"); result.addStringVariable( LinkBuildVariables.INTERFACE_LIBRARY_BUILDER.getVariableName(), "ignored"); result.addStringSequenceVariable( LinkBuildVariables.LINKSTAMP_PATHS.getVariableName(), linkstampOutputs); return result; } private FeatureConfiguration getMockFeatureConfiguration() throws Exception { ImmutableList<CToolchain.Feature> features = new ImmutableList.Builder<CToolchain.Feature>() .addAll( CppActionConfigs.getLegacyFeatures( CppPlatform.LINUX, ImmutableSet.of(), "MOCK_LINKER_TOOL", /* supportsEmbeddedRuntimes= */ true, /* supportsInterfaceSharedLibraries= */ false)) .addAll(CppActionConfigs.getFeaturesToAppearLastInFeaturesList(ImmutableSet.of())) .build(); ImmutableList<CToolchain.ActionConfig> actionConfigs = CppActionConfigs.getLegacyActionConfigs( CppPlatform.LINUX, "MOCK_GCC_TOOL", "MOCK_AR_TOOL", "MOCK_STRIP_TOOL", /* supportsInterfaceSharedLibraries= */ false, /* existingActionConfigNames= */ ImmutableSet.of()); return CcToolchainTestHelper.buildFeatures(features, actionConfigs) .getFeatureConfiguration( ImmutableSet.of( Link.LinkTargetType.EXECUTABLE.getActionName(), Link.LinkTargetType.NODEPS_DYNAMIC_LIBRARY.getActionName(), Link.LinkTargetType.STATIC_LIBRARY.getActionName(), CppActionNames.CPP_COMPILE, CppActionNames.LINKSTAMP_COMPILE, CppRuleClasses.INCLUDES, CppRuleClasses.PREPROCESSOR_DEFINES, CppRuleClasses.INCLUDE_PATHS, CppRuleClasses.PIC)); } private LinkCommandLine.Builder minimalConfiguration(CcToolchainVariables.Builder variables) throws Exception { return new LinkCommandLine.Builder() .setBuildVariables(variables.build()) .setFeatureConfiguration(getMockFeatureConfiguration()); } private LinkCommandLine.Builder minimalConfiguration() throws Exception { return minimalConfiguration(getMockBuildVariables()); } private void assertError(String expectedSubstring, LinkCommandLine.Builder builder) { RuntimeException e = assertThrows(RuntimeException.class, () -> builder.build()); assertThat(e).hasMessageThat().contains(expectedSubstring); } @Test public void testStaticLinkWithBuildInfoHeadersIsError() throws Exception { assertError( "build info headers may only be present", minimalConfiguration() .setLinkTargetType(LinkTargetType.STATIC_LIBRARY) .setLinkingMode(LinkingMode.STATIC) .setBuildInfoHeaderArtifacts( ImmutableList.of(scratchArtifact("FakeBuildInfoHeaderArtifact1")))); } /** * Tests that when linking without linkstamps, the exec command is the same as the link command. */ @Test public void testLinkCommandIsExecCommandWhenNoLinkstamps() throws Exception { LinkCommandLine linkConfig = minimalConfiguration() .setActionName(LinkTargetType.EXECUTABLE.getActionName()) .setLinkTargetType(LinkTargetType.EXECUTABLE) .build(); List<String> rawLinkArgv = linkConfig.getRawLinkArgv(); assertThat(linkConfig.arguments()).isEqualTo(rawLinkArgv); } /** Tests that symbol count output does not appear in argv when it should not. */ @Test public void testSymbolCountsDisabled() throws Exception { LinkCommandLine linkConfig = minimalConfiguration() .forceToolPath("foo/bar/gcc") .setLinkTargetType(LinkTargetType.NODEPS_DYNAMIC_LIBRARY) .setLinkingMode(LinkingMode.STATIC) .build(); List<String> argv = linkConfig.getRawLinkArgv(); for (String arg : argv) { assertThat(arg).doesNotContain("print-symbol-counts"); } } @Test public void testLibrariesToLink() throws Exception { CcToolchainVariables.Builder variables = getMockBuildVariables() .addCustomBuiltVariable( LinkBuildVariables.LIBRARIES_TO_LINK.getVariableName(), new SequenceBuilder() .addValue(LibraryToLinkValue.forStaticLibrary("foo", false)) .addValue(LibraryToLinkValue.forStaticLibrary("bar", true))); LinkCommandLine linkConfig = minimalConfiguration(variables) .forceToolPath("foo/bar/gcc") .setActionName(LinkTargetType.NODEPS_DYNAMIC_LIBRARY.getActionName()) .setLinkTargetType(LinkTargetType.NODEPS_DYNAMIC_LIBRARY) .setLinkingMode(LinkingMode.STATIC) .build(); String commandLine = Joiner.on(" ").join(linkConfig.getRawLinkArgv()); assertThat(commandLine).matches(".*foo -Wl,-whole-archive bar -Wl,-no-whole-archive.*"); } @Test public void testLibrarySearchDirectories() throws Exception { CcToolchainVariables.Builder variables = getMockBuildVariables() .addStringSequenceVariable( LinkBuildVariables.LIBRARY_SEARCH_DIRECTORIES.getVariableName(), ImmutableList.of("foo", "bar")); LinkCommandLine linkConfig = minimalConfiguration(variables) .setActionName(LinkTargetType.NODEPS_DYNAMIC_LIBRARY.getActionName()) .setLinkTargetType(LinkTargetType.NODEPS_DYNAMIC_LIBRARY) .setLinkingMode(LinkingMode.STATIC) .build(); assertThat(linkConfig.getRawLinkArgv()).containsAtLeast("-Lfoo", "-Lbar").inOrder(); } @Test public void testLinkerParamFileForStaticLibrary() throws Exception { CcToolchainVariables.Builder variables = getMockBuildVariables() .addStringVariable( LinkBuildVariables.LINKER_PARAM_FILE.getVariableName(), "foo/bar.param"); LinkCommandLine linkConfig = minimalConfiguration(variables) .setActionName(LinkTargetType.STATIC_LIBRARY.getActionName()) .setLinkTargetType(LinkTargetType.STATIC_LIBRARY) .setLinkingMode(Link.LinkingMode.STATIC) .build(); assertThat(linkConfig.getRawLinkArgv()).contains("@foo/bar.param"); } @Test public void testLinkerParamFileForDynamicLibrary() throws Exception { CcToolchainVariables.Builder variables = getMockBuildVariables() .addStringVariable( LinkBuildVariables.LINKER_PARAM_FILE.getVariableName(), "foo/bar.param"); LinkCommandLine linkConfig = minimalConfiguration(variables) .setActionName(LinkTargetType.NODEPS_DYNAMIC_LIBRARY.getActionName()) .setLinkTargetType(LinkTargetType.NODEPS_DYNAMIC_LIBRARY) .setLinkingMode(Link.LinkingMode.STATIC) .build(); assertThat(linkConfig.getRawLinkArgv()).contains("@foo/bar.param"); } private List<String> basicArgv(LinkTargetType targetType) throws Exception { return basicArgv(targetType, getMockBuildVariables()); } private List<String> basicArgv(LinkTargetType targetType, CcToolchainVariables.Builder variables) throws Exception { LinkCommandLine linkConfig = minimalConfiguration(variables) .setActionName(targetType.getActionName()) .setLinkTargetType(targetType) .setLinkingMode(LinkingMode.STATIC) .build(); return linkConfig.arguments(); } /** Tests that a "--force_pic" configuration applies "-pie" to executable links. */ @Test public void testPicMode() throws Exception { String pieArg = "-pie"; // Disabled: assertThat(basicArgv(LinkTargetType.EXECUTABLE)).doesNotContain(pieArg); assertThat(basicArgv(LinkTargetType.NODEPS_DYNAMIC_LIBRARY)).doesNotContain(pieArg); assertThat(basicArgv(LinkTargetType.STATIC_LIBRARY)).doesNotContain(pieArg); assertThat(basicArgv(LinkTargetType.PIC_STATIC_LIBRARY)).doesNotContain(pieArg); assertThat(basicArgv(LinkTargetType.ALWAYS_LINK_STATIC_LIBRARY)).doesNotContain(pieArg); assertThat(basicArgv(LinkTargetType.ALWAYS_LINK_PIC_STATIC_LIBRARY)).doesNotContain(pieArg); CcToolchainVariables.Builder picVariables = getMockBuildVariables() .addStringVariable(LinkBuildVariables.FORCE_PIC.getVariableName(), ""); // Enabled: useConfiguration("--force_pic"); assertThat(basicArgv(LinkTargetType.EXECUTABLE, picVariables)).contains(pieArg); assertThat(basicArgv(LinkTargetType.NODEPS_DYNAMIC_LIBRARY, picVariables)) .doesNotContain(pieArg); assertThat(basicArgv(LinkTargetType.STATIC_LIBRARY, picVariables)).doesNotContain(pieArg); assertThat(basicArgv(LinkTargetType.PIC_STATIC_LIBRARY, picVariables)).doesNotContain(pieArg); assertThat(basicArgv(LinkTargetType.ALWAYS_LINK_STATIC_LIBRARY, picVariables)) .doesNotContain(pieArg); assertThat(basicArgv(LinkTargetType.ALWAYS_LINK_PIC_STATIC_LIBRARY, picVariables)) .doesNotContain(pieArg); } @Test public void testSplitStaticLinkCommand() throws Exception { useConfiguration("--nostart_end_lib"); Artifact paramFile = scratchArtifact("some/file.params"); LinkCommandLine linkConfig = minimalConfiguration( getMockBuildVariables() .addStringVariable( LinkBuildVariables.OUTPUT_EXECPATH.getVariableName(), "a/FakeOutput") .addStringVariable( LinkBuildVariables.LINKER_PARAM_FILE.getVariableName(), "some/file.params")) .setActionName(LinkTargetType.STATIC_LIBRARY.getActionName()) .setLinkTargetType(LinkTargetType.STATIC_LIBRARY) .forceToolPath("foo/bar/ar") .setParamFile(paramFile) .build(); Pair<List<String>, List<String>> result = linkConfig.splitCommandline(); assertThat(result.first).isEqualTo(Arrays.asList("foo/bar/ar", "@some/file.params")); assertThat(result.second).isEqualTo(Arrays.asList("rcsD", "a/FakeOutput")); } @Test public void testSplitDynamicLinkCommand() throws Exception { useConfiguration("--nostart_end_lib"); Artifact paramFile = scratchArtifact("some/file.params"); LinkCommandLine linkConfig = minimalConfiguration( getMockBuildVariables() .addStringVariable( LinkBuildVariables.OUTPUT_EXECPATH.getVariableName(), "a/FakeOutput") .addStringVariable( LinkBuildVariables.LINKER_PARAM_FILE.getVariableName(), "some/file.params") .addStringSequenceVariable( LinkBuildVariables.USER_LINK_FLAGS.getVariableName(), ImmutableList.of(""))) .setActionName(LinkTargetType.DYNAMIC_LIBRARY.getActionName()) .setLinkTargetType(LinkTargetType.DYNAMIC_LIBRARY) .forceToolPath("foo/bar/linker") .setParamFile(paramFile) .build(); Pair<List<String>, List<String>> result = linkConfig.splitCommandline(); assertThat(result.first).containsExactly("foo/bar/linker", "@some/file.params").inOrder(); assertThat(result.second).containsExactly("-shared", "-o", "a/FakeOutput", "").inOrder(); } @Test public void testStaticLinkCommand() throws Exception { useConfiguration("--nostart_end_lib"); LinkCommandLine linkConfig = minimalConfiguration( getMockBuildVariables() .addStringVariable( LinkBuildVariables.OUTPUT_EXECPATH.getVariableName(), "a/FakeOutput")) .forceToolPath("foo/bar/ar") .setActionName(LinkTargetType.STATIC_LIBRARY.getActionName()) .setLinkTargetType(LinkTargetType.STATIC_LIBRARY) .build(); List<String> result = linkConfig.getRawLinkArgv(); assertThat(result).isEqualTo(Arrays.asList("foo/bar/ar", "rcsD", "a/FakeOutput")); } @Test public void testSplitAlwaysLinkLinkCommand() throws Exception { CcToolchainVariables.Builder variables = CcToolchainVariables.builder() .addStringVariable(CcCommon.SYSROOT_VARIABLE_NAME, "/usr/grte/v1") .addStringVariable(LinkBuildVariables.OUTPUT_EXECPATH.getVariableName(), "a/FakeOutput") .addStringVariable( LinkBuildVariables.LINKER_PARAM_FILE.getVariableName(), "some/file.params") .addCustomBuiltVariable( LinkBuildVariables.LIBRARIES_TO_LINK.getVariableName(), new CcToolchainVariables.SequenceBuilder() .addValue(LibraryToLinkValue.forObjectFile("foo.o", false)) .addValue(LibraryToLinkValue.forObjectFile("bar.o", false))); Artifact paramFile = scratchArtifact("some/file.params"); LinkCommandLine linkConfig = minimalConfiguration(variables) .setActionName(LinkTargetType.ALWAYS_LINK_STATIC_LIBRARY.getActionName()) .setLinkTargetType(LinkTargetType.ALWAYS_LINK_STATIC_LIBRARY) .forceToolPath("foo/bar/ar") .setParamFile(paramFile) .build(); Pair<List<String>, List<String>> result = linkConfig.splitCommandline(); assertThat(result.first).isEqualTo(Arrays.asList("foo/bar/ar", "@some/file.params")); assertThat(result.second).isEqualTo(Arrays.asList("rcsD", "a/FakeOutput", "foo.o", "bar.o")); } private SpecialArtifact createTreeArtifact(String name) { FileSystem fs = scratch.getFileSystem(); Path execRoot = fs.getPath(TestUtils.tmpDir()); PathFragment execPath = PathFragment.create("out").getRelative(name); return ActionsTestUtil.createTreeArtifactWithGeneratingAction( ArtifactRoot.asDerivedRoot(execRoot, RootType.Output, "out"), execPath); } private void verifyArguments( Iterable<String> arguments, Iterable<String> allowedArguments, Iterable<String> disallowedArguments) { assertThat(arguments).containsAtLeastElementsIn(allowedArguments); assertThat(arguments).containsNoneIn(disallowedArguments); } @Test public void testTreeArtifactLink() throws Exception { SpecialArtifact testTreeArtifact = createTreeArtifact("library_directory"); TreeFileArtifact library0 = TreeFileArtifact.createTreeOutput(testTreeArtifact, "library0.o"); TreeFileArtifact library1 = TreeFileArtifact.createTreeOutput(testTreeArtifact, "library1.o"); ArtifactExpander expander = new ArtifactExpander() { @Override public void expand(Artifact artifact, Collection<? super Artifact> output) { if (artifact.equals(testTreeArtifact)) { output.add(library0); output.add(library1); } }; }; Iterable<String> treeArtifactsPaths = ImmutableList.of(testTreeArtifact.getExecPathString()); Iterable<String> treeFileArtifactsPaths = ImmutableList.of(library0.getExecPathString(), library1.getExecPathString()); Artifact paramFile = scratchArtifact("some/file.params"); LinkCommandLine linkConfig = minimalConfiguration( getMockBuildVariables() .addStringVariable( LinkBuildVariables.LINKER_PARAM_FILE.getVariableName(), "some/file.params") .addCustomBuiltVariable( LinkBuildVariables.LIBRARIES_TO_LINK.getVariableName(), new CcToolchainVariables.SequenceBuilder() .addValue( LibraryToLinkValue.forObjectFileGroup( ImmutableList.of(testTreeArtifact), false)))) .forceToolPath("foo/bar/gcc") .setActionName(LinkTargetType.STATIC_LIBRARY.getActionName()) .setLinkTargetType(LinkTargetType.STATIC_LIBRARY) .setLinkingMode(Link.LinkingMode.STATIC) .setParamFile(paramFile) .build(); // Should only reference the tree artifact. verifyArguments(linkConfig.arguments(null), treeArtifactsPaths, treeFileArtifactsPaths); verifyArguments(linkConfig.getRawLinkArgv(null), treeArtifactsPaths, treeFileArtifactsPaths); verifyArguments( linkConfig.paramCmdLine().arguments(null), treeArtifactsPaths, treeFileArtifactsPaths); // Should only reference tree file artifacts. verifyArguments(linkConfig.arguments(expander), treeFileArtifactsPaths, treeArtifactsPaths); verifyArguments( linkConfig.getRawLinkArgv(expander), treeFileArtifactsPaths, treeArtifactsPaths); verifyArguments( linkConfig.paramCmdLine().arguments(expander), treeFileArtifactsPaths, treeArtifactsPaths); } }
20,642
0.702984
0.702015
457
44.168491
29.847315
100
false
false
0
0
0
0
0
0
0.531729
false
false
12
da0c4c77b4c3ea21d89d7fa54cfb848e6da7a33e
31,155,692,798,308
65a931e21cee213d2dad700f56947b785eb90462
/comp6231/assignment2/src/DRSCommon/DRSCommonServiceOperations.java
d046950ea7aecff18ba12646888a33686072b0a7
[]
no_license
joeyzhang1989/sample_code
https://github.com/joeyzhang1989/sample_code
ed2de587c07aede145e872f6d76ef8a3d72a20d4
395258ce85d2f72c357cbd669c028a684e4ad56c
refs/heads/master
2016-08-08T08:46:43.703000
2014-11-20T17:33:10
2014-11-20T17:33:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package DRSCommon; /** * DRSCommon/DRSCommonServiceOperations.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from D:/workspace/comp6231ass2/src/DRSCommon.idl * Saturday, October 27, 2012 6:12:47 PM EDT */ public interface DRSCommonServiceOperations { int buy (String customerID, String itemID, int numberOfItem); int returnNumOfItem (String customerID, String itemID, int numberOfItem); String checkStock (String itemID); int exchange (String customerID, String boughtItemID, int boughtNumber, String desiredItemID, int desiredNumber); } // interface DRSCommonServiceOperations
UTF-8
Java
635
java
DRSCommonServiceOperations.java
Java
[]
null
[]
package DRSCommon; /** * DRSCommon/DRSCommonServiceOperations.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from D:/workspace/comp6231ass2/src/DRSCommon.idl * Saturday, October 27, 2012 6:12:47 PM EDT */ public interface DRSCommonServiceOperations { int buy (String customerID, String itemID, int numberOfItem); int returnNumOfItem (String customerID, String itemID, int numberOfItem); String checkStock (String itemID); int exchange (String customerID, String boughtItemID, int boughtNumber, String desiredItemID, int desiredNumber); } // interface DRSCommonServiceOperations
635
0.762205
0.733858
17
35.35294
32.012756
115
false
false
0
0
0
0
0
0
0.941176
false
false
12
ff277af06c3c2b1940eed25de630bf0456b6969e
2,422,361,593,096
fb92fb1a82182260879b6f7660bc69b4df634850
/src/FirstSample.java
ccfc24230f250dee7631631602db72f71bc4c810
[]
no_license
xubowen0601/study
https://github.com/xubowen0601/study
8e34619c3ba0cb23b7753713caeefd4079638085
00bdad9e66f2b3ee2fe77376963a58a53c095e5a
refs/heads/master
2023-02-21T05:37:05.618000
2021-01-11T09:16:29
2021-01-11T09:16:29
314,500,273
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import static java.lang.Math.*; public class FirstSample { public static void main(String[] args) { System.out.println("We will not use 'Hello World!'"); System.out.println(2.0 - 1.1); int vacation = 12; System.out.println(vacation); double salary = 65000.0; System.out.println(salary); final double CM_PER_INCH = 2.54; double paperWidth = 8.5; double paperHeight = 11; System.out.println("Paper size in centimeters:" + paperWidth * CM_PER_INCH + "by" + paperHeight * CM_PER_INCH); double x = 4; double y = Math.sqrt(x); System.out.println(y); double a = 10; double y1 = pow(x, a); System.out.println(y1); double d = 9.997; int nd = (int) Math.round(d); System.out.println(nd); int m = 7; int n = 7; int e = 2 * ++m; int f = 2 * n++; System.out.println(e + " " + f); String greeting = "hello"; System.out.println("Hello".equals(greeting)); System.out.println("Hello".equalsIgnoreCase(greeting)); } } /** * */
UTF-8
Java
1,163
java
FirstSample.java
Java
[]
null
[]
import static java.lang.Math.*; public class FirstSample { public static void main(String[] args) { System.out.println("We will not use 'Hello World!'"); System.out.println(2.0 - 1.1); int vacation = 12; System.out.println(vacation); double salary = 65000.0; System.out.println(salary); final double CM_PER_INCH = 2.54; double paperWidth = 8.5; double paperHeight = 11; System.out.println("Paper size in centimeters:" + paperWidth * CM_PER_INCH + "by" + paperHeight * CM_PER_INCH); double x = 4; double y = Math.sqrt(x); System.out.println(y); double a = 10; double y1 = pow(x, a); System.out.println(y1); double d = 9.997; int nd = (int) Math.round(d); System.out.println(nd); int m = 7; int n = 7; int e = 2 * ++m; int f = 2 * n++; System.out.println(e + " " + f); String greeting = "hello"; System.out.println("Hello".equals(greeting)); System.out.println("Hello".equalsIgnoreCase(greeting)); } } /** * */
1,163
0.530524
0.503009
37
30.432432
17.803038
79
false
false
0
0
0
0
0
0
0.783784
false
false
12
c68a5d07eb04274d2e331cd20c5c544c982597b9
2,422,361,592,011
0221b3f7cb59c86179df5df8d170788d01166e97
/src/main/java/com/catalina/tokobat/dao/UserDao.java
9e9ba246cf78f857d7c5e4890744c2b0c27fad5b
[]
no_license
CatalinaID/tokobat-api
https://github.com/CatalinaID/tokobat-api
20d9a4943a3205c3def9eff0a7170335901becf9
d600fc38eab48a79e5a9089bae7a12377061f32b
refs/heads/master
2021-01-10T18:12:41.380000
2016-02-26T22:41:47
2016-02-26T22:41:47
50,477,764
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.catalina.tokobat.dao; import com.catalina.tokobat.entity.User; import java.util.List; /** * Created by Alifa on 1/29/2016. */ public interface UserDao { List<User> getAllUser(); User getUserById(Long id); User addNewUser(User user); User updateUser(User user); User findByUsername(String username); }
UTF-8
Java
338
java
UserDao.java
Java
[ { "context": "y.User;\n\nimport java.util.List;\n\n/**\n * Created by Alifa on 1/29/2016.\n */\npublic interface UserDao {\n ", "end": 124, "score": 0.9169503450393677, "start": 119, "tag": "USERNAME", "value": "Alifa" } ]
null
[]
package com.catalina.tokobat.dao; import com.catalina.tokobat.entity.User; import java.util.List; /** * Created by Alifa on 1/29/2016. */ public interface UserDao { List<User> getAllUser(); User getUserById(Long id); User addNewUser(User user); User updateUser(User user); User findByUsername(String username); }
338
0.710059
0.689349
16
20.125
15.337353
41
false
false
0
0
0
0
0
0
0.5
false
false
12
527d33b570158cf7cce0a3c72e18324f6fd22bca
24,137,716,231,297
57de10bc7884c5bee2c53ae24d826aaed4cde095
/SpringBootAdminClient/src/main/java/com/sam/admin/client/model/Person.java
97f0fd8d67eb72648008d44bf2298984b2a22f6d
[]
no_license
samirandeb/SamRepo
https://github.com/samirandeb/SamRepo
1994014dfe6d30e2348471e141f95c9b9ebc650b
b6af61f3b9f196ab68aea2a96adb2da781da1a07
refs/heads/master
2022-08-04T04:01:36.699000
2020-06-14T04:04:51
2020-06-14T04:04:51
61,801,746
1
0
null
false
2022-06-28T14:53:53
2016-06-23T11:57:23
2022-06-09T11:39:55
2022-06-28T14:53:53
35,763
1
0
3
JavaScript
false
false
package com.sam.admin.client.model; public class Person { //private Long id; private String fname; private String lname; private Long age; public Person(String fname, String lname, Long age) { super(); this.fname = fname; this.lname = lname; this.age = age; } /*public Long getId() { return id; } public void setId(Long id) { this.id = id; }*/ public String getFname() { return fname; } public void setFname(String fname) { this.fname = fname; } public String getLname() { return lname; } public void setLname(String lname) { this.lname = lname; } public Long getAge() { return age; } public void setAge(Long age) { this.age = age; } }
UTF-8
Java
735
java
Person.java
Java
[]
null
[]
package com.sam.admin.client.model; public class Person { //private Long id; private String fname; private String lname; private Long age; public Person(String fname, String lname, Long age) { super(); this.fname = fname; this.lname = lname; this.age = age; } /*public Long getId() { return id; } public void setId(Long id) { this.id = id; }*/ public String getFname() { return fname; } public void setFname(String fname) { this.fname = fname; } public String getLname() { return lname; } public void setLname(String lname) { this.lname = lname; } public Long getAge() { return age; } public void setAge(Long age) { this.age = age; } }
735
0.613605
0.613605
43
15.093023
12.782281
54
false
false
0
0
0
0
0
0
1.604651
false
false
12
e4f224de3dd69794ccffc76f775ecbe6887b51fa
27,522,150,455,066
eaef94ecfbbe42266cc97cf0b7272ae5cc6dbbee
/src/main/java/concurrency/ThreadInterfacesReview.java
990feb25dbf0bec93d09262e189fec3976fa0fc3
[]
no_license
MatheusY/1zo-819-part-2
https://github.com/MatheusY/1zo-819-part-2
d986b9075f4ea8fbd47b2694c288558fc5ea7ffa
02470012ff7967e3ecb8c0bc343897fff124befb
refs/heads/main
2023-04-14T22:24:53.040000
2021-04-25T22:32:38
2021-04-25T22:32:38
354,155,824
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package concurrency; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.function.Supplier; /* The Learn Programming Academy Java SE 11 Developer 1Z0-819 OCP Course - Part 2 Section 11: Concurrency Topic: Submitting Callable vs Runnable vs Supplier */ // Don't forget that Thread implements Runnable interface but // Thread itself has a run() method which does nothing in this instance class ThreadDoesNothing extends Thread { ThreadDoesNothing() { System.out.println("ThreadDoesNothing created"); } } // Custom thread overrides the run() method class ThreadDoesSomething extends Thread { public void run() { // Unchecked Exception throw new RuntimeException("Extended Thread chokes"); } } public class ThreadInterfacesReview { public static void main(String[] args) { // Custom Thread does not override Thread's run() method new ThreadDoesNothing().start(); // Custom Thread implements run(), throws RuntimeException new ThreadDoesSomething().start(); // Get instance of SingleThreadExecutor ExecutorService service = Executors.newSingleThreadExecutor(); // Call execute on service, and pass it an instance of Thread service.execute(new ThreadDoesNothing()); // Call submit on service, and pass it an instance of Thread Future<?> f = service.submit(new ThreadDoesSomething()); // Runnable variable assigned a lambda expression that // throws unchecked exception Runnable r1 = () -> { throw new RuntimeException("Runnable chokes in service.execute()"); }; // Runnable r1 = () -> { // throw new Exception ( // "Runnable chokes in service.execute()"); // }; // Callable c = () -> { // throw new Throwable( // "Callable chokes in service.submit()"); // }; try { // execute method called which is void service.execute(r1); } catch (Exception e) { e.printStackTrace(); } // Runnable variable assigned a lambda expression that // throws unchecked exception Runnable r2 = () -> { throw new RuntimeException("Runnable chokes in service.submit()"); }; // submit method called which returns a Future Future<?> f1 = service.submit(r2); // Callable variable assigned a lambda expression that // throws unchecked exception Callable<Void> c = () -> { throw new RuntimeException("Callable chokes in service.submit()"); }; // submit method called returns a Future Future f2 = service.submit(c); // Supplier Supplier s = () -> { throw new RuntimeException( "Suppplier::get chokes in service.submit()"); }; // Future f3 = service.submit(s::get); service.shutdown(); System.out.println(f); System.out.println(f1); System.out.println(f2); } }
UTF-8
Java
2,838
java
ThreadInterfacesReview.java
Java
[]
null
[]
package concurrency; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.function.Supplier; /* The Learn Programming Academy Java SE 11 Developer 1Z0-819 OCP Course - Part 2 Section 11: Concurrency Topic: Submitting Callable vs Runnable vs Supplier */ // Don't forget that Thread implements Runnable interface but // Thread itself has a run() method which does nothing in this instance class ThreadDoesNothing extends Thread { ThreadDoesNothing() { System.out.println("ThreadDoesNothing created"); } } // Custom thread overrides the run() method class ThreadDoesSomething extends Thread { public void run() { // Unchecked Exception throw new RuntimeException("Extended Thread chokes"); } } public class ThreadInterfacesReview { public static void main(String[] args) { // Custom Thread does not override Thread's run() method new ThreadDoesNothing().start(); // Custom Thread implements run(), throws RuntimeException new ThreadDoesSomething().start(); // Get instance of SingleThreadExecutor ExecutorService service = Executors.newSingleThreadExecutor(); // Call execute on service, and pass it an instance of Thread service.execute(new ThreadDoesNothing()); // Call submit on service, and pass it an instance of Thread Future<?> f = service.submit(new ThreadDoesSomething()); // Runnable variable assigned a lambda expression that // throws unchecked exception Runnable r1 = () -> { throw new RuntimeException("Runnable chokes in service.execute()"); }; // Runnable r1 = () -> { // throw new Exception ( // "Runnable chokes in service.execute()"); // }; // Callable c = () -> { // throw new Throwable( // "Callable chokes in service.submit()"); // }; try { // execute method called which is void service.execute(r1); } catch (Exception e) { e.printStackTrace(); } // Runnable variable assigned a lambda expression that // throws unchecked exception Runnable r2 = () -> { throw new RuntimeException("Runnable chokes in service.submit()"); }; // submit method called which returns a Future Future<?> f1 = service.submit(r2); // Callable variable assigned a lambda expression that // throws unchecked exception Callable<Void> c = () -> { throw new RuntimeException("Callable chokes in service.submit()"); }; // submit method called returns a Future Future f2 = service.submit(c); // Supplier Supplier s = () -> { throw new RuntimeException( "Suppplier::get chokes in service.submit()"); }; // Future f3 = service.submit(s::get); service.shutdown(); System.out.println(f); System.out.println(f1); System.out.println(f2); } }
2,838
0.699084
0.692037
103
26.553398
22.036478
71
false
false
0
0
0
0
0
0
1.640777
false
false
12
332c875619f858f4d9767a579a28a17f16f1a567
22,703,197,156,005
75996fe8fb07f219f63595f23f3025969763d983
/FTSP Maven Webapp/src/main/java/com/fujitsu/manager/reportManager/action/ReportAction.java
93fb44b2b8221867486d5ec1dff06a4b2785911f
[]
no_license
caiwei56011/FTSP
https://github.com/caiwei56011/FTSP
6482dee9aae4b3ca291bf1d005ef20597348ef5e
4a66588ffe815587e09950ac51d39a7327bad2f9
refs/heads/master
2021-04-17T00:28:50.819000
2016-03-30T02:05:33
2016-03-30T02:05:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fujitsu.manager.reportManager.action; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import com.fujitsu.IService.ICommonManagerService; import com.fujitsu.IService.IExportExcel; import com.fujitsu.IService.IAlarmManagementService; import com.fujitsu.IService.IMethodLog; import com.fujitsu.IService.IReportManagerService; import com.fujitsu.abstractAction.DownloadAction; import com.fujitsu.common.CommonDefine; import com.fujitsu.common.CommonException; import com.fujitsu.util.ExportExcelUtil; import com.mongodb.DBObject; import fusioncharts.FusionChartDesigner; public class ReportAction extends DownloadAction { private static final long serialVersionUID = 1L; private static final String TABLE_PRI="t_pm_origi_data_collect"; private static final String TABLE_PRI_MONTH="t_pm_origi_data_collect_month"; private static final String COLOR_CRITICAL="ff0000"; private static final String COLOR_MAJOR="ff8000"; private static final String COLOR_MINOR="ffff00"; private static final String COLOR_WARNING="800000"; @Resource public IReportManagerService reportManagerService; @Resource public ICommonManagerService commonManagerService; @Resource public IAlarmManagementService alarmManagementService; // 表名 public String table_name = ""; private boolean displayAll; private boolean displayNone; private String query; int nodeId; int nodeLevel; int endId; int endLevel; String text; boolean hasPath; private String level; private Map<String, String> condMap; public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public int getNodeId() { return nodeId; } public void setNodeId(int nodeId) { this.nodeId = nodeId; } public int getNodeLevel() { return nodeLevel; } public void setNodeLevel(int nodeLevel) { this.nodeLevel = nodeLevel; } public int getEndId() { return endId; } public void setEndId(int endId) { this.endId = endId; } public int getEndLevel() { return endLevel; } public void setEndLevel(int endLevel) { this.endLevel = endLevel; } public String getText() { return text; } public void setText(String text) { this.text = text; } public boolean isHasPath() { return hasPath; } public void setHasPath(boolean hasPath) { this.hasPath = hasPath; } public String getQuery() { return query; } public void setQuery(String query) { this.query = query; } public boolean isDisplayAll() { return displayAll; } public void setDisplayAll(boolean displayAll) { this.displayAll = displayAll; } public boolean isDisplayNone() { return displayNone; } public void setDisplayNone(boolean displayNone) { this.displayNone = displayNone; } public String getTable_name() { return table_name; } public void setTable_name(String table_name) { this.table_name = table_name; } // 查询参数 private String jsonString; public String getJsonString() { return jsonString; } public void setJsonString(String jsonString) { this.jsonString = jsonString; } /** * Method name: getResourceChartByStation <BR> * Description: 按局站查询资源统计信息<BR> * Remark: 2013-12-05<BR> * @author CaiJiaJia * @return String<BR> */ @IMethodLog(desc = "按局站查询资源统计信息") @SuppressWarnings({ "unchecked", "rawtypes" }) public String getResourceChartByStation(){ try { // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; // 将查询结果转成FusionCharts所需格式 String xmlString = ""; FusionChartDesigner fcd = new FusionChartDesigner(); // 按局站查询资源统计信息 if(paramMap.get("stationId")!=null){ // 判断是页面上那个chart图 if("left".equals(paramMap.get("flag").toString())){ // 需要统计的局站ID和名称 String[] stationIdSize = paramMap.get("stationId").toString().split(","); String[] stationNameSize = paramMap.get("stationName").toString().split(","); List<Map> mdListMap = new ArrayList<Map>(); for (int i = 0; i < stationIdSize.length; i++) { Map map = new HashMap(); map.put("RESOURCE_STATION_ID", Integer.parseInt(stationIdSize[i])); mdListMap.add(map); } // 按网元型号查询某局站的资源统计信息 List<Map> resourceList = reportManagerService.getResourceChartByStationAndNeModel(paramMap); // 行专列 rowToCol(resourceList, mdListMap, "NE_MODEL", "COUNT", "RESOURCE_STATION_ID"); for(int i=0;i<mdListMap.size();i++){ fcd.addSerialDatasList(stationNameSize[i], (ArrayList<Map>) resourceList, "NE_MODEL", mdListMap.get(i).get("RESOURCE_STATION_ID").toString()); } }else{ // 查询某些局站下的所有网元型号 List<Map> neModelList = reportManagerService.getAllNeModelsByStation(paramMap); String neModel = ""; if(neModelList.size()>0){ for (int i = 0; i < neModelList.size(); i++) { neModel += neModelList.get(i).get("NE_MODEL").toString()+","; } neModel = neModel.substring(0,neModel.lastIndexOf(",")); paramMap.put("neModel", neModel); } List<Map> resourceList = reportManagerService.getResourceChartByNeModelAndStation(paramMap); // 行专列 rowToCol(resourceList, neModelList, "RESOURCE_STATION_ID", "COUNT", "NE_MODEL"); for(int i=0;i<neModelList.size();i++){ fcd.addSerialDatasList(neModelList.get(i).get("NE_MODEL").toString(), (ArrayList<Map>) resourceList, "STATION_NAME", neModelList.get(i).get("NE_MODEL").toString()); } } } xmlString = fcd.getManyDimensionsXmlData("","",""); // 将封装成Map格式,用来转成JSON,返回前台 Map<String, Object> valueMap = new HashMap<String, Object>(); valueMap.put("xml", xmlString); resultObj = JSONObject.fromObject(valueMap); } catch (CommonException e) { result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(e.getErrorMessage()); resultObj = JSONObject.fromObject(result); } return RESULT_OBJ; } /** * * Method name: rowToCol <BR> * Description: rowToCol <BR> * Remark: <BR> * @param list<Map> 所有集合 * @param mdListMap 所需要行转列的信息 NET_TYPE:移动,NET_TYPE:联通,NET_TYPE:电信 * @param fcXKey 对应要配置在x轴的字段 * @param fcYKey 对应要配置在y周的字段 * @param dType mdListMap中的key */ private void rowToCol(List<Map> list, List<Map> mdListMap, String fcXKey, String fcYKey, String dType){ Map map = new HashMap(); int mdSizeFlag = 0; Map rowMap1 = null; Map rowMap2 = null; String xValue = ""; Set set = new HashSet(); for (int i = 0; i < list.size(); i++) { mdSizeFlag = 1; rowMap1 = list.get(i); xValue = rowMap1.get(fcXKey).toString(); for (int j = 0; j <mdListMap.size(); j++) { Map mdRowMap = mdListMap.get(j); rowMap1.put(mdRowMap.get(dType).toString(),0); } rowMap1.put(rowMap1.get(dType).toString(),rowMap1.get(fcYKey).toString()); set.add(rowMap1.get(dType).toString()); for (int j = i + 1; j < list.size(); j++) { rowMap2 = list.get(j); if (xValue.equals(rowMap2.get(fcXKey).toString())) { rowMap1.put(rowMap2.get(dType).toString(),rowMap2.get(fcYKey).toString()); set.add(rowMap2.get(dType).toString()); list.remove(j); --j; if (++mdSizeFlag == mdListMap.size()) { break; } } } } } /** * Method name: getResourceDetailByStation <BR> * Description: 按局站查询资源详细信息<BR> * Remark: 2013-12-06<BR> * @author CaiJiaJia * @return String<BR> */ @IMethodLog(desc = "按局站查询资源详细信息") @SuppressWarnings("unchecked") public String getResourceDetailByStation(){ try { // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; // 定义一个Map接受查询返回的值 Map<String, Object> resotrceMap = reportManagerService.getResourceDetailByStation(paramMap,start,limit); // 将返回的结果转成JSON对象,返回前台 resultObj = JSONObject.fromObject(resotrceMap); } catch (CommonException e) { result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(e.getErrorMessage()); resultObj = JSONObject.fromObject(result); } return RESULT_OBJ; } /** * Method name: getEmsGroupInfo_Resource <BR> * Description: 资源报表--按网管分组查询<BR> * Remark: 2013-12-02<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @IMethodLog(desc = "查询getEmsGroupInfo") @SuppressWarnings("unchecked") public String getEmsGroupInfo_Resource(){ try { // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap = reportManagerService.getEmsGroupInfo_Resource(paramMap,start,limit); // 将返回的结果转成JSON对象,返回前台 resultObj = JSONObject.fromObject(resultMap); } catch (CommonException e) { result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(e.getErrorMessage()); resultObj = JSONObject.fromObject(result); } return RESULT_OBJ; } /** * Method name: emsGroupFusionChart_Resource <BR> * Description: 资源报表--fusionChart<BR> * Remark: 2013-12-03<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @SuppressWarnings("unchecked") public String emsGroupFusionChart_Resource() throws CommonException{ // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; List<Map<String,Object>> List = reportManagerService.getEmsGroupFusionChart_Resource(paramMap); /** 设置fusionChart */ String chartXml = ""; ArrayList<Map> xmlList = new ArrayList<Map>(); for(int i=0; i<List.size();i++){ Map lom = List.get(i); xmlList.add((Map)lom); } FusionChartDesigner fcd = new FusionChartDesigner(); fcd.setOneDimensionList(xmlList, "X", "Y"); fcd.setChart_bgcolor("#F3f3f3"); fcd.setChart_caption("按网管分组统计"); fcd.setChart_xAxisName(""); fcd.setChart_yAxisName(""); fcd.setChartClickEnable(true); chartXml = fcd.getOneDimensionsXMLData(); Map<String,String> xmlMap = new HashMap<String,String>(); xmlMap.put("xml", chartXml); Object obj = (Object)xmlMap; resultObj = JSONObject.fromObject(obj); return RESULT_OBJ; } /** * Method name: getEmsInfo_Resource <BR> * Description: 资源报表--按网管分组查询<BR> * Remark: 2013-12-02<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @IMethodLog(desc = "查询getEmsGroupInfo") @SuppressWarnings("unchecked") public String getEmsInfo_Resource(){ try { // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap = reportManagerService.getEmsInfo_Resource(paramMap,start,limit); // 将返回的结果转成JSON对象,返回前台 resultObj = JSONObject.fromObject(resultMap); } catch (CommonException e) { result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(e.getErrorMessage()); resultObj = JSONObject.fromObject(result); } return RESULT_OBJ; } /** * Method name: emsFusionChart_Resource <BR> * Description: 资源报表--fusionChart<BR> * Remark: 2013-12-03<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @SuppressWarnings("unchecked") public String emsFusionChart_Resource() throws CommonException{ // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; List<Map<String,Object>> List = reportManagerService.getEmsFusionChart_Resource(paramMap); /** 设置fusionChart */ String chartXml = ""; ArrayList<Map> xmlList = new ArrayList<Map>(); for(int i=0; i<List.size();i++){ Map lom = List.get(i); xmlList.add((Map)lom); } FusionChartDesigner fcd = new FusionChartDesigner(); fcd.setOneDimensionList(xmlList, "X", "Y"); fcd.setChart_bgcolor("#F3f3f3"); fcd.setChart_caption(""); fcd.setChart_xAxisName(""); fcd.setChart_yAxisName(""); //fcd.setChart_rotateLabels("1"); //fcd.setChart_slantLabels("1"); //fcd.getChartNodePro().put("maxColWidth","30"); fcd.getChartNodePro().put("baseFontSize","12"); fcd.setLabelDisplay("WRAP"); fcd.setChartClickEnable(true); chartXml = fcd.getOneDimensionsXMLData(); Map<String,String> xmlMap = new HashMap<String,String>(); xmlMap.put("xml", chartXml); Object obj = (Object)xmlMap; resultObj = JSONObject.fromObject(obj); return RESULT_OBJ; } /** * Method name: getEmsGroupInfo_Performance <BR> * Description: 性能报表--按网管分组查询<BR> * Remark: 2013-12-11<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @IMethodLog(desc = "查询getEmsGroupInfo") @SuppressWarnings("unchecked") public String getEmsGroupInfo_Performance(){ try { Map<String, Object> paramMap = (Map<String, Object>)JSONObject.fromObject(jsonString); String timeType=(String)paramMap.get("timeType"); if("day".equals(timeType)){ setTable_name(TABLE_PRI); }else{ setTable_name(TABLE_PRI+"_month"); } paramMap.put("table_name",table_name); paramMap.put("timeType", paramMap.get("timeType")); paramMap.put("time",paramMap.get("time").toString()); paramMap.put("query","list"); Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap = reportManagerService.getEmsGroupInfo_Performance(paramMap,start,limit); // 将返回的结果转成JSON对象,返回前台 resultObj = JSONObject.fromObject(resultMap); } catch (CommonException e) { result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(e.getErrorMessage()); resultObj = JSONObject.fromObject(result); } return RESULT_OBJ; } public void setFusionChartSettings(FusionChartDesigner fcd_1){ fcd_1.setChart_caption(""); fcd_1.setChart_xAxisName(""); fcd_1.setChart_yAxisName(""); fcd_1.setChart_bgcolor("#F3f3f3"); //fcd_1.setChart_bgcolor("#ffffff"); fcd_1.setChart_showValues("1"); fcd_1.getChartNodePro().put("baseFontSize","12"); fcd_1.setLabelDisplay("WRAP"); fcd_1.setChartClickEnable(true); fcd_1.setChart_show_legend("1"); fcd_1.setChart_legend_position("right"); fcd_1.setChart_percent_label("1"); fcd_1.setChart_Decimals("2"); fcd_1.getChartNodePro().put("pieRadius","150");//饼状图半径控制 //fcd_1.getChartNodePro().put("maxColWidth","30"); fcd_1.getChartNodePro().put("showAboutMenuItem","0"); fcd_1.getChartNodePro().put("showPrintMenuItem","0"); } /** * Method name: fusionChart_Performance <BR> * Description: 性能报表--fusionChart<BR> * Remark: 2013-12-11<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @SuppressWarnings("unchecked") public String fusionChart_Performance() throws CommonException{ Map<String, Object> paramMap = (Map<String, Object>)JSONObject.fromObject(jsonString); String timeType=paramMap.get("timeType").toString(); if("day".equals(timeType)){ paramMap.put("table_name","t_pm_origi_data_collect"); }else{ paramMap.put("table_name","t_pm_origi_data_collect_month"); } paramMap.put("timeType",timeType); paramMap.put("time",paramMap.get("time").toString()); Map<String,String> xmlMap = new HashMap<String,String>(); level=paramMap.get("level")==null?"":paramMap.get("level").toString(); if(level==null || "".equals(level)){//生成第一层图表 String chartXml_1 = ""; Map<String, Object> map = reportManagerService.getEmsGroupInfo_Performance(paramMap,start,limit); List<Map> List_1=(List<Map>)map.get("rows"); List emsGroupIdList = new ArrayList<String>(); for (Map m : List_1) { emsGroupIdList.add(m.get("base_ems_group_id")); } FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setxListOneDimensionAdditionnal(emsGroupIdList); fcd_1.setOneDimensionList(List_1, "group_name", "cou"); fcd_1.getUserDefinedProperty().put("level","one"); fcd_1.setChart_caption(paramMap.get("time").toString()+"异常性能按网管分组统计"); chartXml_1 = fcd_1.getOneDimensionsXMLData(); xmlMap.put("xml_1", chartXml_1); }else if(level!=null && "one".equals(level)){//点击第一层图表进来 String chartXml_1 = ""; Map<String, Object> map=null; if("year".equals(timeType)){ map = reportManagerService.getPMMonthDataByEmsGroup(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setChart_showValues("0"); fcd_1.addSerialDatasList("计数值3级",(ArrayList)List_1,"retrieval_time","count_3"); fcd_1.addSerialDatasList("计数值2级",(ArrayList)List_1,"retrieval_time","count_2"); fcd_1.addSerialDatasList("计数值1级",(ArrayList)List_1,"retrieval_time","count_1"); fcd_1.addSerialDatasList("物理量3级",(ArrayList)List_1,"retrieval_time","physics_3"); fcd_1.addSerialDatasList("物理量2级",(ArrayList)List_1,"retrieval_time","physics_2"); fcd_1.addSerialDatasList("物理量1级",(ArrayList)List_1,"retrieval_time","physics_1"); fcd_1.getUserDefinedProperty().put("level","two"); fcd_1.getUserDefinedProperty().put("emsId",paramMap.get("group_name")); fcd_1.setChart_caption(paramMap.get("time").toString()+paramMap.get("label")+"网管组异常性能分布"); chartXml_1 = fcd_1.getManyDimensionsXmlData(); xmlMap.put("xml_1", chartXml_1); }else if("month".equals(timeType)){ paramMap.put("query_month",paramMap.get("time").toString()); map = reportManagerService.getPMDayDataByEmsGroup(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setChart_showValues("0"); fcd_1.addSerialDatasList("计数值3级",(ArrayList)List_1,"retrieval_time","count_3"); fcd_1.addSerialDatasList("计数值2级",(ArrayList)List_1,"retrieval_time","count_2"); fcd_1.addSerialDatasList("计数值1级",(ArrayList)List_1,"retrieval_time","count_1"); fcd_1.addSerialDatasList("物理量3级",(ArrayList)List_1,"retrieval_time","physics_3"); fcd_1.addSerialDatasList("物理量2级",(ArrayList)List_1,"retrieval_time","physics_2"); fcd_1.addSerialDatasList("物理量1级",(ArrayList)List_1,"retrieval_time","physics_1"); fcd_1.getUserDefinedProperty().put("level","two"); fcd_1.getUserDefinedProperty().put("emsId",paramMap.get("group_name")); fcd_1.setChart_caption(paramMap.get("time").toString()+paramMap.get("label")+"网管组异常性能分布"); chartXml_1 = fcd_1.getManyDimensionsXmlData(); xmlMap.put("xml_1", chartXml_1); }else if("day".equals(timeType)){ paramMap.put("query_day",paramMap.get("time").toString()); map = reportManagerService.getPMDayDataByQueryDayAndGroup(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setOneDimensionList(List_1, "type_level", "cou"); fcd_1.getUserDefinedProperty().put("level","three"); fcd_1.setChart_caption(paramMap.get("query_day").toString()+paramMap.get("label")+"网管组异常性能分布"); chartXml_1 = fcd_1.getOneDimensionsXMLData(); xmlMap.put("xml_1", chartXml_1); } }else if(level!=null && "two".equals(level)){//点击第二层图表进来 String chartXml_1 = ""; Map<String, Object> map=null; if("year".equals(timeType)){ paramMap.put("query_month",paramMap.get("label")); map = reportManagerService.getPMDayDataByEmsGroup(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setChart_showValues("0"); fcd_1.addSerialDatasList("计数值3级",(ArrayList)List_1,"retrieval_time","count_3"); fcd_1.addSerialDatasList("计数值2级",(ArrayList)List_1,"retrieval_time","count_2"); fcd_1.addSerialDatasList("计数值1级",(ArrayList)List_1,"retrieval_time","count_1"); fcd_1.addSerialDatasList("物理量3级",(ArrayList)List_1,"retrieval_time","physics_3"); fcd_1.addSerialDatasList("物理量2级",(ArrayList)List_1,"retrieval_time","physics_2"); fcd_1.addSerialDatasList("物理量1级",(ArrayList)List_1,"retrieval_time","physics_1"); fcd_1.getUserDefinedProperty().put("level","three"); fcd_1.setChart_caption(paramMap.get("label").toString()+paramMap.get("gName")+"网管组异常性能分布"); chartXml_1 = fcd_1.getManyDimensionsXmlData(); xmlMap.put("xml_1", chartXml_1); }else if("month".equals(timeType)){ paramMap.put("group_name",paramMap.get("group_name")); paramMap.put("query_day",paramMap.get("label")); map = reportManagerService.getPMDayDataByQueryDayAndGroup(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setOneDimensionList(List_1, "type_level", "cou"); fcd_1.getUserDefinedProperty().put("level","three"); fcd_1.setChart_caption(paramMap.get("label").toString()+paramMap.get("gName")+"网管组异常性能分布"); chartXml_1 = fcd_1.getOneDimensionsXMLData(); xmlMap.put("xml_1", chartXml_1); } } Object obj = (Object)xmlMap; resultObj = JSONObject.fromObject(obj); return RESULT_OBJ; } @SuppressWarnings("unchecked") public String emsFusionChart_Alarm() throws CommonException{ Map<String, Object> paramMap = (Map<String, Object>)JSONObject.fromObject(jsonString); String timeType=paramMap.get("timeType").toString(); paramMap.put("timeType",timeType); paramMap.put("time",paramMap.get("time").toString()); Map<String, Object> resultMap = new HashMap<String, Object>(); Map<String,String> xmlMap = new HashMap<String,String>(); level=paramMap.get("level")==null?"":paramMap.get("level").toString(); if(level==null || "".equals(level)){//生成第一层图表 resultMap = reportManagerService.getReportAlarmByEms(paramMap); List<Map> List_1=(List<Map>)resultMap.get("rows"); List emsIdList = new ArrayList<String>(); for (Map m : List_1) { emsIdList.add(m.get("base_ems_connection_id")); } String chartXml_1 = ""; FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setxListOneDimensionAdditionnal(emsIdList); fcd_1.setOneDimensionList(List_1, "display_name", "cou"); fcd_1.getUserDefinedProperty().put("level","one"); fcd_1.setChart_caption(paramMap.get("time").toString()+"告警按网管统计"); chartXml_1 = fcd_1.getOneDimensionsXMLData(); xmlMap.put("xml_1", chartXml_1); }else if(level!=null && "one".equals(level)){//点击第一层图表进来 String chartXml_1 = ""; Map<String, Object> map=null; if("year".equals(timeType)){ map =reportManagerService.getAlarmMonthDataByEms(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setChart_showValues("0"); fcd_1.addSerialDatasList("提示",COLOR_WARNING,(ArrayList)List_1,"first_time","ps_warning"); fcd_1.addSerialDatasList("一般",COLOR_MINOR,(ArrayList)List_1,"first_time","ps_minor"); fcd_1.addSerialDatasList("重要",COLOR_MAJOR,(ArrayList)List_1,"first_time","ps_major"); fcd_1.addSerialDatasList("紧急",COLOR_CRITICAL,(ArrayList)List_1,"first_time","ps_critical"); fcd_1.getUserDefinedProperty().put("level","two"); fcd_1.getUserDefinedProperty().put("emsId",paramMap.get("EMS_NAME")); fcd_1.setChart_caption(paramMap.get("time").toString()+paramMap.get("label")+"告警分布"); chartXml_1 = fcd_1.getManyDimensionsXmlData(); xmlMap.put("xml_1", chartXml_1); }else if("month".equals(timeType)){ paramMap.put("query_month",paramMap.get("time").toString()); map = reportManagerService.getAlarmDayDataByEms(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setChart_showValues("0"); fcd_1.addSerialDatasList("提示",COLOR_WARNING,(ArrayList)List_1,"first_time","ps_warning"); fcd_1.addSerialDatasList("一般",COLOR_MINOR,(ArrayList)List_1,"first_time","ps_minor"); fcd_1.addSerialDatasList("重要",COLOR_MAJOR,(ArrayList)List_1,"first_time","ps_major"); fcd_1.addSerialDatasList("紧急",COLOR_CRITICAL,(ArrayList)List_1,"first_time","ps_critical"); fcd_1.getUserDefinedProperty().put("level","two"); fcd_1.getUserDefinedProperty().put("emsId",paramMap.get("EMS_NAME")); fcd_1.setChart_caption(paramMap.get("time").toString()+paramMap.get("label")+"告警分布"); chartXml_1 = fcd_1.getManyDimensionsXmlData(); xmlMap.put("xml_1", chartXml_1); }else if("day".equals(timeType)){ paramMap.put("query_day",paramMap.get("time").toString()); map = reportManagerService.getAlarmDayDataByQueryDayAndEms(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setOneDimensionList(List_1, "type_level", "cou"); fcd_1.getUserDefinedProperty().put("level","three"); fcd_1.setChart_caption(paramMap.get("query_day").toString()+paramMap.get("label")+"告警分布"); chartXml_1 = fcd_1.getOneDimensionsXMLData(); xmlMap.put("xml_1", chartXml_1); } }else if(level!=null && "two".equals(level)){//点击第二层图表进来 String chartXml_1 = ""; Map<String, Object> map=null; if("year".equals(timeType)){ paramMap.put("query_month",paramMap.get("label")); map = reportManagerService.getAlarmDayDataByEms(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setChart_showValues("0"); fcd_1.addSerialDatasList("提示",COLOR_WARNING,(ArrayList)List_1,"first_time","ps_warning"); fcd_1.addSerialDatasList("一般",COLOR_MINOR,(ArrayList)List_1,"first_time","ps_minor"); fcd_1.addSerialDatasList("重要",COLOR_MAJOR,(ArrayList)List_1,"first_time","ps_major"); fcd_1.addSerialDatasList("紧急",COLOR_CRITICAL,(ArrayList)List_1,"first_time","ps_critical"); fcd_1.getUserDefinedProperty().put("level","three"); fcd_1.setChart_caption(paramMap.get("label").toString()+paramMap.get("eName")+"告警分布"); chartXml_1 = fcd_1.getManyDimensionsXmlData(); xmlMap.put("xml_1", chartXml_1); }else if("month".equals(timeType)){ paramMap.put("query_day",paramMap.get("label")); map = reportManagerService.getAlarmDayDataByQueryDayAndEms(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setOneDimensionList(List_1, "type_level", "cou"); fcd_1.getUserDefinedProperty().put("level","three"); fcd_1.setChart_caption(paramMap.get("query_day").toString()+paramMap.get("eName")+"告警分布"); chartXml_1 = fcd_1.getOneDimensionsXMLData(); xmlMap.put("xml_1", chartXml_1); } } Object obj = (Object)xmlMap; resultObj = JSONObject.fromObject(obj); return RESULT_OBJ; } /** * Method name: getEmsInfo_Performance <BR> * Description: 性能报表--按网管查询<BR> * Remark: 2013-12-11<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @IMethodLog(desc = "查询getEmsInfo") @SuppressWarnings("unchecked") public String getEmsInfo_Performance(){ // try { // // 将参数专程JSON对象 // JSONObject jsonObject = JSONObject.fromObject(jsonString); // // 将JSON对象转成Map对象 // Map<String, Object> paramMap = new HashMap<String, Object>(); // paramMap = (Map<String, Object>) jsonObject; // setTable_name(TABLE_PRI+paramMap.get("time").toString().substring(0,4)); // paramMap.put("table_name",table_name); // paramMap.put("timeType", paramMap.get("timeType")); // paramMap.put("time",paramMap.get("time").toString()); // paramMap.put("query","list"); // Map<String, Object> resultMap = new HashMap<String, Object>(); // resultMap = reportManagerService.getEmsInfo_Performance(paramMap,start,limit); // // 将返回的结果转成JSON对象,返回前台 // resultObj = JSONObject.fromObject(resultMap); // } catch (CommonException e) { // result.setReturnResult(CommonDefine.FAILED); // result.setReturnMessage(e.getErrorMessage()); // resultObj = JSONObject.fromObject(result); // } return RESULT_OBJ; } /** * Method name: emsFusionChart_Performance <BR> * Description: 性能报表--fusionChart<BR> * Remark: 2013-12-11<BR> * * @author YuanJia * @return List<Map<String, Object>><BR> */ @SuppressWarnings("unchecked") public String emsFusionChart_Performance() throws CommonException { String timeType = condMap.get("timeType").toString(); Map<String, String> xmlMap = new HashMap<String, String>(); level = condMap.get("level") == null ? "" : condMap.get("level") .toString(); String title = ""; try { SimpleDateFormat msdf = new SimpleDateFormat("yyyy年MM月"); SimpleDateFormat dsdf = new SimpleDateFormat("yyyy年MM月dd日"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM"); if (condMap.get("timeType").equals("day")){ Date time = sdf1.parse(condMap.get("time")); title = dsdf.format(time); } else if (condMap.get("timeType").equals("month")){ Date time = sdf2.parse(condMap.get("time")); title = msdf.format(time); } else if (condMap.get("timeType").equals("year")){ title = condMap.get("time")+"年"; } } catch (ParseException e) { e.printStackTrace(); } if (level == null || "".equals(level)) {// 生成第一层图表 String flag = condMap.get("firstGraph").toString(); if ("1".equals(flag)) { String chartXml_1 = ""; String chartXml_2 = ""; if (condMap.get("timeType").equals("day")) condMap.put("table_name", TABLE_PRI); else condMap.put("table_name", TABLE_PRI_MONTH); condMap.put("query", "chart"); Map<String, Object> map = reportManagerService .getEmsInfo_Performance(condMap, start, limit); // 获取fusion_01数据源 List<Map> List_1 = (List<Map>) map.get("rows"); List emsIdList = new ArrayList<String>(); for (Map m : List_1) { emsIdList.add(m.get("BASE_EMS_CONNECTION_ID")); } FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); // 需要emsId,因为网管名有可能重复 fcd_1.setxListOneDimensionAdditionnal(emsIdList); fcd_1.setOneDimensionList(List_1, "DISPLAY_NAME", "COU"); fcd_1.getUserDefinedProperty().put("level", "one"); fcd_1.setChart_caption(title + "异常性能按网管统计"); chartXml_1 = fcd_1.getOneDimensionsXMLData(); // System.out.println(chartXml_1); xmlMap.put("xml_1", chartXml_1); } } else if (level != null && "one".equals(level)) {// 点击第一层图表进来 String chartXml_1 = ""; Map<String, Object> map = null; if ("year".equals(timeType)) { map = reportManagerService.getPMDataPerMonthByEmsId(condMap); List<Map> List_1 = (List<Map>) map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setChart_showValues("0"); fcd_1.addSerialDatasList("计数值3级", (ArrayList) List_1, "retrieval_time", "count_3"); fcd_1.addSerialDatasList("计数值2级", (ArrayList) List_1, "retrieval_time", "count_2"); fcd_1.addSerialDatasList("计数值1级", (ArrayList) List_1, "retrieval_time", "count_1"); fcd_1.addSerialDatasList("物理量3级", (ArrayList) List_1, "retrieval_time", "physics_3"); fcd_1.addSerialDatasList("物理量2级", (ArrayList) List_1, "retrieval_time", "physics_2"); fcd_1.addSerialDatasList("物理量1级", (ArrayList) List_1, "retrieval_time", "physics_1"); fcd_1.getUserDefinedProperty().put("level", "two"); fcd_1.getUserDefinedProperty().put("emsId", condMap.get("emsId")); fcd_1.setChart_caption(title + condMap.get("label") + "异常性能分布"); chartXml_1 = fcd_1.getManyDimensionsXmlData(); xmlMap.put("xml_1", chartXml_1); } else if ("month".equals(timeType)) { map = reportManagerService.getPMDataPerMonthByEmsId(condMap); List<Map> List_1 = (List<Map>) map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setChart_showValues("0"); fcd_1.addSerialDatasList("计数值3级", (ArrayList) List_1, "retrieval_time", "count_3"); fcd_1.addSerialDatasList("计数值2级", (ArrayList) List_1, "retrieval_time", "count_2"); fcd_1.addSerialDatasList("计数值1级", (ArrayList) List_1, "retrieval_time", "count_1"); fcd_1.addSerialDatasList("物理量3级", (ArrayList) List_1, "retrieval_time", "physics_3"); fcd_1.addSerialDatasList("物理量2级", (ArrayList) List_1, "retrieval_time", "physics_2"); fcd_1.addSerialDatasList("物理量1级", (ArrayList) List_1, "retrieval_time", "physics_1"); fcd_1.getUserDefinedProperty().put("level", "two"); fcd_1.getUserDefinedProperty().put("emsId", condMap.get("emsId")); fcd_1.setChart_caption(title + condMap.get("label") + "异常性能分布"); chartXml_1 = fcd_1.getManyDimensionsXmlData(); xmlMap.put("xml_1", chartXml_1); } else if ("day".equals(timeType)) { condMap.put("query_day", condMap.get("time").toString()); map = reportManagerService.getPMDataPerDayEms(condMap); List<Map> List_1 = (List<Map>) map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setOneDimensionList(List_1, "type_level", "cou"); fcd_1.getUserDefinedProperty().put("level", "three"); fcd_1.setChartClickEnable(false); fcd_1.setChart_caption(title + condMap.get("label") + "异常性能分布"); chartXml_1 = fcd_1.getOneDimensionsXMLData(); xmlMap.put("xml_1", chartXml_1); } } else if (level != null && "two".equals(level)) {// 点击第二层图表进来 String chartXml_1 = ""; Map<String, Object> map = null; if ("year".equals(timeType)) { condMap.put("query_month", condMap.get("label")); map = reportManagerService.getPMDataPerDayByEmsId(condMap); List<Map> List_1 = (List<Map>) map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setChart_showValues("0"); fcd_1.addSerialDatasList("计数值3级", (ArrayList) List_1, "retrieval_time", "count_3"); fcd_1.addSerialDatasList("计数值2级", (ArrayList) List_1, "retrieval_time", "count_2"); fcd_1.addSerialDatasList("计数值1级", (ArrayList) List_1, "retrieval_time", "count_1"); fcd_1.addSerialDatasList("物理量3级", (ArrayList) List_1, "retrieval_time", "physics_3"); fcd_1.addSerialDatasList("物理量2级", (ArrayList) List_1, "retrieval_time", "physics_2"); fcd_1.addSerialDatasList("物理量1级", (ArrayList) List_1, "retrieval_time", "physics_1"); fcd_1.setChartClickEnable(false); fcd_1.getUserDefinedProperty().put("level", "three"); String emsName = reportManagerService.getEmsName(condMap); fcd_1.setChart_caption(condMap.get("label") + emsName + "异常性能分布"); chartXml_1 = fcd_1.getManyDimensionsXmlData(); xmlMap.put("xml_1", chartXml_1); } else if ("month".equals(timeType)) { condMap.put("query_day", condMap.get("label")); map = reportManagerService.getPMDataPerDayEms(condMap); List<Map> List_1 = (List<Map>) map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setOneDimensionList(List_1, "type_level", "cou"); fcd_1.getUserDefinedProperty().put("level", "three"); fcd_1.setChartClickEnable(false); String emsName = reportManagerService.getEmsName(condMap); fcd_1.setChart_caption(condMap.get("label") +emsName+"异常性能分布"); chartXml_1 = fcd_1.getOneDimensionsXMLData(); xmlMap.put("xml_1", chartXml_1); } } Object obj = (Object) xmlMap; resultObj = JSONObject.fromObject(obj); return RESULT_OBJ; } /** * Method name: getEmsInfo_Alarm <BR> * Description: 告警报表--按网管查询<BR> * Remark: 2013-12-19<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @IMethodLog(desc = "查询getEmsInfo_Alarm") @SuppressWarnings("unchecked") public String getEmsInfo_Alarm(){ try { // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; String t=paramMap.get("time").toString().replaceAll("-", ""); int time=Integer.parseInt(t); int groupId=0; int[] ems=null; if(paramMap.get("GROUPID")!=null && !"".equals(paramMap.get("GROUPID"))){ groupId=Integer.parseInt(paramMap.get("GROUPID").toString()); } if(paramMap.get("EMSIDS")!=null && !"".equals(paramMap.get("EMSIDS"))){ String emsIds=paramMap.get("EMSIDS").toString(); if(emsIds!=""){ String[] ids=emsIds.split(","); ems=new int[ids.length]; for(int i=0;i<ids.length;i++){ ems[i]=Integer.parseInt(ids[i]); } } } setTable_name(CommonDefine.T_HISTORY_ALARM); Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap = alarmManagementService.getReportAlarmByEms(groupId,ems,this.getTable_name(),start,limit,time); /** 此处数据为假,仅供测试*/ if(resultMap==null || resultMap.get("rows")==null || ((List<DBObject>)resultMap.get("rows")).size()==0){ setTable_name(CommonDefine.T_CURRENT_ALARM); resultMap = alarmManagementService.getReportAlarmByEms(groupId,ems,this.getTable_name(),start,limit,time); } // 将返回的结果转成JSON对象,返回前台 resultObj = JSONObject.fromObject(resultMap); } catch (Exception e) { e.printStackTrace(); result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(getText(e.getMessage())); resultObj = JSONObject.fromObject(result); } return RESULT_OBJ; } /** * Method name: emsFusionChart_Alarm <BR> * Description: 告警报表--fusionChart<BR> * Remark: 2013-12-19<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ // @SuppressWarnings("unchecked") // public String emsFusionChart_Alarm() throws CommonException{ // // 将参数专程JSON对象 // JSONObject jsonObject = JSONObject.fromObject(jsonString); // // 将JSON对象转成Map对象 // Map<String, Object> paramMap = new HashMap<String, Object>(); // paramMap = (Map<String, Object>) jsonObject; // String timeType=paramMap.get("timeType").toString(); // String t=paramMap.get("time").toString().replaceAll("-", ""); // int time=Integer.parseInt(t); // int groupId=0; // int[] ems=null; // if(paramMap.get("GROUPID")!=null && !"".equals(paramMap.get("GROUPID"))){ // groupId=Integer.parseInt(paramMap.get("GROUPID").toString()); // } // if(paramMap.get("EMSIDS")!=null && !"".equals(paramMap.get("EMSIDS"))){ // String emsIds=paramMap.get("EMSIDS").toString(); // if(emsIds!=""){ // String[] ids=emsIds.split(","); // ems=new int[ids.length]; // for(int i=0;i<ids.length;i++){ // ems[i]=Integer.parseInt(ids[i]); // } // } // } // Map<String, Object> resultMap = new HashMap<String, Object>(); // Map<String,String> xmlMap = new HashMap<String,String>(); // level=paramMap.get("level")==null?"":paramMap.get("level").toString(); // if(level==null || "".equals(level)){//生成第一层图表 // setTable_name(CommonDefine.T_CURRENT_ALARM); // resultMap = faultManagerService.getReportAlarmByEms(groupId,ems,this.getTable_name(),start,limit,time); // if(resultMap==null || resultMap.get("rows")==null || ((List<DBObject>)resultMap.get("rows")).size()==0){ // setTable_name(CommonDefine.T_HISTORY_ALARM); // resultMap = faultManagerService.getReportAlarmByEms(groupId,ems,this.getTable_name(),start,limit,time); // } // List<Map> List_1=(List<Map>)resultMap.get("rows"); // String chartXml_1 = ""; // FusionChartDesigner fcd_1 = new FusionChartDesigner(); // setFusionChartSettings(fcd_1); // fcd_1.setOneDimensionList(List_1, "EMS_NAME", "count"); // fcd_1.getUserDefinedProperty().put("level","one"); // fcd_1.setChart_caption(paramMap.get("time").toString()+"告警按网管统计"); // chartXml_1 = fcd_1.getOneDimensionsXMLData(); // xmlMap.put("xml_1", chartXml_1); // }else if(level!=null && "one".equals(level)){//点击第一层图表进来 // String chartXml_1 = ""; // Map<String, Object> map=null; // if("year".equals(timeType)){ // paramMap.put("table_name", CommonDefine.T_CURRENT_ALARM); // resultMap =faultManagerService.getAlarmMonthDataByEms(paramMap); // if(resultMap==null || resultMap.get("rows")==null || ((List<DBObject>)resultMap.get("rows")).size()==0){ // paramMap.put("table_name", CommonDefine.T_HISTORY_ALARM); // resultMap = faultManagerService.getAlarmMonthDataByEms(paramMap); // } // List<Map> List_1=(List<Map>)map.get("rows"); // FusionChartDesigner fcd_1 = new FusionChartDesigner(); // setFusionChartSettings(fcd_1); // fcd_1.addSerialDatasList("计数值3级",(ArrayList)List_1,"retrieval_time","count_3"); // fcd_1.addSerialDatasList("计数值2级",(ArrayList)List_1,"retrieval_time","count_2"); // fcd_1.addSerialDatasList("计数值1级",(ArrayList)List_1,"retrieval_time","count_1"); // fcd_1.addSerialDatasList("物理量3级",(ArrayList)List_1,"retrieval_time","physics_3"); // fcd_1.addSerialDatasList("物理量2级",(ArrayList)List_1,"retrieval_time","physics_2"); // fcd_1.addSerialDatasList("物理量1级",(ArrayList)List_1,"retrieval_time","physics_1"); // fcd_1.getUserDefinedProperty().put("level","two"); // fcd_1.setChart_caption(paramMap.get("time").toString()+paramMap.get("label")+"网管组异常性能分布"); // chartXml_1 = fcd_1.getManyDimensionsXmlData(); // xmlMap.put("xml_1", chartXml_1); // }else if("month".equals(timeType)){ // paramMap.put("group_name",paramMap.get("label")); // paramMap.put("query_month",paramMap.get("time").toString()); // map = reportManagerService.getPMDayDataByEmsGroup(paramMap); // List<Map> List_1=(List<Map>)map.get("rows"); // FusionChartDesigner fcd_1 = new FusionChartDesigner(); // setFusionChartSettings(fcd_1); // fcd_1.addSerialDatasList("计数值3级",(ArrayList)List_1,"retrieval_time","count_3"); // fcd_1.addSerialDatasList("计数值2级",(ArrayList)List_1,"retrieval_time","count_2"); // fcd_1.addSerialDatasList("计数值1级",(ArrayList)List_1,"retrieval_time","count_1"); // fcd_1.addSerialDatasList("物理量3级",(ArrayList)List_1,"retrieval_time","physics_3"); // fcd_1.addSerialDatasList("物理量2级",(ArrayList)List_1,"retrieval_time","physics_2"); // fcd_1.addSerialDatasList("物理量1级",(ArrayList)List_1,"retrieval_time","physics_1"); // fcd_1.getUserDefinedProperty().put("level","two"); // fcd_1.setChart_caption(paramMap.get("time").toString()+paramMap.get("label")+"网管组异常性能分布"); // chartXml_1 = fcd_1.getManyDimensionsXmlData(); // xmlMap.put("xml_1", chartXml_1); // }else if("day".equals(timeType)){ // paramMap.put("group_name",paramMap.get("group_name")); // paramMap.put("query_day",paramMap.get("time").toString()); // map = reportManagerService.getPMDayDataByQueryDayAndGroup(paramMap); // List<Map> List_1=(List<Map>)map.get("rows"); // FusionChartDesigner fcd_1 = new FusionChartDesigner(); // setFusionChartSettings(fcd_1); // fcd_1.setOneDimensionList(List_1, "type_level", "cou"); // fcd_1.getUserDefinedProperty().put("level","three"); // fcd_1.setChart_caption(paramMap.get("label")+"异常性能按网管分组统计"); // chartXml_1 = fcd_1.getOneDimensionsXMLData(); // xmlMap.put("xml_1", chartXml_1); // } // }else if(level!=null && "two".equals(level)){//点击第二层图表进来 // String chartXml_1 = ""; // Map<String, Object> map=null; // if("year".equals(timeType)){ // paramMap.put("group_name",paramMap.get("group_name")); // paramMap.put("query_month",paramMap.get("label")); // map = reportManagerService.getPMDayDataByEmsGroup(paramMap); // List<Map> List_1=(List<Map>)map.get("rows"); // FusionChartDesigner fcd_1 = new FusionChartDesigner(); // setFusionChartSettings(fcd_1); // fcd_1.addSerialDatasList("计数值3级",(ArrayList)List_1,"retrieval_time","count_3"); // fcd_1.addSerialDatasList("计数值2级",(ArrayList)List_1,"retrieval_time","count_2"); // fcd_1.addSerialDatasList("计数值1级",(ArrayList)List_1,"retrieval_time","count_1"); // fcd_1.addSerialDatasList("物理量3级",(ArrayList)List_1,"retrieval_time","physics_3"); // fcd_1.addSerialDatasList("物理量2级",(ArrayList)List_1,"retrieval_time","physics_2"); // fcd_1.addSerialDatasList("物理量1级",(ArrayList)List_1,"retrieval_time","physics_1"); // fcd_1.getUserDefinedProperty().put("level","three"); // fcd_1.setChart_caption(paramMap.get("label").toString()+paramMap.get("group_name")+"网管组异常性能分布"); // chartXml_1 = fcd_1.getManyDimensionsXmlData(); // xmlMap.put("xml_1", chartXml_1); // }else if("month".equals(timeType)){ // paramMap.put("group_name",paramMap.get("group_name")); // paramMap.put("query_day",paramMap.get("label")); // map = reportManagerService.getPMDayDataByQueryDayAndGroup(paramMap); // List<Map> List_1=(List<Map>)map.get("rows"); // FusionChartDesigner fcd_1 = new FusionChartDesigner(); // setFusionChartSettings(fcd_1); // fcd_1.setOneDimensionList(List_1, "type_level", "cou"); // fcd_1.getUserDefinedProperty().put("level","three"); // fcd_1.setChart_caption(paramMap.get("label")+"异常性能按网管分组统计"); // chartXml_1 = fcd_1.getOneDimensionsXMLData(); // xmlMap.put("xml_1", chartXml_1); // } // } // Object obj = (Object)xmlMap; // resultObj = JSONObject.fromObject(obj); // return RESULT_OBJ; // // // } /** * Method name: getEmsGroupInfo_Circuit <BR> * Description: 资源报表--按网管分组查询<BR> * Remark: 2013-12-02<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @IMethodLog(desc = "查询getEmsGroupInfo_Circuit") @SuppressWarnings("unchecked") public String getEmsGroupInfo_Circuit(){ try { // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap = reportManagerService.getEmsGroupInfo_Circuit(paramMap,start,limit); // 将返回的结果转成JSON对象,返回前台 resultObj = JSONObject.fromObject(resultMap); } catch (CommonException e) { result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(e.getErrorMessage()); resultObj = JSONObject.fromObject(result); } return RESULT_OBJ; } /** * Method name: emsGroupFusionChart_Circuit <BR> * Description: 资源报表--fusionChart<BR> * Remark: 2013-12-23<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @SuppressWarnings("unchecked") public String emsGroupFusionChart_Circuit() throws CommonException{ // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; List<Map<String,Object>> List = null; FusionChartDesigner fcd = new FusionChartDesigner(); if(paramMap.get("PARA")!=null){ List = reportManagerService.getEmsGroupFusionChart_Circuit_1(paramMap); fcd.setChart_caption("电路:按网管分组统计"); }else{ List = reportManagerService.getEmsGroupFusionChart_Circuit_2(paramMap); fcd.setChart_caption("按网管统计"); } /** 设置fusionChart */ String chartXml = ""; ArrayList<Map> xmlList = new ArrayList<Map>(); for(int i=0; i<List.size();i++){ Map lom = List.get(i); xmlList.add((Map)lom); } fcd.setOneDimensionList(xmlList, "X", "Y"); fcd.setChart_bgcolor("#F3f3f3"); fcd.setChart_xAxisName(""); fcd.setChart_yAxisName(""); fcd.setChartClickEnable(true); chartXml = fcd.getOneDimensionsXMLData(); Map<String,String> xmlMap = new HashMap<String,String>(); xmlMap.put("xml", chartXml); Object obj = (Object)xmlMap; resultObj = JSONObject.fromObject(obj); return RESULT_OBJ; } @IMethodLog(desc = "查询所有网管分组") public String getAllEmsGroups(){ try { // 查询所有网管分组 List<Map> dataList = commonManagerService.getAllEmsGroups(sysUserId,displayAll,displayNone, false); // 将返回的结果转成JSON对象,返回前台 Map map = new HashMap(); map.put("rows", dataList); resultObj = JSONObject.fromObject(map); } catch (CommonException e) { result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(e.getErrorMessage()); resultObj = JSONObject.fromObject(result); } return RESULT_OBJ; } // @IMethodLog(desc = "导出性能数据按网管统计") // @SuppressWarnings("unchecked") // public void exportEmsInfo_Performance(){ // HttpServletResponse response = ServletActionContext.getResponse(); // try { // // 将参数专程JSON对象 // JSONObject jsonObject = JSONObject.fromObject(jsonString); // // 将JSON对象转成Map对象 // Map<String, Object> paramMap = new HashMap<String, Object>(); // paramMap = (Map<String, Object>) jsonObject; // if("month".equals(paramMap.get("timeType")) || "day".equals(paramMap.get("timeType"))){ // String time = paramMap.get("time").toString().split("-")[0] + "_" + paramMap.get("time").toString().split("-")[1]; // setTable_name("t_pm_origi_data_2_" + time); // }else{ // String time = paramMap.get("time").toString().split("-")[0]; // setTable_name("t_pm_origi_data_2_" + time); // } // if("day".equals(paramMap.get("timeType"))){ // paramMap.put("day",paramMap.get("time").toString()); // } // paramMap.put("table_name", table_name); // Map<String, Object> resultMap = new HashMap<String, Object>(); // resultMap = reportManagerService.getEmsInfo_Performance(paramMap,0,limit); // // 将返回的结果转成JSON对象,返回前台 // List<Map<String, Object>> list = (List<Map<String, Object>>)resultMap.get("rows"); // //Export Excel // String myFlieName="性能数据按网管统计.xls"; // response.setContentType("application/vnd.ms-excel"); // response.addHeader("Content-Disposition","attachment; filename="+new String(myFlieName.getBytes("gb2312"), "ISO8859-1" )); // OutputStream os = response.getOutputStream(); // WritableWorkbook wwb = null; // wwb = Workbook.createWorkbook(os); // if(wwb!=null){ // WritableSheet ws = wwb.createSheet("性能数据按网管分组统计", 0); // ws.addCell(new Label(0, 0,"异常等级")); // ws.addCell(new Label(1, 0,"网管分组")); // ws.addCell(new Label(2, 0,"网管")); // ws.addCell(new Label(3, 0,"子网")); // ws.addCell(new Label(4, 0,"网元")); // ws.addCell(new Label(5, 0,"型号")); // ws.addCell(new Label(6, 0,"端口")); // ws.addCell(new Label(7, 0,"业务类型")); // ws.addCell(new Label(8, 0,"端口类型")); // ws.addCell(new Label(9, 0,"速率")); // ws.addCell(new Label(10, 0,"通道")); // ws.addCell(new Label(11, 0,"性能时间")); // ws.addCell(new Label(12, 0,"方向")); // ws.addCell(new Label(13, 0,"性能值")); // ws.addCell(new Label(14, 0,"性能基准值")); // ws.addCell(new Label(15, 0,"连续异常")); // ws.addCell(new Label(16, 0,"性能分析模板")); // ws.addCell(new Label(17, 0,"采集时间")); // for(int i=0;i<list.size();i++){ // int value=(list.get(i).get("EXCEPTION_LV")==null?0:Integer.valueOf(list.get(i).get("EXCEPTION_LV").toString())); // String gjjb="";//异常级别 // WritableCellFormat wff_color = new WritableCellFormat(); // if(value==0){ // wff_color.setBackground(Colour.GREEN); // gjjb="正常"; // }else if(value==1){ // wff_color.setBackground(Colour.YELLOW); // gjjb="告警等级1"; // }else if(value==2){ // wff_color.setBackground(Colour.ORANGE); // gjjb="告警等级2"; // }else if(value==3){ // wff_color.setBackground(Colour.RED); // gjjb="告警等级3"; // } // ws.addCell(new Label(0, i+1,gjjb,wff_color)); // ws.addCell(new Label(1, i+1,list.get(i).get("DISPLAY_EMS_GROUP")==null?"":list.get(i).get("DISPLAY_EMS_GROUP").toString())); // ws.addCell(new Label(2, i+1,list.get(i).get("DISPLAY_EMS")==null?"":list.get(i).get("DISPLAY_EMS").toString())); // ws.addCell(new Label(3, i+1,list.get(i).get("DISPLAY_SUBNET")==null?"":list.get(i).get("DISPLAY_SUBNET").toString())); // ws.addCell(new Label(4, i+1,list.get(i).get("DISPLAY_NE")==null?"":list.get(i).get("DISPLAY_NE").toString())); // ws.addCell(new Label(5, i+1,list.get(i).get("NET_TYPE")==null?"":list.get(i).get("NET_TYPE").toString())); // ws.addCell(new Label(6, i+1,list.get(i).get("PORT")==null?"":list.get(i).get("PORT").toString())); // ws.addCell(new Label(7, i+1,list.get(i).get("BUSINESS_TYPE")==null?"":list.get(i).get("BUSINESS_TYPE").toString())); // ws.addCell(new Label(8, i+1,list.get(i).get("PTP_TYPE")==null?"":list.get(i).get("PTP_TYPE").toString())); // ws.addCell(new Label(9, i+1,list.get(i).get("SPEED")==null?"":list.get(i).get("SPEED").toString())); // ws.addCell(new Label(10, i+1,list.get(i).get("DISPLAY_CTP")==null?"":list.get(i).get("DISPLAY_CTP").toString())); // ws.addCell(new Label(11, i+1,list.get(i).get("PERFORMANCE_EVENT")==null?"":list.get(i).get("PERFORMANCE_EVENT").toString())); // ws.addCell(new Label(12, i+1,list.get(i).get("DIRECTION")==null?"":list.get(i).get("DIRECTION").toString())); // ws.addCell(new Label(13, i+1,list.get(i).get("PM_VALUE")==null?"":list.get(i).get("PM_VALUE").toString())); // ws.addCell(new Label(14, i+1,list.get(i).get("PM_COMPARE_VALUE")==null?"":list.get(i).get("PM_COMPARE_VALUE").toString())); // ws.addCell(new Label(15, i+1,list.get(i).get("EXCEPTION_COUNT")==null?"":list.get(i).get("EXCEPTION_COUNT").toString())); // ws.addCell(new Label(16, i+1,list.get(i).get("DISPLAY_TEMPLATE_NAME")==null?"":list.get(i).get("DISPLAY_TEMPLATE_NAME").toString())); // ws.addCell(new Label(17, i+1,list.get(i).get("COLLECT_TIME")==null?"":list.get(i).get("COLLECT_TIME").toString())); // } // try { // wwb.write(); // } catch (IOException e) { // e.printStackTrace(); // }finally{ // wwb.close(); // os.close(); // response.flushBuffer(); // } // } // // } catch (Exception e) { // e.printStackTrace(); // } // } @IMethodLog(desc = "导出性能数据按网管统计") @SuppressWarnings("unchecked") public String exportEmsInfo_Performance(){ // // 将参数专程JSON对象 // JSONObject jsonObject = JSONObject.fromObject(jsonString); // // 将JSON对象转成Map对象 // Map<String, Object> paramMap = new HashMap<String, Object>(); // paramMap = (Map<String, Object>) jsonObject; // setTable_name(TABLE_PRI+paramMap.get("time").toString().substring(0,4)); // paramMap.put("table_name",table_name); // paramMap.put("timeType", paramMap.get("timeType")); // paramMap.put("time",paramMap.get("time").toString()); // paramMap.put("query","list"); // Map<String, Object> resultMap = new HashMap<String, Object>(); // try { // resultMap = reportManagerService.getEmsInfo_Performance(paramMap,start,limit); // } catch (CommonException e) { // e.printStackTrace(); // } // List<Map> list = (List<Map>)resultMap.get("rows"); // String destination = null; // String myFlieName="性能数据按网管统计"; // IExportExcel ex=new ExportExcelUtil(CommonDefine.PATH_ROOT+ CommonDefine.EXCEL.TEMP_DIR,myFlieName); // destination = ex.writeExcel(list,CommonDefine.EXCEL.REPORT_PERFROMANCE_EMS, false); // setFilePath(destination); return RESULT_DOWNLOAD; } @IMethodLog(desc = "导出性能数据按网管分组统计") @SuppressWarnings("unchecked") public String exportEmsGroupInfo_Performance(){ // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; setTable_name(TABLE_PRI+paramMap.get("time").toString().substring(0,4)); paramMap.put("table_name",table_name); paramMap.put("timeType", paramMap.get("timeType")); paramMap.put("time",paramMap.get("time").toString()); paramMap.put("query","list"); Map<String, Object> resultMap = new HashMap<String, Object>(); try { resultMap = reportManagerService.getEmsGroupInfo_Performance(paramMap,start,limit); } catch (CommonException e) { e.printStackTrace(); } // 将返回的结果转成JSON对象,返回前台 List<Map> list = (List<Map>)resultMap.get("rows"); String destination = null; String myFlieName="性能数据按网管分组统计"; IExportExcel ex=new ExportExcelUtil(CommonDefine.PATH_ROOT+ CommonDefine.EXCEL.TEMP_DIR,myFlieName); destination = ex.writeExcel(list,CommonDefine.EXCEL.REPORT_PERFROMANCE_EMS, false); setFilePath(destination); return RESULT_DOWNLOAD; } @IMethodLog(desc = "导出告警按网管统计") @SuppressWarnings("unchecked") public String exportEmsInfo_Alarm(){ // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; String t=paramMap.get("time").toString().replaceAll("-", ""); int time=Integer.parseInt(t); int groupId=0; int[] ems=null; if(paramMap.get("GROUPID")!=null && !"".equals(paramMap.get("GROUPID"))){ groupId=Integer.parseInt(paramMap.get("GROUPID").toString()); } if(paramMap.get("EMSIDS")!=null && !"".equals(paramMap.get("EMSIDS"))){ String emsIds=paramMap.get("EMSIDS").toString(); if(emsIds!=""){ String[] ids=emsIds.split(","); ems=new int[ids.length]; for(int i=0;i<ids.length;i++){ ems[i]=Integer.parseInt(ids[i]); } } } setTable_name(CommonDefine.T_HISTORY_ALARM); Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap = alarmManagementService.getReportAlarmByEms(groupId,ems,this.getTable_name(),start,limit,time); /** 此处数据为假,仅供测试*/ if(resultMap==null || resultMap.get("rows")==null || ((List<DBObject>)resultMap.get("rows")).size()==0){ setTable_name(CommonDefine.T_CURRENT_ALARM); resultMap = alarmManagementService.getReportAlarmByEms(groupId,ems,this.getTable_name(),start,limit,time); } List<Map> list = (List<Map>)resultMap.get("rows"); String destination = null; String myFlieName="告警按网管统计"; IExportExcel ex=new ExportExcelUtil(CommonDefine.PATH_ROOT + CommonDefine.EXCEL.TEMP_DIR,myFlieName); destination = ex.writeExcel(list,CommonDefine.EXCEL.REPORT_ALARM_EMS, false); setFilePath(destination); return RESULT_DOWNLOAD; } @IMethodLog(desc = "导出网元数量按网管统计") @SuppressWarnings("unchecked") public String exportEmsInfo_Resource(){ // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; Map<String, Object> resultMap = new HashMap<String, Object>(); try { resultMap = reportManagerService.getEmsInfo_Resource(paramMap,start,limit); } catch (CommonException e1) { e1.printStackTrace(); } // 将返回的结果转成JSON对象,返回前台 List<Map> list = (List<Map>)resultMap.get("rows"); String destination = null; String myFlieName="资源数据按网管统计"; IExportExcel ex=new ExportExcelUtil(CommonDefine.PATH_ROOT + CommonDefine.EXCEL.TEMP_DIR,myFlieName); destination = ex.writeExcel(list,CommonDefine.EXCEL.REPORT_RESOURCE_EMS, false); setFilePath(destination); return RESULT_DOWNLOAD; } @SuppressWarnings("unchecked") @IMethodLog(desc = "共通树:获取所有子节点") public String getChildNodes() { String returnString = RESULT_OBJ; try { if (endLevel > 0) { List<Map> nodes = commonManagerService.treeGetChildNodes(nodeId, nodeLevel, endLevel,sysUserId); dealNodes(nodes);//网管分组为-1时 resultArray = JSONArray.fromObject(nodes); }else{ resultArray=new JSONArray(); } returnString = RESULT_ARRAY; } catch (CommonException e) { result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(e.getErrorMessage()); resultObj = JSONObject.fromObject(result); returnString = RESULT_OBJ; } return returnString; } private void dealNodes(List<Map> nodes) { for(int i=nodes.size()-1;i>=0;i--){ Map m=nodes.get(i); int nodeLevel=(Integer)m.get("nodeLevel"); if(nodeLevel==1){ nodes.remove(i); } } } /** * 调用性能存储过程job * @throws CommonException */ @IMethodLog(desc = "调用性能存储过程job") @SuppressWarnings("rawtypes") public String callPerformanceSPJob(){ try { Map param=new HashMap(); param.put("month","2013-03"); param.put("jobTime","0 0 23 2 * ?"); Map returnParm=reportManagerService.callPerformanceSPJob(param); result.setReturnResult(CommonDefine.SUCCESS); result.setReturnMessage("设置成功"); } catch (Exception e) { e.printStackTrace(); result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(e.getMessage()); } resultObj = JSONObject.fromObject(result); return RESULT_OBJ; } public Map<String, String> getCondMap() { return condMap; } public void setCondMap(Map<String, String> condMap) { this.condMap = condMap; } }
UTF-8
Java
64,898
java
ReportAction.java
Java
[ { "context": "询资源统计信息<BR>\n\t * Remark: 2013-12-05<BR>\n\t * @author CaiJiaJia\n\t * @return String<BR>\n\t */\n\t@IMethodLog(desc = \"", "end": 3437, "score": 0.9982674717903137, "start": 3428, "tag": "NAME", "value": "CaiJiaJia" }, { "context": "询资源详细信息<BR>\n\t * Remark: 2013-12-06<BR>\n\t * @author CaiJiaJia\n\t * @return String<BR>\n\t */\n\t@IMethodLog(desc = \"", "end": 7933, "score": 0.9764668941497803, "start": 7924, "tag": "NAME", "value": "CaiJiaJia" }, { "context": "按网管分组查询<BR>\n\t * Remark: 2013-12-02<BR>\n\t * @author YuanJia\n\t * @return List<Map<String, Object>><BR>\n\t */\n\t@", "end": 8841, "score": 0.9931160807609558, "start": 8834, "tag": "NAME", "value": "YuanJia" }, { "context": "onChart<BR>\n\t * Remark: 2013-12-03<BR>\n\t * @author YuanJia\n\t * @return List<Map<String, Object>><BR>\n\t */\n\t@", "end": 9802, "score": 0.9992057085037231, "start": 9795, "tag": "NAME", "value": "YuanJia" }, { "context": "按网管分组查询<BR>\n\t * Remark: 2013-12-02<BR>\n\t * @author YuanJia\n\t * @return List<Map<String, Object>><BR>\n\t */\n\t@", "end": 11078, "score": 0.9725145101547241, "start": 11071, "tag": "NAME", "value": "YuanJia" }, { "context": "onChart<BR>\n\t * Remark: 2013-12-03<BR>\n\t * @author YuanJia\n\t * @return List<Map<String, Object>><BR>\n\t */\n\t@", "end": 12024, "score": 0.9976011514663696, "start": 12017, "tag": "NAME", "value": "YuanJia" }, { "context": "按网管分组查询<BR>\n\t * Remark: 2013-12-11<BR>\n\t * @author YuanJia\n\t * @return List<Map<String, Object>><BR>\n\t */\n\t@", "end": 13494, "score": 0.9994615912437439, "start": 13487, "tag": "NAME", "value": "YuanJia" }, { "context": "onChart<BR>\n\t * Remark: 2013-12-11<BR>\n\t * @author YuanJia\n\t * @return List<Map<String, Object>><BR>\n\t */\n\t@", "end": 15459, "score": 0.9997875094413757, "start": 15452, "tag": "NAME", "value": "YuanJia" }, { "context": "--按网管查询<BR>\n\t * Remark: 2013-12-11<BR>\n\t * @author YuanJia\n\t * @return List<Map<String, Object>><BR>\n\t */\n\t@", "end": 27836, "score": 0.9996956586837769, "start": 27829, "tag": "NAME", "value": "YuanJia" }, { "context": "rt<BR>\n\t * Remark: 2013-12-11<BR>\n\t * \n\t * @author YuanJia\n\t * @return List<Map<String, Object>><BR>\n\t */\n\t@", "end": 29091, "score": 0.9986792802810669, "start": 29084, "tag": "NAME", "value": "YuanJia" }, { "context": "--按网管查询<BR>\n\t * Remark: 2013-12-19<BR>\n\t * @author YuanJia\n\t * @return List<Map<String, Object>><BR>\n\t */\n\t@", "end": 36597, "score": 0.9990109205245972, "start": 36590, "tag": "NAME", "value": "YuanJia" }, { "context": "onChart<BR>\n\t * Remark: 2013-12-19<BR>\n\t * @author YuanJia\n\t * @return List<Map<String, Object>><BR>\n\t */\n//", "end": 38531, "score": 0.9883197546005249, "start": 38524, "tag": "NAME", "value": "YuanJia" }, { "context": "按网管分组查询<BR>\n\t * Remark: 2013-12-02<BR>\n\t * @author YuanJia\n\t * @return List<Map<String, Object>><BR>\n\t */\n\t@", "end": 46206, "score": 0.9976181387901306, "start": 46199, "tag": "NAME", "value": "YuanJia" }, { "context": "onChart<BR>\n\t * Remark: 2013-12-23<BR>\n\t * @author YuanJia\n\t * @return List<Map<String, Object>><BR>\n\t */\n\t@", "end": 47172, "score": 0.999705970287323, "start": 47165, "tag": "NAME", "value": "YuanJia" } ]
null
[]
package com.fujitsu.manager.reportManager.action; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import com.fujitsu.IService.ICommonManagerService; import com.fujitsu.IService.IExportExcel; import com.fujitsu.IService.IAlarmManagementService; import com.fujitsu.IService.IMethodLog; import com.fujitsu.IService.IReportManagerService; import com.fujitsu.abstractAction.DownloadAction; import com.fujitsu.common.CommonDefine; import com.fujitsu.common.CommonException; import com.fujitsu.util.ExportExcelUtil; import com.mongodb.DBObject; import fusioncharts.FusionChartDesigner; public class ReportAction extends DownloadAction { private static final long serialVersionUID = 1L; private static final String TABLE_PRI="t_pm_origi_data_collect"; private static final String TABLE_PRI_MONTH="t_pm_origi_data_collect_month"; private static final String COLOR_CRITICAL="ff0000"; private static final String COLOR_MAJOR="ff8000"; private static final String COLOR_MINOR="ffff00"; private static final String COLOR_WARNING="800000"; @Resource public IReportManagerService reportManagerService; @Resource public ICommonManagerService commonManagerService; @Resource public IAlarmManagementService alarmManagementService; // 表名 public String table_name = ""; private boolean displayAll; private boolean displayNone; private String query; int nodeId; int nodeLevel; int endId; int endLevel; String text; boolean hasPath; private String level; private Map<String, String> condMap; public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public int getNodeId() { return nodeId; } public void setNodeId(int nodeId) { this.nodeId = nodeId; } public int getNodeLevel() { return nodeLevel; } public void setNodeLevel(int nodeLevel) { this.nodeLevel = nodeLevel; } public int getEndId() { return endId; } public void setEndId(int endId) { this.endId = endId; } public int getEndLevel() { return endLevel; } public void setEndLevel(int endLevel) { this.endLevel = endLevel; } public String getText() { return text; } public void setText(String text) { this.text = text; } public boolean isHasPath() { return hasPath; } public void setHasPath(boolean hasPath) { this.hasPath = hasPath; } public String getQuery() { return query; } public void setQuery(String query) { this.query = query; } public boolean isDisplayAll() { return displayAll; } public void setDisplayAll(boolean displayAll) { this.displayAll = displayAll; } public boolean isDisplayNone() { return displayNone; } public void setDisplayNone(boolean displayNone) { this.displayNone = displayNone; } public String getTable_name() { return table_name; } public void setTable_name(String table_name) { this.table_name = table_name; } // 查询参数 private String jsonString; public String getJsonString() { return jsonString; } public void setJsonString(String jsonString) { this.jsonString = jsonString; } /** * Method name: getResourceChartByStation <BR> * Description: 按局站查询资源统计信息<BR> * Remark: 2013-12-05<BR> * @author CaiJiaJia * @return String<BR> */ @IMethodLog(desc = "按局站查询资源统计信息") @SuppressWarnings({ "unchecked", "rawtypes" }) public String getResourceChartByStation(){ try { // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; // 将查询结果转成FusionCharts所需格式 String xmlString = ""; FusionChartDesigner fcd = new FusionChartDesigner(); // 按局站查询资源统计信息 if(paramMap.get("stationId")!=null){ // 判断是页面上那个chart图 if("left".equals(paramMap.get("flag").toString())){ // 需要统计的局站ID和名称 String[] stationIdSize = paramMap.get("stationId").toString().split(","); String[] stationNameSize = paramMap.get("stationName").toString().split(","); List<Map> mdListMap = new ArrayList<Map>(); for (int i = 0; i < stationIdSize.length; i++) { Map map = new HashMap(); map.put("RESOURCE_STATION_ID", Integer.parseInt(stationIdSize[i])); mdListMap.add(map); } // 按网元型号查询某局站的资源统计信息 List<Map> resourceList = reportManagerService.getResourceChartByStationAndNeModel(paramMap); // 行专列 rowToCol(resourceList, mdListMap, "NE_MODEL", "COUNT", "RESOURCE_STATION_ID"); for(int i=0;i<mdListMap.size();i++){ fcd.addSerialDatasList(stationNameSize[i], (ArrayList<Map>) resourceList, "NE_MODEL", mdListMap.get(i).get("RESOURCE_STATION_ID").toString()); } }else{ // 查询某些局站下的所有网元型号 List<Map> neModelList = reportManagerService.getAllNeModelsByStation(paramMap); String neModel = ""; if(neModelList.size()>0){ for (int i = 0; i < neModelList.size(); i++) { neModel += neModelList.get(i).get("NE_MODEL").toString()+","; } neModel = neModel.substring(0,neModel.lastIndexOf(",")); paramMap.put("neModel", neModel); } List<Map> resourceList = reportManagerService.getResourceChartByNeModelAndStation(paramMap); // 行专列 rowToCol(resourceList, neModelList, "RESOURCE_STATION_ID", "COUNT", "NE_MODEL"); for(int i=0;i<neModelList.size();i++){ fcd.addSerialDatasList(neModelList.get(i).get("NE_MODEL").toString(), (ArrayList<Map>) resourceList, "STATION_NAME", neModelList.get(i).get("NE_MODEL").toString()); } } } xmlString = fcd.getManyDimensionsXmlData("","",""); // 将封装成Map格式,用来转成JSON,返回前台 Map<String, Object> valueMap = new HashMap<String, Object>(); valueMap.put("xml", xmlString); resultObj = JSONObject.fromObject(valueMap); } catch (CommonException e) { result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(e.getErrorMessage()); resultObj = JSONObject.fromObject(result); } return RESULT_OBJ; } /** * * Method name: rowToCol <BR> * Description: rowToCol <BR> * Remark: <BR> * @param list<Map> 所有集合 * @param mdListMap 所需要行转列的信息 NET_TYPE:移动,NET_TYPE:联通,NET_TYPE:电信 * @param fcXKey 对应要配置在x轴的字段 * @param fcYKey 对应要配置在y周的字段 * @param dType mdListMap中的key */ private void rowToCol(List<Map> list, List<Map> mdListMap, String fcXKey, String fcYKey, String dType){ Map map = new HashMap(); int mdSizeFlag = 0; Map rowMap1 = null; Map rowMap2 = null; String xValue = ""; Set set = new HashSet(); for (int i = 0; i < list.size(); i++) { mdSizeFlag = 1; rowMap1 = list.get(i); xValue = rowMap1.get(fcXKey).toString(); for (int j = 0; j <mdListMap.size(); j++) { Map mdRowMap = mdListMap.get(j); rowMap1.put(mdRowMap.get(dType).toString(),0); } rowMap1.put(rowMap1.get(dType).toString(),rowMap1.get(fcYKey).toString()); set.add(rowMap1.get(dType).toString()); for (int j = i + 1; j < list.size(); j++) { rowMap2 = list.get(j); if (xValue.equals(rowMap2.get(fcXKey).toString())) { rowMap1.put(rowMap2.get(dType).toString(),rowMap2.get(fcYKey).toString()); set.add(rowMap2.get(dType).toString()); list.remove(j); --j; if (++mdSizeFlag == mdListMap.size()) { break; } } } } } /** * Method name: getResourceDetailByStation <BR> * Description: 按局站查询资源详细信息<BR> * Remark: 2013-12-06<BR> * @author CaiJiaJia * @return String<BR> */ @IMethodLog(desc = "按局站查询资源详细信息") @SuppressWarnings("unchecked") public String getResourceDetailByStation(){ try { // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; // 定义一个Map接受查询返回的值 Map<String, Object> resotrceMap = reportManagerService.getResourceDetailByStation(paramMap,start,limit); // 将返回的结果转成JSON对象,返回前台 resultObj = JSONObject.fromObject(resotrceMap); } catch (CommonException e) { result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(e.getErrorMessage()); resultObj = JSONObject.fromObject(result); } return RESULT_OBJ; } /** * Method name: getEmsGroupInfo_Resource <BR> * Description: 资源报表--按网管分组查询<BR> * Remark: 2013-12-02<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @IMethodLog(desc = "查询getEmsGroupInfo") @SuppressWarnings("unchecked") public String getEmsGroupInfo_Resource(){ try { // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap = reportManagerService.getEmsGroupInfo_Resource(paramMap,start,limit); // 将返回的结果转成JSON对象,返回前台 resultObj = JSONObject.fromObject(resultMap); } catch (CommonException e) { result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(e.getErrorMessage()); resultObj = JSONObject.fromObject(result); } return RESULT_OBJ; } /** * Method name: emsGroupFusionChart_Resource <BR> * Description: 资源报表--fusionChart<BR> * Remark: 2013-12-03<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @SuppressWarnings("unchecked") public String emsGroupFusionChart_Resource() throws CommonException{ // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; List<Map<String,Object>> List = reportManagerService.getEmsGroupFusionChart_Resource(paramMap); /** 设置fusionChart */ String chartXml = ""; ArrayList<Map> xmlList = new ArrayList<Map>(); for(int i=0; i<List.size();i++){ Map lom = List.get(i); xmlList.add((Map)lom); } FusionChartDesigner fcd = new FusionChartDesigner(); fcd.setOneDimensionList(xmlList, "X", "Y"); fcd.setChart_bgcolor("#F3f3f3"); fcd.setChart_caption("按网管分组统计"); fcd.setChart_xAxisName(""); fcd.setChart_yAxisName(""); fcd.setChartClickEnable(true); chartXml = fcd.getOneDimensionsXMLData(); Map<String,String> xmlMap = new HashMap<String,String>(); xmlMap.put("xml", chartXml); Object obj = (Object)xmlMap; resultObj = JSONObject.fromObject(obj); return RESULT_OBJ; } /** * Method name: getEmsInfo_Resource <BR> * Description: 资源报表--按网管分组查询<BR> * Remark: 2013-12-02<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @IMethodLog(desc = "查询getEmsGroupInfo") @SuppressWarnings("unchecked") public String getEmsInfo_Resource(){ try { // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap = reportManagerService.getEmsInfo_Resource(paramMap,start,limit); // 将返回的结果转成JSON对象,返回前台 resultObj = JSONObject.fromObject(resultMap); } catch (CommonException e) { result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(e.getErrorMessage()); resultObj = JSONObject.fromObject(result); } return RESULT_OBJ; } /** * Method name: emsFusionChart_Resource <BR> * Description: 资源报表--fusionChart<BR> * Remark: 2013-12-03<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @SuppressWarnings("unchecked") public String emsFusionChart_Resource() throws CommonException{ // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; List<Map<String,Object>> List = reportManagerService.getEmsFusionChart_Resource(paramMap); /** 设置fusionChart */ String chartXml = ""; ArrayList<Map> xmlList = new ArrayList<Map>(); for(int i=0; i<List.size();i++){ Map lom = List.get(i); xmlList.add((Map)lom); } FusionChartDesigner fcd = new FusionChartDesigner(); fcd.setOneDimensionList(xmlList, "X", "Y"); fcd.setChart_bgcolor("#F3f3f3"); fcd.setChart_caption(""); fcd.setChart_xAxisName(""); fcd.setChart_yAxisName(""); //fcd.setChart_rotateLabels("1"); //fcd.setChart_slantLabels("1"); //fcd.getChartNodePro().put("maxColWidth","30"); fcd.getChartNodePro().put("baseFontSize","12"); fcd.setLabelDisplay("WRAP"); fcd.setChartClickEnable(true); chartXml = fcd.getOneDimensionsXMLData(); Map<String,String> xmlMap = new HashMap<String,String>(); xmlMap.put("xml", chartXml); Object obj = (Object)xmlMap; resultObj = JSONObject.fromObject(obj); return RESULT_OBJ; } /** * Method name: getEmsGroupInfo_Performance <BR> * Description: 性能报表--按网管分组查询<BR> * Remark: 2013-12-11<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @IMethodLog(desc = "查询getEmsGroupInfo") @SuppressWarnings("unchecked") public String getEmsGroupInfo_Performance(){ try { Map<String, Object> paramMap = (Map<String, Object>)JSONObject.fromObject(jsonString); String timeType=(String)paramMap.get("timeType"); if("day".equals(timeType)){ setTable_name(TABLE_PRI); }else{ setTable_name(TABLE_PRI+"_month"); } paramMap.put("table_name",table_name); paramMap.put("timeType", paramMap.get("timeType")); paramMap.put("time",paramMap.get("time").toString()); paramMap.put("query","list"); Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap = reportManagerService.getEmsGroupInfo_Performance(paramMap,start,limit); // 将返回的结果转成JSON对象,返回前台 resultObj = JSONObject.fromObject(resultMap); } catch (CommonException e) { result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(e.getErrorMessage()); resultObj = JSONObject.fromObject(result); } return RESULT_OBJ; } public void setFusionChartSettings(FusionChartDesigner fcd_1){ fcd_1.setChart_caption(""); fcd_1.setChart_xAxisName(""); fcd_1.setChart_yAxisName(""); fcd_1.setChart_bgcolor("#F3f3f3"); //fcd_1.setChart_bgcolor("#ffffff"); fcd_1.setChart_showValues("1"); fcd_1.getChartNodePro().put("baseFontSize","12"); fcd_1.setLabelDisplay("WRAP"); fcd_1.setChartClickEnable(true); fcd_1.setChart_show_legend("1"); fcd_1.setChart_legend_position("right"); fcd_1.setChart_percent_label("1"); fcd_1.setChart_Decimals("2"); fcd_1.getChartNodePro().put("pieRadius","150");//饼状图半径控制 //fcd_1.getChartNodePro().put("maxColWidth","30"); fcd_1.getChartNodePro().put("showAboutMenuItem","0"); fcd_1.getChartNodePro().put("showPrintMenuItem","0"); } /** * Method name: fusionChart_Performance <BR> * Description: 性能报表--fusionChart<BR> * Remark: 2013-12-11<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @SuppressWarnings("unchecked") public String fusionChart_Performance() throws CommonException{ Map<String, Object> paramMap = (Map<String, Object>)JSONObject.fromObject(jsonString); String timeType=paramMap.get("timeType").toString(); if("day".equals(timeType)){ paramMap.put("table_name","t_pm_origi_data_collect"); }else{ paramMap.put("table_name","t_pm_origi_data_collect_month"); } paramMap.put("timeType",timeType); paramMap.put("time",paramMap.get("time").toString()); Map<String,String> xmlMap = new HashMap<String,String>(); level=paramMap.get("level")==null?"":paramMap.get("level").toString(); if(level==null || "".equals(level)){//生成第一层图表 String chartXml_1 = ""; Map<String, Object> map = reportManagerService.getEmsGroupInfo_Performance(paramMap,start,limit); List<Map> List_1=(List<Map>)map.get("rows"); List emsGroupIdList = new ArrayList<String>(); for (Map m : List_1) { emsGroupIdList.add(m.get("base_ems_group_id")); } FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setxListOneDimensionAdditionnal(emsGroupIdList); fcd_1.setOneDimensionList(List_1, "group_name", "cou"); fcd_1.getUserDefinedProperty().put("level","one"); fcd_1.setChart_caption(paramMap.get("time").toString()+"异常性能按网管分组统计"); chartXml_1 = fcd_1.getOneDimensionsXMLData(); xmlMap.put("xml_1", chartXml_1); }else if(level!=null && "one".equals(level)){//点击第一层图表进来 String chartXml_1 = ""; Map<String, Object> map=null; if("year".equals(timeType)){ map = reportManagerService.getPMMonthDataByEmsGroup(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setChart_showValues("0"); fcd_1.addSerialDatasList("计数值3级",(ArrayList)List_1,"retrieval_time","count_3"); fcd_1.addSerialDatasList("计数值2级",(ArrayList)List_1,"retrieval_time","count_2"); fcd_1.addSerialDatasList("计数值1级",(ArrayList)List_1,"retrieval_time","count_1"); fcd_1.addSerialDatasList("物理量3级",(ArrayList)List_1,"retrieval_time","physics_3"); fcd_1.addSerialDatasList("物理量2级",(ArrayList)List_1,"retrieval_time","physics_2"); fcd_1.addSerialDatasList("物理量1级",(ArrayList)List_1,"retrieval_time","physics_1"); fcd_1.getUserDefinedProperty().put("level","two"); fcd_1.getUserDefinedProperty().put("emsId",paramMap.get("group_name")); fcd_1.setChart_caption(paramMap.get("time").toString()+paramMap.get("label")+"网管组异常性能分布"); chartXml_1 = fcd_1.getManyDimensionsXmlData(); xmlMap.put("xml_1", chartXml_1); }else if("month".equals(timeType)){ paramMap.put("query_month",paramMap.get("time").toString()); map = reportManagerService.getPMDayDataByEmsGroup(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setChart_showValues("0"); fcd_1.addSerialDatasList("计数值3级",(ArrayList)List_1,"retrieval_time","count_3"); fcd_1.addSerialDatasList("计数值2级",(ArrayList)List_1,"retrieval_time","count_2"); fcd_1.addSerialDatasList("计数值1级",(ArrayList)List_1,"retrieval_time","count_1"); fcd_1.addSerialDatasList("物理量3级",(ArrayList)List_1,"retrieval_time","physics_3"); fcd_1.addSerialDatasList("物理量2级",(ArrayList)List_1,"retrieval_time","physics_2"); fcd_1.addSerialDatasList("物理量1级",(ArrayList)List_1,"retrieval_time","physics_1"); fcd_1.getUserDefinedProperty().put("level","two"); fcd_1.getUserDefinedProperty().put("emsId",paramMap.get("group_name")); fcd_1.setChart_caption(paramMap.get("time").toString()+paramMap.get("label")+"网管组异常性能分布"); chartXml_1 = fcd_1.getManyDimensionsXmlData(); xmlMap.put("xml_1", chartXml_1); }else if("day".equals(timeType)){ paramMap.put("query_day",paramMap.get("time").toString()); map = reportManagerService.getPMDayDataByQueryDayAndGroup(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setOneDimensionList(List_1, "type_level", "cou"); fcd_1.getUserDefinedProperty().put("level","three"); fcd_1.setChart_caption(paramMap.get("query_day").toString()+paramMap.get("label")+"网管组异常性能分布"); chartXml_1 = fcd_1.getOneDimensionsXMLData(); xmlMap.put("xml_1", chartXml_1); } }else if(level!=null && "two".equals(level)){//点击第二层图表进来 String chartXml_1 = ""; Map<String, Object> map=null; if("year".equals(timeType)){ paramMap.put("query_month",paramMap.get("label")); map = reportManagerService.getPMDayDataByEmsGroup(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setChart_showValues("0"); fcd_1.addSerialDatasList("计数值3级",(ArrayList)List_1,"retrieval_time","count_3"); fcd_1.addSerialDatasList("计数值2级",(ArrayList)List_1,"retrieval_time","count_2"); fcd_1.addSerialDatasList("计数值1级",(ArrayList)List_1,"retrieval_time","count_1"); fcd_1.addSerialDatasList("物理量3级",(ArrayList)List_1,"retrieval_time","physics_3"); fcd_1.addSerialDatasList("物理量2级",(ArrayList)List_1,"retrieval_time","physics_2"); fcd_1.addSerialDatasList("物理量1级",(ArrayList)List_1,"retrieval_time","physics_1"); fcd_1.getUserDefinedProperty().put("level","three"); fcd_1.setChart_caption(paramMap.get("label").toString()+paramMap.get("gName")+"网管组异常性能分布"); chartXml_1 = fcd_1.getManyDimensionsXmlData(); xmlMap.put("xml_1", chartXml_1); }else if("month".equals(timeType)){ paramMap.put("group_name",paramMap.get("group_name")); paramMap.put("query_day",paramMap.get("label")); map = reportManagerService.getPMDayDataByQueryDayAndGroup(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setOneDimensionList(List_1, "type_level", "cou"); fcd_1.getUserDefinedProperty().put("level","three"); fcd_1.setChart_caption(paramMap.get("label").toString()+paramMap.get("gName")+"网管组异常性能分布"); chartXml_1 = fcd_1.getOneDimensionsXMLData(); xmlMap.put("xml_1", chartXml_1); } } Object obj = (Object)xmlMap; resultObj = JSONObject.fromObject(obj); return RESULT_OBJ; } @SuppressWarnings("unchecked") public String emsFusionChart_Alarm() throws CommonException{ Map<String, Object> paramMap = (Map<String, Object>)JSONObject.fromObject(jsonString); String timeType=paramMap.get("timeType").toString(); paramMap.put("timeType",timeType); paramMap.put("time",paramMap.get("time").toString()); Map<String, Object> resultMap = new HashMap<String, Object>(); Map<String,String> xmlMap = new HashMap<String,String>(); level=paramMap.get("level")==null?"":paramMap.get("level").toString(); if(level==null || "".equals(level)){//生成第一层图表 resultMap = reportManagerService.getReportAlarmByEms(paramMap); List<Map> List_1=(List<Map>)resultMap.get("rows"); List emsIdList = new ArrayList<String>(); for (Map m : List_1) { emsIdList.add(m.get("base_ems_connection_id")); } String chartXml_1 = ""; FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setxListOneDimensionAdditionnal(emsIdList); fcd_1.setOneDimensionList(List_1, "display_name", "cou"); fcd_1.getUserDefinedProperty().put("level","one"); fcd_1.setChart_caption(paramMap.get("time").toString()+"告警按网管统计"); chartXml_1 = fcd_1.getOneDimensionsXMLData(); xmlMap.put("xml_1", chartXml_1); }else if(level!=null && "one".equals(level)){//点击第一层图表进来 String chartXml_1 = ""; Map<String, Object> map=null; if("year".equals(timeType)){ map =reportManagerService.getAlarmMonthDataByEms(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setChart_showValues("0"); fcd_1.addSerialDatasList("提示",COLOR_WARNING,(ArrayList)List_1,"first_time","ps_warning"); fcd_1.addSerialDatasList("一般",COLOR_MINOR,(ArrayList)List_1,"first_time","ps_minor"); fcd_1.addSerialDatasList("重要",COLOR_MAJOR,(ArrayList)List_1,"first_time","ps_major"); fcd_1.addSerialDatasList("紧急",COLOR_CRITICAL,(ArrayList)List_1,"first_time","ps_critical"); fcd_1.getUserDefinedProperty().put("level","two"); fcd_1.getUserDefinedProperty().put("emsId",paramMap.get("EMS_NAME")); fcd_1.setChart_caption(paramMap.get("time").toString()+paramMap.get("label")+"告警分布"); chartXml_1 = fcd_1.getManyDimensionsXmlData(); xmlMap.put("xml_1", chartXml_1); }else if("month".equals(timeType)){ paramMap.put("query_month",paramMap.get("time").toString()); map = reportManagerService.getAlarmDayDataByEms(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setChart_showValues("0"); fcd_1.addSerialDatasList("提示",COLOR_WARNING,(ArrayList)List_1,"first_time","ps_warning"); fcd_1.addSerialDatasList("一般",COLOR_MINOR,(ArrayList)List_1,"first_time","ps_minor"); fcd_1.addSerialDatasList("重要",COLOR_MAJOR,(ArrayList)List_1,"first_time","ps_major"); fcd_1.addSerialDatasList("紧急",COLOR_CRITICAL,(ArrayList)List_1,"first_time","ps_critical"); fcd_1.getUserDefinedProperty().put("level","two"); fcd_1.getUserDefinedProperty().put("emsId",paramMap.get("EMS_NAME")); fcd_1.setChart_caption(paramMap.get("time").toString()+paramMap.get("label")+"告警分布"); chartXml_1 = fcd_1.getManyDimensionsXmlData(); xmlMap.put("xml_1", chartXml_1); }else if("day".equals(timeType)){ paramMap.put("query_day",paramMap.get("time").toString()); map = reportManagerService.getAlarmDayDataByQueryDayAndEms(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setOneDimensionList(List_1, "type_level", "cou"); fcd_1.getUserDefinedProperty().put("level","three"); fcd_1.setChart_caption(paramMap.get("query_day").toString()+paramMap.get("label")+"告警分布"); chartXml_1 = fcd_1.getOneDimensionsXMLData(); xmlMap.put("xml_1", chartXml_1); } }else if(level!=null && "two".equals(level)){//点击第二层图表进来 String chartXml_1 = ""; Map<String, Object> map=null; if("year".equals(timeType)){ paramMap.put("query_month",paramMap.get("label")); map = reportManagerService.getAlarmDayDataByEms(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setChart_showValues("0"); fcd_1.addSerialDatasList("提示",COLOR_WARNING,(ArrayList)List_1,"first_time","ps_warning"); fcd_1.addSerialDatasList("一般",COLOR_MINOR,(ArrayList)List_1,"first_time","ps_minor"); fcd_1.addSerialDatasList("重要",COLOR_MAJOR,(ArrayList)List_1,"first_time","ps_major"); fcd_1.addSerialDatasList("紧急",COLOR_CRITICAL,(ArrayList)List_1,"first_time","ps_critical"); fcd_1.getUserDefinedProperty().put("level","three"); fcd_1.setChart_caption(paramMap.get("label").toString()+paramMap.get("eName")+"告警分布"); chartXml_1 = fcd_1.getManyDimensionsXmlData(); xmlMap.put("xml_1", chartXml_1); }else if("month".equals(timeType)){ paramMap.put("query_day",paramMap.get("label")); map = reportManagerService.getAlarmDayDataByQueryDayAndEms(paramMap); List<Map> List_1=(List<Map>)map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setOneDimensionList(List_1, "type_level", "cou"); fcd_1.getUserDefinedProperty().put("level","three"); fcd_1.setChart_caption(paramMap.get("query_day").toString()+paramMap.get("eName")+"告警分布"); chartXml_1 = fcd_1.getOneDimensionsXMLData(); xmlMap.put("xml_1", chartXml_1); } } Object obj = (Object)xmlMap; resultObj = JSONObject.fromObject(obj); return RESULT_OBJ; } /** * Method name: getEmsInfo_Performance <BR> * Description: 性能报表--按网管查询<BR> * Remark: 2013-12-11<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @IMethodLog(desc = "查询getEmsInfo") @SuppressWarnings("unchecked") public String getEmsInfo_Performance(){ // try { // // 将参数专程JSON对象 // JSONObject jsonObject = JSONObject.fromObject(jsonString); // // 将JSON对象转成Map对象 // Map<String, Object> paramMap = new HashMap<String, Object>(); // paramMap = (Map<String, Object>) jsonObject; // setTable_name(TABLE_PRI+paramMap.get("time").toString().substring(0,4)); // paramMap.put("table_name",table_name); // paramMap.put("timeType", paramMap.get("timeType")); // paramMap.put("time",paramMap.get("time").toString()); // paramMap.put("query","list"); // Map<String, Object> resultMap = new HashMap<String, Object>(); // resultMap = reportManagerService.getEmsInfo_Performance(paramMap,start,limit); // // 将返回的结果转成JSON对象,返回前台 // resultObj = JSONObject.fromObject(resultMap); // } catch (CommonException e) { // result.setReturnResult(CommonDefine.FAILED); // result.setReturnMessage(e.getErrorMessage()); // resultObj = JSONObject.fromObject(result); // } return RESULT_OBJ; } /** * Method name: emsFusionChart_Performance <BR> * Description: 性能报表--fusionChart<BR> * Remark: 2013-12-11<BR> * * @author YuanJia * @return List<Map<String, Object>><BR> */ @SuppressWarnings("unchecked") public String emsFusionChart_Performance() throws CommonException { String timeType = condMap.get("timeType").toString(); Map<String, String> xmlMap = new HashMap<String, String>(); level = condMap.get("level") == null ? "" : condMap.get("level") .toString(); String title = ""; try { SimpleDateFormat msdf = new SimpleDateFormat("yyyy年MM月"); SimpleDateFormat dsdf = new SimpleDateFormat("yyyy年MM月dd日"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM"); if (condMap.get("timeType").equals("day")){ Date time = sdf1.parse(condMap.get("time")); title = dsdf.format(time); } else if (condMap.get("timeType").equals("month")){ Date time = sdf2.parse(condMap.get("time")); title = msdf.format(time); } else if (condMap.get("timeType").equals("year")){ title = condMap.get("time")+"年"; } } catch (ParseException e) { e.printStackTrace(); } if (level == null || "".equals(level)) {// 生成第一层图表 String flag = condMap.get("firstGraph").toString(); if ("1".equals(flag)) { String chartXml_1 = ""; String chartXml_2 = ""; if (condMap.get("timeType").equals("day")) condMap.put("table_name", TABLE_PRI); else condMap.put("table_name", TABLE_PRI_MONTH); condMap.put("query", "chart"); Map<String, Object> map = reportManagerService .getEmsInfo_Performance(condMap, start, limit); // 获取fusion_01数据源 List<Map> List_1 = (List<Map>) map.get("rows"); List emsIdList = new ArrayList<String>(); for (Map m : List_1) { emsIdList.add(m.get("BASE_EMS_CONNECTION_ID")); } FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); // 需要emsId,因为网管名有可能重复 fcd_1.setxListOneDimensionAdditionnal(emsIdList); fcd_1.setOneDimensionList(List_1, "DISPLAY_NAME", "COU"); fcd_1.getUserDefinedProperty().put("level", "one"); fcd_1.setChart_caption(title + "异常性能按网管统计"); chartXml_1 = fcd_1.getOneDimensionsXMLData(); // System.out.println(chartXml_1); xmlMap.put("xml_1", chartXml_1); } } else if (level != null && "one".equals(level)) {// 点击第一层图表进来 String chartXml_1 = ""; Map<String, Object> map = null; if ("year".equals(timeType)) { map = reportManagerService.getPMDataPerMonthByEmsId(condMap); List<Map> List_1 = (List<Map>) map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setChart_showValues("0"); fcd_1.addSerialDatasList("计数值3级", (ArrayList) List_1, "retrieval_time", "count_3"); fcd_1.addSerialDatasList("计数值2级", (ArrayList) List_1, "retrieval_time", "count_2"); fcd_1.addSerialDatasList("计数值1级", (ArrayList) List_1, "retrieval_time", "count_1"); fcd_1.addSerialDatasList("物理量3级", (ArrayList) List_1, "retrieval_time", "physics_3"); fcd_1.addSerialDatasList("物理量2级", (ArrayList) List_1, "retrieval_time", "physics_2"); fcd_1.addSerialDatasList("物理量1级", (ArrayList) List_1, "retrieval_time", "physics_1"); fcd_1.getUserDefinedProperty().put("level", "two"); fcd_1.getUserDefinedProperty().put("emsId", condMap.get("emsId")); fcd_1.setChart_caption(title + condMap.get("label") + "异常性能分布"); chartXml_1 = fcd_1.getManyDimensionsXmlData(); xmlMap.put("xml_1", chartXml_1); } else if ("month".equals(timeType)) { map = reportManagerService.getPMDataPerMonthByEmsId(condMap); List<Map> List_1 = (List<Map>) map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setChart_showValues("0"); fcd_1.addSerialDatasList("计数值3级", (ArrayList) List_1, "retrieval_time", "count_3"); fcd_1.addSerialDatasList("计数值2级", (ArrayList) List_1, "retrieval_time", "count_2"); fcd_1.addSerialDatasList("计数值1级", (ArrayList) List_1, "retrieval_time", "count_1"); fcd_1.addSerialDatasList("物理量3级", (ArrayList) List_1, "retrieval_time", "physics_3"); fcd_1.addSerialDatasList("物理量2级", (ArrayList) List_1, "retrieval_time", "physics_2"); fcd_1.addSerialDatasList("物理量1级", (ArrayList) List_1, "retrieval_time", "physics_1"); fcd_1.getUserDefinedProperty().put("level", "two"); fcd_1.getUserDefinedProperty().put("emsId", condMap.get("emsId")); fcd_1.setChart_caption(title + condMap.get("label") + "异常性能分布"); chartXml_1 = fcd_1.getManyDimensionsXmlData(); xmlMap.put("xml_1", chartXml_1); } else if ("day".equals(timeType)) { condMap.put("query_day", condMap.get("time").toString()); map = reportManagerService.getPMDataPerDayEms(condMap); List<Map> List_1 = (List<Map>) map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setOneDimensionList(List_1, "type_level", "cou"); fcd_1.getUserDefinedProperty().put("level", "three"); fcd_1.setChartClickEnable(false); fcd_1.setChart_caption(title + condMap.get("label") + "异常性能分布"); chartXml_1 = fcd_1.getOneDimensionsXMLData(); xmlMap.put("xml_1", chartXml_1); } } else if (level != null && "two".equals(level)) {// 点击第二层图表进来 String chartXml_1 = ""; Map<String, Object> map = null; if ("year".equals(timeType)) { condMap.put("query_month", condMap.get("label")); map = reportManagerService.getPMDataPerDayByEmsId(condMap); List<Map> List_1 = (List<Map>) map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setChart_showValues("0"); fcd_1.addSerialDatasList("计数值3级", (ArrayList) List_1, "retrieval_time", "count_3"); fcd_1.addSerialDatasList("计数值2级", (ArrayList) List_1, "retrieval_time", "count_2"); fcd_1.addSerialDatasList("计数值1级", (ArrayList) List_1, "retrieval_time", "count_1"); fcd_1.addSerialDatasList("物理量3级", (ArrayList) List_1, "retrieval_time", "physics_3"); fcd_1.addSerialDatasList("物理量2级", (ArrayList) List_1, "retrieval_time", "physics_2"); fcd_1.addSerialDatasList("物理量1级", (ArrayList) List_1, "retrieval_time", "physics_1"); fcd_1.setChartClickEnable(false); fcd_1.getUserDefinedProperty().put("level", "three"); String emsName = reportManagerService.getEmsName(condMap); fcd_1.setChart_caption(condMap.get("label") + emsName + "异常性能分布"); chartXml_1 = fcd_1.getManyDimensionsXmlData(); xmlMap.put("xml_1", chartXml_1); } else if ("month".equals(timeType)) { condMap.put("query_day", condMap.get("label")); map = reportManagerService.getPMDataPerDayEms(condMap); List<Map> List_1 = (List<Map>) map.get("rows"); FusionChartDesigner fcd_1 = new FusionChartDesigner(); setFusionChartSettings(fcd_1); fcd_1.setOneDimensionList(List_1, "type_level", "cou"); fcd_1.getUserDefinedProperty().put("level", "three"); fcd_1.setChartClickEnable(false); String emsName = reportManagerService.getEmsName(condMap); fcd_1.setChart_caption(condMap.get("label") +emsName+"异常性能分布"); chartXml_1 = fcd_1.getOneDimensionsXMLData(); xmlMap.put("xml_1", chartXml_1); } } Object obj = (Object) xmlMap; resultObj = JSONObject.fromObject(obj); return RESULT_OBJ; } /** * Method name: getEmsInfo_Alarm <BR> * Description: 告警报表--按网管查询<BR> * Remark: 2013-12-19<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @IMethodLog(desc = "查询getEmsInfo_Alarm") @SuppressWarnings("unchecked") public String getEmsInfo_Alarm(){ try { // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; String t=paramMap.get("time").toString().replaceAll("-", ""); int time=Integer.parseInt(t); int groupId=0; int[] ems=null; if(paramMap.get("GROUPID")!=null && !"".equals(paramMap.get("GROUPID"))){ groupId=Integer.parseInt(paramMap.get("GROUPID").toString()); } if(paramMap.get("EMSIDS")!=null && !"".equals(paramMap.get("EMSIDS"))){ String emsIds=paramMap.get("EMSIDS").toString(); if(emsIds!=""){ String[] ids=emsIds.split(","); ems=new int[ids.length]; for(int i=0;i<ids.length;i++){ ems[i]=Integer.parseInt(ids[i]); } } } setTable_name(CommonDefine.T_HISTORY_ALARM); Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap = alarmManagementService.getReportAlarmByEms(groupId,ems,this.getTable_name(),start,limit,time); /** 此处数据为假,仅供测试*/ if(resultMap==null || resultMap.get("rows")==null || ((List<DBObject>)resultMap.get("rows")).size()==0){ setTable_name(CommonDefine.T_CURRENT_ALARM); resultMap = alarmManagementService.getReportAlarmByEms(groupId,ems,this.getTable_name(),start,limit,time); } // 将返回的结果转成JSON对象,返回前台 resultObj = JSONObject.fromObject(resultMap); } catch (Exception e) { e.printStackTrace(); result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(getText(e.getMessage())); resultObj = JSONObject.fromObject(result); } return RESULT_OBJ; } /** * Method name: emsFusionChart_Alarm <BR> * Description: 告警报表--fusionChart<BR> * Remark: 2013-12-19<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ // @SuppressWarnings("unchecked") // public String emsFusionChart_Alarm() throws CommonException{ // // 将参数专程JSON对象 // JSONObject jsonObject = JSONObject.fromObject(jsonString); // // 将JSON对象转成Map对象 // Map<String, Object> paramMap = new HashMap<String, Object>(); // paramMap = (Map<String, Object>) jsonObject; // String timeType=paramMap.get("timeType").toString(); // String t=paramMap.get("time").toString().replaceAll("-", ""); // int time=Integer.parseInt(t); // int groupId=0; // int[] ems=null; // if(paramMap.get("GROUPID")!=null && !"".equals(paramMap.get("GROUPID"))){ // groupId=Integer.parseInt(paramMap.get("GROUPID").toString()); // } // if(paramMap.get("EMSIDS")!=null && !"".equals(paramMap.get("EMSIDS"))){ // String emsIds=paramMap.get("EMSIDS").toString(); // if(emsIds!=""){ // String[] ids=emsIds.split(","); // ems=new int[ids.length]; // for(int i=0;i<ids.length;i++){ // ems[i]=Integer.parseInt(ids[i]); // } // } // } // Map<String, Object> resultMap = new HashMap<String, Object>(); // Map<String,String> xmlMap = new HashMap<String,String>(); // level=paramMap.get("level")==null?"":paramMap.get("level").toString(); // if(level==null || "".equals(level)){//生成第一层图表 // setTable_name(CommonDefine.T_CURRENT_ALARM); // resultMap = faultManagerService.getReportAlarmByEms(groupId,ems,this.getTable_name(),start,limit,time); // if(resultMap==null || resultMap.get("rows")==null || ((List<DBObject>)resultMap.get("rows")).size()==0){ // setTable_name(CommonDefine.T_HISTORY_ALARM); // resultMap = faultManagerService.getReportAlarmByEms(groupId,ems,this.getTable_name(),start,limit,time); // } // List<Map> List_1=(List<Map>)resultMap.get("rows"); // String chartXml_1 = ""; // FusionChartDesigner fcd_1 = new FusionChartDesigner(); // setFusionChartSettings(fcd_1); // fcd_1.setOneDimensionList(List_1, "EMS_NAME", "count"); // fcd_1.getUserDefinedProperty().put("level","one"); // fcd_1.setChart_caption(paramMap.get("time").toString()+"告警按网管统计"); // chartXml_1 = fcd_1.getOneDimensionsXMLData(); // xmlMap.put("xml_1", chartXml_1); // }else if(level!=null && "one".equals(level)){//点击第一层图表进来 // String chartXml_1 = ""; // Map<String, Object> map=null; // if("year".equals(timeType)){ // paramMap.put("table_name", CommonDefine.T_CURRENT_ALARM); // resultMap =faultManagerService.getAlarmMonthDataByEms(paramMap); // if(resultMap==null || resultMap.get("rows")==null || ((List<DBObject>)resultMap.get("rows")).size()==0){ // paramMap.put("table_name", CommonDefine.T_HISTORY_ALARM); // resultMap = faultManagerService.getAlarmMonthDataByEms(paramMap); // } // List<Map> List_1=(List<Map>)map.get("rows"); // FusionChartDesigner fcd_1 = new FusionChartDesigner(); // setFusionChartSettings(fcd_1); // fcd_1.addSerialDatasList("计数值3级",(ArrayList)List_1,"retrieval_time","count_3"); // fcd_1.addSerialDatasList("计数值2级",(ArrayList)List_1,"retrieval_time","count_2"); // fcd_1.addSerialDatasList("计数值1级",(ArrayList)List_1,"retrieval_time","count_1"); // fcd_1.addSerialDatasList("物理量3级",(ArrayList)List_1,"retrieval_time","physics_3"); // fcd_1.addSerialDatasList("物理量2级",(ArrayList)List_1,"retrieval_time","physics_2"); // fcd_1.addSerialDatasList("物理量1级",(ArrayList)List_1,"retrieval_time","physics_1"); // fcd_1.getUserDefinedProperty().put("level","two"); // fcd_1.setChart_caption(paramMap.get("time").toString()+paramMap.get("label")+"网管组异常性能分布"); // chartXml_1 = fcd_1.getManyDimensionsXmlData(); // xmlMap.put("xml_1", chartXml_1); // }else if("month".equals(timeType)){ // paramMap.put("group_name",paramMap.get("label")); // paramMap.put("query_month",paramMap.get("time").toString()); // map = reportManagerService.getPMDayDataByEmsGroup(paramMap); // List<Map> List_1=(List<Map>)map.get("rows"); // FusionChartDesigner fcd_1 = new FusionChartDesigner(); // setFusionChartSettings(fcd_1); // fcd_1.addSerialDatasList("计数值3级",(ArrayList)List_1,"retrieval_time","count_3"); // fcd_1.addSerialDatasList("计数值2级",(ArrayList)List_1,"retrieval_time","count_2"); // fcd_1.addSerialDatasList("计数值1级",(ArrayList)List_1,"retrieval_time","count_1"); // fcd_1.addSerialDatasList("物理量3级",(ArrayList)List_1,"retrieval_time","physics_3"); // fcd_1.addSerialDatasList("物理量2级",(ArrayList)List_1,"retrieval_time","physics_2"); // fcd_1.addSerialDatasList("物理量1级",(ArrayList)List_1,"retrieval_time","physics_1"); // fcd_1.getUserDefinedProperty().put("level","two"); // fcd_1.setChart_caption(paramMap.get("time").toString()+paramMap.get("label")+"网管组异常性能分布"); // chartXml_1 = fcd_1.getManyDimensionsXmlData(); // xmlMap.put("xml_1", chartXml_1); // }else if("day".equals(timeType)){ // paramMap.put("group_name",paramMap.get("group_name")); // paramMap.put("query_day",paramMap.get("time").toString()); // map = reportManagerService.getPMDayDataByQueryDayAndGroup(paramMap); // List<Map> List_1=(List<Map>)map.get("rows"); // FusionChartDesigner fcd_1 = new FusionChartDesigner(); // setFusionChartSettings(fcd_1); // fcd_1.setOneDimensionList(List_1, "type_level", "cou"); // fcd_1.getUserDefinedProperty().put("level","three"); // fcd_1.setChart_caption(paramMap.get("label")+"异常性能按网管分组统计"); // chartXml_1 = fcd_1.getOneDimensionsXMLData(); // xmlMap.put("xml_1", chartXml_1); // } // }else if(level!=null && "two".equals(level)){//点击第二层图表进来 // String chartXml_1 = ""; // Map<String, Object> map=null; // if("year".equals(timeType)){ // paramMap.put("group_name",paramMap.get("group_name")); // paramMap.put("query_month",paramMap.get("label")); // map = reportManagerService.getPMDayDataByEmsGroup(paramMap); // List<Map> List_1=(List<Map>)map.get("rows"); // FusionChartDesigner fcd_1 = new FusionChartDesigner(); // setFusionChartSettings(fcd_1); // fcd_1.addSerialDatasList("计数值3级",(ArrayList)List_1,"retrieval_time","count_3"); // fcd_1.addSerialDatasList("计数值2级",(ArrayList)List_1,"retrieval_time","count_2"); // fcd_1.addSerialDatasList("计数值1级",(ArrayList)List_1,"retrieval_time","count_1"); // fcd_1.addSerialDatasList("物理量3级",(ArrayList)List_1,"retrieval_time","physics_3"); // fcd_1.addSerialDatasList("物理量2级",(ArrayList)List_1,"retrieval_time","physics_2"); // fcd_1.addSerialDatasList("物理量1级",(ArrayList)List_1,"retrieval_time","physics_1"); // fcd_1.getUserDefinedProperty().put("level","three"); // fcd_1.setChart_caption(paramMap.get("label").toString()+paramMap.get("group_name")+"网管组异常性能分布"); // chartXml_1 = fcd_1.getManyDimensionsXmlData(); // xmlMap.put("xml_1", chartXml_1); // }else if("month".equals(timeType)){ // paramMap.put("group_name",paramMap.get("group_name")); // paramMap.put("query_day",paramMap.get("label")); // map = reportManagerService.getPMDayDataByQueryDayAndGroup(paramMap); // List<Map> List_1=(List<Map>)map.get("rows"); // FusionChartDesigner fcd_1 = new FusionChartDesigner(); // setFusionChartSettings(fcd_1); // fcd_1.setOneDimensionList(List_1, "type_level", "cou"); // fcd_1.getUserDefinedProperty().put("level","three"); // fcd_1.setChart_caption(paramMap.get("label")+"异常性能按网管分组统计"); // chartXml_1 = fcd_1.getOneDimensionsXMLData(); // xmlMap.put("xml_1", chartXml_1); // } // } // Object obj = (Object)xmlMap; // resultObj = JSONObject.fromObject(obj); // return RESULT_OBJ; // // // } /** * Method name: getEmsGroupInfo_Circuit <BR> * Description: 资源报表--按网管分组查询<BR> * Remark: 2013-12-02<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @IMethodLog(desc = "查询getEmsGroupInfo_Circuit") @SuppressWarnings("unchecked") public String getEmsGroupInfo_Circuit(){ try { // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap = reportManagerService.getEmsGroupInfo_Circuit(paramMap,start,limit); // 将返回的结果转成JSON对象,返回前台 resultObj = JSONObject.fromObject(resultMap); } catch (CommonException e) { result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(e.getErrorMessage()); resultObj = JSONObject.fromObject(result); } return RESULT_OBJ; } /** * Method name: emsGroupFusionChart_Circuit <BR> * Description: 资源报表--fusionChart<BR> * Remark: 2013-12-23<BR> * @author YuanJia * @return List<Map<String, Object>><BR> */ @SuppressWarnings("unchecked") public String emsGroupFusionChart_Circuit() throws CommonException{ // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; List<Map<String,Object>> List = null; FusionChartDesigner fcd = new FusionChartDesigner(); if(paramMap.get("PARA")!=null){ List = reportManagerService.getEmsGroupFusionChart_Circuit_1(paramMap); fcd.setChart_caption("电路:按网管分组统计"); }else{ List = reportManagerService.getEmsGroupFusionChart_Circuit_2(paramMap); fcd.setChart_caption("按网管统计"); } /** 设置fusionChart */ String chartXml = ""; ArrayList<Map> xmlList = new ArrayList<Map>(); for(int i=0; i<List.size();i++){ Map lom = List.get(i); xmlList.add((Map)lom); } fcd.setOneDimensionList(xmlList, "X", "Y"); fcd.setChart_bgcolor("#F3f3f3"); fcd.setChart_xAxisName(""); fcd.setChart_yAxisName(""); fcd.setChartClickEnable(true); chartXml = fcd.getOneDimensionsXMLData(); Map<String,String> xmlMap = new HashMap<String,String>(); xmlMap.put("xml", chartXml); Object obj = (Object)xmlMap; resultObj = JSONObject.fromObject(obj); return RESULT_OBJ; } @IMethodLog(desc = "查询所有网管分组") public String getAllEmsGroups(){ try { // 查询所有网管分组 List<Map> dataList = commonManagerService.getAllEmsGroups(sysUserId,displayAll,displayNone, false); // 将返回的结果转成JSON对象,返回前台 Map map = new HashMap(); map.put("rows", dataList); resultObj = JSONObject.fromObject(map); } catch (CommonException e) { result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(e.getErrorMessage()); resultObj = JSONObject.fromObject(result); } return RESULT_OBJ; } // @IMethodLog(desc = "导出性能数据按网管统计") // @SuppressWarnings("unchecked") // public void exportEmsInfo_Performance(){ // HttpServletResponse response = ServletActionContext.getResponse(); // try { // // 将参数专程JSON对象 // JSONObject jsonObject = JSONObject.fromObject(jsonString); // // 将JSON对象转成Map对象 // Map<String, Object> paramMap = new HashMap<String, Object>(); // paramMap = (Map<String, Object>) jsonObject; // if("month".equals(paramMap.get("timeType")) || "day".equals(paramMap.get("timeType"))){ // String time = paramMap.get("time").toString().split("-")[0] + "_" + paramMap.get("time").toString().split("-")[1]; // setTable_name("t_pm_origi_data_2_" + time); // }else{ // String time = paramMap.get("time").toString().split("-")[0]; // setTable_name("t_pm_origi_data_2_" + time); // } // if("day".equals(paramMap.get("timeType"))){ // paramMap.put("day",paramMap.get("time").toString()); // } // paramMap.put("table_name", table_name); // Map<String, Object> resultMap = new HashMap<String, Object>(); // resultMap = reportManagerService.getEmsInfo_Performance(paramMap,0,limit); // // 将返回的结果转成JSON对象,返回前台 // List<Map<String, Object>> list = (List<Map<String, Object>>)resultMap.get("rows"); // //Export Excel // String myFlieName="性能数据按网管统计.xls"; // response.setContentType("application/vnd.ms-excel"); // response.addHeader("Content-Disposition","attachment; filename="+new String(myFlieName.getBytes("gb2312"), "ISO8859-1" )); // OutputStream os = response.getOutputStream(); // WritableWorkbook wwb = null; // wwb = Workbook.createWorkbook(os); // if(wwb!=null){ // WritableSheet ws = wwb.createSheet("性能数据按网管分组统计", 0); // ws.addCell(new Label(0, 0,"异常等级")); // ws.addCell(new Label(1, 0,"网管分组")); // ws.addCell(new Label(2, 0,"网管")); // ws.addCell(new Label(3, 0,"子网")); // ws.addCell(new Label(4, 0,"网元")); // ws.addCell(new Label(5, 0,"型号")); // ws.addCell(new Label(6, 0,"端口")); // ws.addCell(new Label(7, 0,"业务类型")); // ws.addCell(new Label(8, 0,"端口类型")); // ws.addCell(new Label(9, 0,"速率")); // ws.addCell(new Label(10, 0,"通道")); // ws.addCell(new Label(11, 0,"性能时间")); // ws.addCell(new Label(12, 0,"方向")); // ws.addCell(new Label(13, 0,"性能值")); // ws.addCell(new Label(14, 0,"性能基准值")); // ws.addCell(new Label(15, 0,"连续异常")); // ws.addCell(new Label(16, 0,"性能分析模板")); // ws.addCell(new Label(17, 0,"采集时间")); // for(int i=0;i<list.size();i++){ // int value=(list.get(i).get("EXCEPTION_LV")==null?0:Integer.valueOf(list.get(i).get("EXCEPTION_LV").toString())); // String gjjb="";//异常级别 // WritableCellFormat wff_color = new WritableCellFormat(); // if(value==0){ // wff_color.setBackground(Colour.GREEN); // gjjb="正常"; // }else if(value==1){ // wff_color.setBackground(Colour.YELLOW); // gjjb="告警等级1"; // }else if(value==2){ // wff_color.setBackground(Colour.ORANGE); // gjjb="告警等级2"; // }else if(value==3){ // wff_color.setBackground(Colour.RED); // gjjb="告警等级3"; // } // ws.addCell(new Label(0, i+1,gjjb,wff_color)); // ws.addCell(new Label(1, i+1,list.get(i).get("DISPLAY_EMS_GROUP")==null?"":list.get(i).get("DISPLAY_EMS_GROUP").toString())); // ws.addCell(new Label(2, i+1,list.get(i).get("DISPLAY_EMS")==null?"":list.get(i).get("DISPLAY_EMS").toString())); // ws.addCell(new Label(3, i+1,list.get(i).get("DISPLAY_SUBNET")==null?"":list.get(i).get("DISPLAY_SUBNET").toString())); // ws.addCell(new Label(4, i+1,list.get(i).get("DISPLAY_NE")==null?"":list.get(i).get("DISPLAY_NE").toString())); // ws.addCell(new Label(5, i+1,list.get(i).get("NET_TYPE")==null?"":list.get(i).get("NET_TYPE").toString())); // ws.addCell(new Label(6, i+1,list.get(i).get("PORT")==null?"":list.get(i).get("PORT").toString())); // ws.addCell(new Label(7, i+1,list.get(i).get("BUSINESS_TYPE")==null?"":list.get(i).get("BUSINESS_TYPE").toString())); // ws.addCell(new Label(8, i+1,list.get(i).get("PTP_TYPE")==null?"":list.get(i).get("PTP_TYPE").toString())); // ws.addCell(new Label(9, i+1,list.get(i).get("SPEED")==null?"":list.get(i).get("SPEED").toString())); // ws.addCell(new Label(10, i+1,list.get(i).get("DISPLAY_CTP")==null?"":list.get(i).get("DISPLAY_CTP").toString())); // ws.addCell(new Label(11, i+1,list.get(i).get("PERFORMANCE_EVENT")==null?"":list.get(i).get("PERFORMANCE_EVENT").toString())); // ws.addCell(new Label(12, i+1,list.get(i).get("DIRECTION")==null?"":list.get(i).get("DIRECTION").toString())); // ws.addCell(new Label(13, i+1,list.get(i).get("PM_VALUE")==null?"":list.get(i).get("PM_VALUE").toString())); // ws.addCell(new Label(14, i+1,list.get(i).get("PM_COMPARE_VALUE")==null?"":list.get(i).get("PM_COMPARE_VALUE").toString())); // ws.addCell(new Label(15, i+1,list.get(i).get("EXCEPTION_COUNT")==null?"":list.get(i).get("EXCEPTION_COUNT").toString())); // ws.addCell(new Label(16, i+1,list.get(i).get("DISPLAY_TEMPLATE_NAME")==null?"":list.get(i).get("DISPLAY_TEMPLATE_NAME").toString())); // ws.addCell(new Label(17, i+1,list.get(i).get("COLLECT_TIME")==null?"":list.get(i).get("COLLECT_TIME").toString())); // } // try { // wwb.write(); // } catch (IOException e) { // e.printStackTrace(); // }finally{ // wwb.close(); // os.close(); // response.flushBuffer(); // } // } // // } catch (Exception e) { // e.printStackTrace(); // } // } @IMethodLog(desc = "导出性能数据按网管统计") @SuppressWarnings("unchecked") public String exportEmsInfo_Performance(){ // // 将参数专程JSON对象 // JSONObject jsonObject = JSONObject.fromObject(jsonString); // // 将JSON对象转成Map对象 // Map<String, Object> paramMap = new HashMap<String, Object>(); // paramMap = (Map<String, Object>) jsonObject; // setTable_name(TABLE_PRI+paramMap.get("time").toString().substring(0,4)); // paramMap.put("table_name",table_name); // paramMap.put("timeType", paramMap.get("timeType")); // paramMap.put("time",paramMap.get("time").toString()); // paramMap.put("query","list"); // Map<String, Object> resultMap = new HashMap<String, Object>(); // try { // resultMap = reportManagerService.getEmsInfo_Performance(paramMap,start,limit); // } catch (CommonException e) { // e.printStackTrace(); // } // List<Map> list = (List<Map>)resultMap.get("rows"); // String destination = null; // String myFlieName="性能数据按网管统计"; // IExportExcel ex=new ExportExcelUtil(CommonDefine.PATH_ROOT+ CommonDefine.EXCEL.TEMP_DIR,myFlieName); // destination = ex.writeExcel(list,CommonDefine.EXCEL.REPORT_PERFROMANCE_EMS, false); // setFilePath(destination); return RESULT_DOWNLOAD; } @IMethodLog(desc = "导出性能数据按网管分组统计") @SuppressWarnings("unchecked") public String exportEmsGroupInfo_Performance(){ // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; setTable_name(TABLE_PRI+paramMap.get("time").toString().substring(0,4)); paramMap.put("table_name",table_name); paramMap.put("timeType", paramMap.get("timeType")); paramMap.put("time",paramMap.get("time").toString()); paramMap.put("query","list"); Map<String, Object> resultMap = new HashMap<String, Object>(); try { resultMap = reportManagerService.getEmsGroupInfo_Performance(paramMap,start,limit); } catch (CommonException e) { e.printStackTrace(); } // 将返回的结果转成JSON对象,返回前台 List<Map> list = (List<Map>)resultMap.get("rows"); String destination = null; String myFlieName="性能数据按网管分组统计"; IExportExcel ex=new ExportExcelUtil(CommonDefine.PATH_ROOT+ CommonDefine.EXCEL.TEMP_DIR,myFlieName); destination = ex.writeExcel(list,CommonDefine.EXCEL.REPORT_PERFROMANCE_EMS, false); setFilePath(destination); return RESULT_DOWNLOAD; } @IMethodLog(desc = "导出告警按网管统计") @SuppressWarnings("unchecked") public String exportEmsInfo_Alarm(){ // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; String t=paramMap.get("time").toString().replaceAll("-", ""); int time=Integer.parseInt(t); int groupId=0; int[] ems=null; if(paramMap.get("GROUPID")!=null && !"".equals(paramMap.get("GROUPID"))){ groupId=Integer.parseInt(paramMap.get("GROUPID").toString()); } if(paramMap.get("EMSIDS")!=null && !"".equals(paramMap.get("EMSIDS"))){ String emsIds=paramMap.get("EMSIDS").toString(); if(emsIds!=""){ String[] ids=emsIds.split(","); ems=new int[ids.length]; for(int i=0;i<ids.length;i++){ ems[i]=Integer.parseInt(ids[i]); } } } setTable_name(CommonDefine.T_HISTORY_ALARM); Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap = alarmManagementService.getReportAlarmByEms(groupId,ems,this.getTable_name(),start,limit,time); /** 此处数据为假,仅供测试*/ if(resultMap==null || resultMap.get("rows")==null || ((List<DBObject>)resultMap.get("rows")).size()==0){ setTable_name(CommonDefine.T_CURRENT_ALARM); resultMap = alarmManagementService.getReportAlarmByEms(groupId,ems,this.getTable_name(),start,limit,time); } List<Map> list = (List<Map>)resultMap.get("rows"); String destination = null; String myFlieName="告警按网管统计"; IExportExcel ex=new ExportExcelUtil(CommonDefine.PATH_ROOT + CommonDefine.EXCEL.TEMP_DIR,myFlieName); destination = ex.writeExcel(list,CommonDefine.EXCEL.REPORT_ALARM_EMS, false); setFilePath(destination); return RESULT_DOWNLOAD; } @IMethodLog(desc = "导出网元数量按网管统计") @SuppressWarnings("unchecked") public String exportEmsInfo_Resource(){ // 将参数专程JSON对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); // 将JSON对象转成Map对象 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap = (Map<String, Object>) jsonObject; Map<String, Object> resultMap = new HashMap<String, Object>(); try { resultMap = reportManagerService.getEmsInfo_Resource(paramMap,start,limit); } catch (CommonException e1) { e1.printStackTrace(); } // 将返回的结果转成JSON对象,返回前台 List<Map> list = (List<Map>)resultMap.get("rows"); String destination = null; String myFlieName="资源数据按网管统计"; IExportExcel ex=new ExportExcelUtil(CommonDefine.PATH_ROOT + CommonDefine.EXCEL.TEMP_DIR,myFlieName); destination = ex.writeExcel(list,CommonDefine.EXCEL.REPORT_RESOURCE_EMS, false); setFilePath(destination); return RESULT_DOWNLOAD; } @SuppressWarnings("unchecked") @IMethodLog(desc = "共通树:获取所有子节点") public String getChildNodes() { String returnString = RESULT_OBJ; try { if (endLevel > 0) { List<Map> nodes = commonManagerService.treeGetChildNodes(nodeId, nodeLevel, endLevel,sysUserId); dealNodes(nodes);//网管分组为-1时 resultArray = JSONArray.fromObject(nodes); }else{ resultArray=new JSONArray(); } returnString = RESULT_ARRAY; } catch (CommonException e) { result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(e.getErrorMessage()); resultObj = JSONObject.fromObject(result); returnString = RESULT_OBJ; } return returnString; } private void dealNodes(List<Map> nodes) { for(int i=nodes.size()-1;i>=0;i--){ Map m=nodes.get(i); int nodeLevel=(Integer)m.get("nodeLevel"); if(nodeLevel==1){ nodes.remove(i); } } } /** * 调用性能存储过程job * @throws CommonException */ @IMethodLog(desc = "调用性能存储过程job") @SuppressWarnings("rawtypes") public String callPerformanceSPJob(){ try { Map param=new HashMap(); param.put("month","2013-03"); param.put("jobTime","0 0 23 2 * ?"); Map returnParm=reportManagerService.callPerformanceSPJob(param); result.setReturnResult(CommonDefine.SUCCESS); result.setReturnMessage("设置成功"); } catch (Exception e) { e.printStackTrace(); result.setReturnResult(CommonDefine.FAILED); result.setReturnMessage(e.getMessage()); } resultObj = JSONObject.fromObject(result); return RESULT_OBJ; } public Map<String, String> getCondMap() { return condMap; } public void setCondMap(Map<String, String> condMap) { this.condMap = condMap; } }
64,898
0.673279
0.658874
1,514
39.854691
26.65683
170
false
false
0
0
0
0
0
0
3.677675
false
false
12
32fcebf5ac6d87fac0eaf77f6220b9bccdad12c8
25,477,746,034,332
54a0b2133ebaadf88a920479f89f77260942af11
/src/com/syntax/class13/DogProgram.java
0d9a1649a1235850d3ad852bfba26fa9f853b80c
[]
no_license
JustFatCat/JavaBatch8
https://github.com/JustFatCat/JavaBatch8
162a28917b1f5d7a5961873702dcbc2f145f4469
08d2eea2664d3fca10d7d36d23ebc9f7e0de36fb
refs/heads/main
2023-01-20T12:35:59.876000
2020-12-03T13:54:55
2020-12-03T13:54:55
304,907,925
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.syntax.class13; public class DogProgram { public static void main(String[] args) { Dog shepherd= new Dog(); shepherd.numberOfLegs = 4; shepherd.age = 7; shepherd.name = "Shep"; shepherd.color = "white"; shepherd.breed = "Golden"; shepherd.hasMaster = true; shepherd.bark(); shepherd.play(); shepherd.sleep(); shepherd.sit(); } }
UTF-8
Java
439
java
DogProgram.java
Java
[ { "context": " shepherd.age = 7;\n shepherd.name = \"Shep\";\n shepherd.color = \"white\";\n sheph", "end": 223, "score": 0.9996215105056763, "start": 219, "tag": "NAME", "value": "Shep" } ]
null
[]
package com.syntax.class13; public class DogProgram { public static void main(String[] args) { Dog shepherd= new Dog(); shepherd.numberOfLegs = 4; shepherd.age = 7; shepherd.name = "Shep"; shepherd.color = "white"; shepherd.breed = "Golden"; shepherd.hasMaster = true; shepherd.bark(); shepherd.play(); shepherd.sleep(); shepherd.sit(); } }
439
0.560364
0.551253
18
23.388889
12.785143
44
false
false
0
0
0
0
0
0
0.666667
false
false
12
f605ce8ffb372dc72f835be895b28e2acc734107
15,736,760,173,500
e7ce2e07d02002c7e721c573c6ac0b48b9e4e6c9
/src/main/java/za/co/jacon/btca/exchange/bitfinex/accumulator/BitfinexPriceAccumulator.java
a72d4d9bae3021b4712ec53c4567aad160a810fd
[]
no_license
jaconza/btca
https://github.com/jaconza/btca
5433797c7fab3d2fe83bb0cdf27dd3bc879497b6
2a0d449a872e95e9efdfd0a12f94111e2924b25d
refs/heads/master
2021-05-30T19:55:36.649000
2015-12-10T20:35:49
2015-12-10T20:35:49
47,785,333
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package za.co.jacon.btca.exchange.bitfinex.accumulator; import org.apache.log4j.Logger; import za.co.jacon.btca.accumulator.PollingAccumulator; import za.co.jacon.btca.distributor.Distributor; import za.co.jacon.btca.exchange.bitfinex.api.BitfinexApi; import za.co.jacon.btca.model.TransactionVO; import java.util.List; /** * The Bitfinex accumulator. * * Accumulates information from the Bitfinex exchange and publishes it to the distributors registered in the system. */ public class BitfinexPriceAccumulator extends PollingAccumulator<TransactionVO> { private final Logger LOGGER = Logger.getLogger(BitfinexPriceAccumulator.class); protected final BitfinexApi api; /** * Class constructor. * * Sets up the accumulator to start accumulating information. The accumulator is not started on construct. * @param distributors the message distributors * @param api the bitnex api implementation * @param pollDelay how often to poll the api for the latest information. */ public BitfinexPriceAccumulator(final List<Distributor<TransactionVO>> distributors, final BitfinexApi api, final int pollDelay) { super(distributors, pollDelay); LOGGER.debug("Initiating " + BitfinexPriceAccumulator.class + " with delay " + pollDelay); this.api = api; } /** * The run method gets called by the scheduled task responsible for polling the bitfinex api. It is responsible * for calling the api and converting the response to the correct POJO. * * It is also responsible to pass the correct value to the distributor */ @Override public void run() { TransactionVO transaction = api.getLatestTransaction(); if (transaction != null) { for (Distributor distributor: distributors) { distributor.distribute(transaction, "bitfinex"); } } } }
UTF-8
Java
1,913
java
BitfinexPriceAccumulator.java
Java
[]
null
[]
package za.co.jacon.btca.exchange.bitfinex.accumulator; import org.apache.log4j.Logger; import za.co.jacon.btca.accumulator.PollingAccumulator; import za.co.jacon.btca.distributor.Distributor; import za.co.jacon.btca.exchange.bitfinex.api.BitfinexApi; import za.co.jacon.btca.model.TransactionVO; import java.util.List; /** * The Bitfinex accumulator. * * Accumulates information from the Bitfinex exchange and publishes it to the distributors registered in the system. */ public class BitfinexPriceAccumulator extends PollingAccumulator<TransactionVO> { private final Logger LOGGER = Logger.getLogger(BitfinexPriceAccumulator.class); protected final BitfinexApi api; /** * Class constructor. * * Sets up the accumulator to start accumulating information. The accumulator is not started on construct. * @param distributors the message distributors * @param api the bitnex api implementation * @param pollDelay how often to poll the api for the latest information. */ public BitfinexPriceAccumulator(final List<Distributor<TransactionVO>> distributors, final BitfinexApi api, final int pollDelay) { super(distributors, pollDelay); LOGGER.debug("Initiating " + BitfinexPriceAccumulator.class + " with delay " + pollDelay); this.api = api; } /** * The run method gets called by the scheduled task responsible for polling the bitfinex api. It is responsible * for calling the api and converting the response to the correct POJO. * * It is also responsible to pass the correct value to the distributor */ @Override public void run() { TransactionVO transaction = api.getLatestTransaction(); if (transaction != null) { for (Distributor distributor: distributors) { distributor.distribute(transaction, "bitfinex"); } } } }
1,913
0.714062
0.713539
53
35.094341
36.334019
134
false
false
0
0
0
0
0
0
0.339623
false
false
12
0c413258f199080fde8088f8040229cfb5d92f3d
27,015,344,326,002
6c58e5fdf9227c8c769171c18c08b59c93b50780
/app/src/main/java/com/can/mz/utils/DimensionUtils.java
5825153d2b33dceb1e79caa3420f71bb7916fdbc
[]
no_license
cmyeyi/smm
https://github.com/cmyeyi/smm
47996c2b354ab87e09ba4d309d4d6377f3056ab2
6f4882644557c2c6b421569ec8231a39bbf7238e
refs/heads/master
2020-03-26T23:45:36.823000
2020-03-01T11:06:09
2020-03-01T11:06:09
145,501,618
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.can.mz.utils; import android.content.Context; import java.lang.reflect.Field; public final class DimensionUtils { /** * dp转换px * * @param context * @param dip * @return */ public static int dpToPx(Context context, float dip) { final float SCALE = context.getResources().getDisplayMetrics().density; float valueDips = dip; int valuePixels = (int) (valueDips * SCALE + 0.5f); return valuePixels; } /** * 将px值转换为sp值,保证文字大小不变 * * @param pxValue * @param fontScale * (DisplayMetrics类中属性scaledDensity) * @return */ public static float px2sp(float pxValue, float fontScale){ // 注意返回float不是int防止产生误差 return pxValue / fontScale + 0.5f; } // 获取手机状态栏高度 public static int getStatusBarHeight(Context context) { Class<?> c = null; Object obj = null; Field field = null; int x = 0, statusBarHeight = 0; try { c = Class.forName("com.android.internal.R$dimen"); obj = c.newInstance(); field = c.getField("status_bar_height"); x = Integer.parseInt(field.get(obj).toString()); statusBarHeight = context.getResources().getDimensionPixelSize(x); } catch (Exception e1) { e1.printStackTrace(); } return statusBarHeight; } // /** // * 获取屏幕的宽度 pixel // */ // public static int getScreenWidth() { // DisplayMetrics dm = C.getAppContext().getResources().getDisplayMetrics(); // return dm.widthPixels; // } // // /** // * 获取屏幕的高度 pixel // */ // public static int getScreenHeight() { // DisplayMetrics dm = C.getAppContext().getResources().getDisplayMetrics(); // return dm.heightPixels; // } // // /** // * 获取状态栏的高度 pixel // */ // public static int getStatusBarHeight() { // int statusBar = getStatusBarHeight(C.getAppContext()); // if (statusBar == 0) { // statusBar = (int) (25 * C.getAppContext().getResources().getDisplayMetrics().density + 0.5); // } // return statusBar; // } }
UTF-8
Java
2,068
java
DimensionUtils.java
Java
[]
null
[]
package com.can.mz.utils; import android.content.Context; import java.lang.reflect.Field; public final class DimensionUtils { /** * dp转换px * * @param context * @param dip * @return */ public static int dpToPx(Context context, float dip) { final float SCALE = context.getResources().getDisplayMetrics().density; float valueDips = dip; int valuePixels = (int) (valueDips * SCALE + 0.5f); return valuePixels; } /** * 将px值转换为sp值,保证文字大小不变 * * @param pxValue * @param fontScale * (DisplayMetrics类中属性scaledDensity) * @return */ public static float px2sp(float pxValue, float fontScale){ // 注意返回float不是int防止产生误差 return pxValue / fontScale + 0.5f; } // 获取手机状态栏高度 public static int getStatusBarHeight(Context context) { Class<?> c = null; Object obj = null; Field field = null; int x = 0, statusBarHeight = 0; try { c = Class.forName("com.android.internal.R$dimen"); obj = c.newInstance(); field = c.getField("status_bar_height"); x = Integer.parseInt(field.get(obj).toString()); statusBarHeight = context.getResources().getDimensionPixelSize(x); } catch (Exception e1) { e1.printStackTrace(); } return statusBarHeight; } // /** // * 获取屏幕的宽度 pixel // */ // public static int getScreenWidth() { // DisplayMetrics dm = C.getAppContext().getResources().getDisplayMetrics(); // return dm.widthPixels; // } // // /** // * 获取屏幕的高度 pixel // */ // public static int getScreenHeight() { // DisplayMetrics dm = C.getAppContext().getResources().getDisplayMetrics(); // return dm.heightPixels; // } // // /** // * 获取状态栏的高度 pixel // */ // public static int getStatusBarHeight() { // int statusBar = getStatusBarHeight(C.getAppContext()); // if (statusBar == 0) { // statusBar = (int) (25 * C.getAppContext().getResources().getDisplayMetrics().density + 0.5); // } // return statusBar; // } }
2,068
0.642562
0.635331
79
23.506329
22.199825
97
false
false
0
0
0
0
0
0
1.455696
false
false
12
0cd096198bf59187101d806d17e82e343f5e9783
14,456,859,923,804
762f2a533fcf5fa55371dc8555d12cc5195fdae7
/src/jvm/final_project/control/SMSParser.java
9c89d7b6239dd8ea4766ba263829437133bafec3
[ "Apache-2.0" ]
permissive
jconnuck/fencing
https://github.com/jconnuck/fencing
529a346f04450f79192f41f8c9b19d1504985788
2f81de60c0b984a2b9e4cbe51895b9dd55d1d2bd
refs/heads/master
2020-05-19T09:12:57.113000
2011-05-14T23:24:32
2011-05-14T23:24:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package final_project.control; import java.util.Scanner; import java.util.Calendar; import final_project.model.store.*; import final_project.view.PoolObserverPanel; //import mocks.*; public class SMSParser { private IDataStore _store; private SMSController _control; private Calendar _cal; public SMSParser(IDataStore s, SMSController ctrl) { _store = s; _control = ctrl; _cal = Calendar.getInstance(); } /** * This method handles parsing the message from the API & * then calling the appropriate other methods on the data that * it gets out of the line. */ public void parseOutput(String received, String number) { Scanner s = new Scanner(received); //First, getting the first word String firstWord = s.next(); System.out.println("First word: " + firstWord); //Find sender id int id = -1; for(IPerson p: _store.getPeople()) { if(p.getPhoneNumber().equals(number)) { System.out.println("Number match found!"); id = p.getID(); } } //Message: "help string" if (firstWord.equalsIgnoreCase("help")) { if(id == -1) return; /* Alerting the proper group for help (either technical or medical) */ if(s.hasNext()) { String groupToAlert = s.next(); if(groupToAlert.equalsIgnoreCase("medical")) { _control.alertGUI(PoolObserverPanel.Status.MEDICAL, received, _cal.getTime()); _control.sendGroupMessage("Medical", received); _control.setGUIStatusLabel(PoolObserverPanel.Status.MEDICAL, id); } else if(groupToAlert.equalsIgnoreCase("technical")) { _control.alertGUI(PoolObserverPanel.Status.TECHNICAL, received, _cal.getTime()); _control.sendGroupMessage("Technical", received); _control.setGUIStatusLabel(PoolObserverPanel.Status.TECHNICAL, id); } else if (groupToAlert.equalsIgnoreCase("fixed")) { _control.alertGUI(PoolObserverPanel.Status.TECHNICAL, received, _cal.getTime()); _control.setGUIStatusLabel(PoolObserverPanel.Status.FENCING, id); } else { _control.alertGUI(null, received, _cal.getTime()); } } } // Message: "Fixed strip 5" else if(firstWord.equalsIgnoreCase("fixed")) { _control.alertGUI(PoolObserverPanel.Status.TECHNICAL, received, _cal.getTime()); _control.setGUIStatusLabel(PoolObserverPanel.Status.FENCING, id); } // Message: "Ready on strip 3" else if(firstWord.equalsIgnoreCase("ready")) { _control.alertGUI(PoolObserverPanel.Status.TECHNICAL, received, _cal.getTime()); _control.setGUIStatusLabel(PoolObserverPanel.Status.FENCING, id); } // Message: "Follow first last" or "follow clubName" else if(firstWord.equalsIgnoreCase("follow")) { String firstName = "", lastName = ""; if(s.hasNext()) firstName = s.next(); if(s.hasNext()) lastName = s.next(); this.subscribeUserToObservable(firstName, lastName, number); } // Message: "unsubscribe first last" or "Unsubscribe clubName" else if(firstWord.equalsIgnoreCase("unsubscribe")) { String firstName = "", lastName = ""; if(s.hasNext()) firstName = s.next(); if(s.hasNext()) lastName = s.next(); this.unsubscribeUserToObservable(firstName, lastName, number); } //Message: "refswap number" else if(firstWord.equalsIgnoreCase("Refswap")) { String newRefNumber = ""; if(s.hasNext()) newRefNumber = s.next(); this.swapRefs(number, newRefNumber); } //Message "result id beat id this-that" or "id beat id this to that" else if(firstWord.equalsIgnoreCase("result") || firstWord.equalsIgnoreCase("rescore")) { int refID =0, winID = 0, loseID = 0, winScore = 0, loseScore = 0; /* Looping through to find the ref ID of this number */ boolean found = false; for (IReferee i: _store.getReferees()) { if(i.getPhoneNumber().equals(number)) { refID = i.getID(); found = true; break; } } if(!found) { _control.sendMessage("We're sorry, this number is not registered as a referee.", number); return; } /* Now, parsing out fencer IDs and score */ if(s.hasNextInt()) winID = s.nextInt(); if(s.hasNext() && !s.next().equalsIgnoreCase("beat")) { //Eating "beat" token _control.sendMessage("We're sorry, this message could not be parsed.", number); return; } if(s.hasNextInt()) loseID = s.nextInt(); else { _control.sendMessage("We're sorry, this message could not be parsed.", number); return; } if(s.hasNextInt()) winScore = s.nextInt(); else { _control.sendMessage("We're sorry, this message could not be parsed.", number); return; } if(s.hasNext()) { String next = s.next(); if (!next.equalsIgnoreCase("to") && !next.equalsIgnoreCase("-")){ //Eating "to"/"-" token _control.sendMessage("We're sorry, this message could not be parsed.", number); return; } } if(s.hasNextInt()) loseScore = s.nextInt(); else { _control.sendMessage("We're sorry, this message could not be parsed.", number); return; } /* NOW THAT WE'VE PARSED OUT ALL OF THE DATA */ if(firstWord.toLowerCase().equalsIgnoreCase("rescore")) { //changing the mistaken results _control.rescoreLastMatch(refID, winID, winScore, loseID, loseScore); } else { try{ _control.returnResults(refID, winID, winScore, loseID, loseScore); }catch (IllegalArgumentException e){ _control.sendMessage("Result not for current bout. Check fencer id's?", number); } } } else { _control.sendMessage("We're sorry, this message could not be parsed.", number); } } //Subscribes a user to an IObservable public boolean subscribeUserToObservable(String firstNameToSubscribeTo, String lastNameToSubscribeTo, String number) { //Checking to see that the person is registered in the database -- linear search through all people. boolean found = false; if(_store == null) return false; int idSpectator = -1; for (IPerson i: _store.getPeople()) { if(i.getPhoneNumber().equals(number)) { found = true; idSpectator = i.getID(); break; } } if (!found) { return false; } /* Checking to see that the person/club to be followed exists */ found = false; int counter = 0; //To make sure that we don't get duplicates int idToFollow = 0; if(lastNameToSubscribeTo.equals("")) { // Last name empty, this is a club. for (IClub i: _store.getClubs()) { if(i.getName().equalsIgnoreCase(firstNameToSubscribeTo.toLowerCase())) { idToFollow = i.getID(); found = true; counter++; } } } else { for (IPlayer i: _store.getPlayers()) { if(i.getFirstName().equalsIgnoreCase(firstNameToSubscribeTo.toLowerCase())) { if (i.getLastName().equalsIgnoreCase(lastNameToSubscribeTo)) { idToFollow = i.getID(); found = true; counter++; } } } } /* Handling error messages */ if (!found) { _control.sendMessage("We're sorry, no fencer or group was found with this name.", number); return false; } else if (counter > 1) { _control.sendMessage("Multiple entries found for this name. Please respond with \"follow\" followed by an ID number.", number); return false; } /* ACTUALLY SUBSCRIBING USER */ final int finalID = idSpectator; final int finalIDToFollow = idToFollow; _store.runTransaction(new Runnable(){ public void run(){ IPerson spect = _store.getPerson(finalID).addWatched(finalIDToFollow); _store.putData(spect); } }); _control.updateSubscriberGUI(); _control.sendMessage("You were successfully subscribed to " + firstNameToSubscribeTo + " " + lastNameToSubscribeTo + "!", number); return true; } public boolean unsubscribeUserToObservable(String firstToUnsubscribe, String lastToUnsubscribe, String number) { //Finding the spectator at this phone number int idToFind = 0; boolean found = false; for (IPerson i: _store.getPeople()) { if (i.getPhoneNumber().equals(number)) { idToFind = i.getID(); found = true; break; } } if(!found) { _control.sendMessage("Error: this phone number is not registered.", number); return false; } /* Finding the person/club to be unsubscribed from*/ found = false; int counter = 0; //To make sure that we don't get duplicates int idToUnfollow = 0; if(lastToUnsubscribe.equals("")) { // Last name empty, this is a club. for (IClub i: _store.getClubs()) { if(i.getName().equalsIgnoreCase(firstToUnsubscribe)) { idToUnfollow = i.getID(); found = true; counter++; } } } else { for (IPlayer i: _store.getPlayers()) { if(i.getFirstName().equalsIgnoreCase(firstToUnsubscribe)) { if (i.getLastName().equalsIgnoreCase(lastToUnsubscribe)) { idToUnfollow = i.getID(); found = true; counter++; } } } } /* Handling errors */ if(!found) { _control.sendMessage("We're sorry, no fencer or group was found with this name.", number); return false; } if(counter > 1) { _control.sendMessage("Multiple entries found for this name. Please respond with \"unsubscribe\"" + " followed by an ID number.", number); return false; } /* UNSUBSCRIBING */ final IPerson spect = _store.getPerson(idToFind); found = false; for(Object o: spect.getWatched()) { Integer i = (Integer) o; if(i == idToFind) { found = true; break; } } if(!found) { _control.sendMessage("We're sorry, it does not appear that you are subscribed to this fencer", number); return false; } if (spect == null || spect.removeWatched(idToUnfollow) == null) { _control.sendMessage("Error: unsubscription not successful", number); return false; } else { _control.sendMessage("You have been successfully unsubscribed from " + firstToUnsubscribe + " " + lastToUnsubscribe + " .", number); //Cleaning up Spectator if (spect.getWatched().isEmpty()) { _store.runTransaction(new Runnable() { public void run() { _store.removeData(spect); } }); } return false; } } public boolean swapRefs(String oldRefNumber, String newRefNumber){ /** * Looking up ref ids by searching through list of referees. If either * phone number does not belong to a registered ref, the swap will not * go through. */ int oldRefID = 0, newRefID = 0; boolean found = false; for(IReferee i : _store.getReferees()){ if (i.getPhoneNumber().equals(oldRefNumber)) { oldRefID = i.getID(); found = true; break; } } if (!found) { _control.sendMessage("You (message sender) are not registered as a referee.", oldRefNumber); return false; } /* NEW REFEREE */ found = false; for(IReferee i : _store.getReferees()){ if (i.getPhoneNumber().equals(newRefNumber)) { newRefID = i.getID(); found = true; break; } } if (!found) { _control.sendMessage("You (message sender) are not registered as a referee.", oldRefNumber); return false; } /* Now we know both numbers are valid referees */ _control.swapRefs(oldRefID, newRefID); _control.sendMessage("Swap successful", oldRefNumber); return true; } }
UTF-8
Java
11,112
java
SMSParser.java
Java
[]
null
[]
package final_project.control; import java.util.Scanner; import java.util.Calendar; import final_project.model.store.*; import final_project.view.PoolObserverPanel; //import mocks.*; public class SMSParser { private IDataStore _store; private SMSController _control; private Calendar _cal; public SMSParser(IDataStore s, SMSController ctrl) { _store = s; _control = ctrl; _cal = Calendar.getInstance(); } /** * This method handles parsing the message from the API & * then calling the appropriate other methods on the data that * it gets out of the line. */ public void parseOutput(String received, String number) { Scanner s = new Scanner(received); //First, getting the first word String firstWord = s.next(); System.out.println("First word: " + firstWord); //Find sender id int id = -1; for(IPerson p: _store.getPeople()) { if(p.getPhoneNumber().equals(number)) { System.out.println("Number match found!"); id = p.getID(); } } //Message: "help string" if (firstWord.equalsIgnoreCase("help")) { if(id == -1) return; /* Alerting the proper group for help (either technical or medical) */ if(s.hasNext()) { String groupToAlert = s.next(); if(groupToAlert.equalsIgnoreCase("medical")) { _control.alertGUI(PoolObserverPanel.Status.MEDICAL, received, _cal.getTime()); _control.sendGroupMessage("Medical", received); _control.setGUIStatusLabel(PoolObserverPanel.Status.MEDICAL, id); } else if(groupToAlert.equalsIgnoreCase("technical")) { _control.alertGUI(PoolObserverPanel.Status.TECHNICAL, received, _cal.getTime()); _control.sendGroupMessage("Technical", received); _control.setGUIStatusLabel(PoolObserverPanel.Status.TECHNICAL, id); } else if (groupToAlert.equalsIgnoreCase("fixed")) { _control.alertGUI(PoolObserverPanel.Status.TECHNICAL, received, _cal.getTime()); _control.setGUIStatusLabel(PoolObserverPanel.Status.FENCING, id); } else { _control.alertGUI(null, received, _cal.getTime()); } } } // Message: "Fixed strip 5" else if(firstWord.equalsIgnoreCase("fixed")) { _control.alertGUI(PoolObserverPanel.Status.TECHNICAL, received, _cal.getTime()); _control.setGUIStatusLabel(PoolObserverPanel.Status.FENCING, id); } // Message: "Ready on strip 3" else if(firstWord.equalsIgnoreCase("ready")) { _control.alertGUI(PoolObserverPanel.Status.TECHNICAL, received, _cal.getTime()); _control.setGUIStatusLabel(PoolObserverPanel.Status.FENCING, id); } // Message: "Follow first last" or "follow clubName" else if(firstWord.equalsIgnoreCase("follow")) { String firstName = "", lastName = ""; if(s.hasNext()) firstName = s.next(); if(s.hasNext()) lastName = s.next(); this.subscribeUserToObservable(firstName, lastName, number); } // Message: "unsubscribe first last" or "Unsubscribe clubName" else if(firstWord.equalsIgnoreCase("unsubscribe")) { String firstName = "", lastName = ""; if(s.hasNext()) firstName = s.next(); if(s.hasNext()) lastName = s.next(); this.unsubscribeUserToObservable(firstName, lastName, number); } //Message: "refswap number" else if(firstWord.equalsIgnoreCase("Refswap")) { String newRefNumber = ""; if(s.hasNext()) newRefNumber = s.next(); this.swapRefs(number, newRefNumber); } //Message "result id beat id this-that" or "id beat id this to that" else if(firstWord.equalsIgnoreCase("result") || firstWord.equalsIgnoreCase("rescore")) { int refID =0, winID = 0, loseID = 0, winScore = 0, loseScore = 0; /* Looping through to find the ref ID of this number */ boolean found = false; for (IReferee i: _store.getReferees()) { if(i.getPhoneNumber().equals(number)) { refID = i.getID(); found = true; break; } } if(!found) { _control.sendMessage("We're sorry, this number is not registered as a referee.", number); return; } /* Now, parsing out fencer IDs and score */ if(s.hasNextInt()) winID = s.nextInt(); if(s.hasNext() && !s.next().equalsIgnoreCase("beat")) { //Eating "beat" token _control.sendMessage("We're sorry, this message could not be parsed.", number); return; } if(s.hasNextInt()) loseID = s.nextInt(); else { _control.sendMessage("We're sorry, this message could not be parsed.", number); return; } if(s.hasNextInt()) winScore = s.nextInt(); else { _control.sendMessage("We're sorry, this message could not be parsed.", number); return; } if(s.hasNext()) { String next = s.next(); if (!next.equalsIgnoreCase("to") && !next.equalsIgnoreCase("-")){ //Eating "to"/"-" token _control.sendMessage("We're sorry, this message could not be parsed.", number); return; } } if(s.hasNextInt()) loseScore = s.nextInt(); else { _control.sendMessage("We're sorry, this message could not be parsed.", number); return; } /* NOW THAT WE'VE PARSED OUT ALL OF THE DATA */ if(firstWord.toLowerCase().equalsIgnoreCase("rescore")) { //changing the mistaken results _control.rescoreLastMatch(refID, winID, winScore, loseID, loseScore); } else { try{ _control.returnResults(refID, winID, winScore, loseID, loseScore); }catch (IllegalArgumentException e){ _control.sendMessage("Result not for current bout. Check fencer id's?", number); } } } else { _control.sendMessage("We're sorry, this message could not be parsed.", number); } } //Subscribes a user to an IObservable public boolean subscribeUserToObservable(String firstNameToSubscribeTo, String lastNameToSubscribeTo, String number) { //Checking to see that the person is registered in the database -- linear search through all people. boolean found = false; if(_store == null) return false; int idSpectator = -1; for (IPerson i: _store.getPeople()) { if(i.getPhoneNumber().equals(number)) { found = true; idSpectator = i.getID(); break; } } if (!found) { return false; } /* Checking to see that the person/club to be followed exists */ found = false; int counter = 0; //To make sure that we don't get duplicates int idToFollow = 0; if(lastNameToSubscribeTo.equals("")) { // Last name empty, this is a club. for (IClub i: _store.getClubs()) { if(i.getName().equalsIgnoreCase(firstNameToSubscribeTo.toLowerCase())) { idToFollow = i.getID(); found = true; counter++; } } } else { for (IPlayer i: _store.getPlayers()) { if(i.getFirstName().equalsIgnoreCase(firstNameToSubscribeTo.toLowerCase())) { if (i.getLastName().equalsIgnoreCase(lastNameToSubscribeTo)) { idToFollow = i.getID(); found = true; counter++; } } } } /* Handling error messages */ if (!found) { _control.sendMessage("We're sorry, no fencer or group was found with this name.", number); return false; } else if (counter > 1) { _control.sendMessage("Multiple entries found for this name. Please respond with \"follow\" followed by an ID number.", number); return false; } /* ACTUALLY SUBSCRIBING USER */ final int finalID = idSpectator; final int finalIDToFollow = idToFollow; _store.runTransaction(new Runnable(){ public void run(){ IPerson spect = _store.getPerson(finalID).addWatched(finalIDToFollow); _store.putData(spect); } }); _control.updateSubscriberGUI(); _control.sendMessage("You were successfully subscribed to " + firstNameToSubscribeTo + " " + lastNameToSubscribeTo + "!", number); return true; } public boolean unsubscribeUserToObservable(String firstToUnsubscribe, String lastToUnsubscribe, String number) { //Finding the spectator at this phone number int idToFind = 0; boolean found = false; for (IPerson i: _store.getPeople()) { if (i.getPhoneNumber().equals(number)) { idToFind = i.getID(); found = true; break; } } if(!found) { _control.sendMessage("Error: this phone number is not registered.", number); return false; } /* Finding the person/club to be unsubscribed from*/ found = false; int counter = 0; //To make sure that we don't get duplicates int idToUnfollow = 0; if(lastToUnsubscribe.equals("")) { // Last name empty, this is a club. for (IClub i: _store.getClubs()) { if(i.getName().equalsIgnoreCase(firstToUnsubscribe)) { idToUnfollow = i.getID(); found = true; counter++; } } } else { for (IPlayer i: _store.getPlayers()) { if(i.getFirstName().equalsIgnoreCase(firstToUnsubscribe)) { if (i.getLastName().equalsIgnoreCase(lastToUnsubscribe)) { idToUnfollow = i.getID(); found = true; counter++; } } } } /* Handling errors */ if(!found) { _control.sendMessage("We're sorry, no fencer or group was found with this name.", number); return false; } if(counter > 1) { _control.sendMessage("Multiple entries found for this name. Please respond with \"unsubscribe\"" + " followed by an ID number.", number); return false; } /* UNSUBSCRIBING */ final IPerson spect = _store.getPerson(idToFind); found = false; for(Object o: spect.getWatched()) { Integer i = (Integer) o; if(i == idToFind) { found = true; break; } } if(!found) { _control.sendMessage("We're sorry, it does not appear that you are subscribed to this fencer", number); return false; } if (spect == null || spect.removeWatched(idToUnfollow) == null) { _control.sendMessage("Error: unsubscription not successful", number); return false; } else { _control.sendMessage("You have been successfully unsubscribed from " + firstToUnsubscribe + " " + lastToUnsubscribe + " .", number); //Cleaning up Spectator if (spect.getWatched().isEmpty()) { _store.runTransaction(new Runnable() { public void run() { _store.removeData(spect); } }); } return false; } } public boolean swapRefs(String oldRefNumber, String newRefNumber){ /** * Looking up ref ids by searching through list of referees. If either * phone number does not belong to a registered ref, the swap will not * go through. */ int oldRefID = 0, newRefID = 0; boolean found = false; for(IReferee i : _store.getReferees()){ if (i.getPhoneNumber().equals(oldRefNumber)) { oldRefID = i.getID(); found = true; break; } } if (!found) { _control.sendMessage("You (message sender) are not registered as a referee.", oldRefNumber); return false; } /* NEW REFEREE */ found = false; for(IReferee i : _store.getReferees()){ if (i.getPhoneNumber().equals(newRefNumber)) { newRefID = i.getID(); found = true; break; } } if (!found) { _control.sendMessage("You (message sender) are not registered as a referee.", oldRefNumber); return false; } /* Now we know both numbers are valid referees */ _control.swapRefs(oldRefID, newRefID); _control.sendMessage("Swap successful", oldRefNumber); return true; } }
11,112
0.660097
0.658387
384
27.9375
28.047974
132
false
false
0
0
0
0
0
0
3.216146
false
false
12
cdf1d7eeef0605be0148617b41bb56b377820007
23,364,622,109,285
8144c2f81e0c1b190dc237b921b292af83df3c07
/MyApp.FileExplorer-0.0.1-SNAPSHOT/src/main/java/MyApp/FileExplorer/FileUtil.java
2cda6c4d15ea564c8754050e577002883834f452
[]
no_license
GlibKostsov/textFileExploration
https://github.com/GlibKostsov/textFileExploration
4a211815acd86c12013f983e411a048bb2f5fe5c
384b791700d7f4fe72e43d54d44ad8c85d7cda06
refs/heads/master
2016-08-12T22:24:10.569000
2016-02-22T01:23:08
2016-02-22T01:23:08
52,230,906
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package MyApp.FileExplorer; import java.io.File; import java.util.Scanner; public class FileUtil { public static void checkFile(String fileName) { try { File myFile = new File(fileName); Scanner scanner = new Scanner(myFile); String longestWord = ""; while (scanner.hasNextLine()) { Scanner wordScanner = new Scanner(scanner.nextLine()); while (wordScanner.hasNext()) { String str = wordScanner.next(); if (!str.matches("[a-zA-Z]+")){ String[] dirtyString = str.replaceAll("\\W", " ").split(" "); for (String s: dirtyString) { if(s.length()>longestWord.length()) longestWord= s; } } else{ if(str.length()>longestWord.length()) longestWord= str; } } } System.out.printf("The longest word is: %s", longestWord) ; } catch (Exception exc) { System.err.printf("Error reading file: %s" , exc); } } }
UTF-8
Java
1,247
java
FileUtil.java
Java
[]
null
[]
package MyApp.FileExplorer; import java.io.File; import java.util.Scanner; public class FileUtil { public static void checkFile(String fileName) { try { File myFile = new File(fileName); Scanner scanner = new Scanner(myFile); String longestWord = ""; while (scanner.hasNextLine()) { Scanner wordScanner = new Scanner(scanner.nextLine()); while (wordScanner.hasNext()) { String str = wordScanner.next(); if (!str.matches("[a-zA-Z]+")){ String[] dirtyString = str.replaceAll("\\W", " ").split(" "); for (String s: dirtyString) { if(s.length()>longestWord.length()) longestWord= s; } } else{ if(str.length()>longestWord.length()) longestWord= str; } } } System.out.printf("The longest word is: %s", longestWord) ; } catch (Exception exc) { System.err.printf("Error reading file: %s" , exc); } } }
1,247
0.448276
0.448276
41
28.414635
22.362835
80
false
false
0
0
0
0
0
0
2.365854
false
false
12
3c91e2dee9e1ddbfc20751979c1e4036f0c0a1db
2,224,793,127,349
06237a2d67bfd0ed18e81e7903794524f422dedd
/mybetispring/src/nwp/entity/Student.java
e38a6253186912a2762b233c98f153b18e867abb
[]
no_license
nwp65535/mybit
https://github.com/nwp65535/mybit
883f14256932e8f7fce818ff956068cfd431566e
255bd0fe331b224379b08420acca597c6e9cbb8a
refs/heads/master
2020-04-07T07:40:31.799000
2018-11-19T08:15:58
2018-11-19T08:15:58
158,184,829
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package nwp.entity; public class Student { private Integer sid; private String sname; private String smiaoshu; private Cla cla; public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getSmiaoshu() { return smiaoshu; } public void setSmiaoshu(String smiaoshu) { this.smiaoshu = smiaoshu; } public Cla getCla() { return cla; } public void setCla(Cla cla) { this.cla = cla; } }
UTF-8
Java
600
java
Student.java
Java
[]
null
[]
package nwp.entity; public class Student { private Integer sid; private String sname; private String smiaoshu; private Cla cla; public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getSmiaoshu() { return smiaoshu; } public void setSmiaoshu(String smiaoshu) { this.smiaoshu = smiaoshu; } public Cla getCla() { return cla; } public void setCla(Cla cla) { this.cla = cla; } }
600
0.648333
0.648333
33
16.181818
12.028891
43
false
false
0
0
0
0
0
0
1.515152
false
false
12
b4a1c4099d2c6653fe46117f753cdb2ae4fc1f6b
8,048,768,751,478
3743d566d4690c29d329870d0346685aa16ae0e2
/alibaba-sentinel-consumer-order-80/src/main/java/com/kon/cloud/sentinel/consumer/controller/OrderController.java
73c9ae5a05c8b6398755f8859d5b5b04a4f7b484
[]
no_license
q821863269/cloud-2020
https://github.com/q821863269/cloud-2020
7f8417f55345f38ccc0c53349e5b506649344336
6303553b395af7c7d5b9849fa06de61fc39e15ae
refs/heads/master
2022-07-05T13:28:49.025000
2020-03-29T12:41:56
2020-03-29T12:41:56
246,864,138
4
1
null
false
2022-06-21T02:58:46
2020-03-12T15:07:27
2020-03-29T07:16:33
2022-06-21T02:58:46
38,631
1
0
1
Java
false
false
package com.kon.cloud.sentinel.consumer.controller; import com.alibaba.csp.sentinel.annotation.SentinelResource; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.kon.cloud.common.vo.R; import com.kon.cloud.common.vo.Result; import com.kon.cloud.sentinel.consumer.feign.PaymentService; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; /** * 订单控制器 * * @author Lin Kun * @create 2020/3/13 */ @Slf4j @RestController @RequestMapping("/consumer") public class OrderController { private static final String PAYMENT_URL = "http://nacos-provider-payment"; @Resource(name = "serviceRestTemplate") private RestTemplate restTemplate; // -------------------------------------------------------------------------------------------------- //@SentinelResource(value = "fallback") // 没有配置,直接返回error //@SentinelResource(value = "fallback", fallback = "handlerFallback") // 只配置了fallback //@SentinelResource(value = "fallback", blockHandler = "blockHandler") // 只配置了fallback @SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler") @GetMapping("/fallback/{id}") public Result fallback(@PathVariable("id") Long id) { Result result = restTemplate.getForObject(PAYMENT_URL + "/payment/" + id, Result.class); if (id == 4) { throw new IllegalArgumentException("非法参数异常"); } else { assert result != null; if (result.getData() == null) { throw new NullPointerException("该ID没有对应记录,空指针异常"); } } return result; } // fallback方法 public Result handlerFallback(@PathVariable("id") Long id, Throwable e) { return R.no(e.getMessage()); } // blockHandler方法 public Result blockHandler(@PathVariable("id") Long id, BlockException e) { return R.no(e.getMessage()); } // -------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------- @Resource private PaymentService paymentService; @GetMapping("/payment/{id}") public Result getPaymentById(@PathVariable("id") Long id) { return paymentService.getPaymentById(id); } // -------------------------------------------------------------------------------------------------- }
UTF-8
Java
2,639
java
OrderController.java
Java
[ { "context": "x.annotation.Resource;\n\n/**\n * 订单控制器\n *\n * @author Lin Kun\n * @create 2020/3/13\n */\n@Slf4j\n@RestController\n@", "end": 514, "score": 0.9998194575309753, "start": 507, "tag": "NAME", "value": "Lin Kun" } ]
null
[]
package com.kon.cloud.sentinel.consumer.controller; import com.alibaba.csp.sentinel.annotation.SentinelResource; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.kon.cloud.common.vo.R; import com.kon.cloud.common.vo.Result; import com.kon.cloud.sentinel.consumer.feign.PaymentService; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; /** * 订单控制器 * * @author <NAME> * @create 2020/3/13 */ @Slf4j @RestController @RequestMapping("/consumer") public class OrderController { private static final String PAYMENT_URL = "http://nacos-provider-payment"; @Resource(name = "serviceRestTemplate") private RestTemplate restTemplate; // -------------------------------------------------------------------------------------------------- //@SentinelResource(value = "fallback") // 没有配置,直接返回error //@SentinelResource(value = "fallback", fallback = "handlerFallback") // 只配置了fallback //@SentinelResource(value = "fallback", blockHandler = "blockHandler") // 只配置了fallback @SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler") @GetMapping("/fallback/{id}") public Result fallback(@PathVariable("id") Long id) { Result result = restTemplate.getForObject(PAYMENT_URL + "/payment/" + id, Result.class); if (id == 4) { throw new IllegalArgumentException("非法参数异常"); } else { assert result != null; if (result.getData() == null) { throw new NullPointerException("该ID没有对应记录,空指针异常"); } } return result; } // fallback方法 public Result handlerFallback(@PathVariable("id") Long id, Throwable e) { return R.no(e.getMessage()); } // blockHandler方法 public Result blockHandler(@PathVariable("id") Long id, BlockException e) { return R.no(e.getMessage()); } // -------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------- @Resource private PaymentService paymentService; @GetMapping("/payment/{id}") public Result getPaymentById(@PathVariable("id") Long id) { return paymentService.getPaymentById(id); } // -------------------------------------------------------------------------------------------------- }
2,638
0.568851
0.564535
74
33.445946
32.289291
105
false
false
0
0
0
0
0
0
0.378378
false
false
12
1a780c20e3b96d0790ab2c34285bbbca31835cb1
37,615,323,578,493
db15e41c3ca1181c051960988b4539afbcd981d9
/src/main/java/at/s110103/skywars/listener/PlayerJoinListener.java
e3ca9f1aa4a2222889da0e2d4cf2f743bf7de5a0
[]
no_license
s110103/SkyWars
https://github.com/s110103/SkyWars
7230ac64b34442da073498cece4e21fe31d39244
4c0999555f920c063b90f25833c77335faf04791
refs/heads/master
2020-08-12T00:55:32.474000
2019-10-13T22:03:39
2019-10-13T22:03:39
214,660,090
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package at.s110103.skywars.listener; import at.s110103.skywars.methods.locations.LocationGet_Method; import at.s110103.skywars.status.GameStatus; import at.s110103.skywars.utilities.Utils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; public class PlayerJoinListener implements Listener { @EventHandler public void onJoin(PlayerJoinEvent e) { Player player = e.getPlayer(); e.setJoinMessage(null); if(Utils.getGameStatus() == GameStatus.LOBBY) { Bukkit.broadcastMessage("§8» §a" + player.getName() + " §7hat das Spiel betreten"); if(LocationGet_Method.getLocation(player, "lobby") != null) { player.teleport(LocationGet_Method.getLocation(player, "lobby")); } } else if(Utils.getGameStatus() == GameStatus.RESTART) { if(LocationGet_Method.getLocation(player, "restart") != null) { player.teleport(LocationGet_Method.getLocation(player, "restart")); } else { if(LocationGet_Method.getLocation(player, "lobby") != null) { player.teleport(LocationGet_Method.getLocation(player, "lobby")); } } } else { } } }
UTF-8
Java
1,365
java
PlayerJoinListener.java
Java
[]
null
[]
package at.s110103.skywars.listener; import at.s110103.skywars.methods.locations.LocationGet_Method; import at.s110103.skywars.status.GameStatus; import at.s110103.skywars.utilities.Utils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; public class PlayerJoinListener implements Listener { @EventHandler public void onJoin(PlayerJoinEvent e) { Player player = e.getPlayer(); e.setJoinMessage(null); if(Utils.getGameStatus() == GameStatus.LOBBY) { Bukkit.broadcastMessage("§8» §a" + player.getName() + " §7hat das Spiel betreten"); if(LocationGet_Method.getLocation(player, "lobby") != null) { player.teleport(LocationGet_Method.getLocation(player, "lobby")); } } else if(Utils.getGameStatus() == GameStatus.RESTART) { if(LocationGet_Method.getLocation(player, "restart") != null) { player.teleport(LocationGet_Method.getLocation(player, "restart")); } else { if(LocationGet_Method.getLocation(player, "lobby") != null) { player.teleport(LocationGet_Method.getLocation(player, "lobby")); } } } else { } } }
1,365
0.646583
0.62748
38
34.815788
28.867077
95
false
false
0
0
0
0
0
0
0.552632
false
false
12
5427babf08454177496c4a569a9180363f517c57
23,733,989,329,051
52a53a6e1d5276e6c4b1b24c66d806d7f71ab4a3
/Assignment 2/HandIn/ReadFile.java
19aef71f4aad5ad519f6dbac94cd1a9c55ea349f
[]
no_license
yid164/Introduction-to-Artificial-Intelligence
https://github.com/yid164/Introduction-to-Artificial-Intelligence
a962d2e5a8cac0d057f1a720794fbd8e04e371ab
7ce791a4cddc4b59cffbb1ae890a2230dd2dad6f
refs/heads/master
2020-06-26T08:10:08.511000
2019-07-30T05:30:20
2019-07-30T05:30:20
199,580,144
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class ReadFile { //ArrayList<Problem> problems; public static ArrayList<Problem> readProblemFile(String dir) { ArrayList<Double> given_list = null; double target = 0; ArrayList<Problem> problems = new ArrayList<>(); File file = new File(dir); Scanner scanner = null; try{ scanner = new Scanner(file); while(scanner.hasNext()) { given_list = new ArrayList<>(); String words [] = scanner.nextLine().split(" "); target = Double.parseDouble(words[0]); for ( int i = 1; i< words.length; i++) { given_list.add(Double.parseDouble(words[i])); } problems.add(new Problem(target, given_list)); } }catch (FileNotFoundException fe) { System.out.println(fe.fillInStackTrace()); } return problems; } }
UTF-8
Java
1,104
java
ReadFile.java
Java
[]
null
[]
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class ReadFile { //ArrayList<Problem> problems; public static ArrayList<Problem> readProblemFile(String dir) { ArrayList<Double> given_list = null; double target = 0; ArrayList<Problem> problems = new ArrayList<>(); File file = new File(dir); Scanner scanner = null; try{ scanner = new Scanner(file); while(scanner.hasNext()) { given_list = new ArrayList<>(); String words [] = scanner.nextLine().split(" "); target = Double.parseDouble(words[0]); for ( int i = 1; i< words.length; i++) { given_list.add(Double.parseDouble(words[i])); } problems.add(new Problem(target, given_list)); } }catch (FileNotFoundException fe) { System.out.println(fe.fillInStackTrace()); } return problems; } }
1,104
0.537138
0.53442
41
25.926828
21.38884
65
false
false
0
0
0
0
0
0
0.512195
false
false
12
688ae52dd7eedc78baf73f9428a157ab27d703de
33,449,205,341,105
201b14aa1ab118ecc6b04e9e70d64bb5ca898d2e
/blog-common/src/main/java/com/whl/blog/web/common/DESedeUtil.java
8541b0b97c8ba1febca165455d95eecc924da1b2
[]
no_license
whling/blog
https://github.com/whling/blog
819bded9dce5ce385ca12f7a19457e7ca15a7183
4b1fbd75e575ddd2234a5211f31144955c54ddfc
refs/heads/master
2020-03-11T07:00:12.790000
2018-04-20T00:56:57
2018-04-20T00:57:06
129,846,173
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.whl.blog.web.common; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; /** * Created by whling on 2017/6/29. */ public class DESedeUtil { public static String desEnCode(String srcStr) { try { Key localKey = jdMethod_super("cputest".getBytes()); Cipher localCipher = Cipher.getInstance("DES"); localCipher.init(1, localKey); return byteArr2HexStr(localCipher.doFinal(srcStr.getBytes())); } catch (InvalidKeyException localInvalidKeyException) { localInvalidKeyException.printStackTrace(); } catch (NoSuchAlgorithmException localNoSuchAlgorithmException) { localNoSuchAlgorithmException.printStackTrace(); } catch (NoSuchPaddingException localNoSuchPaddingException) { localNoSuchPaddingException.printStackTrace(); } catch (Exception localException) { localException.printStackTrace(); } return "0"; } public static String desDeCode(String desStr) { try { Key localKey = jdMethod_super("cputest".getBytes()); Cipher localCipher = Cipher.getInstance("DES"); localCipher.init(2, localKey); return new String(localCipher.doFinal(hexStr2ByteArr(desStr))); } catch (InvalidKeyException localInvalidKeyException) { localInvalidKeyException.printStackTrace(); } catch (NoSuchAlgorithmException localNoSuchAlgorithmException) { localNoSuchAlgorithmException.printStackTrace(); } catch (NoSuchPaddingException localNoSuchPaddingException) { localNoSuchPaddingException.printStackTrace(); } catch (Exception localException) { localException.printStackTrace(); } return "0"; } private static Key jdMethod_super(byte[] paramArrayOfByte) throws Exception { byte[] arrayOfByte = new byte[8]; for (int i = 0; (i < paramArrayOfByte.length) && (i < arrayOfByte.length); i++) { arrayOfByte[i] = paramArrayOfByte[i]; } SecretKeySpec localSecretKeySpec = new SecretKeySpec(arrayOfByte, "DES"); return localSecretKeySpec; } public static String byteArr2HexStr(byte[] paramArrayOfByte) throws Exception { int i = paramArrayOfByte.length; StringBuffer localStringBuffer = new StringBuffer(i * 2); for (int j = 0; j < i; j++) { int k = paramArrayOfByte[j]; while (k < 0) { k += 256; } if (k < 16) { localStringBuffer.append("0"); } localStringBuffer.append(Integer.toString(k, 16)); } return localStringBuffer.toString(); } public static byte[] hexStr2ByteArr(String paramString) throws Exception { byte[] arrayOfByte1 = paramString.getBytes(); int i = arrayOfByte1.length; byte[] arrayOfByte2 = new byte[i / 2]; for (int j = 0; j < i; j += 2) { String str = new String(arrayOfByte1, j, 2); arrayOfByte2[(j / 2)] = ((byte) Integer.parseInt(str, 16)); } return arrayOfByte2; } }
UTF-8
Java
3,373
java
DESedeUtil.java
Java
[ { "context": "urity.NoSuchAlgorithmException;\n\n/**\n * Created by whling on 2017/6/29.\n */\npublic class DESedeUtil {\n\n ", "end": 286, "score": 0.9995864629745483, "start": 280, "tag": "USERNAME", "value": "whling" } ]
null
[]
package com.whl.blog.web.common; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; /** * Created by whling on 2017/6/29. */ public class DESedeUtil { public static String desEnCode(String srcStr) { try { Key localKey = jdMethod_super("cputest".getBytes()); Cipher localCipher = Cipher.getInstance("DES"); localCipher.init(1, localKey); return byteArr2HexStr(localCipher.doFinal(srcStr.getBytes())); } catch (InvalidKeyException localInvalidKeyException) { localInvalidKeyException.printStackTrace(); } catch (NoSuchAlgorithmException localNoSuchAlgorithmException) { localNoSuchAlgorithmException.printStackTrace(); } catch (NoSuchPaddingException localNoSuchPaddingException) { localNoSuchPaddingException.printStackTrace(); } catch (Exception localException) { localException.printStackTrace(); } return "0"; } public static String desDeCode(String desStr) { try { Key localKey = jdMethod_super("cputest".getBytes()); Cipher localCipher = Cipher.getInstance("DES"); localCipher.init(2, localKey); return new String(localCipher.doFinal(hexStr2ByteArr(desStr))); } catch (InvalidKeyException localInvalidKeyException) { localInvalidKeyException.printStackTrace(); } catch (NoSuchAlgorithmException localNoSuchAlgorithmException) { localNoSuchAlgorithmException.printStackTrace(); } catch (NoSuchPaddingException localNoSuchPaddingException) { localNoSuchPaddingException.printStackTrace(); } catch (Exception localException) { localException.printStackTrace(); } return "0"; } private static Key jdMethod_super(byte[] paramArrayOfByte) throws Exception { byte[] arrayOfByte = new byte[8]; for (int i = 0; (i < paramArrayOfByte.length) && (i < arrayOfByte.length); i++) { arrayOfByte[i] = paramArrayOfByte[i]; } SecretKeySpec localSecretKeySpec = new SecretKeySpec(arrayOfByte, "DES"); return localSecretKeySpec; } public static String byteArr2HexStr(byte[] paramArrayOfByte) throws Exception { int i = paramArrayOfByte.length; StringBuffer localStringBuffer = new StringBuffer(i * 2); for (int j = 0; j < i; j++) { int k = paramArrayOfByte[j]; while (k < 0) { k += 256; } if (k < 16) { localStringBuffer.append("0"); } localStringBuffer.append(Integer.toString(k, 16)); } return localStringBuffer.toString(); } public static byte[] hexStr2ByteArr(String paramString) throws Exception { byte[] arrayOfByte1 = paramString.getBytes(); int i = arrayOfByte1.length; byte[] arrayOfByte2 = new byte[i / 2]; for (int j = 0; j < i; j += 2) { String str = new String(arrayOfByte1, j, 2); arrayOfByte2[(j / 2)] = ((byte) Integer.parseInt(str, 16)); } return arrayOfByte2; } }
3,373
0.632078
0.619923
96
34.135418
26.603813
89
false
false
0
0
0
0
0
0
0.572917
false
false
12
6fc16c443efec99d99ea6e230379f8b1a5c27959
19,301,583,066,308
ff3482ef4644009e1415663e0d03c89361eed7ce
/src/ddmp/projecttetra/Utilities.java
b683304f7d6cf2891cc02ef20c2257834dd88b22
[]
no_license
dset/Tetra
https://github.com/dset/Tetra
41cdf263b051032063a05082b9ccc6d2989f4ac4
9fe1ddf5839d1bbb7cfcd1bc1c31c5b9c4d29aa2
refs/heads/master
2021-01-20T10:09:09.825000
2012-05-10T00:15:58
2012-05-10T00:15:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ddmp.projecttetra; import com.badlogic.gdx.math.Vector2; /** * Holds utility methods. */ public class Utilities { /** * Returns a random float f, such that low <= f < high. */ public static float getRandomFloatBetween(float low, float high) { if(high < low) { throw new IllegalArgumentException("high < low"); } return (float) (low + (high - low) * Math.random()); } /** * Returns a random int i, such that low <= i <= high. */ public static int getRandomIntBetween(int low, int high) { if(high < low) { throw new IllegalArgumentException("high < low"); } return (int) (low + (high + 1 - low) * Math.random()); } /** * Rotates the given vector by angle radians. */ public static void rotateVector(Vector2 vector, float angle) { if(vector == null) { throw new IllegalArgumentException("vector == null"); } float x = (float) (vector.x * Math.cos(angle) - vector.y * Math.sin(angle)); float y = (float) (vector.x * Math.sin(angle) + vector.y * Math.cos(angle)); vector.set(x, y); } }
UTF-8
Java
1,056
java
Utilities.java
Java
[]
null
[]
package ddmp.projecttetra; import com.badlogic.gdx.math.Vector2; /** * Holds utility methods. */ public class Utilities { /** * Returns a random float f, such that low <= f < high. */ public static float getRandomFloatBetween(float low, float high) { if(high < low) { throw new IllegalArgumentException("high < low"); } return (float) (low + (high - low) * Math.random()); } /** * Returns a random int i, such that low <= i <= high. */ public static int getRandomIntBetween(int low, int high) { if(high < low) { throw new IllegalArgumentException("high < low"); } return (int) (low + (high + 1 - low) * Math.random()); } /** * Rotates the given vector by angle radians. */ public static void rotateVector(Vector2 vector, float angle) { if(vector == null) { throw new IllegalArgumentException("vector == null"); } float x = (float) (vector.x * Math.cos(angle) - vector.y * Math.sin(angle)); float y = (float) (vector.x * Math.sin(angle) + vector.y * Math.cos(angle)); vector.set(x, y); } }
1,056
0.635417
0.632576
43
23.55814
25.525457
78
false
false
0
0
0
0
0
0
1.581395
false
false
13
02f5088bd57406e5fcccf67146c5802a2596ce9e
14,937,896,255,502
9ffbcf3069e2eff72d3dacd208799a839d6ec9d1
/src/com/mpnet/bitswarm/io/protocols/MPIoHandler.java
168519f599e527d6adf37a7bcd6e0b80c32e7a3b
[]
no_license
mengtest/MPNetServer
https://github.com/mengtest/MPNetServer
63bdb577e14eeb0d80992a4d5d5e89126201ec9a
5ef2e826eb838d4f658bf7f620ab586e92311c0a
refs/heads/master
2020-11-23T20:36:05.308000
2015-03-24T07:16:05
2015-03-24T07:16:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mpnet.bitswarm.io.protocols; import com.mpnet.MPNetServer; import com.mpnet.bitswarm.data.IPacket; import com.mpnet.bitswarm.data.Packet; import com.mpnet.bitswarm.data.TransportType; import com.mpnet.bitswarm.io.AbstractIOHandler; import com.mpnet.bitswarm.io.IProtocolCodec; import com.mpnet.bitswarm.sessions.ISession; import com.mpnet.bitswarm.sessions.Session; import com.mpnet.common.data.IMPObject; import com.mpnet.common.data.MPObject; import com.mpnet.config.DefaultConstants; import com.mpnet.entities.User; import com.mpnet.exceptions.ExceptionMessageComposer; import com.mpnet.exceptions.MPCodecException; import java.net.SocketAddress; import java.nio.channels.DatagramChannel; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @ClassName: MPIoHandler * @Description: TODO(这里用一句话描述这个类的作用) * @author daixiwei daixiwei15@126.com * @date 2015年3月18日 上午11:47:53 * */ public class MPIoHandler extends AbstractIOHandler { private static final int UDP_PACKET_MIN_SIZE = 13; private static final String KEY_UDP_HANDSHAKE = "h"; private final BinaryIoHandler binHandler; private final Logger logger; private final MPNetServer mpnet; public MPIoHandler() { this.logger = LoggerFactory.getLogger(getClass()); this.mpnet = MPNetServer.getInstance(); this.binHandler = new BinaryIoHandler(this); setCodec(new MPProtocolCodec(this)); } public void onDataRead(ISession session, byte[] data) { if ((data == null) || (data.length < 1)) { throw new IllegalArgumentException("Unexpected null or empty byte array!"); } ProtocolType sessionProtocol = (ProtocolType) session.getSystemProperty(Session.PROTOCOL); if (sessionProtocol == null) { if (data[0] == 60) { return; } session.setSystemProperty(Session.PROTOCOL, ProtocolType.BINARY); session.setSystemProperty(Session.PACKET_READ_STATE, PacketReadState.WAIT_NEW_PACKET); } this.binHandler.handleRead(session, data); } public void setCodec(IProtocolCodec codec) { super.setCodec(codec); this.binHandler.setProtocolCodec(codec); } public long getReadPackets() { return this.binHandler.getReadPackets(); } public long getIncomingDroppedPackets() { return this.binHandler.getIncomingDroppedPackets(); } public void onDataRead(DatagramChannel channel, SocketAddress address, byte[] data) { String senderIP = null; int senderPort = 0; try { if (data.length < 4) { throw new MPCodecException("Packet too small: " + data.length + " bytes"); } PacketHeader packetHeader = decodeFirstHeaderByte(data[0]); int msb = data[1] & 0xFF; int lsb = data[2] & 0xFF; int dataSize = msb * 256 + lsb; if (dataSize < UDP_PACKET_MIN_SIZE) { throw new MPCodecException("Packet data too small: " + data.length + " bytes"); } String[] adrData = address.toString().split("\\:"); senderIP = adrData[0].substring(1); senderPort = Integer.parseInt(adrData[1]); byte[] mpObjData = new byte[data.length - 3]; System.arraycopy(data, 3, mpObjData, 0, mpObjData.length); if (mpObjData.length != dataSize) { throw new MPCodecException("Packet truncated. Expected: " + dataSize + ", only got: " + mpObjData.length); } if (packetHeader.isCompressed()) { try { mpObjData = binHandler.getPacketCompressor().uncompress(mpObjData); } catch (Exception e) { throw new RuntimeException(e); } } IMPObject reqObj = MPObject.newFromBinaryData(mpObjData); ISession session = validateUDPRequest(senderIP, senderPort, reqObj); if (reqObj.containsKey(KEY_UDP_HANDSHAKE)) { if (logger.isDebugEnabled()) { logger.debug("UDP Handshake OK: " + session); } if (session.getDatagramChannel() == null) { session.setDatagrmChannel(channel); sendUDPHandshakeResponse(session); } else { logger.warn("Client already UDP inited: " + session.toString()); } return; } IPacket newPacket = new Packet(); newPacket.setData(reqObj); newPacket.setSender(session); newPacket.setOriginalSize(dataSize); newPacket.setTransportType(TransportType.UDP); newPacket.setAttribute("type", ProtocolType.BINARY); this.codec.onPacketRead(newPacket); } catch (RuntimeException err) { this.logger.warn("Problems decoding UDP packet from: " + senderIP + ":" + senderPort + ", " + err); err.printStackTrace(); } catch (MPCodecException codecErr) { this.logger.warn(String.format("Discard UDP packet from %s:%s, reason: %s ", new Object[] { senderIP, Integer.valueOf(senderPort), codecErr.getMessage() })); } } private ISession validateUDPRequest(String senderIP, int senderPort, IMPObject packet) throws MPCodecException { if (!packet.containsKey("c")) { throw new MPCodecException("Missing controllerId"); } if (!packet.containsKey("u")) { throw new MPCodecException("Missing userId"); } if (!packet.containsKey("i")) { throw new MPCodecException("Missing packet id"); } int userId = packet.getInt("u").intValue(); User sender = this.mpnet.getUserManager().getUserById(userId); if (sender == null) { throw new MPCodecException("User does not exist, id: " + userId); } ISession session = sender.getSession(); if (!session.getAddress().equals(senderIP)) { throw new MPCodecException(String.format("Sender IP doesn't match TCP session address: %s != %s", senderIP, session.getAddress())); } Integer sessionUdpPort = (Integer) session.getSystemProperty(DefaultConstants.USP_UDP_PORT); if (sessionUdpPort == null) { session.setSystemProperty(DefaultConstants.USP_UDP_PORT, Integer.valueOf(senderPort)); } else if (senderPort != sessionUdpPort.intValue()) { throw new MPCodecException(String.format("Sender UDP Port doesn't match current session linkPort: %s != %s", senderPort, sessionUdpPort)); } return sender.getSession(); } public void onDataWrite(IPacket packet) { if (packet.getRecipients().size() > 0) { try { this.binHandler.handleWrite(packet); } catch (Exception e) { ExceptionMessageComposer composer = new ExceptionMessageComposer(e); this.logger.warn(composer.toString()); } } } public PacketHeader decodeFirstHeaderByte(byte headerByte) { return new PacketHeader((headerByte & 0x80) > 0, (headerByte & 0x40) > 0, (headerByte & 0x20) > 0, (headerByte & 0x10) > 0, (headerByte & 0x8) > 0); } public byte encodeFirstHeaderByte(PacketHeader packetHeader) { byte headerByte = 0; if (packetHeader.isBinary()) { headerByte = (byte) (headerByte + 128); } if (packetHeader.isEncrypted()) { headerByte = (byte) (headerByte + 64); } if (packetHeader.isCompressed()) { headerByte = (byte) (headerByte + 32); } if (packetHeader.isBlueBoxed()) { headerByte = (byte) (headerByte + 16); } if (packetHeader.isBigSized()) { headerByte = (byte) (headerByte + 8); } return headerByte; } private void sendUDPHandshakeResponse(ISession recipient) { IMPObject responseObj = new MPObject(); responseObj.putByte("c", (byte) 1); responseObj.putByte(KEY_UDP_HANDSHAKE, (byte) 1); responseObj.putShort("a", (byte) 0); IPacket udpResponsePacket = new Packet(); udpResponsePacket.setTransportType(TransportType.UDP); udpResponsePacket.setRecipients(Arrays.asList(recipient)); udpResponsePacket.setData(responseObj); onDataWrite(udpResponsePacket); } }
UTF-8
Java
7,512
java
MPIoHandler.java
Java
[ { "context": "\n * @Description: TODO(这里用一句话描述这个类的作用) \n * @author daixiwei daixiwei15@126.com\n * @date 2015年3月18日 上午11:47:53", "end": 882, "score": 0.9913724064826965, "start": 874, "tag": "USERNAME", "value": "daixiwei" }, { "context": "ription: TODO(这里用一句话描述这个类的作用) \n * @author daixiwei daixiwei15@126.com\n * @date 2015年3月18日 上午11:47:53 \n *\n */\npublic cla", "end": 901, "score": 0.9998950362205505, "start": 883, "tag": "EMAIL", "value": "daixiwei15@126.com" } ]
null
[]
package com.mpnet.bitswarm.io.protocols; import com.mpnet.MPNetServer; import com.mpnet.bitswarm.data.IPacket; import com.mpnet.bitswarm.data.Packet; import com.mpnet.bitswarm.data.TransportType; import com.mpnet.bitswarm.io.AbstractIOHandler; import com.mpnet.bitswarm.io.IProtocolCodec; import com.mpnet.bitswarm.sessions.ISession; import com.mpnet.bitswarm.sessions.Session; import com.mpnet.common.data.IMPObject; import com.mpnet.common.data.MPObject; import com.mpnet.config.DefaultConstants; import com.mpnet.entities.User; import com.mpnet.exceptions.ExceptionMessageComposer; import com.mpnet.exceptions.MPCodecException; import java.net.SocketAddress; import java.nio.channels.DatagramChannel; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @ClassName: MPIoHandler * @Description: TODO(这里用一句话描述这个类的作用) * @author daixiwei <EMAIL> * @date 2015年3月18日 上午11:47:53 * */ public class MPIoHandler extends AbstractIOHandler { private static final int UDP_PACKET_MIN_SIZE = 13; private static final String KEY_UDP_HANDSHAKE = "h"; private final BinaryIoHandler binHandler; private final Logger logger; private final MPNetServer mpnet; public MPIoHandler() { this.logger = LoggerFactory.getLogger(getClass()); this.mpnet = MPNetServer.getInstance(); this.binHandler = new BinaryIoHandler(this); setCodec(new MPProtocolCodec(this)); } public void onDataRead(ISession session, byte[] data) { if ((data == null) || (data.length < 1)) { throw new IllegalArgumentException("Unexpected null or empty byte array!"); } ProtocolType sessionProtocol = (ProtocolType) session.getSystemProperty(Session.PROTOCOL); if (sessionProtocol == null) { if (data[0] == 60) { return; } session.setSystemProperty(Session.PROTOCOL, ProtocolType.BINARY); session.setSystemProperty(Session.PACKET_READ_STATE, PacketReadState.WAIT_NEW_PACKET); } this.binHandler.handleRead(session, data); } public void setCodec(IProtocolCodec codec) { super.setCodec(codec); this.binHandler.setProtocolCodec(codec); } public long getReadPackets() { return this.binHandler.getReadPackets(); } public long getIncomingDroppedPackets() { return this.binHandler.getIncomingDroppedPackets(); } public void onDataRead(DatagramChannel channel, SocketAddress address, byte[] data) { String senderIP = null; int senderPort = 0; try { if (data.length < 4) { throw new MPCodecException("Packet too small: " + data.length + " bytes"); } PacketHeader packetHeader = decodeFirstHeaderByte(data[0]); int msb = data[1] & 0xFF; int lsb = data[2] & 0xFF; int dataSize = msb * 256 + lsb; if (dataSize < UDP_PACKET_MIN_SIZE) { throw new MPCodecException("Packet data too small: " + data.length + " bytes"); } String[] adrData = address.toString().split("\\:"); senderIP = adrData[0].substring(1); senderPort = Integer.parseInt(adrData[1]); byte[] mpObjData = new byte[data.length - 3]; System.arraycopy(data, 3, mpObjData, 0, mpObjData.length); if (mpObjData.length != dataSize) { throw new MPCodecException("Packet truncated. Expected: " + dataSize + ", only got: " + mpObjData.length); } if (packetHeader.isCompressed()) { try { mpObjData = binHandler.getPacketCompressor().uncompress(mpObjData); } catch (Exception e) { throw new RuntimeException(e); } } IMPObject reqObj = MPObject.newFromBinaryData(mpObjData); ISession session = validateUDPRequest(senderIP, senderPort, reqObj); if (reqObj.containsKey(KEY_UDP_HANDSHAKE)) { if (logger.isDebugEnabled()) { logger.debug("UDP Handshake OK: " + session); } if (session.getDatagramChannel() == null) { session.setDatagrmChannel(channel); sendUDPHandshakeResponse(session); } else { logger.warn("Client already UDP inited: " + session.toString()); } return; } IPacket newPacket = new Packet(); newPacket.setData(reqObj); newPacket.setSender(session); newPacket.setOriginalSize(dataSize); newPacket.setTransportType(TransportType.UDP); newPacket.setAttribute("type", ProtocolType.BINARY); this.codec.onPacketRead(newPacket); } catch (RuntimeException err) { this.logger.warn("Problems decoding UDP packet from: " + senderIP + ":" + senderPort + ", " + err); err.printStackTrace(); } catch (MPCodecException codecErr) { this.logger.warn(String.format("Discard UDP packet from %s:%s, reason: %s ", new Object[] { senderIP, Integer.valueOf(senderPort), codecErr.getMessage() })); } } private ISession validateUDPRequest(String senderIP, int senderPort, IMPObject packet) throws MPCodecException { if (!packet.containsKey("c")) { throw new MPCodecException("Missing controllerId"); } if (!packet.containsKey("u")) { throw new MPCodecException("Missing userId"); } if (!packet.containsKey("i")) { throw new MPCodecException("Missing packet id"); } int userId = packet.getInt("u").intValue(); User sender = this.mpnet.getUserManager().getUserById(userId); if (sender == null) { throw new MPCodecException("User does not exist, id: " + userId); } ISession session = sender.getSession(); if (!session.getAddress().equals(senderIP)) { throw new MPCodecException(String.format("Sender IP doesn't match TCP session address: %s != %s", senderIP, session.getAddress())); } Integer sessionUdpPort = (Integer) session.getSystemProperty(DefaultConstants.USP_UDP_PORT); if (sessionUdpPort == null) { session.setSystemProperty(DefaultConstants.USP_UDP_PORT, Integer.valueOf(senderPort)); } else if (senderPort != sessionUdpPort.intValue()) { throw new MPCodecException(String.format("Sender UDP Port doesn't match current session linkPort: %s != %s", senderPort, sessionUdpPort)); } return sender.getSession(); } public void onDataWrite(IPacket packet) { if (packet.getRecipients().size() > 0) { try { this.binHandler.handleWrite(packet); } catch (Exception e) { ExceptionMessageComposer composer = new ExceptionMessageComposer(e); this.logger.warn(composer.toString()); } } } public PacketHeader decodeFirstHeaderByte(byte headerByte) { return new PacketHeader((headerByte & 0x80) > 0, (headerByte & 0x40) > 0, (headerByte & 0x20) > 0, (headerByte & 0x10) > 0, (headerByte & 0x8) > 0); } public byte encodeFirstHeaderByte(PacketHeader packetHeader) { byte headerByte = 0; if (packetHeader.isBinary()) { headerByte = (byte) (headerByte + 128); } if (packetHeader.isEncrypted()) { headerByte = (byte) (headerByte + 64); } if (packetHeader.isCompressed()) { headerByte = (byte) (headerByte + 32); } if (packetHeader.isBlueBoxed()) { headerByte = (byte) (headerByte + 16); } if (packetHeader.isBigSized()) { headerByte = (byte) (headerByte + 8); } return headerByte; } private void sendUDPHandshakeResponse(ISession recipient) { IMPObject responseObj = new MPObject(); responseObj.putByte("c", (byte) 1); responseObj.putByte(KEY_UDP_HANDSHAKE, (byte) 1); responseObj.putShort("a", (byte) 0); IPacket udpResponsePacket = new Packet(); udpResponsePacket.setTransportType(TransportType.UDP); udpResponsePacket.setRecipients(Arrays.asList(recipient)); udpResponsePacket.setData(responseObj); onDataWrite(udpResponsePacket); } }
7,501
0.708456
0.698287
232
31.219828
28.323545
160
false
false
0
0
0
0
0
0
2.719828
false
false
13
759259ac05d497b5545da372520bf13537200610
31,318,901,566,256
080173631a570e7d032a1d500c54d21df6356a5a
/FBPM/CRM/fcs-crm-facade-wsp/src/main/java/com/born/fcs/crm/ws/service/order/DistributionOrder.java
e76fc23f6f7be33ec7f727bf2d97a0c79ae725ee
[]
no_license
cckmit/fcs
https://github.com/cckmit/fcs
d3d577284859b517f3ecc0519b25e2a8add64ca2
6ea55733a4aeade931149ee02bc9d3867301d047
refs/heads/master
2022-04-28T12:09:00.393000
2018-02-08T03:55:32
2018-02-08T03:55:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.born.fcs.crm.ws.service.order; import com.born.fcs.pm.ws.order.base.ValidateOrderBase; /** * 客户移交分配 * */ public class DistributionOrder extends ValidateOrderBase { private static final long serialVersionUID = -9094343097754419322L; /** 用户Id */ private long userId; /** 客户经理ID */ private long customerManagerId; /** 客户经理 */ private String customerManager; /** 业务总监ID */ private long directorId; /** 业务总监 */ private String director; /** 部门Id */ private long depId; /** 部门名 */ private String depName; /** 全部门 */ private String depPath; @Override public void check() { validateHasZore(userId, "用户Id不能为空"); } public long getUserId() { return this.userId; } public void setUserId(long userId) { this.userId = userId; } public String getCustomerManager() { return this.customerManager; } public void setCustomerManager(String customerManager) { this.customerManager = customerManager; } public String getDirector() { return this.director; } public void setDirector(String director) { this.director = director; } public long getCustomerManagerId() { return this.customerManagerId; } public void setCustomerManagerId(long customerManagerId) { this.customerManagerId = customerManagerId; } public long getDirectorId() { return this.directorId; } public void setDirectorId(long directorId) { this.directorId = directorId; } public long getDepId() { return this.depId; } public void setDepId(long depId) { this.depId = depId; } public String getDepName() { return this.depName; } public void setDepName(String depName) { this.depName = depName; } public String getDepPath() { return this.depPath; } public void setDepPath(String depPath) { this.depPath = depPath; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("DistributionOrder [userId="); builder.append(userId); builder.append(", customerManagerId="); builder.append(customerManagerId); builder.append(", customerManager="); builder.append(customerManager); builder.append(", directorId="); builder.append(directorId); builder.append(", director="); builder.append(director); builder.append(", depId="); builder.append(depId); builder.append(", depName="); builder.append(depName); builder.append(", depPath="); builder.append(depPath); builder.append("]"); return builder.toString(); } }
UTF-8
Java
2,544
java
DistributionOrder.java
Java
[]
null
[]
package com.born.fcs.crm.ws.service.order; import com.born.fcs.pm.ws.order.base.ValidateOrderBase; /** * 客户移交分配 * */ public class DistributionOrder extends ValidateOrderBase { private static final long serialVersionUID = -9094343097754419322L; /** 用户Id */ private long userId; /** 客户经理ID */ private long customerManagerId; /** 客户经理 */ private String customerManager; /** 业务总监ID */ private long directorId; /** 业务总监 */ private String director; /** 部门Id */ private long depId; /** 部门名 */ private String depName; /** 全部门 */ private String depPath; @Override public void check() { validateHasZore(userId, "用户Id不能为空"); } public long getUserId() { return this.userId; } public void setUserId(long userId) { this.userId = userId; } public String getCustomerManager() { return this.customerManager; } public void setCustomerManager(String customerManager) { this.customerManager = customerManager; } public String getDirector() { return this.director; } public void setDirector(String director) { this.director = director; } public long getCustomerManagerId() { return this.customerManagerId; } public void setCustomerManagerId(long customerManagerId) { this.customerManagerId = customerManagerId; } public long getDirectorId() { return this.directorId; } public void setDirectorId(long directorId) { this.directorId = directorId; } public long getDepId() { return this.depId; } public void setDepId(long depId) { this.depId = depId; } public String getDepName() { return this.depName; } public void setDepName(String depName) { this.depName = depName; } public String getDepPath() { return this.depPath; } public void setDepPath(String depPath) { this.depPath = depPath; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("DistributionOrder [userId="); builder.append(userId); builder.append(", customerManagerId="); builder.append(customerManagerId); builder.append(", customerManager="); builder.append(customerManager); builder.append(", directorId="); builder.append(directorId); builder.append(", director="); builder.append(director); builder.append(", depId="); builder.append(depId); builder.append(", depName="); builder.append(depName); builder.append(", depPath="); builder.append(depPath); builder.append("]"); return builder.toString(); } }
2,544
0.706645
0.698947
121
19.396694
16.69289
68
false
false
0
0
0
0
0
0
1.677686
false
false
13
b614c51cd613342a39c15adc8a307185652cf02f
23,716,809,444,056
13598b530a21952959b51ecebce81310995b1dcc
/1.P/Curs 1/Magazin.java
ddb8588fb160c2b7298762ef14cf4c1fc4a0ef9f
[]
no_license
kashann/java-telacad
https://github.com/kashann/java-telacad
04c9c0258e7d872bb34aebaee97ee99c0ead2475
250fe71d2c00ac30af51bf270a845fd85c24c650
refs/heads/master
2020-07-14T18:46:24.503000
2019-08-30T13:37:23
2019-08-30T13:37:23
205,376,727
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; import java.io.*; public class Magazin{ private static Magazin SINGLETON; private List<Produs> produse = new ArrayList<>(); private Magazin(){ } public static Magazin getInstance(){ if(SINGLETON == null){ SINGLETON = new Magazin(); } return SINGLETON; } public void adaugaProdus(Produs p){ this.produse.add(p); } public void afisareProduse(){ //for(Produs p:produse){ // System.out.println(p); //} ////produse.forEach(p -> System.out.println(p)); produse.forEach(System.out::println); } public void salvareProduse(String fis){ try(PrintStream out = new PrintStream(fis)){ produse.forEach(out::println); }catch(FileNotFoundException e){ e.printStackTrace(); } } public void citireProduse(String fisier){ try( FileInputStream fis = new FileInputStream(fisier); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); ){ String line; while((line = br.readLine()) != null){ String [] v = line.split("\\s+"); String nume = v[0]; double pret = Double.parseDouble(v[1]); Produs p = new Produs(nume, pret); produse.add(p); } }catch(Exception e){ e.printStackTrace(); } } }
UTF-8
Java
1,547
java
Magazin.java
Java
[]
null
[]
import java.util.*; import java.io.*; public class Magazin{ private static Magazin SINGLETON; private List<Produs> produse = new ArrayList<>(); private Magazin(){ } public static Magazin getInstance(){ if(SINGLETON == null){ SINGLETON = new Magazin(); } return SINGLETON; } public void adaugaProdus(Produs p){ this.produse.add(p); } public void afisareProduse(){ //for(Produs p:produse){ // System.out.println(p); //} ////produse.forEach(p -> System.out.println(p)); produse.forEach(System.out::println); } public void salvareProduse(String fis){ try(PrintStream out = new PrintStream(fis)){ produse.forEach(out::println); }catch(FileNotFoundException e){ e.printStackTrace(); } } public void citireProduse(String fisier){ try( FileInputStream fis = new FileInputStream(fisier); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); ){ String line; while((line = br.readLine()) != null){ String [] v = line.split("\\s+"); String nume = v[0]; double pret = Double.parseDouble(v[1]); Produs p = new Produs(nume, pret); produse.add(p); } }catch(Exception e){ e.printStackTrace(); } } }
1,547
0.527473
0.52618
56
26.642857
18.626429
63
false
false
0
0
0
0
0
0
0.410714
false
false
13
cbfa96f56fd5bfe18ca093ddaee75cc19aace4d7
19,370,302,554,964
34bcf41c98b60da861b2d90c332a0a879815a6c2
/src/main/java/com/etermax/spacehorse/core/specialoffer/cheat/RemoveSpecialOfferCheat.java
4534dc34ceba8e0a3443bdce814d2d85fe6d7a1a
[]
no_license
damianciocca/horse-api
https://github.com/damianciocca/horse-api
af3c15ad749b81541cffa62f68824fe0df69b2f2
2f8df8a50081a2c2ad2dc57d15932776d93c3f2e
refs/heads/master
2020-03-19T21:22:45.733000
2018-06-11T14:32:13
2018-06-11T14:32:13
136,938,331
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.etermax.spacehorse.core.specialoffer.cheat; import com.etermax.spacehorse.core.catalog.model.Catalog; import com.etermax.spacehorse.core.cheat.model.Cheat; import com.etermax.spacehorse.core.cheat.resource.response.CheatResponse; import com.etermax.spacehorse.core.player.model.Player; import com.etermax.spacehorse.core.specialoffer.model.SpecialOfferBoard; import com.etermax.spacehorse.core.specialoffer.model.SpecialOfferBoardRepository; public class RemoveSpecialOfferCheat extends Cheat { private final SpecialOfferBoardRepository specialOfferBoardRepository; public RemoveSpecialOfferCheat(SpecialOfferBoardRepository specialOfferBoardRepository) { this.specialOfferBoardRepository = specialOfferBoardRepository; } @Override public String getCheatId() { return "removeSpecialOffer"; } @Override public CheatResponse apply(Player player, String[] parameters, Catalog catalog) { String specialOfferId = getParameterString(parameters, 0); SpecialOfferBoard specialOfferBoard = specialOfferBoardRepository.findOrDefaultBy(player); specialOfferBoard.cheatRemoveSpecialOffer(specialOfferId); specialOfferBoardRepository.addOrUpdate(player, specialOfferBoard); return new CheatResponse(specialOfferId); } }
UTF-8
Java
1,248
java
RemoveSpecialOfferCheat.java
Java
[]
null
[]
package com.etermax.spacehorse.core.specialoffer.cheat; import com.etermax.spacehorse.core.catalog.model.Catalog; import com.etermax.spacehorse.core.cheat.model.Cheat; import com.etermax.spacehorse.core.cheat.resource.response.CheatResponse; import com.etermax.spacehorse.core.player.model.Player; import com.etermax.spacehorse.core.specialoffer.model.SpecialOfferBoard; import com.etermax.spacehorse.core.specialoffer.model.SpecialOfferBoardRepository; public class RemoveSpecialOfferCheat extends Cheat { private final SpecialOfferBoardRepository specialOfferBoardRepository; public RemoveSpecialOfferCheat(SpecialOfferBoardRepository specialOfferBoardRepository) { this.specialOfferBoardRepository = specialOfferBoardRepository; } @Override public String getCheatId() { return "removeSpecialOffer"; } @Override public CheatResponse apply(Player player, String[] parameters, Catalog catalog) { String specialOfferId = getParameterString(parameters, 0); SpecialOfferBoard specialOfferBoard = specialOfferBoardRepository.findOrDefaultBy(player); specialOfferBoard.cheatRemoveSpecialOffer(specialOfferId); specialOfferBoardRepository.addOrUpdate(player, specialOfferBoard); return new CheatResponse(specialOfferId); } }
1,248
0.844551
0.84375
32
38.03125
32.635757
92
false
false
0
0
0
0
0
0
1.3125
false
false
13
029023f58c8e9338b64b517fdd56f18b913dbdf5
8,143,258,046,876
47d4ded02ab6c0f8bb2c6d4822e2a7876cf287e4
/src/main/java/components/ElectricMotor.java
3803513d4ddb756ca00f5650845c16d60774cb45
[]
no_license
fionaw237/composition-lab-CodeClanCars
https://github.com/fionaw237/composition-lab-CodeClanCars
09538b865ca509c0d8dbc944becb43d18107ab5f
44139fde693563a2455a1d72089ea901c4b2e850
refs/heads/master
2020-03-30T16:47:50.093000
2018-10-03T18:04:06
2018-10-03T18:04:06
151,427,364
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package components; import interfaces.CanPowerVehicle; public class ElectricMotor implements CanPowerVehicle{ private String voltage; private String power; public ElectricMotor(String voltage, String power){ this.voltage = voltage; this.power = power; } public String getVoltage() { return voltage; } public String getPower() { return power; } }
UTF-8
Java
416
java
ElectricMotor.java
Java
[]
null
[]
package components; import interfaces.CanPowerVehicle; public class ElectricMotor implements CanPowerVehicle{ private String voltage; private String power; public ElectricMotor(String voltage, String power){ this.voltage = voltage; this.power = power; } public String getVoltage() { return voltage; } public String getPower() { return power; } }
416
0.663462
0.663462
22
17.90909
17.077122
55
false
false
0
0
0
0
0
0
0.409091
false
false
13
b9d50d7729ac89b94d8428445a9865e75c16563a
27,977,417,007,869
9a15fc313d69e49a18d96aeae17fb5ff618b9026
/copyconst.java
4940a7139e15c31aadbfdea2c653a34310d739ce
[]
no_license
ravi-gohil/OOP
https://github.com/ravi-gohil/OOP
f50f6c3fe6ae39424e701571ba25dc00d0e9055e
71e987893ff1e0857de23017d175e07c01950af4
refs/heads/master
2021-01-11T17:37:03.225000
2017-01-23T12:56:26
2017-01-23T12:56:26
79,804,233
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class copyconst { int id; String name; copyconst(int i, String n) { id = i; name = n; } copyconst(copyconst c) { id = c.id; name = c.name; } void display() { System.out.println("Id is "+id+"and name is"+name); } public static void main (String args[]) { copyconst s1=new copyconst(23,"abc"), s2= new copyconst(s1); s1.display(); s2.display(); } }
UTF-8
Java
423
java
copyconst.java
Java
[]
null
[]
public class copyconst { int id; String name; copyconst(int i, String n) { id = i; name = n; } copyconst(copyconst c) { id = c.id; name = c.name; } void display() { System.out.println("Id is "+id+"and name is"+name); } public static void main (String args[]) { copyconst s1=new copyconst(23,"abc"), s2= new copyconst(s1); s1.display(); s2.display(); } }
423
0.553191
0.536643
28
13.035714
15.954136
64
false
false
0
0
0
0
0
0
1.714286
false
false
13
473d9ca7162565fadbd05415af118cdea77aa612
24,361,054,508,562
545509d26f6fee0840c095147b935fb2d7c85490
/src/layouts/TitleScreenLayout.java
4fdba5f07fb885754d44399547f26da4bdfe28e8
[]
no_license
mjemnawaz/stick-fight-game
https://github.com/mjemnawaz/stick-fight-game
8d20cc24205c2bb2cb2ef45133752cf8dba44992
ed9b6859a0a3488969136c7b2a6d3c35c1c5e04c
refs/heads/master
2023-02-19T00:56:10.718000
2021-01-22T23:23:59
2021-01-22T23:23:59
331,368,066
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package layouts; import constants.GlobalConstants; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class TitleScreenLayout { public static void display(Scene mainScene, String location) { double width = GlobalConstants.getWidth(); double height = GlobalConstants.getHeight(); Label label1= new Label("Stick Wars"); label1.setId("titleLabel"); label1.setPadding(new Insets(height/6.0, 0, height/12.0, 0)); Button signInButton = new Button("SIGN IN"); Button createAccountButton = new Button("CREATE ACCOUNT"); Button playAsGuestButton = new Button("PLAY AS GUEST"); Button viewLeaderBoardButton = new Button("VIEW LEADERBOARD"); signInButton.getStyleClass().add("titleScreenButton"); createAccountButton.getStyleClass().add("titleScreenButton"); playAsGuestButton.getStyleClass().add("titleScreenButton"); viewLeaderBoardButton.getStyleClass().add("titleScreenButton"); VBox layout1 = new VBox(10); layout1.getChildren().addAll(label1, signInButton, createAccountButton, playAsGuestButton, viewLeaderBoardButton); layout1.getStyleClass().add("titleScreens"); layout1.setAlignment(Pos.TOP_CENTER); layout1.setPrefWidth(width/3.5); signInButton.setMinWidth(layout1.getPrefWidth()); createAccountButton.setMinWidth(layout1.getPrefWidth()); playAsGuestButton.setMinWidth(layout1.getPrefWidth()); viewLeaderBoardButton.setMinWidth(layout1.getPrefWidth()); Stage primaryStage = GlobalConstants.getPrimaryStage(); signInButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { StackPane loginPage = LayoutCollection.getLoginLayout(layout1); primaryStage.getScene().setRoot(loginPage); } }); playAsGuestButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { StackPane lobby = LayoutCollection.getLobby(layout1); primaryStage.getScene().setRoot(lobby); } }); mainScene = new Scene(layout1, width, height); GlobalConstants.setMainScene(mainScene); mainScene.getStylesheets().add("https://fonts.googleapis.com/css?family=Inconsolata:bold"); mainScene.getStylesheets().add("https://fonts.googleapis.com/css?family=Inconsolata"); primaryStage.setScene(mainScene); mainScene.getStylesheets().add(location); primaryStage.show(); } }
UTF-8
Java
2,681
java
TitleScreenLayout.java
Java
[]
null
[]
package layouts; import constants.GlobalConstants; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class TitleScreenLayout { public static void display(Scene mainScene, String location) { double width = GlobalConstants.getWidth(); double height = GlobalConstants.getHeight(); Label label1= new Label("Stick Wars"); label1.setId("titleLabel"); label1.setPadding(new Insets(height/6.0, 0, height/12.0, 0)); Button signInButton = new Button("SIGN IN"); Button createAccountButton = new Button("CREATE ACCOUNT"); Button playAsGuestButton = new Button("PLAY AS GUEST"); Button viewLeaderBoardButton = new Button("VIEW LEADERBOARD"); signInButton.getStyleClass().add("titleScreenButton"); createAccountButton.getStyleClass().add("titleScreenButton"); playAsGuestButton.getStyleClass().add("titleScreenButton"); viewLeaderBoardButton.getStyleClass().add("titleScreenButton"); VBox layout1 = new VBox(10); layout1.getChildren().addAll(label1, signInButton, createAccountButton, playAsGuestButton, viewLeaderBoardButton); layout1.getStyleClass().add("titleScreens"); layout1.setAlignment(Pos.TOP_CENTER); layout1.setPrefWidth(width/3.5); signInButton.setMinWidth(layout1.getPrefWidth()); createAccountButton.setMinWidth(layout1.getPrefWidth()); playAsGuestButton.setMinWidth(layout1.getPrefWidth()); viewLeaderBoardButton.setMinWidth(layout1.getPrefWidth()); Stage primaryStage = GlobalConstants.getPrimaryStage(); signInButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { StackPane loginPage = LayoutCollection.getLoginLayout(layout1); primaryStage.getScene().setRoot(loginPage); } }); playAsGuestButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { StackPane lobby = LayoutCollection.getLobby(layout1); primaryStage.getScene().setRoot(lobby); } }); mainScene = new Scene(layout1, width, height); GlobalConstants.setMainScene(mainScene); mainScene.getStylesheets().add("https://fonts.googleapis.com/css?family=Inconsolata:bold"); mainScene.getStylesheets().add("https://fonts.googleapis.com/css?family=Inconsolata"); primaryStage.setScene(mainScene); mainScene.getStylesheets().add(location); primaryStage.show(); } }
2,681
0.761656
0.751585
77
33.81818
25.62199
116
false
false
0
0
0
0
0
0
2.506494
false
false
13
937e908e3ae0db4d6540482842a651152f28d3c0
28,673,201,711,909
b03cc2264c9da12fff7fbe6fdfb146b22e01d315
/hw7/src/main/java/com/av/services/ObjectFormatter.java
aa7b776b2df78642737b56d584d78f6bd85069d9
[]
no_license
drliho86/2021-02-otus-spring-vasiliev-alexey
https://github.com/drliho86/2021-02-otus-spring-vasiliev-alexey
3c49d34dad0e4b4489415e7ebdab667ab1de6c66
4bd50295f36dd958544c352cadc6b67a328b1777
refs/heads/master
2023-06-02T18:21:09.803000
2021-06-09T17:26:46
2021-06-09T17:26:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.av.services; import com.fasterxml.jackson.core.JsonProcessingException; public interface ObjectFormatter { String format(Object object) throws JsonProcessingException; }
UTF-8
Java
188
java
ObjectFormatter.java
Java
[]
null
[]
package com.av.services; import com.fasterxml.jackson.core.JsonProcessingException; public interface ObjectFormatter { String format(Object object) throws JsonProcessingException; }
188
0.824468
0.824468
7
25.857143
25.390823
64
false
false
0
0
0
0
0
0
0.428571
false
false
13
5893ecc67fd27ce0a0da68b1c8faa0f2c9d7358f
18,442,589,569,776
59a4e4643444ac5f0c5d1c222558e013303d7fce
/src/main/java/com/group/service/impl/BorrowbooksServiceImpl.java
c1f764ca79d8bd0ac929734ea4ec9a30fa92761c
[]
no_license
KnightAlduin/tushuguanlixitong
https://github.com/KnightAlduin/tushuguanlixitong
85352cef361ad8f9f95ce4d7522bb6bbc3e6aa2c
87caaa2e27aeba4bcf1f3d966133d81a8966d757
refs/heads/master
2023-03-15T16:20:51.922000
2020-08-06T00:45:29
2020-08-06T00:45:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.group.service.impl; import com.group.dao.BorrowbooksMapper; import com.group.pojo.Borrowbooks; import com.group.service.BorrowbooksService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class BorrowbooksServiceImpl implements BorrowbooksService { @Autowired BorrowbooksMapper dao; public int add(Borrowbooks borrowbooks) { return dao.insertSelective(borrowbooks); } public int select(Integer userid) { return dao.select(userid); } public Borrowbooks selectbyid(Integer bookid) { return dao.selectByid(bookid); } public List<Borrowbooks> selectByuserid(Integer userid) { return dao.selectBtuseid(userid); } public int updateBybookid(Borrowbooks borrowbooks) { return dao.updateByPrimaryKeySelective(borrowbooks); } public Borrowbooks selectByid(Integer bookid) { return dao.selectByPrimaryKey(bookid); } }
UTF-8
Java
1,033
java
BorrowbooksServiceImpl.java
Java
[]
null
[]
package com.group.service.impl; import com.group.dao.BorrowbooksMapper; import com.group.pojo.Borrowbooks; import com.group.service.BorrowbooksService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class BorrowbooksServiceImpl implements BorrowbooksService { @Autowired BorrowbooksMapper dao; public int add(Borrowbooks borrowbooks) { return dao.insertSelective(borrowbooks); } public int select(Integer userid) { return dao.select(userid); } public Borrowbooks selectbyid(Integer bookid) { return dao.selectByid(bookid); } public List<Borrowbooks> selectByuserid(Integer userid) { return dao.selectBtuseid(userid); } public int updateBybookid(Borrowbooks borrowbooks) { return dao.updateByPrimaryKeySelective(borrowbooks); } public Borrowbooks selectByid(Integer bookid) { return dao.selectByPrimaryKey(bookid); } }
1,033
0.738625
0.738625
39
25.487179
22.739182
67
false
false
0
0
0
0
0
0
0.358974
false
false
13
3514163461cf6e321aaec3070229110d00229388
21,938,692,968,453
5a5f355d6c34fddbff997233592bc6041af9eb38
/src/day09/LanguagePicker_SwitchStatement_Task4_Ayse.java
d97388b0f3ddf75a84538fb86be15527dae1c3fc
[]
no_license
AyseYB/JavaProgrammingB15Online
https://github.com/AyseYB/JavaProgrammingB15Online
19ea64bdd143c8fda4d1591400ea6e0f6d26e4b7
24f1eb09ab209c636122fcf5074e51d7bff7bbad
refs/heads/master
2021-01-16T15:13:26.852000
2020-02-26T04:22:15
2020-02-26T04:22:15
243,164,084
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package day09; public class LanguagePicker_SwitchStatement_Task4_Ayse { public static void main(String[] args) { System.out.println("Welcome to Cybertek Call Center"); System.out.println(" Please select your language option from 1- 7"); /* assume you are on the call and you have been given option to be * greeted by the language of your choice according to the number you provided. * 1--> " hellp" * 2--> " salam" * 3 --> " hola" * 4 --> "Privet" * 5 --> Merhaba" * 6--> Szia" * 7-- > bonjour" * the program should set the value of a string variable called greeting * to this valee 1--> " hello, SDET" */ int languageOption = 1; String greeting =""; switch (languageOption) { case 1: greeting = "Salam"; case 2 : greeting =" hello"; case 3 : greeting = " hola"; case 4: greeting= " Privet"; case 5: greeting = "MErhaba"; case 6: greeting= "Szia"; case 7: greeting= "Bonjour"; } } }
UTF-8
Java
1,323
java
LanguagePicker_SwitchStatement_Task4_Ayse.java
Java
[]
null
[]
package day09; public class LanguagePicker_SwitchStatement_Task4_Ayse { public static void main(String[] args) { System.out.println("Welcome to Cybertek Call Center"); System.out.println(" Please select your language option from 1- 7"); /* assume you are on the call and you have been given option to be * greeted by the language of your choice according to the number you provided. * 1--> " hellp" * 2--> " salam" * 3 --> " hola" * 4 --> "Privet" * 5 --> Merhaba" * 6--> Szia" * 7-- > bonjour" * the program should set the value of a string variable called greeting * to this valee 1--> " hello, SDET" */ int languageOption = 1; String greeting =""; switch (languageOption) { case 1: greeting = "Salam"; case 2 : greeting =" hello"; case 3 : greeting = " hola"; case 4: greeting= " Privet"; case 5: greeting = "MErhaba"; case 6: greeting= "Szia"; case 7: greeting= "Bonjour"; } } }
1,323
0.456538
0.440665
49
26
23.096956
87
false
false
0
0
0
0
0
0
0.265306
false
false
13
1d5561d643408a19f318d161043c99f0acb6330a
20,641,612,840,055
f7c63d27c7a95f8d29925e25ba459110feab1b59
/app/src/main/java/android_team/gymme_client/gym/manage_profile/GymEditDataActivity.java
398ccfbfdb28ba6fdcd07443b2de71ff9dc9b66a
[]
no_license
giovannirigotti/gymme-client
https://github.com/giovannirigotti/gymme-client
fa3316099d72c28db4cfdf7bb069f17ae6106dbf
acb8bd13dd219e42fb98052d9dffab398547d5dd
refs/heads/main
2023-03-05T20:20:31.889000
2021-02-18T10:26:00
2021-02-18T10:26:00
331,703,887
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package android_team.gymme_client.gym.manage_profile; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Switch; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import android_team.gymme_client.R; import android_team.gymme_client.login.LoginActivity; import butterknife.BindView; import butterknife.ButterKnife; public class GymEditDataActivity extends AppCompatActivity { private int user_id; private int pool, box_ring, aerobics, spa, wifi, parking_area, personal_trainer, nutritionist, impedance_balance, courses, showers; //region BINDING ELEMENTI VIEW @BindView(R.id.gymSwitchSignUpPool) Switch _switchSignUpPool; @BindView(R.id.gymSwitchSignupBoxRing) Switch _switchSignupBoxRing; @BindView(R.id.gymSwitchSignupAerobics) Switch _switchSignupAerobics; @BindView(R.id.gymSwitchSignUpSpa) Switch _switchSignUpSpa; @BindView(R.id.gymSwitchSignUpWifi) Switch _switchSignUpWifi; @BindView(R.id.gymSwitchSignUpParking) Switch _switchSignUpParking; @BindView(R.id.gymSwitchSignUpPersonalTrainer) Switch _switchSignUpPersonalTrainer; @BindView(R.id.gymSwitchSignUpNutritionist) Switch _switchSignUpNutritionist; @BindView(R.id.gymSwitchSignUpImpedenceBalance) Switch _switchSignUpImpedenceBalance; @BindView(R.id.gymSwitchSignUpCourses) Switch _switchSignUpCourses; @BindView(R.id.gymSwitchSignUpShowers) Switch _switchSignUpShowers; @BindView(R.id.btn_gym_confirm_data) Button _btn_gym_confirm_data; //endregion @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gym_edit_data); ButterKnife.bind(this); //region CHECK INTENT.EXTRAS RECEIVED Intent i = getIntent(); if (!i.hasExtra("user_id")) { Toast.makeText(this, "user_id mancante", Toast.LENGTH_LONG).show(); Intent new_i = new Intent(this, LoginActivity.class); startActivity(new_i); } else { user_id = i.getIntExtra("user_id", -1); Log.w("user_id ricevuto:", String.valueOf(user_id)); if (user_id == -1) { Toast.makeText(this, "Utente non creato", Toast.LENGTH_LONG).show(); Intent new_i = new Intent(this, LoginActivity.class); startActivity(new_i); } } //endregion // GetGymData(): caricare la configurazione dei tasti in base ai campi salvati nel DB per la palestra in questione: // - SCARICO DATI mediante query sul db e lo user_id // - SETTO VIEW grazie ai dati ricevuti GetGymData(); // BUTTON AVANTI MENAGEMENT _btn_gym_confirm_data.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // UpdateBooleanData(): update dei dati booleani della palestra. UpdateBooleanData(); } }); } //region GYM DATA MANAGMNET // Get data & Set View private void GetGymData() { //Gym Data GymEditDataActivity.GetGymDataConnection asyncTaskTrainer = (GymEditDataActivity.GetGymDataConnection) new GymEditDataActivity.GetGymDataConnection(new GymEditDataActivity.GetGymDataConnection.AsyncResponse() { @Override public void processFinish(int _pool, int _box_ring, int _aerobics, int _spa, int _wifi, int _parking_area, int _personal_traienr, int _nutritionist, int _impedance_balance, int _courses, int _showers) { if (_pool == -1) { Toast.makeText(GymEditDataActivity.this, "Errore nel recuperare i dati", Toast.LENGTH_SHORT).show(); Intent new_i = new Intent(GymEditDataActivity.this, LoginActivity.class); startActivity(new_i); finish(); } else if (_pool == 1 || _pool == 0) { // - SETTO VIEW grazie ai dati ricevuti if (_pool == 1) { pool = _pool; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignUpPool.setChecked(true); } }); } if (_box_ring == 1) { box_ring = _box_ring; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignupBoxRing.setChecked(true); } }); } if (_aerobics == 1) { aerobics = _aerobics; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignupAerobics.setChecked(true); } }); } if (_spa == 1) { spa = _spa; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignUpSpa.setChecked(true); } }); } if (_wifi == 1) { wifi = _wifi; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignUpWifi.setChecked(true); } }); } if (_parking_area == 1) { parking_area = _parking_area; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignUpParking.setChecked(true); } }); } if (_personal_traienr == 1) { personal_trainer = _personal_traienr; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignUpPersonalTrainer.setChecked(true); } }); } if (_nutritionist == 1) { nutritionist = _nutritionist; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignUpNutritionist.setChecked(true); } }); } if (_impedance_balance == 1) { impedance_balance = _impedance_balance; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignUpImpedenceBalance.setChecked(true); } }); } if (_courses == 1) { courses = _courses; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignUpCourses.setChecked(true); } }); } if (_showers == 1) { showers = _showers; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignUpShowers.setChecked(true); } }); } } else { runOnUiThread(new Runnable() { public void run() { Toast.makeText(GymEditDataActivity.this, "Errore del server", Toast.LENGTH_SHORT).show(); } }); } } }).execute(String.valueOf(user_id)); } private static class GetGymDataConnection extends AsyncTask<String, String, JsonObject> { public interface AsyncResponse { void processFinish(int _pool, int _box_ring, int _aerobics, int _spa, int _wifi, int _parking_area, int _personal_traienr, int _nutritionist, int _impedance_balance, int _courses, int _showers); } public GymEditDataActivity.GetGymDataConnection.AsyncResponse delegate = null; public GetGymDataConnection(GymEditDataActivity.GetGymDataConnection.AsyncResponse delegate) { this.delegate = delegate; } @Override protected JsonObject doInBackground(String... params) { URL url; HttpURLConnection urlConnection = null; JsonObject user = null; try { url = new URL("http://10.0.2.2:4000/gym/get_boolean_data/" + params[0]); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(5000); urlConnection.connect(); int responseCode = urlConnection.getResponseCode(); urlConnection.disconnect(); if (responseCode == HttpURLConnection.HTTP_OK) { //Log.e("Server response", "HTTP_OK"); String responseString = readStream(urlConnection.getInputStream()); //Log.e("Server customer", responseString); user = JsonParser.parseString(responseString).getAsJsonObject(); delegate.processFinish(user.get("pool").getAsInt(), user.get("box_ring").getAsInt(), user.get("aerobics").getAsInt(), user.get("spa").getAsInt(), user.get("wifi").getAsInt(), user.get("parking_area").getAsInt(), user.get("personal_trainer_service").getAsInt(), user.get("nutritionist_service").getAsInt(), user.get("impedance_balance").getAsInt(), user.get("courses").getAsInt(), user.get("showers").getAsInt()); } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) { //Log.e("Server response", "HTTP_NOT_FOUND"); delegate.processFinish(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1); } } catch (IOException e) { e.printStackTrace(); } finally { if (urlConnection != null) urlConnection.disconnect(); } return user; } private String readStream(InputStream in) throws UnsupportedEncodingException { BufferedReader reader = null; StringBuffer response = new StringBuffer(); try { reader = new BufferedReader(new InputStreamReader(in)); String line = ""; while ((line = reader.readLine()) != null) { response.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return response.toString(); } } // Updating datas private void UpdateBooleanData() { // AGGIORNO STATO ATTUALE DEGLI SWITCH updateFields(); // METODO-CLASSE PER CHIAMARE LA POST CORRETTA SUL SERVER GymEditDataActivity.UpdateBooleanDataConnection asyncTask = (GymEditDataActivity.UpdateBooleanDataConnection) new GymEditDataActivity.UpdateBooleanDataConnection(new GymEditDataActivity.UpdateBooleanDataConnection.AsyncResponse() { @Override public void processFinish(Integer output) { if (output == 200) { runOnUiThread(new Runnable() { public void run() { //Toast.makeText(GymEditDataActivity.this, "SUCCESS, boolan data aggiornati", Toast.LENGTH_SHORT).show(); // REDIRECT TO PROFILE GYM ACTIVITY //Log.e("REDIRECT", "Gym Profile Activity"); Intent i = new Intent(getApplicationContext(), GymProfileActivity.class); i.putExtra("user_id", user_id); startActivity(i); } }); } else { runOnUiThread(new Runnable() { public void run() { Toast.makeText(GymEditDataActivity.this, "Errore sul server", Toast.LENGTH_SHORT).show(); } }); } } }).execute(String.valueOf(user_id), String.valueOf(pool), String.valueOf(box_ring), String.valueOf(aerobics), String.valueOf(spa), String.valueOf(wifi), String.valueOf(parking_area), String.valueOf(personal_trainer), String.valueOf(nutritionist), String.valueOf(impedance_balance), String.valueOf(courses), String.valueOf(showers)); } private void updateFields() { pool = switchToInt(_switchSignUpPool.isChecked()); box_ring = switchToInt(_switchSignupBoxRing.isChecked()); aerobics = switchToInt(_switchSignupAerobics.isChecked()); spa = switchToInt(_switchSignUpSpa.isChecked()); wifi = switchToInt(_switchSignUpWifi.isChecked()); parking_area = switchToInt(_switchSignUpParking.isChecked()); personal_trainer = switchToInt(_switchSignUpPersonalTrainer.isChecked()); nutritionist = switchToInt(_switchSignUpNutritionist.isChecked()); impedance_balance = switchToInt(_switchSignUpImpedenceBalance.isChecked()); courses = switchToInt(_switchSignUpCourses.isChecked()); showers = switchToInt(_switchSignUpShowers.isChecked()); } private int switchToInt(boolean checked) { return (checked == true) ? 1 : 0; } public static class UpdateBooleanDataConnection extends AsyncTask<String, String, Integer> { // you may separate this or combined to caller class. public interface AsyncResponse { void processFinish(Integer output); } public GymEditDataActivity.UpdateBooleanDataConnection.AsyncResponse delegate = null; public UpdateBooleanDataConnection(GymEditDataActivity.UpdateBooleanDataConnection.AsyncResponse delegate) { this.delegate = delegate; } @Override protected Integer doInBackground(String... params) { URL url; HttpURLConnection urlConnection = null; JsonObject user = null; int responseCode = 500; try { url = new URL("http://10.0.2.2:4000/gym/update_boolean_data/"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setConnectTimeout(5000); urlConnection.setRequestProperty("Content-Type", "application/json"); JsonObject paramsJson = new JsonObject(); paramsJson.addProperty("user_id", params[0]); paramsJson.addProperty("pool", params[1]); paramsJson.addProperty("box_ring", params[2]); paramsJson.addProperty("aerobics", params[3]); paramsJson.addProperty("spa", params[4]); paramsJson.addProperty("wifi", params[5]); paramsJson.addProperty("parking_area", params[6]); paramsJson.addProperty("personal_trainer_service", params[7]); paramsJson.addProperty("nutritionist_service", params[8]); paramsJson.addProperty("impedance_balance", params[9]); paramsJson.addProperty("courses", params[10]); paramsJson.addProperty("showers", params[11]); urlConnection.setDoOutput(true); OutputStream os = urlConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(paramsJson.toString()); writer.flush(); writer.close(); os.close(); urlConnection.connect(); responseCode = urlConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { //Log.e("BOOLEAN DATA", "CAMBIATI SUL DB"); responseCode = 200; delegate.processFinish(responseCode); } else { //Log.e("BOOLEAN DATA", "Error"); responseCode = 500; delegate.processFinish(responseCode); urlConnection.disconnect(); } } catch (IOException e) { e.printStackTrace(); responseCode = 69; delegate.processFinish(responseCode); } finally { if (urlConnection != null) urlConnection.disconnect(); } return responseCode; } } //endregion }
UTF-8
Java
18,976
java
GymEditDataActivity.java
Java
[ { "context": " try {\n url = new URL(\"http://10.0.2.2:4000/gym/get_boolean_data/\" + params[0]);\n ", "end": 10384, "score": 0.9976081848144531, "start": 10376, "tag": "IP_ADDRESS", "value": "10.0.2.2" }, { "context": " try {\n url = new URL(\"http://10.0.2.2:4000/gym/update_boolean_data/\");\n ", "end": 16507, "score": 0.7238499522209167, "start": 16500, "tag": "IP_ADDRESS", "value": "0.0.2.2" } ]
null
[]
package android_team.gymme_client.gym.manage_profile; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Switch; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import android_team.gymme_client.R; import android_team.gymme_client.login.LoginActivity; import butterknife.BindView; import butterknife.ButterKnife; public class GymEditDataActivity extends AppCompatActivity { private int user_id; private int pool, box_ring, aerobics, spa, wifi, parking_area, personal_trainer, nutritionist, impedance_balance, courses, showers; //region BINDING ELEMENTI VIEW @BindView(R.id.gymSwitchSignUpPool) Switch _switchSignUpPool; @BindView(R.id.gymSwitchSignupBoxRing) Switch _switchSignupBoxRing; @BindView(R.id.gymSwitchSignupAerobics) Switch _switchSignupAerobics; @BindView(R.id.gymSwitchSignUpSpa) Switch _switchSignUpSpa; @BindView(R.id.gymSwitchSignUpWifi) Switch _switchSignUpWifi; @BindView(R.id.gymSwitchSignUpParking) Switch _switchSignUpParking; @BindView(R.id.gymSwitchSignUpPersonalTrainer) Switch _switchSignUpPersonalTrainer; @BindView(R.id.gymSwitchSignUpNutritionist) Switch _switchSignUpNutritionist; @BindView(R.id.gymSwitchSignUpImpedenceBalance) Switch _switchSignUpImpedenceBalance; @BindView(R.id.gymSwitchSignUpCourses) Switch _switchSignUpCourses; @BindView(R.id.gymSwitchSignUpShowers) Switch _switchSignUpShowers; @BindView(R.id.btn_gym_confirm_data) Button _btn_gym_confirm_data; //endregion @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gym_edit_data); ButterKnife.bind(this); //region CHECK INTENT.EXTRAS RECEIVED Intent i = getIntent(); if (!i.hasExtra("user_id")) { Toast.makeText(this, "user_id mancante", Toast.LENGTH_LONG).show(); Intent new_i = new Intent(this, LoginActivity.class); startActivity(new_i); } else { user_id = i.getIntExtra("user_id", -1); Log.w("user_id ricevuto:", String.valueOf(user_id)); if (user_id == -1) { Toast.makeText(this, "Utente non creato", Toast.LENGTH_LONG).show(); Intent new_i = new Intent(this, LoginActivity.class); startActivity(new_i); } } //endregion // GetGymData(): caricare la configurazione dei tasti in base ai campi salvati nel DB per la palestra in questione: // - SCARICO DATI mediante query sul db e lo user_id // - SETTO VIEW grazie ai dati ricevuti GetGymData(); // BUTTON AVANTI MENAGEMENT _btn_gym_confirm_data.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // UpdateBooleanData(): update dei dati booleani della palestra. UpdateBooleanData(); } }); } //region GYM DATA MANAGMNET // Get data & Set View private void GetGymData() { //Gym Data GymEditDataActivity.GetGymDataConnection asyncTaskTrainer = (GymEditDataActivity.GetGymDataConnection) new GymEditDataActivity.GetGymDataConnection(new GymEditDataActivity.GetGymDataConnection.AsyncResponse() { @Override public void processFinish(int _pool, int _box_ring, int _aerobics, int _spa, int _wifi, int _parking_area, int _personal_traienr, int _nutritionist, int _impedance_balance, int _courses, int _showers) { if (_pool == -1) { Toast.makeText(GymEditDataActivity.this, "Errore nel recuperare i dati", Toast.LENGTH_SHORT).show(); Intent new_i = new Intent(GymEditDataActivity.this, LoginActivity.class); startActivity(new_i); finish(); } else if (_pool == 1 || _pool == 0) { // - SETTO VIEW grazie ai dati ricevuti if (_pool == 1) { pool = _pool; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignUpPool.setChecked(true); } }); } if (_box_ring == 1) { box_ring = _box_ring; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignupBoxRing.setChecked(true); } }); } if (_aerobics == 1) { aerobics = _aerobics; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignupAerobics.setChecked(true); } }); } if (_spa == 1) { spa = _spa; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignUpSpa.setChecked(true); } }); } if (_wifi == 1) { wifi = _wifi; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignUpWifi.setChecked(true); } }); } if (_parking_area == 1) { parking_area = _parking_area; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignUpParking.setChecked(true); } }); } if (_personal_traienr == 1) { personal_trainer = _personal_traienr; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignUpPersonalTrainer.setChecked(true); } }); } if (_nutritionist == 1) { nutritionist = _nutritionist; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignUpNutritionist.setChecked(true); } }); } if (_impedance_balance == 1) { impedance_balance = _impedance_balance; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignUpImpedenceBalance.setChecked(true); } }); } if (_courses == 1) { courses = _courses; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignUpCourses.setChecked(true); } }); } if (_showers == 1) { showers = _showers; runOnUiThread(new Runnable() { public void run() { //SETTO VIEW grazie ai dati ricevuti _switchSignUpShowers.setChecked(true); } }); } } else { runOnUiThread(new Runnable() { public void run() { Toast.makeText(GymEditDataActivity.this, "Errore del server", Toast.LENGTH_SHORT).show(); } }); } } }).execute(String.valueOf(user_id)); } private static class GetGymDataConnection extends AsyncTask<String, String, JsonObject> { public interface AsyncResponse { void processFinish(int _pool, int _box_ring, int _aerobics, int _spa, int _wifi, int _parking_area, int _personal_traienr, int _nutritionist, int _impedance_balance, int _courses, int _showers); } public GymEditDataActivity.GetGymDataConnection.AsyncResponse delegate = null; public GetGymDataConnection(GymEditDataActivity.GetGymDataConnection.AsyncResponse delegate) { this.delegate = delegate; } @Override protected JsonObject doInBackground(String... params) { URL url; HttpURLConnection urlConnection = null; JsonObject user = null; try { url = new URL("http://10.0.2.2:4000/gym/get_boolean_data/" + params[0]); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(5000); urlConnection.connect(); int responseCode = urlConnection.getResponseCode(); urlConnection.disconnect(); if (responseCode == HttpURLConnection.HTTP_OK) { //Log.e("Server response", "HTTP_OK"); String responseString = readStream(urlConnection.getInputStream()); //Log.e("Server customer", responseString); user = JsonParser.parseString(responseString).getAsJsonObject(); delegate.processFinish(user.get("pool").getAsInt(), user.get("box_ring").getAsInt(), user.get("aerobics").getAsInt(), user.get("spa").getAsInt(), user.get("wifi").getAsInt(), user.get("parking_area").getAsInt(), user.get("personal_trainer_service").getAsInt(), user.get("nutritionist_service").getAsInt(), user.get("impedance_balance").getAsInt(), user.get("courses").getAsInt(), user.get("showers").getAsInt()); } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) { //Log.e("Server response", "HTTP_NOT_FOUND"); delegate.processFinish(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1); } } catch (IOException e) { e.printStackTrace(); } finally { if (urlConnection != null) urlConnection.disconnect(); } return user; } private String readStream(InputStream in) throws UnsupportedEncodingException { BufferedReader reader = null; StringBuffer response = new StringBuffer(); try { reader = new BufferedReader(new InputStreamReader(in)); String line = ""; while ((line = reader.readLine()) != null) { response.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return response.toString(); } } // Updating datas private void UpdateBooleanData() { // AGGIORNO STATO ATTUALE DEGLI SWITCH updateFields(); // METODO-CLASSE PER CHIAMARE LA POST CORRETTA SUL SERVER GymEditDataActivity.UpdateBooleanDataConnection asyncTask = (GymEditDataActivity.UpdateBooleanDataConnection) new GymEditDataActivity.UpdateBooleanDataConnection(new GymEditDataActivity.UpdateBooleanDataConnection.AsyncResponse() { @Override public void processFinish(Integer output) { if (output == 200) { runOnUiThread(new Runnable() { public void run() { //Toast.makeText(GymEditDataActivity.this, "SUCCESS, boolan data aggiornati", Toast.LENGTH_SHORT).show(); // REDIRECT TO PROFILE GYM ACTIVITY //Log.e("REDIRECT", "Gym Profile Activity"); Intent i = new Intent(getApplicationContext(), GymProfileActivity.class); i.putExtra("user_id", user_id); startActivity(i); } }); } else { runOnUiThread(new Runnable() { public void run() { Toast.makeText(GymEditDataActivity.this, "Errore sul server", Toast.LENGTH_SHORT).show(); } }); } } }).execute(String.valueOf(user_id), String.valueOf(pool), String.valueOf(box_ring), String.valueOf(aerobics), String.valueOf(spa), String.valueOf(wifi), String.valueOf(parking_area), String.valueOf(personal_trainer), String.valueOf(nutritionist), String.valueOf(impedance_balance), String.valueOf(courses), String.valueOf(showers)); } private void updateFields() { pool = switchToInt(_switchSignUpPool.isChecked()); box_ring = switchToInt(_switchSignupBoxRing.isChecked()); aerobics = switchToInt(_switchSignupAerobics.isChecked()); spa = switchToInt(_switchSignUpSpa.isChecked()); wifi = switchToInt(_switchSignUpWifi.isChecked()); parking_area = switchToInt(_switchSignUpParking.isChecked()); personal_trainer = switchToInt(_switchSignUpPersonalTrainer.isChecked()); nutritionist = switchToInt(_switchSignUpNutritionist.isChecked()); impedance_balance = switchToInt(_switchSignUpImpedenceBalance.isChecked()); courses = switchToInt(_switchSignUpCourses.isChecked()); showers = switchToInt(_switchSignUpShowers.isChecked()); } private int switchToInt(boolean checked) { return (checked == true) ? 1 : 0; } public static class UpdateBooleanDataConnection extends AsyncTask<String, String, Integer> { // you may separate this or combined to caller class. public interface AsyncResponse { void processFinish(Integer output); } public GymEditDataActivity.UpdateBooleanDataConnection.AsyncResponse delegate = null; public UpdateBooleanDataConnection(GymEditDataActivity.UpdateBooleanDataConnection.AsyncResponse delegate) { this.delegate = delegate; } @Override protected Integer doInBackground(String... params) { URL url; HttpURLConnection urlConnection = null; JsonObject user = null; int responseCode = 500; try { url = new URL("http://10.0.2.2:4000/gym/update_boolean_data/"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setConnectTimeout(5000); urlConnection.setRequestProperty("Content-Type", "application/json"); JsonObject paramsJson = new JsonObject(); paramsJson.addProperty("user_id", params[0]); paramsJson.addProperty("pool", params[1]); paramsJson.addProperty("box_ring", params[2]); paramsJson.addProperty("aerobics", params[3]); paramsJson.addProperty("spa", params[4]); paramsJson.addProperty("wifi", params[5]); paramsJson.addProperty("parking_area", params[6]); paramsJson.addProperty("personal_trainer_service", params[7]); paramsJson.addProperty("nutritionist_service", params[8]); paramsJson.addProperty("impedance_balance", params[9]); paramsJson.addProperty("courses", params[10]); paramsJson.addProperty("showers", params[11]); urlConnection.setDoOutput(true); OutputStream os = urlConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(paramsJson.toString()); writer.flush(); writer.close(); os.close(); urlConnection.connect(); responseCode = urlConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { //Log.e("BOOLEAN DATA", "CAMBIATI SUL DB"); responseCode = 200; delegate.processFinish(responseCode); } else { //Log.e("BOOLEAN DATA", "Error"); responseCode = 500; delegate.processFinish(responseCode); urlConnection.disconnect(); } } catch (IOException e) { e.printStackTrace(); responseCode = 69; delegate.processFinish(responseCode); } finally { if (urlConnection != null) urlConnection.disconnect(); } return responseCode; } } //endregion }
18,976
0.526823
0.522344
437
42.425629
33.763779
239
false
false
0
0
0
0
0
0
0.691076
false
false
13
f15b3d3190db19d6c3f76bd73a37019057609f78
9,990,093,934,984
bb2f903ff43b928087c74129e4db2d37e75b5f9f
/app/src/main/java/com/geli/m/coustomview/recyclerviewscrollerview/FastScrollUtils.java
5c144be0aee78643d3291703d8907b89101f89e0
[]
no_license
namezhouyu/geliandroid
https://github.com/namezhouyu/geliandroid
c5e869a46aa125f780740d42f3de24f0d651c995
6a7f2c6413d471c92cb8faabfe634a2bc2274051
refs/heads/master
2021-02-10T02:03:45.256000
2020-03-02T12:09:35
2020-03-02T12:09:35
244,342,465
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.geli.m.coustomview.recyclerviewscrollerview; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.View; /** * Created by mklimczak on 31/07/15. */ public class FastScrollUtils { /** * 获取"本控件"在屏幕的"Y坐标" * * getLocationInWindow -- 计算此视图在其窗口中的坐标。参数必须是两个整数的数组。方法返回后,数组按顺序包含X和Y位置。 * @param view * @return */ public static float getViewRawY(View view) { int[] location = new int[2]; location[0] = 0; location[1] = (int) view.getY(); ((View)view.getParent()).getLocationInWindow(location); return location[1]; } /** * 获取"本控件"在屏幕的"X坐标" * getLocationInWindow -- 计算此视图在其窗口中的坐标。参数必须是两个整数的数组。方法返回后,数组按顺序包含X和Y位置。 * @param view * @return */ public static float getViewRawX(View view) { int[] location = new int[2]; location[0] = (int) view.getX(); location[1] = 0; ((View)view.getParent()).getLocationInWindow(location); return location[0]; } /** * 边界内取数 * * 小于"最小边界" 返回 min <br> * 大于"最大边界" 返回 max <br> * 在"边界"内的 , 返回 Value * * @param min * @param max * @param value * @return */ public static float getValueInRange(float min, float max, float value) { float minimum = Math.max(min, value); return Math.min(minimum, max); } /** * 为"控件" 设置背景 * @param view 控件 * @param drawable 资源文件 */ public static void setBackground(View view, Drawable drawable){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { view.setBackground(drawable); } else { view.setBackgroundDrawable(drawable); } } }
UTF-8
Java
2,093
java
FastScrollUtils.java
Java
[ { "context": "uild;\nimport android.view.View;\n\n/**\n * Created by mklimczak on 31/07/15.\n */\npublic class FastScrollUtils {\n\n", "end": 180, "score": 0.999669075012207, "start": 171, "tag": "USERNAME", "value": "mklimczak" } ]
null
[]
package com.geli.m.coustomview.recyclerviewscrollerview; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.View; /** * Created by mklimczak on 31/07/15. */ public class FastScrollUtils { /** * 获取"本控件"在屏幕的"Y坐标" * * getLocationInWindow -- 计算此视图在其窗口中的坐标。参数必须是两个整数的数组。方法返回后,数组按顺序包含X和Y位置。 * @param view * @return */ public static float getViewRawY(View view) { int[] location = new int[2]; location[0] = 0; location[1] = (int) view.getY(); ((View)view.getParent()).getLocationInWindow(location); return location[1]; } /** * 获取"本控件"在屏幕的"X坐标" * getLocationInWindow -- 计算此视图在其窗口中的坐标。参数必须是两个整数的数组。方法返回后,数组按顺序包含X和Y位置。 * @param view * @return */ public static float getViewRawX(View view) { int[] location = new int[2]; location[0] = (int) view.getX(); location[1] = 0; ((View)view.getParent()).getLocationInWindow(location); return location[0]; } /** * 边界内取数 * * 小于"最小边界" 返回 min <br> * 大于"最大边界" 返回 max <br> * 在"边界"内的 , 返回 Value * * @param min * @param max * @param value * @return */ public static float getValueInRange(float min, float max, float value) { float minimum = Math.max(min, value); return Math.min(minimum, max); } /** * 为"控件" 设置背景 * @param view 控件 * @param drawable 资源文件 */ public static void setBackground(View view, Drawable drawable){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { view.setBackground(drawable); } else { view.setBackgroundDrawable(drawable); } } }
2,093
0.57071
0.561766
71
24.197184
21.131792
76
false
false
0
0
0
0
0
0
0.323944
false
false
13
07bbfc181a76cb2820d36a2376b856d98458a4b9
31,868,657,393,063
eb4857971159cb80994f77a904337799e879f241
/spring-cloud-gateway-service-dynamic-redis/src/main/java/com/lidong/gateway/GatewayApplication.java
8fce1c87cf6dfd24346e57e798c7d499b98bfddf
[ "Apache-2.0" ]
permissive
AlexAnYang/spring-cloud-learning-example
https://github.com/AlexAnYang/spring-cloud-learning-example
b4c21ab47986b2a7275056db46cdccf2f8cfec9e
72a1a6eeb7796eff99f221d32ee406cafd4b4b25
refs/heads/master
2020-09-04T23:11:16.345000
2019-09-19T03:15:20
2019-09-19T03:15:20
219,919,982
1
0
Apache-2.0
true
2019-11-06T05:38:17
2019-11-06T05:38:16
2019-10-31T09:44:19
2019-09-19T03:15:47
365
0
0
0
null
false
false
package com.lidong.gateway; import com.lidong.gateway.repository.RedisRouteDefinitionRepository; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.gateway.route.InMemoryRouteDefinitionRepository; import org.springframework.cloud.gateway.route.RouteDefinitionWriter; import org.springframework.context.annotation.Bean; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; /** * 开启服务发现 * * CachingRouteDefinitionLocator 缓存目标 * CompositeRouteDefinitionLocator 组合多种 * DiscoveryClientRouteDefinitionLocator 从注册中心 * InMemoryRouteDefinitionRepository 读取内存中的 * PropertiesRouteDefinitionLocator 读取配置文件 GatewayProperties yml/properties * RouteDefinitionRepository 从存储器读取 * * @Bean * @ConditionalOnMissingBean(RouteDefinitionRepository.class) * public InMemoryRouteDefinitionRepository inMemoryRouteDefinitionRepository() { * return new InMemoryRouteDefinitionRepository(); * } * 通过上面代码,可以看到如果没有RouteDefinitionRepository的实例, * 则默认用InMemoryRouteDefinitionRepository。而做动态路由的关键就在这里。 * 即通过自定义的RouteDefinitionRepository类,来提供路由配置信息。 * */ @EnableDiscoveryClient @EnableJpaRepositories(basePackages = "com.lidong.gateway") @EntityScan(basePackages = {"com.lidong.gateway.entity"}) @SpringBootApplication public class GatewayApplication { /** * * @return */ @Bean public RouteDefinitionWriter routeDefinitionWriter() { return new RedisRouteDefinitionRepository(); } public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } }
UTF-8
Java
1,986
java
GatewayApplication.java
Java
[]
null
[]
package com.lidong.gateway; import com.lidong.gateway.repository.RedisRouteDefinitionRepository; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.gateway.route.InMemoryRouteDefinitionRepository; import org.springframework.cloud.gateway.route.RouteDefinitionWriter; import org.springframework.context.annotation.Bean; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; /** * 开启服务发现 * * CachingRouteDefinitionLocator 缓存目标 * CompositeRouteDefinitionLocator 组合多种 * DiscoveryClientRouteDefinitionLocator 从注册中心 * InMemoryRouteDefinitionRepository 读取内存中的 * PropertiesRouteDefinitionLocator 读取配置文件 GatewayProperties yml/properties * RouteDefinitionRepository 从存储器读取 * * @Bean * @ConditionalOnMissingBean(RouteDefinitionRepository.class) * public InMemoryRouteDefinitionRepository inMemoryRouteDefinitionRepository() { * return new InMemoryRouteDefinitionRepository(); * } * 通过上面代码,可以看到如果没有RouteDefinitionRepository的实例, * 则默认用InMemoryRouteDefinitionRepository。而做动态路由的关键就在这里。 * 即通过自定义的RouteDefinitionRepository类,来提供路由配置信息。 * */ @EnableDiscoveryClient @EnableJpaRepositories(basePackages = "com.lidong.gateway") @EntityScan(basePackages = {"com.lidong.gateway.entity"}) @SpringBootApplication public class GatewayApplication { /** * * @return */ @Bean public RouteDefinitionWriter routeDefinitionWriter() { return new RedisRouteDefinitionRepository(); } public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } }
1,986
0.812569
0.812569
53
32.905659
27.413166
82
false
false
0
0
0
0
0
0
0.358491
false
false
13
c15234a70dca2e58173ed5ff98b1097a71348b79
32,985,348,851,145
05ab2e539cea5899179f2ceea83a4dd7965c644b
/app/src/main/java/com/ssd/yiqiwa/model/entity/MacOrderSubPo.java
23d729df22a1b94ecece5405ab3e2a109b29fc81
[]
no_license
lxpanup/yiqiwa_as
https://github.com/lxpanup/yiqiwa_as
3e6228e3c06eecb86e731b57dcf1a10f9d999bd4
3087599f0774b00f168387c84f8a46c22feb4646
refs/heads/master
2020-07-07T21:32:13.391000
2019-09-03T16:32:30
2019-09-03T16:32:30
203,482,888
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ssd.yiqiwa.model.entity; import android.os.Parcel; import android.os.Parcelable; public class MacOrderSubPo implements Parcelable { private String city; private String count; private String county; private String createDate; private String giftScore; private String giftScoreRemark; private String managerId; private String managerStart; private String orderNum; private String orderSubNum; private String orderType; private String osId; private String price; private String priceUint; private String productCoverImage; private String productId; private String productTitle; private String province; private String publisherId; private String remark; private String rentFrom; private String status; private String userId; public MacOrderSubPo() { } public MacOrderSubPo(String city, String count, String county, String createDate, String giftScore, String giftScoreRemark, String managerId, String managerStart, String orderNum, String orderSubNum, String orderType, String osId, String price, String priceUint, String productCoverImage, String productId, String productTitle, String province, String publisherId, String remark, String rentFrom, String status, String userId) { this.city = city; this.count = count; this.county = county; this.createDate = createDate; this.giftScore = giftScore; this.giftScoreRemark = giftScoreRemark; this.managerId = managerId; this.managerStart = managerStart; this.orderNum = orderNum; this.orderSubNum = orderSubNum; this.orderType = orderType; this.osId = osId; this.price = price; this.priceUint = priceUint; this.productCoverImage = productCoverImage; this.productId = productId; this.productTitle = productTitle; this.province = province; this.publisherId = publisherId; this.remark = remark; this.rentFrom = rentFrom; this.status = status; this.userId = userId; } protected MacOrderSubPo(Parcel in) { city = in.readString(); count = in.readString(); county = in.readString(); createDate = in.readString(); giftScore = in.readString(); giftScoreRemark = in.readString(); managerId = in.readString(); managerStart = in.readString(); orderNum = in.readString(); orderSubNum = in.readString(); orderType = in.readString(); osId = in.readString(); price = in.readString(); priceUint = in.readString(); productCoverImage = in.readString(); productId = in.readString(); productTitle = in.readString(); province = in.readString(); publisherId = in.readString(); remark = in.readString(); rentFrom = in.readString(); status = in.readString(); userId = in.readString(); } public static final Creator<MacOrderSubPo> CREATOR = new Creator<MacOrderSubPo>() { @Override public MacOrderSubPo createFromParcel(Parcel in) { return new MacOrderSubPo(in); } @Override public MacOrderSubPo[] newArray(int size) { return new MacOrderSubPo[size]; } }; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCount() { return count; } public void setCount(String count) { this.count = count; } public String getCounty() { return county; } public void setCounty(String county) { this.county = county; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this.createDate = createDate; } public String getGiftScore() { return giftScore; } public void setGiftScore(String giftScore) { this.giftScore = giftScore; } public String getGiftScoreRemark() { return giftScoreRemark; } public void setGiftScoreRemark(String giftScoreRemark) { this.giftScoreRemark = giftScoreRemark; } public String getManagerId() { return managerId; } public void setManagerId(String managerId) { this.managerId = managerId; } public String getManagerStart() { return managerStart; } public void setManagerStart(String managerStart) { this.managerStart = managerStart; } public String getOrderNum() { return orderNum; } public void setOrderNum(String orderNum) { this.orderNum = orderNum; } public String getOrderSubNum() { return orderSubNum; } public void setOrderSubNum(String orderSubNum) { this.orderSubNum = orderSubNum; } public String getOrderType() { return orderType; } public void setOrderType(String orderType) { this.orderType = orderType; } public String getOsId() { return osId; } public void setOsId(String osId) { this.osId = osId; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getPriceUint() { return priceUint; } public void setPriceUint(String priceUint) { this.priceUint = priceUint; } public String getProductCoverImage() { return productCoverImage; } public void setProductCoverImage(String productCoverImage) { this.productCoverImage = productCoverImage; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getProductTitle() { return productTitle; } public void setProductTitle(String productTitle) { this.productTitle = productTitle; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getPublisherId() { return publisherId; } public void setPublisherId(String publisherId) { this.publisherId = publisherId; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getRentFrom() { return rentFrom; } public void setRentFrom(String rentFrom) { this.rentFrom = rentFrom; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(city); dest.writeString(count); dest.writeString(county); dest.writeString(createDate); dest.writeString(giftScore); dest.writeString(giftScoreRemark); dest.writeString(managerId); dest.writeString(managerStart); dest.writeString(orderNum); dest.writeString(orderSubNum); dest.writeString(orderType); dest.writeString(osId); dest.writeString(price); dest.writeString(priceUint); dest.writeString(productCoverImage); dest.writeString(productId); dest.writeString(productTitle); dest.writeString(province); dest.writeString(publisherId); dest.writeString(remark); dest.writeString(rentFrom); dest.writeString(status); dest.writeString(userId); } }
UTF-8
Java
8,120
java
MacOrderSubPo.java
Java
[]
null
[]
package com.ssd.yiqiwa.model.entity; import android.os.Parcel; import android.os.Parcelable; public class MacOrderSubPo implements Parcelable { private String city; private String count; private String county; private String createDate; private String giftScore; private String giftScoreRemark; private String managerId; private String managerStart; private String orderNum; private String orderSubNum; private String orderType; private String osId; private String price; private String priceUint; private String productCoverImage; private String productId; private String productTitle; private String province; private String publisherId; private String remark; private String rentFrom; private String status; private String userId; public MacOrderSubPo() { } public MacOrderSubPo(String city, String count, String county, String createDate, String giftScore, String giftScoreRemark, String managerId, String managerStart, String orderNum, String orderSubNum, String orderType, String osId, String price, String priceUint, String productCoverImage, String productId, String productTitle, String province, String publisherId, String remark, String rentFrom, String status, String userId) { this.city = city; this.count = count; this.county = county; this.createDate = createDate; this.giftScore = giftScore; this.giftScoreRemark = giftScoreRemark; this.managerId = managerId; this.managerStart = managerStart; this.orderNum = orderNum; this.orderSubNum = orderSubNum; this.orderType = orderType; this.osId = osId; this.price = price; this.priceUint = priceUint; this.productCoverImage = productCoverImage; this.productId = productId; this.productTitle = productTitle; this.province = province; this.publisherId = publisherId; this.remark = remark; this.rentFrom = rentFrom; this.status = status; this.userId = userId; } protected MacOrderSubPo(Parcel in) { city = in.readString(); count = in.readString(); county = in.readString(); createDate = in.readString(); giftScore = in.readString(); giftScoreRemark = in.readString(); managerId = in.readString(); managerStart = in.readString(); orderNum = in.readString(); orderSubNum = in.readString(); orderType = in.readString(); osId = in.readString(); price = in.readString(); priceUint = in.readString(); productCoverImage = in.readString(); productId = in.readString(); productTitle = in.readString(); province = in.readString(); publisherId = in.readString(); remark = in.readString(); rentFrom = in.readString(); status = in.readString(); userId = in.readString(); } public static final Creator<MacOrderSubPo> CREATOR = new Creator<MacOrderSubPo>() { @Override public MacOrderSubPo createFromParcel(Parcel in) { return new MacOrderSubPo(in); } @Override public MacOrderSubPo[] newArray(int size) { return new MacOrderSubPo[size]; } }; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCount() { return count; } public void setCount(String count) { this.count = count; } public String getCounty() { return county; } public void setCounty(String county) { this.county = county; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this.createDate = createDate; } public String getGiftScore() { return giftScore; } public void setGiftScore(String giftScore) { this.giftScore = giftScore; } public String getGiftScoreRemark() { return giftScoreRemark; } public void setGiftScoreRemark(String giftScoreRemark) { this.giftScoreRemark = giftScoreRemark; } public String getManagerId() { return managerId; } public void setManagerId(String managerId) { this.managerId = managerId; } public String getManagerStart() { return managerStart; } public void setManagerStart(String managerStart) { this.managerStart = managerStart; } public String getOrderNum() { return orderNum; } public void setOrderNum(String orderNum) { this.orderNum = orderNum; } public String getOrderSubNum() { return orderSubNum; } public void setOrderSubNum(String orderSubNum) { this.orderSubNum = orderSubNum; } public String getOrderType() { return orderType; } public void setOrderType(String orderType) { this.orderType = orderType; } public String getOsId() { return osId; } public void setOsId(String osId) { this.osId = osId; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getPriceUint() { return priceUint; } public void setPriceUint(String priceUint) { this.priceUint = priceUint; } public String getProductCoverImage() { return productCoverImage; } public void setProductCoverImage(String productCoverImage) { this.productCoverImage = productCoverImage; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getProductTitle() { return productTitle; } public void setProductTitle(String productTitle) { this.productTitle = productTitle; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getPublisherId() { return publisherId; } public void setPublisherId(String publisherId) { this.publisherId = publisherId; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getRentFrom() { return rentFrom; } public void setRentFrom(String rentFrom) { this.rentFrom = rentFrom; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(city); dest.writeString(count); dest.writeString(county); dest.writeString(createDate); dest.writeString(giftScore); dest.writeString(giftScoreRemark); dest.writeString(managerId); dest.writeString(managerStart); dest.writeString(orderNum); dest.writeString(orderSubNum); dest.writeString(orderType); dest.writeString(osId); dest.writeString(price); dest.writeString(priceUint); dest.writeString(productCoverImage); dest.writeString(productId); dest.writeString(productTitle); dest.writeString(province); dest.writeString(publisherId); dest.writeString(remark); dest.writeString(rentFrom); dest.writeString(status); dest.writeString(userId); } }
8,120
0.62032
0.620197
317
24.615143
28.729954
432
false
false
0
0
0
0
0
0
0.529968
false
false
13
7de220749e015c47911b7d593b4b090f94c8f18b
16,569,983,840,762
f1187a34009ad04c8339146c2a56200562c1986f
/Chapter2/Avoid_creating_unnecessary_objects.java
4b343b8b601ea18aeaee16a445c23c207f70da4e
[]
no_license
BigBigBoss/effectiveJava
https://github.com/BigBigBoss/effectiveJava
0bd8b8df294e6e3585b219d947c948f596c1c532
83ac49ddb451b60cbabce778fda0791ad8a7a207
refs/heads/master
2016-09-06T05:15:54.163000
2015-11-11T07:42:33
2015-11-11T07:42:33
40,953,799
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Created by aalexanov on 24.08.15. * * Избегайте создания ненужных объектов * * Часто можно повторно использовать один и тот же объект, вместо создания * новых с похожей функциональностью. * Объект всегда может переиспользоваться, если он неизменяем(immutable) * * Так же можно использовать изменяемые объекты, если вы знаете, что они не будут изменены. * * Избегайте автоупаковку(item05.Sum). * */ public class Avoid_creating_unnecessary_objects { }
UTF-8
Java
736
java
Avoid_creating_unnecessary_objects.java
Java
[ { "context": "/**\n * Created by aalexanov on 24.08.15.\n *\n * Избегайте создания ненужных об", "end": 27, "score": 0.9990596175193787, "start": 18, "tag": "USERNAME", "value": "aalexanov" } ]
null
[]
/** * Created by aalexanov on 24.08.15. * * Избегайте создания ненужных объектов * * Часто можно повторно использовать один и тот же объект, вместо создания * новых с похожей функциональностью. * Объект всегда может переиспользоваться, если он неизменяем(immutable) * * Так же можно использовать изменяемые объекты, если вы знаете, что они не будут изменены. * * Избегайте автоупаковку(item05.Sum). * */ public class Avoid_creating_unnecessary_objects { }
736
0.752665
0.735608
16
28.3125
29.775658
91
false
false
0
0
0
0
0
0
0.25
false
false
13
f1f14cec27353dbda8070466106a51064404ccb9
25,563,645,361,309
6d82f06048d330216b17c19790f29075e62e47d5
/branches/SDK-2/main/util/cli/src/test/dpml/cli/application/CpTest.java
1e42f0ce1f646590a1d68496b9a8dfd52cd3527a
[ "Apache-2.0" ]
permissive
IdelsTak/dpml-svn
https://github.com/IdelsTak/dpml-svn
7d1fc3f1ff56ef2f45ca5f7f3ae88b1ace459b79
9f9bdcf0198566ddcee7befac4a3b2c693631df5
refs/heads/master
2022-03-19T15:50:45.872000
2009-11-23T08:45:39
2009-11-23T08:45:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright 2003-2004 The Apache Software Foundation * Copyright 2005-2006 Stephen McConnell, The Digital Product Management Laboratory * * 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 dpml.cli.application; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import dpml.cli.Argument; import dpml.cli.CommandLine; import dpml.cli.Group; import dpml.cli.Option; import dpml.cli.OptionException; import dpml.cli.builder.ArgumentBuilder; import dpml.cli.builder.DefaultOptionBuilder; import dpml.cli.builder.GroupBuilder; import dpml.cli.commandline.Parser; import dpml.cli.option.ArgumentImpl; import dpml.cli.option.SourceDestArgument; import dpml.cli.util.HelpFormatter; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; /** * <p>Test the <code>cp</code> command. Duplicated Option types are not * tested e.g. -a and -d are the same Option type.</p> * * <p>The following is the man output for 'cp'. See * http://www.rt.com/man/cp.1.html.</p> * * <pre> * CP(1) FSF CP(1) * * NAME cp - copy files and directories * * SYNOPSIS cp [OPTION]... SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY * * DESCRIPTION Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. * * -a, --archive same as -dpR * * -b, --backup make backup before removal * * -d, --no-dereference preserve links * * -f, --force remove existing destinations, never prompt * * -i, --interactive prompt before overwrite * * -l, --link link files instead of copying * * -p, --preserve preserve file attributes if possible * * -P, --parents append source path to DIRECTORY * -r copy recursively, non-directories as files * * --sparse=WHEN control creation of sparse files * * -R, --recursive copy directories recursively * * -s, --symbolic-link make symbolic links instead of copying * * -S, --suffix=SUFFIX override the usual backup suffix * * -u, --update copy only when the SOURCE file is newer than the destination file or when the destination file is missing * * -v, --verbose explain what is being done * * -V, --version-control=WORD override the usual version control * * -x, --one-file-system stay on this file system * * --help display this help and exit * * --version output version information and exit * * By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file when- ever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. * * The backup suffix is ~, unless set with SIMPLE_BACKUP_SUF- FIX. The version control may be set with VERSION_CONTROL, values are: * t, numbered make numbered backups * * nil, existing numbered if numbered backups exist, simple other- wise * * never, simple always make simple backups * * As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. * </pre> * </pre> * * @author Rob Oxspring * @author John Keyes */ public class CpTest extends TestCase { /** Option Builder */ private static final DefaultOptionBuilder OPTION_BUILDER = new DefaultOptionBuilder( ); /** Argument Builder */ private static final ArgumentBuilder ARGUMENT_BUILDER = new ArgumentBuilder( ); /** Group Builder */ private static final GroupBuilder GROUP_BUILDER = new GroupBuilder( ); private Group m_options; private ArgumentImpl m_source; private ArgumentImpl m_dest; private Argument m_targets; private Option m_archive; private Option m_backup; private Option m_noDereference; private Option m_force; private Option m_interactive; private Option m_link; private Option m_preserve; private Option m_parents; private Option m_recursive1; private Option m_sparse; private Option m_recursive2; private Option m_symbolicLink; private Option m_suffix; private Option m_update; private Option m_verbose; private Option m_versionControl; private Option m_oneFileSystem; private Option m_help; private Option m_version; /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public static Test suite( ) { return new TestSuite( CpTest.class ); } /** * DOCUMENT ME! */ public void setUp( ) { m_source = (ArgumentImpl) ARGUMENT_BUILDER.withName( "SOURCE" ).withMinimum( 1 ) .create( ); m_dest = (ArgumentImpl) ARGUMENT_BUILDER.withName( "DEST" ).withMinimum( 1 ) .withMaximum( 1 ).create( ); m_targets = new SourceDestArgument( m_source, m_dest ); m_archive = OPTION_BUILDER.withShortName( "a" ).withLongName( "archive" ) .withDescription( "same as -dpR" ).create( ); m_backup = OPTION_BUILDER.withShortName( "b" ).withLongName( "backup" ) .withDescription( "make backup before removal" ) .create( ); m_noDereference = OPTION_BUILDER.withShortName( "d" ) .withLongName( "no-dereference" ) .withDescription( "preserve links" ).create( ); m_force = OPTION_BUILDER.withShortName( "f" ).withLongName( "force" ) .withDescription( "remove existing destinations, never prompt" ) .create( ); m_interactive = OPTION_BUILDER.withShortName( "i" ).withLongName( "interactive" ) .withDescription( "prompt before overwrite" ) .create( ); m_link = OPTION_BUILDER.withShortName( "l" ).withLongName( "link" ) .withDescription( "link files instead of copying" ) .create( ); m_preserve = OPTION_BUILDER.withShortName( "p" ).withLongName( "preserve" ) .withDescription( "preserve file attributes if possible" ) .create( ); m_parents = OPTION_BUILDER.withShortName( "P" ).withLongName( "parents" ) .withDescription( "append source path to DIRECTORY" ) .create( ); m_recursive1 = OPTION_BUILDER.withShortName( "r" ) .withDescription( "copy recursively, non-directories as files" ) .create( ); m_sparse = OPTION_BUILDER.withLongName( "sparse" ) .withDescription( "control creation of sparse files" ) .withArgument( ARGUMENT_BUILDER.withName( "WHEN" ) .withMinimum( 1 ).withMaximum( 1 ) .withInitialSeparator( '=' ) .create( ) ).create( ); m_recursive2 = OPTION_BUILDER.withShortName( "R" ).withLongName( "recursive" ) .withDescription( "copy directories recursively" ) .create( ); m_symbolicLink = OPTION_BUILDER.withShortName( "s" ) .withLongName( "symbolic-link" ) .withDescription( "make symbolic links instead of copying" ) .create( ); m_suffix = OPTION_BUILDER.withShortName( "S" ).withLongName( "suffix" ) .withDescription( "override the usual backup suffix" ) .withArgument( ARGUMENT_BUILDER.withName( "SUFFIX" ) .withMinimum( 1 ).withMaximum( 1 ) .create( ) ).create( ); m_update = OPTION_BUILDER.withShortName( "u" ).withLongName( "update" ) .withDescription( "copy only when the SOURCE file is newer than the destination file or when the destination file is missing" ) .create( ); m_verbose = OPTION_BUILDER.withShortName( "v" ).withLongName( "verbose" ) .withDescription( "explain what is being done" ) .create( ); m_versionControl = OPTION_BUILDER.withShortName( "V" ) .withLongName( "version-contol" ) .withDescription( "explain what is being done" ) .withArgument( ARGUMENT_BUILDER.withName( "WORD" ) .withInitialSeparator( '=' ) .withMinimum( 1 ) .withMaximum( 1 ) .create( ) ).create( ); m_oneFileSystem = OPTION_BUILDER.withShortName( "x" ) .withLongName( "one-file-system" ) .withDescription( "stay on this file system" ) .create( ); m_help = OPTION_BUILDER.withLongName( "help" ) .withDescription( "display this help and exit" ).create( ); m_version = OPTION_BUILDER.withLongName( "version" ) .withDescription( "output version information and exit" ) .create( ); m_options = GROUP_BUILDER.withOption( m_archive ).withOption( m_backup ) .withOption( m_noDereference ).withOption( m_force ) .withOption( m_interactive ).withOption( m_link ) .withOption( m_preserve ).withOption( m_parents ) .withOption( m_recursive1 ).withOption( m_sparse ) .withOption( m_recursive2 ).withOption( m_symbolicLink ) .withOption( m_suffix ).withOption( m_update ) .withOption( m_verbose ).withOption( m_versionControl ) .withOption( m_oneFileSystem ).withOption( m_help ) .withOption( m_version ).withOption( m_targets ) .withName( "OPTIONS" ).create( ); } /** * DOCUMENT ME! */ public void testNoSource( ) { Parser parser = new Parser( ); parser.setGroup( m_options ); try { parser.parse( new String[0] ); } catch( OptionException mve ) { assertEquals( "Missing value(s) SOURCE [SOURCE ...]", mve.getMessage( ) ); } } /** * DOCUMENT ME! * * @throws OptionException DOCUMENT ME! */ public void testOneSource( ) throws OptionException { final String[] args = new String[]{"source1", "dest1"}; final Parser parser = new Parser( ); parser.setGroup( m_options ); final CommandLine commandLine = parser.parse( args ); assertTrue( commandLine.getValues( m_source ).contains( "source1" ) ); assertEquals( 1, commandLine.getValues( m_source ).size( ) ); assertTrue( commandLine.getValues( m_dest ).contains( "dest1" ) ); assertEquals( 1, commandLine.getValues( m_dest ).size( ) ); } /** * DOCUMENT ME! * * @throws OptionException DOCUMENT ME! */ public void testMultiSource( ) throws OptionException { final String[] args = new String[] { "source1", "source2", "source3", "dest1" }; final Parser parser = new Parser( ); parser.setGroup( m_options ); final CommandLine commandLine = parser.parse( args ); assertTrue( commandLine.getValues( m_source ).contains( "source1" ) ); assertTrue( commandLine.getValues( m_source ).contains( "source2" ) ); assertTrue( commandLine.getValues( m_source ).contains( "source3" ) ); assertEquals( 3, commandLine.getValues( m_source ).size( ) ); assertTrue( commandLine.getValues( m_dest ).contains( "dest1" ) ); assertEquals( 1, commandLine.getValues( m_dest ).size( ) ); } /** * DOCUMENT ME! * * @throws IOException DOCUMENT ME! */ public void testHelp( ) throws IOException { final StringWriter out = new StringWriter( ); final HelpFormatter helpFormatter = new HelpFormatter( ); helpFormatter.setGroup( m_options ); helpFormatter.setPrintWriter( new PrintWriter( out ) ); helpFormatter.print( ); final BufferedReader in = new BufferedReader( new StringReader( out.toString( ) ) ); assertEquals( "Usage: ", in.readLine( ) ); assertEquals( " [-a -b -d -f -i -l -p -P -r --sparse <WHEN> -R -s -S <SUFFIX> -u -v -V <WORD> ", in.readLine( ) ); assertEquals( "-x --help --version] <SOURCE1> [<SOURCE2> ...] <DEST> ", in.readLine( ) ); assertEquals( "OPTIONS ", in.readLine( ) ); assertEquals( " -a (--archive) same as -dpR ", in.readLine( ) ); assertEquals( " -b (--backup) make backup before removal ", in.readLine( ) ); assertEquals( " -d (--no-dereference) preserve links ", in.readLine( ) ); assertEquals( " -f (--force) remove existing destinations, never prompt ", in.readLine( ) ); assertEquals( " -i (--interactive) prompt before overwrite ", in.readLine( ) ); assertEquals( " -l (--link) link files instead of copying ", in.readLine( ) ); assertEquals( " -p (--preserve) preserve file attributes if possible ", in.readLine( ) ); assertEquals( " -P (--parents) append source path to DIRECTORY ", in.readLine( ) ); assertEquals( " -r copy recursively, non-directories as files ", in.readLine( ) ); assertEquals( " --sparse WHEN control creation of sparse files ", in.readLine( ) ); assertEquals( " -R (--recursive) copy directories recursively ", in.readLine( ) ); assertEquals( " -s (--symbolic-link) make symbolic links instead of copying ", in.readLine( ) ); assertEquals( " -S (--suffix) SUFFIX override the usual backup suffix ", in.readLine( ) ); assertEquals( " -u (--update) copy only when the SOURCE file is newer than ", in.readLine( ) ); assertEquals( " the destination file or when the destination ", in.readLine( ) ); assertEquals( " file is missing ", in.readLine( ) ); assertEquals( " -v (--verbose) explain what is being done ", in.readLine( ) ); assertEquals( " -V (--version-contol) WORD explain what is being done ", in.readLine( ) ); assertEquals( " -x (--one-file-system) stay on this file system ", in.readLine( ) ); assertEquals( " --help display this help and exit ", in.readLine( ) ); assertEquals( " --version output version information and exit ", in.readLine( ) ); assertEquals( " SOURCE [SOURCE ...] ", in.readLine( ) ); assertEquals( " DEST ", in.readLine( ) ); assertNull( in.readLine( ) ); } }
UTF-8
Java
17,711
java
CpTest.java
Java
[ { "context": "Apache Software Foundation\r\n * Copyright 2005-2006 Stephen McConnell, The Digital Product Management Laboratory\r\n *\r\n ", "end": 100, "score": 0.9997594952583313, "start": 83, "tag": "NAME", "value": "Stephen McConnell" }, { "context": " regular file. * </pre>\r\n * </pre>\r\n *\r\n * @author Rob Oxspring\r\n * @author John Keyes\r\n */\r\npublic class CpTest ", "end": 3889, "score": 0.9998597502708435, "start": 3877, "tag": "NAME", "value": "Rob Oxspring" }, { "context": " * </pre>\r\n *\r\n * @author Rob Oxspring\r\n * @author John Keyes\r\n */\r\npublic class CpTest extends TestCase\r\n{\r\n ", "end": 3912, "score": 0.9998540282249451, "start": 3902, "tag": "NAME", "value": "John Keyes" } ]
null
[]
/** * Copyright 2003-2004 The Apache Software Foundation * Copyright 2005-2006 <NAME>, The Digital Product Management Laboratory * * 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 dpml.cli.application; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import dpml.cli.Argument; import dpml.cli.CommandLine; import dpml.cli.Group; import dpml.cli.Option; import dpml.cli.OptionException; import dpml.cli.builder.ArgumentBuilder; import dpml.cli.builder.DefaultOptionBuilder; import dpml.cli.builder.GroupBuilder; import dpml.cli.commandline.Parser; import dpml.cli.option.ArgumentImpl; import dpml.cli.option.SourceDestArgument; import dpml.cli.util.HelpFormatter; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; /** * <p>Test the <code>cp</code> command. Duplicated Option types are not * tested e.g. -a and -d are the same Option type.</p> * * <p>The following is the man output for 'cp'. See * http://www.rt.com/man/cp.1.html.</p> * * <pre> * CP(1) FSF CP(1) * * NAME cp - copy files and directories * * SYNOPSIS cp [OPTION]... SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY * * DESCRIPTION Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. * * -a, --archive same as -dpR * * -b, --backup make backup before removal * * -d, --no-dereference preserve links * * -f, --force remove existing destinations, never prompt * * -i, --interactive prompt before overwrite * * -l, --link link files instead of copying * * -p, --preserve preserve file attributes if possible * * -P, --parents append source path to DIRECTORY * -r copy recursively, non-directories as files * * --sparse=WHEN control creation of sparse files * * -R, --recursive copy directories recursively * * -s, --symbolic-link make symbolic links instead of copying * * -S, --suffix=SUFFIX override the usual backup suffix * * -u, --update copy only when the SOURCE file is newer than the destination file or when the destination file is missing * * -v, --verbose explain what is being done * * -V, --version-control=WORD override the usual version control * * -x, --one-file-system stay on this file system * * --help display this help and exit * * --version output version information and exit * * By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file when- ever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. * * The backup suffix is ~, unless set with SIMPLE_BACKUP_SUF- FIX. The version control may be set with VERSION_CONTROL, values are: * t, numbered make numbered backups * * nil, existing numbered if numbered backups exist, simple other- wise * * never, simple always make simple backups * * As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. * </pre> * </pre> * * @author <NAME> * @author <NAME> */ public class CpTest extends TestCase { /** Option Builder */ private static final DefaultOptionBuilder OPTION_BUILDER = new DefaultOptionBuilder( ); /** Argument Builder */ private static final ArgumentBuilder ARGUMENT_BUILDER = new ArgumentBuilder( ); /** Group Builder */ private static final GroupBuilder GROUP_BUILDER = new GroupBuilder( ); private Group m_options; private ArgumentImpl m_source; private ArgumentImpl m_dest; private Argument m_targets; private Option m_archive; private Option m_backup; private Option m_noDereference; private Option m_force; private Option m_interactive; private Option m_link; private Option m_preserve; private Option m_parents; private Option m_recursive1; private Option m_sparse; private Option m_recursive2; private Option m_symbolicLink; private Option m_suffix; private Option m_update; private Option m_verbose; private Option m_versionControl; private Option m_oneFileSystem; private Option m_help; private Option m_version; /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public static Test suite( ) { return new TestSuite( CpTest.class ); } /** * DOCUMENT ME! */ public void setUp( ) { m_source = (ArgumentImpl) ARGUMENT_BUILDER.withName( "SOURCE" ).withMinimum( 1 ) .create( ); m_dest = (ArgumentImpl) ARGUMENT_BUILDER.withName( "DEST" ).withMinimum( 1 ) .withMaximum( 1 ).create( ); m_targets = new SourceDestArgument( m_source, m_dest ); m_archive = OPTION_BUILDER.withShortName( "a" ).withLongName( "archive" ) .withDescription( "same as -dpR" ).create( ); m_backup = OPTION_BUILDER.withShortName( "b" ).withLongName( "backup" ) .withDescription( "make backup before removal" ) .create( ); m_noDereference = OPTION_BUILDER.withShortName( "d" ) .withLongName( "no-dereference" ) .withDescription( "preserve links" ).create( ); m_force = OPTION_BUILDER.withShortName( "f" ).withLongName( "force" ) .withDescription( "remove existing destinations, never prompt" ) .create( ); m_interactive = OPTION_BUILDER.withShortName( "i" ).withLongName( "interactive" ) .withDescription( "prompt before overwrite" ) .create( ); m_link = OPTION_BUILDER.withShortName( "l" ).withLongName( "link" ) .withDescription( "link files instead of copying" ) .create( ); m_preserve = OPTION_BUILDER.withShortName( "p" ).withLongName( "preserve" ) .withDescription( "preserve file attributes if possible" ) .create( ); m_parents = OPTION_BUILDER.withShortName( "P" ).withLongName( "parents" ) .withDescription( "append source path to DIRECTORY" ) .create( ); m_recursive1 = OPTION_BUILDER.withShortName( "r" ) .withDescription( "copy recursively, non-directories as files" ) .create( ); m_sparse = OPTION_BUILDER.withLongName( "sparse" ) .withDescription( "control creation of sparse files" ) .withArgument( ARGUMENT_BUILDER.withName( "WHEN" ) .withMinimum( 1 ).withMaximum( 1 ) .withInitialSeparator( '=' ) .create( ) ).create( ); m_recursive2 = OPTION_BUILDER.withShortName( "R" ).withLongName( "recursive" ) .withDescription( "copy directories recursively" ) .create( ); m_symbolicLink = OPTION_BUILDER.withShortName( "s" ) .withLongName( "symbolic-link" ) .withDescription( "make symbolic links instead of copying" ) .create( ); m_suffix = OPTION_BUILDER.withShortName( "S" ).withLongName( "suffix" ) .withDescription( "override the usual backup suffix" ) .withArgument( ARGUMENT_BUILDER.withName( "SUFFIX" ) .withMinimum( 1 ).withMaximum( 1 ) .create( ) ).create( ); m_update = OPTION_BUILDER.withShortName( "u" ).withLongName( "update" ) .withDescription( "copy only when the SOURCE file is newer than the destination file or when the destination file is missing" ) .create( ); m_verbose = OPTION_BUILDER.withShortName( "v" ).withLongName( "verbose" ) .withDescription( "explain what is being done" ) .create( ); m_versionControl = OPTION_BUILDER.withShortName( "V" ) .withLongName( "version-contol" ) .withDescription( "explain what is being done" ) .withArgument( ARGUMENT_BUILDER.withName( "WORD" ) .withInitialSeparator( '=' ) .withMinimum( 1 ) .withMaximum( 1 ) .create( ) ).create( ); m_oneFileSystem = OPTION_BUILDER.withShortName( "x" ) .withLongName( "one-file-system" ) .withDescription( "stay on this file system" ) .create( ); m_help = OPTION_BUILDER.withLongName( "help" ) .withDescription( "display this help and exit" ).create( ); m_version = OPTION_BUILDER.withLongName( "version" ) .withDescription( "output version information and exit" ) .create( ); m_options = GROUP_BUILDER.withOption( m_archive ).withOption( m_backup ) .withOption( m_noDereference ).withOption( m_force ) .withOption( m_interactive ).withOption( m_link ) .withOption( m_preserve ).withOption( m_parents ) .withOption( m_recursive1 ).withOption( m_sparse ) .withOption( m_recursive2 ).withOption( m_symbolicLink ) .withOption( m_suffix ).withOption( m_update ) .withOption( m_verbose ).withOption( m_versionControl ) .withOption( m_oneFileSystem ).withOption( m_help ) .withOption( m_version ).withOption( m_targets ) .withName( "OPTIONS" ).create( ); } /** * DOCUMENT ME! */ public void testNoSource( ) { Parser parser = new Parser( ); parser.setGroup( m_options ); try { parser.parse( new String[0] ); } catch( OptionException mve ) { assertEquals( "Missing value(s) SOURCE [SOURCE ...]", mve.getMessage( ) ); } } /** * DOCUMENT ME! * * @throws OptionException DOCUMENT ME! */ public void testOneSource( ) throws OptionException { final String[] args = new String[]{"source1", "dest1"}; final Parser parser = new Parser( ); parser.setGroup( m_options ); final CommandLine commandLine = parser.parse( args ); assertTrue( commandLine.getValues( m_source ).contains( "source1" ) ); assertEquals( 1, commandLine.getValues( m_source ).size( ) ); assertTrue( commandLine.getValues( m_dest ).contains( "dest1" ) ); assertEquals( 1, commandLine.getValues( m_dest ).size( ) ); } /** * DOCUMENT ME! * * @throws OptionException DOCUMENT ME! */ public void testMultiSource( ) throws OptionException { final String[] args = new String[] { "source1", "source2", "source3", "dest1" }; final Parser parser = new Parser( ); parser.setGroup( m_options ); final CommandLine commandLine = parser.parse( args ); assertTrue( commandLine.getValues( m_source ).contains( "source1" ) ); assertTrue( commandLine.getValues( m_source ).contains( "source2" ) ); assertTrue( commandLine.getValues( m_source ).contains( "source3" ) ); assertEquals( 3, commandLine.getValues( m_source ).size( ) ); assertTrue( commandLine.getValues( m_dest ).contains( "dest1" ) ); assertEquals( 1, commandLine.getValues( m_dest ).size( ) ); } /** * DOCUMENT ME! * * @throws IOException DOCUMENT ME! */ public void testHelp( ) throws IOException { final StringWriter out = new StringWriter( ); final HelpFormatter helpFormatter = new HelpFormatter( ); helpFormatter.setGroup( m_options ); helpFormatter.setPrintWriter( new PrintWriter( out ) ); helpFormatter.print( ); final BufferedReader in = new BufferedReader( new StringReader( out.toString( ) ) ); assertEquals( "Usage: ", in.readLine( ) ); assertEquals( " [-a -b -d -f -i -l -p -P -r --sparse <WHEN> -R -s -S <SUFFIX> -u -v -V <WORD> ", in.readLine( ) ); assertEquals( "-x --help --version] <SOURCE1> [<SOURCE2> ...] <DEST> ", in.readLine( ) ); assertEquals( "OPTIONS ", in.readLine( ) ); assertEquals( " -a (--archive) same as -dpR ", in.readLine( ) ); assertEquals( " -b (--backup) make backup before removal ", in.readLine( ) ); assertEquals( " -d (--no-dereference) preserve links ", in.readLine( ) ); assertEquals( " -f (--force) remove existing destinations, never prompt ", in.readLine( ) ); assertEquals( " -i (--interactive) prompt before overwrite ", in.readLine( ) ); assertEquals( " -l (--link) link files instead of copying ", in.readLine( ) ); assertEquals( " -p (--preserve) preserve file attributes if possible ", in.readLine( ) ); assertEquals( " -P (--parents) append source path to DIRECTORY ", in.readLine( ) ); assertEquals( " -r copy recursively, non-directories as files ", in.readLine( ) ); assertEquals( " --sparse WHEN control creation of sparse files ", in.readLine( ) ); assertEquals( " -R (--recursive) copy directories recursively ", in.readLine( ) ); assertEquals( " -s (--symbolic-link) make symbolic links instead of copying ", in.readLine( ) ); assertEquals( " -S (--suffix) SUFFIX override the usual backup suffix ", in.readLine( ) ); assertEquals( " -u (--update) copy only when the SOURCE file is newer than ", in.readLine( ) ); assertEquals( " the destination file or when the destination ", in.readLine( ) ); assertEquals( " file is missing ", in.readLine( ) ); assertEquals( " -v (--verbose) explain what is being done ", in.readLine( ) ); assertEquals( " -V (--version-contol) WORD explain what is being done ", in.readLine( ) ); assertEquals( " -x (--one-file-system) stay on this file system ", in.readLine( ) ); assertEquals( " --help display this help and exit ", in.readLine( ) ); assertEquals( " --version output version information and exit ", in.readLine( ) ); assertEquals( " SOURCE [SOURCE ...] ", in.readLine( ) ); assertEquals( " DEST ", in.readLine( ) ); assertNull( in.readLine( ) ); } }
17,690
0.524081
0.520863
399
42.38847
37.343452
356
false
false
0
0
0
0
0
0
0.503759
false
false
13
a80062383029a39327911c5dc89632c371a30eec
10,969,346,482,878
741cbecde787991cd1b768172a213d3c00fe0f9e
/src/main/java/com/example/ordermanagementsystemapi/api/OrderController.java
bc77e28627a164559257f5910a1442814f7ca8dd
[]
no_license
krsmll/kn-order-management-system-api
https://github.com/krsmll/kn-order-management-system-api
08af409fb079beec1e55366ef0800e58d33730c5
ccc1573cd95c9c84ebe5dea45333850c39571697
refs/heads/main
2023-08-26T20:07:22.111000
2021-10-11T00:51:29
2021-10-11T00:51:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.ordermanagementsystemapi.api; import com.example.ordermanagementsystemapi.dto.OrderDto; import com.example.ordermanagementsystemapi.model.Order; import com.example.ordermanagementsystemapi.services.OrderService; import lombok.NoArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Date; import java.util.List; import java.util.stream.Collectors; @RestController @RequestMapping("/api/orders") @NoArgsConstructor public class OrderController { @Autowired private OrderService orderService; @RequestMapping(value = "", method = RequestMethod.GET, produces = {"application/json"}) @ResponseStatus(HttpStatus.OK) public @ResponseBody List<OrderDto> getAllOrders() { return this.orderService.getAll().stream().map(OrderDto::new).collect(Collectors.toList()); } @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = {"application/json"}) @ResponseStatus(HttpStatus.OK) public @ResponseBody OrderDto getOrderById(@PathVariable long id) { return new OrderDto(this.orderService.getOrder(id)); } @RequestMapping(value = "/customer/{id}", method = RequestMethod.GET, produces = {"application/json"}) @ResponseStatus(HttpStatus.OK) public @ResponseBody List<OrderDto> getOrdersByCustomer(@PathVariable long id) { return this.orderService.getOrdersByCustomer(id).stream().map(OrderDto::new).collect(Collectors.toList()); } @RequestMapping(value = "/product/{id}", method = RequestMethod.GET, produces = {"application/json"}) @ResponseStatus(HttpStatus.OK) public @ResponseBody List<OrderDto> getOrdersByProduct(@PathVariable long id) { return this.orderService.getOrdersByProduct(id).stream().map(OrderDto::new).collect(Collectors.toList()); } @RequestMapping(value = "/date/{date}", method = RequestMethod.GET, produces = {"application/json"}) @ResponseStatus(HttpStatus.OK) public @ResponseBody List<OrderDto> getOrdersByDate(@PathVariable @DateTimeFormat(pattern="yyyy-MM-dd") Date date) { return this.orderService.getOrdersByDate(date).stream().map(OrderDto::new).collect(Collectors.toList()); } @RequestMapping(value = "", method = RequestMethod.POST, consumes = {"application/json"}, produces = {"application/json"}) @ResponseStatus(HttpStatus.CREATED) public OrderDto createOrder(@RequestBody OrderDto order, HttpServletRequest request, HttpServletResponse response) { Order createdOrder = this.orderService.createOrder(order); response.setHeader("Location", request.getRequestURL().append("/").append(createdOrder.getId()).toString()); return new OrderDto(createdOrder); } @RequestMapping(value = "", method = RequestMethod.PUT, consumes = {"application/json"}, produces = {"application/json"}) @ResponseStatus(HttpStatus.OK) public OrderDto updateOrder(@RequestBody OrderDto order, HttpServletRequest request, HttpServletResponse response) { Order updatedOrder = this.orderService.updateOrder(order); response.setHeader("Location", request.getRequestURL().append("/").append(updatedOrder.getId()).toString()); return new OrderDto(updatedOrder); } }
UTF-8
Java
3,697
java
OrderController.java
Java
[]
null
[]
package com.example.ordermanagementsystemapi.api; import com.example.ordermanagementsystemapi.dto.OrderDto; import com.example.ordermanagementsystemapi.model.Order; import com.example.ordermanagementsystemapi.services.OrderService; import lombok.NoArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Date; import java.util.List; import java.util.stream.Collectors; @RestController @RequestMapping("/api/orders") @NoArgsConstructor public class OrderController { @Autowired private OrderService orderService; @RequestMapping(value = "", method = RequestMethod.GET, produces = {"application/json"}) @ResponseStatus(HttpStatus.OK) public @ResponseBody List<OrderDto> getAllOrders() { return this.orderService.getAll().stream().map(OrderDto::new).collect(Collectors.toList()); } @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = {"application/json"}) @ResponseStatus(HttpStatus.OK) public @ResponseBody OrderDto getOrderById(@PathVariable long id) { return new OrderDto(this.orderService.getOrder(id)); } @RequestMapping(value = "/customer/{id}", method = RequestMethod.GET, produces = {"application/json"}) @ResponseStatus(HttpStatus.OK) public @ResponseBody List<OrderDto> getOrdersByCustomer(@PathVariable long id) { return this.orderService.getOrdersByCustomer(id).stream().map(OrderDto::new).collect(Collectors.toList()); } @RequestMapping(value = "/product/{id}", method = RequestMethod.GET, produces = {"application/json"}) @ResponseStatus(HttpStatus.OK) public @ResponseBody List<OrderDto> getOrdersByProduct(@PathVariable long id) { return this.orderService.getOrdersByProduct(id).stream().map(OrderDto::new).collect(Collectors.toList()); } @RequestMapping(value = "/date/{date}", method = RequestMethod.GET, produces = {"application/json"}) @ResponseStatus(HttpStatus.OK) public @ResponseBody List<OrderDto> getOrdersByDate(@PathVariable @DateTimeFormat(pattern="yyyy-MM-dd") Date date) { return this.orderService.getOrdersByDate(date).stream().map(OrderDto::new).collect(Collectors.toList()); } @RequestMapping(value = "", method = RequestMethod.POST, consumes = {"application/json"}, produces = {"application/json"}) @ResponseStatus(HttpStatus.CREATED) public OrderDto createOrder(@RequestBody OrderDto order, HttpServletRequest request, HttpServletResponse response) { Order createdOrder = this.orderService.createOrder(order); response.setHeader("Location", request.getRequestURL().append("/").append(createdOrder.getId()).toString()); return new OrderDto(createdOrder); } @RequestMapping(value = "", method = RequestMethod.PUT, consumes = {"application/json"}, produces = {"application/json"}) @ResponseStatus(HttpStatus.OK) public OrderDto updateOrder(@RequestBody OrderDto order, HttpServletRequest request, HttpServletResponse response) { Order updatedOrder = this.orderService.updateOrder(order); response.setHeader("Location", request.getRequestURL().append("/").append(updatedOrder.getId()).toString()); return new OrderDto(updatedOrder); } }
3,697
0.707601
0.707601
92
39.184784
32.062756
120
false
false
0
0
0
0
0
0
0.521739
false
false
13
618ffddbd9487f51f3efc357368e0e042df9d916
2,319,282,380,220
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_56e57ba15c1fc8d06b064c2711d1c8a56b3899d6/DeeCompletionProposalCollector/2_56e57ba15c1fc8d06b064c2711d1c8a56b3899d6_DeeCompletionProposalCollector_s.java
9503aace8e8e9fe01eb1af8489519ecdf3a91557
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
package mmrnmhrm.ui.editor.codeassist; import static melnorme.utilbox.core.Assert.AssertNamespace.assertFail; import mmrnmhrm.ui.DeePluginImages; import mmrnmhrm.ui.views.DeeElementImageProvider; import org.dsource.ddt.ide.core.DeeNature; import org.eclipse.dltk.core.CompletionProposal; import org.eclipse.dltk.core.IScriptProject; import org.eclipse.dltk.core.ISourceModule; import org.eclipse.dltk.ui.text.completion.IScriptCompletionProposal; import org.eclipse.dltk.ui.text.completion.ScriptCompletionProposal; import org.eclipse.dltk.ui.text.completion.ScriptCompletionProposalCollector; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.Image; import dtool.ast.definitions.DefUnit; public class DeeCompletionProposalCollector extends ScriptCompletionProposalCollector { protected final static char[] VAR_TRIGGER = { ' ', '=', ';', '.' }; @Override protected String getNatureId() { return DeeNature.NATURE_ID; } @Override protected char[] getVarTrigger() { return VAR_TRIGGER; } public DeeCompletionProposalCollector(ISourceModule module) { super(module); } @Override public void accept(CompletionProposal proposal) { super.accept(proposal); } // Most of ScriptCompletionProposalCollector functionality is overridden here @Override protected IScriptCompletionProposal createScriptCompletionProposal(CompletionProposal proposal) { if(proposal.getExtraInfo() instanceof DefUnit) { DefUnit defUnit = (DefUnit) proposal.getExtraInfo(); String completion = proposal.getCompletion(); int repStart = proposal.getReplaceStart(); int repLength = proposal.getReplaceEnd() - proposal.getReplaceStart(); Image image = createImage(proposal, defUnit); String displayString = defUnit.toStringForCodeCompletion(); DeeCompletionProposal completionProposal = new DeeCompletionProposal(completion, repStart, repLength, image, displayString, defUnit, null); completionProposal.setTriggerCharacters(getVarTrigger()); return completionProposal; } else { return super.createScriptCompletionProposal(proposal); } } protected Image createImage(CompletionProposal proposal, DefUnit defUnit) { ImageDescriptor imageDesc = getLabelProvider().createImageDescriptor(proposal); if(imageDesc != null) { return DeePluginImages.getImageDescriptorRegistry().get(imageDesc); } else { // ATM, some types of proposals have images that only DeeElementImageProvider can provide return DeeElementImageProvider.getNodeImage(defUnit); } } @Override protected ScriptCompletionProposal createScriptCompletionProposal(String completion, int replaceStart, int length, Image image, String displayString, int i) { throw assertFail(); // return new DeeCompletionProposal(completion, replaceStart, length, image, displayString, i); } @Override protected ScriptCompletionProposal createScriptCompletionProposal(String completion, int replaceStart, int length, Image image, String displayString, int i, boolean isInDoc) { throw assertFail(); // return new DeeCompletionProposal(completion, replaceStart, length, image, displayString, i, isInDoc); } @Override protected ScriptCompletionProposal createOverrideCompletionProposal( IScriptProject scriptProject, ISourceModule compilationUnit, String name, String[] paramTypes, int start, int length, String displayName, String completionProposal) { throw assertFail(); // return new ExamplePythonOverrideCompletionProposal(scriptProject, compilationUnit, // name, paramTypes, start, length, displayName, completionProposal); } }
UTF-8
Java
3,828
java
2_56e57ba15c1fc8d06b064c2711d1c8a56b3899d6_DeeCompletionProposalCollector_s.java
Java
[]
null
[]
package mmrnmhrm.ui.editor.codeassist; import static melnorme.utilbox.core.Assert.AssertNamespace.assertFail; import mmrnmhrm.ui.DeePluginImages; import mmrnmhrm.ui.views.DeeElementImageProvider; import org.dsource.ddt.ide.core.DeeNature; import org.eclipse.dltk.core.CompletionProposal; import org.eclipse.dltk.core.IScriptProject; import org.eclipse.dltk.core.ISourceModule; import org.eclipse.dltk.ui.text.completion.IScriptCompletionProposal; import org.eclipse.dltk.ui.text.completion.ScriptCompletionProposal; import org.eclipse.dltk.ui.text.completion.ScriptCompletionProposalCollector; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.Image; import dtool.ast.definitions.DefUnit; public class DeeCompletionProposalCollector extends ScriptCompletionProposalCollector { protected final static char[] VAR_TRIGGER = { ' ', '=', ';', '.' }; @Override protected String getNatureId() { return DeeNature.NATURE_ID; } @Override protected char[] getVarTrigger() { return VAR_TRIGGER; } public DeeCompletionProposalCollector(ISourceModule module) { super(module); } @Override public void accept(CompletionProposal proposal) { super.accept(proposal); } // Most of ScriptCompletionProposalCollector functionality is overridden here @Override protected IScriptCompletionProposal createScriptCompletionProposal(CompletionProposal proposal) { if(proposal.getExtraInfo() instanceof DefUnit) { DefUnit defUnit = (DefUnit) proposal.getExtraInfo(); String completion = proposal.getCompletion(); int repStart = proposal.getReplaceStart(); int repLength = proposal.getReplaceEnd() - proposal.getReplaceStart(); Image image = createImage(proposal, defUnit); String displayString = defUnit.toStringForCodeCompletion(); DeeCompletionProposal completionProposal = new DeeCompletionProposal(completion, repStart, repLength, image, displayString, defUnit, null); completionProposal.setTriggerCharacters(getVarTrigger()); return completionProposal; } else { return super.createScriptCompletionProposal(proposal); } } protected Image createImage(CompletionProposal proposal, DefUnit defUnit) { ImageDescriptor imageDesc = getLabelProvider().createImageDescriptor(proposal); if(imageDesc != null) { return DeePluginImages.getImageDescriptorRegistry().get(imageDesc); } else { // ATM, some types of proposals have images that only DeeElementImageProvider can provide return DeeElementImageProvider.getNodeImage(defUnit); } } @Override protected ScriptCompletionProposal createScriptCompletionProposal(String completion, int replaceStart, int length, Image image, String displayString, int i) { throw assertFail(); // return new DeeCompletionProposal(completion, replaceStart, length, image, displayString, i); } @Override protected ScriptCompletionProposal createScriptCompletionProposal(String completion, int replaceStart, int length, Image image, String displayString, int i, boolean isInDoc) { throw assertFail(); // return new DeeCompletionProposal(completion, replaceStart, length, image, displayString, i, isInDoc); } @Override protected ScriptCompletionProposal createOverrideCompletionProposal( IScriptProject scriptProject, ISourceModule compilationUnit, String name, String[] paramTypes, int start, int length, String displayName, String completionProposal) { throw assertFail(); // return new ExamplePythonOverrideCompletionProposal(scriptProject, compilationUnit, // name, paramTypes, start, length, displayName, completionProposal); } }
3,828
0.749216
0.749216
101
35.90099
32.620987
116
false
false
0
0
0
0
0
0
2.346535
false
false
13
411c5b8c5056c84da17cb3114c8afa1ceaee40c3
23,356,032,204,473
d0fd4d8ed31e401cd3f51f91c2606074535b3b84
/src/main/java/chapter3/stacks/MyQueue.java
3821128659adf9e639b95160c2031e6474c421bd
[]
no_license
mary-gribova/Trains
https://github.com/mary-gribova/Trains
16e1bf25e50211bd4ce3121553382becd1f4459f
ab1f9c3fdac4cea4c0d59b18aec9941eb1fb1d59
refs/heads/master
2021-01-20T21:01:15.496000
2015-01-16T15:25:48
2015-01-16T15:25:48
28,592,219
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package chapter3.stacks; public class MyQueue<T> { private SubStack<T> forPush; private SubStack<T> forPop; public MyQueue() { forPush = new SubStack<T>(Integer.MAX_VALUE); forPop = new SubStack<T>(Integer.MAX_VALUE); } public void add(T value) { if (!forPop.isEmpty()) { toppleAllInAnother(forPop, forPush); } forPush.push(value); } public T get() { if (!forPush.isEmpty()) { toppleAllInAnother(forPush, forPop); } StackElem<T> elem = forPop.pop(); return elem == null ? null : elem.getValue(); } private void toppleAllInAnother(SubStack<T> from, SubStack<T> to) { StackElem<T> cur = from.pop(); while (cur != null) { to.push(cur.getValue()); cur = from.pop(); } } }
UTF-8
Java
719
java
MyQueue.java
Java
[]
null
[]
package chapter3.stacks; public class MyQueue<T> { private SubStack<T> forPush; private SubStack<T> forPop; public MyQueue() { forPush = new SubStack<T>(Integer.MAX_VALUE); forPop = new SubStack<T>(Integer.MAX_VALUE); } public void add(T value) { if (!forPop.isEmpty()) { toppleAllInAnother(forPop, forPush); } forPush.push(value); } public T get() { if (!forPush.isEmpty()) { toppleAllInAnother(forPush, forPop); } StackElem<T> elem = forPop.pop(); return elem == null ? null : elem.getValue(); } private void toppleAllInAnother(SubStack<T> from, SubStack<T> to) { StackElem<T> cur = from.pop(); while (cur != null) { to.push(cur.getValue()); cur = from.pop(); } } }
719
0.650904
0.649513
34
20.147058
17.526672
68
false
false
0
0
0
0
0
0
1.823529
false
false
13
c36cd4fb146c2589ac72f9cece40efc197580fd5
21,723,944,600,565
3eab61449de995fe5b1401212f959649b9d799a2
/src/main/java/com/profesorp/zuulSpringTest/ZuulSpringTestApplication.java
5c4d5595681331c8227dd269ae75d981f00b54d3
[]
no_license
tarsidi-danesh/zuulSpringTest
https://github.com/tarsidi-danesh/zuulSpringTest
ca628cc9bf76fdd00b77e1b6bf7144df36cf9cac
57a82e0aed227e416b0be994c8c052f40e90897e
refs/heads/master
2021-04-19T12:55:23.479000
2019-03-19T09:51:04
2019-03-19T09:51:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.profesorp.zuulSpringTest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.Bean; import com.profesorp.zuulSpringTest.Filters.PostFilter; import com.profesorp.zuulSpringTest.Filters.PreFilter; import com.profesorp.zuulSpringTest.Filters.PreRewriteFilter; import com.profesorp.zuulSpringTest.Filters.RouteURLFilter; @SpringBootApplication @EnableZuulProxy public class ZuulSpringTestApplication { public static void main(String[] args) { SpringApplication.run(ZuulSpringTestApplication.class, args); } @Bean public RouteURLFilter routerFilter() { return new RouteURLFilter(); } @Bean public PreFilter preFilter() { return new PreFilter(); } @Bean public PreRewriteFilter preRewriteFilter() { return new PreRewriteFilter(); } @Bean public PostFilter postFilter() { return new PostFilter(); } }
UTF-8
Java
1,075
java
ZuulSpringTestApplication.java
Java
[]
null
[]
package com.profesorp.zuulSpringTest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.Bean; import com.profesorp.zuulSpringTest.Filters.PostFilter; import com.profesorp.zuulSpringTest.Filters.PreFilter; import com.profesorp.zuulSpringTest.Filters.PreRewriteFilter; import com.profesorp.zuulSpringTest.Filters.RouteURLFilter; @SpringBootApplication @EnableZuulProxy public class ZuulSpringTestApplication { public static void main(String[] args) { SpringApplication.run(ZuulSpringTestApplication.class, args); } @Bean public RouteURLFilter routerFilter() { return new RouteURLFilter(); } @Bean public PreFilter preFilter() { return new PreFilter(); } @Bean public PreRewriteFilter preRewriteFilter() { return new PreRewriteFilter(); } @Bean public PostFilter postFilter() { return new PostFilter(); } }
1,075
0.764651
0.764651
37
28.054054
22.44145
68
false
false
0
0
0
0
0
0
0.540541
false
false
13
42ce5a28bfcff3ac76aed89495b8c5f22ee0754b
33,337,536,171,824
4f92bfad4d823542727ca4545b59e204c02b4750
/app/src/main/java/com/msisuzney/minisoccer/presenter/SpecialNewsPresenter.java
6e2202363b7cfec01ec6d9ffb31401c01d6bbff4
[]
no_license
msisuzney/MiniSoccer
https://github.com/msisuzney/MiniSoccer
702c81965632e70511ea963b0e6f6c6019742193
586a4a70cf14a99f5c8ac19716e491aab46590d8
refs/heads/master
2020-12-23T22:18:55.010000
2017-07-20T13:47:53
2017-07-20T13:47:53
92,565,871
5
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.msisuzney.minisoccer.presenter; import com.hannesdorfmann.mosby3.mvp.MvpBasePresenter; import com.msisuzney.minisoccer.App; import com.msisuzney.minisoccer.DQDApi.model.news.DaoSession; import com.msisuzney.minisoccer.DQDApi.model.specialNews.ArticleSpecial; import com.msisuzney.minisoccer.DQDApi.model.specialNews.ArticleSpecialDao; import com.msisuzney.minisoccer.DQDApi.model.specialNews.SpecialNews; import com.msisuzney.minisoccer.DQDApi.MyRetrofit; import com.msisuzney.minisoccer.view.SpecialNewsView; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by chenxin. * Date: 2017/5/24. * Time: 13:33. */ public class SpecialNewsPresenter extends MvpBasePresenter<SpecialNewsView> { public static final int LOAD_FROM_DB = 0x02; public static final int LOAD_REFRESH = 0x03; public void loadData(int mode) { if (mode == LOAD_FROM_DB) { loadDataFromDB(); } else if (mode == LOAD_REFRESH) { loadDataFromNet(true); } } private void loadDataFromNet(final boolean pullToRefresh) { MyRetrofit.getMyRetrofit().getApiService().getSpecial().enqueue(new Callback<SpecialNews>() { @Override public void onResponse(Call<SpecialNews> call, Response<SpecialNews> response) { if (isViewAttached()) { try { deleteAllDataInDB(); List<ArticleSpecial> articles = response.body().getArticles(); addDataToDB(articles); getView().setData(articles); getView().showContent(); } catch (Exception e) { getView().showError(new Exception("数据解析加载错误"), pullToRefresh); } } } @Override public void onFailure(Call<SpecialNews> call, Throwable t) { if (isViewAttached()) { getView().showError(new Exception("网络请求错误\n请检查网络连接情况后\n点击重新加载"), pullToRefresh); } } }); } private void addDataToDB(List<ArticleSpecial> articles) { DaoSession daoSession = App.getApp().getDaoSession(); ArticleSpecialDao dao = daoSession.getArticleSpecialDao(); for (ArticleSpecial article : articles) { dao.insert(article); } } private void deleteAllDataInDB() { DaoSession daoSession = App.getApp().getDaoSession(); ArticleSpecialDao dao = daoSession.getArticleSpecialDao(); dao.deleteAll(); } private void loadDataFromDB() { DaoSession daoSession = App.getApp().getDaoSession(); ArticleSpecialDao dao = daoSession.getArticleSpecialDao(); List<ArticleSpecial> articles = dao.loadAll(); if (articles.size() <= 0) { loadDataFromNet(false); } else { if (isViewAttached()) { getView().setData(articles); getView().showContent(); } } } }
UTF-8
Java
3,188
java
SpecialNewsPresenter.java
Java
[ { "context": "e com.msisuzney.minisoccer.presenter;\n\nimport com.hannesdorfmann.mosby3.mvp.MvpBasePresenter;\nimport com.msisuzney", "end": 70, "score": 0.888302743434906, "start": 56, "tag": "USERNAME", "value": "hannesdorfmann" }, { "context": "ack;\nimport retrofit2.Response;\n\n/**\n * Created by chenxin.\n * Date: 2017/5/24.\n * Time: 13:33.\n */\n\npublic ", "end": 651, "score": 0.9942501187324524, "start": 644, "tag": "USERNAME", "value": "chenxin" } ]
null
[]
package com.msisuzney.minisoccer.presenter; import com.hannesdorfmann.mosby3.mvp.MvpBasePresenter; import com.msisuzney.minisoccer.App; import com.msisuzney.minisoccer.DQDApi.model.news.DaoSession; import com.msisuzney.minisoccer.DQDApi.model.specialNews.ArticleSpecial; import com.msisuzney.minisoccer.DQDApi.model.specialNews.ArticleSpecialDao; import com.msisuzney.minisoccer.DQDApi.model.specialNews.SpecialNews; import com.msisuzney.minisoccer.DQDApi.MyRetrofit; import com.msisuzney.minisoccer.view.SpecialNewsView; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by chenxin. * Date: 2017/5/24. * Time: 13:33. */ public class SpecialNewsPresenter extends MvpBasePresenter<SpecialNewsView> { public static final int LOAD_FROM_DB = 0x02; public static final int LOAD_REFRESH = 0x03; public void loadData(int mode) { if (mode == LOAD_FROM_DB) { loadDataFromDB(); } else if (mode == LOAD_REFRESH) { loadDataFromNet(true); } } private void loadDataFromNet(final boolean pullToRefresh) { MyRetrofit.getMyRetrofit().getApiService().getSpecial().enqueue(new Callback<SpecialNews>() { @Override public void onResponse(Call<SpecialNews> call, Response<SpecialNews> response) { if (isViewAttached()) { try { deleteAllDataInDB(); List<ArticleSpecial> articles = response.body().getArticles(); addDataToDB(articles); getView().setData(articles); getView().showContent(); } catch (Exception e) { getView().showError(new Exception("数据解析加载错误"), pullToRefresh); } } } @Override public void onFailure(Call<SpecialNews> call, Throwable t) { if (isViewAttached()) { getView().showError(new Exception("网络请求错误\n请检查网络连接情况后\n点击重新加载"), pullToRefresh); } } }); } private void addDataToDB(List<ArticleSpecial> articles) { DaoSession daoSession = App.getApp().getDaoSession(); ArticleSpecialDao dao = daoSession.getArticleSpecialDao(); for (ArticleSpecial article : articles) { dao.insert(article); } } private void deleteAllDataInDB() { DaoSession daoSession = App.getApp().getDaoSession(); ArticleSpecialDao dao = daoSession.getArticleSpecialDao(); dao.deleteAll(); } private void loadDataFromDB() { DaoSession daoSession = App.getApp().getDaoSession(); ArticleSpecialDao dao = daoSession.getArticleSpecialDao(); List<ArticleSpecial> articles = dao.loadAll(); if (articles.size() <= 0) { loadDataFromNet(false); } else { if (isViewAttached()) { getView().setData(articles); getView().showContent(); } } } }
3,188
0.612852
0.605818
93
32.634407
26.827118
101
false
false
0
0
0
0
0
0
0.44086
false
false
13
5d02fcce06e2cfe6f54691bafd556f2aa2329fb8
26,860,725,488,013
a671241a80b88cd03fa89c1f2447ce688403f4e6
/JavaSETest/src/com/javase/collections/CollectionTest.java
6838480f4d193d57fc34db3266da4f0cac721c6d
[]
no_license
tonghun/GitRepositories
https://github.com/tonghun/GitRepositories
bb9420e2fd5add67348ec32d97e7643205a05f81
11a34f1df852f63c84d4044207d9678f562875bd
refs/heads/master
2021-01-25T09:26:58.331000
2017-07-19T13:50:59
2017-07-19T13:50:59
93,839,180
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.javase.collections; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; @SuppressWarnings("unused") public class CollectionTest { public void test01() { List<String> strs = new ArrayList<String>(); Iterator<String> iterator = strs.iterator(); ListIterator<String> listIterator = strs.listIterator(); } }
UTF-8
Java
400
java
CollectionTest.java
Java
[]
null
[]
package com.javase.collections; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; @SuppressWarnings("unused") public class CollectionTest { public void test01() { List<String> strs = new ArrayList<String>(); Iterator<String> iterator = strs.iterator(); ListIterator<String> listIterator = strs.listIterator(); } }
400
0.7275
0.7225
16
23
17.652903
58
false
false
0
0
0
0
0
0
1
false
false
13
e3613d33f125f72e354c0259631edf1ac87ef54a
9,929,964,452,654
f85af23c6f69cded44cf4ae7be39b76d4c96f3db
/src/test/java/com/app/creditcard/TransactionValidatorTest.java
9d565d4711d71c46002143871a27d526359f29e2
[]
no_license
arvind3m/jutility
https://github.com/arvind3m/jutility
fc8298afc526cda9fd9de7954841fd649589e8c5
e1e0ab45807bd33cd7ead6972f91d0088786804c
refs/heads/master
2020-02-29T16:32:50.990000
2016-09-16T06:43:50
2016-09-16T06:43:50
13,849,647
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.app.creditcard; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Assert; import org.junit.Test; public class TransactionValidatorTest { @Test public void testValidateTransaction() { String transactions[] = TestUtility.getSampleData(); Calendar transactionDate = Calendar.getInstance(); transactionDate.set(2014, 03, 22); Date date = transactionDate.getTime(); BigDecimal threshold = BigDecimal.valueOf(60.00); Set<String> fraudelentCards = TransactionValidator.validateTransaction(transactions, date, threshold); Assert.assertEquals(1, fraudelentCards.size()); for (String creditCardNumber : fraudelentCards) { Assert.assertEquals("10d7ce2f43e35fa57d1bbf8b1eA", creditCardNumber); } Set<String> fraudelentCards2 = TransactionValidator.validateTransaction(TestUtility.getSampleData2(), date, threshold); Assert.assertEquals(2, fraudelentCards2.size()); List<String> dataList = new ArrayList<String>(); dataList.addAll(fraudelentCards2); Assert.assertEquals("10d7ce2f43e35fa57d1bbf8b1eA", dataList.get(0)); Assert.assertEquals("10d7ce2f43e35fa57d1bbf8b1eC", dataList.get(1)); } @Test public void testGroupByCardNumber() { String datas[] = { "AA,2014-04-29T13:15:54,10.00", "BB,2014-04-29T13:15:54,50.00", "CC,2014-04-22T05:15:54,30.00", "AA,2014-04-22T11:15:54,40.00" }; List<CreditCard> cards = TransactionValidator.getCreditCards(datas); Map<String, List<CreditCard>> groupByCardNumber = TransactionValidator.groupByCardNumber(cards); assertEquals(3, groupByCardNumber.size()); String datas2[] = { "AA,2014-04-29T13:15:54,10.00", "AA,2014-03-29T13:15:54,10.00", "", null }; List<CreditCard> cards2 = TransactionValidator.getCreditCards(datas2); Map<String, List<CreditCard>> groupByCardNumber2 = TransactionValidator.groupByCardNumber(cards2); assertEquals(1, groupByCardNumber2.size()); } @Test public void testGroupAndFilterByDate() { String datas[] = TestUtility.getSampleData(); List<CreditCard> cards = TransactionValidator.getCreditCards(datas); Calendar transactionDate = Calendar.getInstance(); transactionDate.set(2014, 03, 22); Date date = transactionDate.getTime(); Map<Date, List<CreditCard>> groupAndFilterByDate = TransactionValidator.groupAndFilterByDate(cards, date); assertEquals(1, groupAndFilterByDate.size()); Calendar transactionDate2 = Calendar.getInstance(); transactionDate2.set(2014, 03, 21); groupAndFilterByDate = TransactionValidator.groupAndFilterByDate(cards, transactionDate2.getTime()); assertEquals(0, groupAndFilterByDate.size()); groupAndFilterByDate = TransactionValidator.groupAndFilterByDate(cards, null); assertEquals(0, groupAndFilterByDate.size()); } @Test public void testCompareAmount() { String datas[] = TestUtility.getSampleData(); List<CreditCard> cards = TransactionValidator.getCreditCards(datas); Calendar transactionDate = Calendar.getInstance(); transactionDate.set(2014, 03, 22); Date date = transactionDate.getTime(); Map<Date, List<CreditCard>> groupAndFilterByDate = TransactionValidator.groupAndFilterByDate(cards, date); assertEquals(1, groupAndFilterByDate.size()); Set<String> compareAmount = TransactionValidator.compareAmount(groupAndFilterByDate, BigDecimal.valueOf(60.00)); assertEquals(1, compareAmount.size()); compareAmount = TransactionValidator.compareAmount(groupAndFilterByDate, BigDecimal.valueOf(70.00)); assertEquals(0, compareAmount.size()); compareAmount = TransactionValidator.compareAmount(groupAndFilterByDate, BigDecimal.valueOf(71.00)); assertEquals(0, compareAmount.size()); compareAmount = TransactionValidator.compareAmount(groupAndFilterByDate, BigDecimal.valueOf(50.00)); assertEquals(1, compareAmount.size()); } @Test public void testGetCreditCards() { String datas[] = TestUtility.getSampleData(); List<CreditCard> creditCards = TransactionValidator.getCreditCards(datas); assertNotNull(creditCards); assertEquals(4, creditCards.size()); assertEquals("10d7ce2f43e35fa57d1bbf8b1eB", creditCards.get(0).getCardNumber()); assertEquals(BigDecimal.valueOf(40.00), creditCards.get(3).getAmount()); String datas2[] = { "10d7ce2f43e35fa57d1bbf8b1eB,2014-04-29T13:15:54", "10d7ce2f43e35fa57d1bbf8b1eA,2014-04-29,50.00", "10d7ce2f43e35fa57d1bbf8b1eA,2014-04-22T05:15:54,3", "", "10d7ce2f43e35fa57d1bbf8b1eA,2014-04-22T11:15:54,40.00" }; List<CreditCard> creditCards2 = creditCards = TransactionValidator.getCreditCards(datas2); assertNotNull(creditCards2); assertEquals(1, creditCards2.size()); assertEquals("10d7ce2f43e35fa57d1bbf8b1eA", creditCards2.get(0).getCardNumber()); } @Test public void testGetCreditCard() { CreditCard card1 = new CreditCard("10d7ce2f43e35fa57d1bbf8b1eB", Timestamp.valueOf("2014-04-29 13:15:54"), BigDecimal.valueOf(10.00)); assertEquals(card1, TransactionValidator.getCreditCard("10d7ce2f43e35fa57d1bbf8b1eB", "2014-04-29T13:15:54", "10.00")); assertNotEquals(card1, TransactionValidator.getCreditCard("10d7ce2f43e35fa57d1bbf8b1eA", "2014-04-29T13:15:54", "10.00")); assertNotEquals(card1, TransactionValidator.getCreditCard("10d7ce2f43e35fa57d1bbf8b1eB", "2014-04-29T13:15:54", "11.00")); assertNotEquals(card1, TransactionValidator.getCreditCard("10d7ce2f43e35fa57d1bbf8b1eB", "2014-04-29T13:15:53", "10.00")); assertNotEquals(card1, TransactionValidator.getCreditCard("", "", "")); assertNotEquals(card1, TransactionValidator.getCreditCard(null, null, null)); } }
UTF-8
Java
5,955
java
TransactionValidatorTest.java
Java
[ { "context": ": fraudelentCards)\r\n\t\t{\r\n\t\t\tAssert.assertEquals(\"10d7ce2f43e35fa57d1bbf8b1eA\", creditCardNumber);\r\n\t\t}\r\n\r\n\t\tSet<String> fraude", "end": 1047, "score": 0.7300338745117188, "start": 1021, "tag": "KEY", "value": "0d7ce2f43e35fa57d1bbf8b1eA" }, { "context": "ce2f43e35fa57d1bbf8b1eA,2014-04-29,50.00\", \"10d7ce2f43e35fa57d1bbf8b1eA,2014-04-22T05:15:54,3\", \"\",\r\n", "end": 4721, "score": 0.6289835572242737, "start": 4720, "tag": "KEY", "value": "2" }, { "context": "a57d1bbf8b1eA,2014-04-22T05:15:54,3\", \"\",\r\n\t\t\"10d7ce2f43e35fa57d1bbf8b1eA,2014-04-22T11:15:54,40.00\" };", "end": 4781, "score": 0.5612743496894836, "start": 4778, "tag": "KEY", "value": "ce2" }, { "context": "8b1eA,2014-04-22T05:15:54,3\", \"\",\r\n\t\t\"10d7ce2f43e35fa57d1bbf8b1eA,2014-04-22T11:15:54,40.00\" };\r\n\t\tList", "end": 4789, "score": 0.6063774824142456, "start": 4786, "tag": "KEY", "value": "5fa" }, { "context": "2014-04-22T05:15:54,3\", \"\",\r\n\t\t\"10d7ce2f43e35fa57d1bbf8b1eA,2014-04-22T11:15:54,40.00\" };\r\n\t\tList<Cre", "end": 4793, "score": 0.5151094198226929, "start": 4792, "tag": "KEY", "value": "1" }, { "context": "als(1, creditCards2.size());\r\n\t\tassertEquals(\"10d7ce2f43e35fa57d1bbf8b1eA\", creditCards2.get(0).getCardNu", "end": 5027, "score": 0.5971722602844238, "start": 5022, "tag": "KEY", "value": "ce2f4" }, { "context": " creditCards2.size());\r\n\t\tassertEquals(\"10d7ce2f43e35fa57d1bbf8b1eA\", creditCards2.get(0).getCardNumber());\r\n\r\n\t}\r\n\r", "end": 5044, "score": 0.6803379058837891, "start": 5028, "tag": "KEY", "value": "e35fa57d1bbf8b1e" }, { "context": "tCard()\r\n\t{\r\n\t\tCreditCard card1 = new CreditCard(\"10d7ce2f43e35fa57d1bbf8b1eB\", Timestamp.valueOf(\"2014-04-29 13:15:54\"), BigDe", "end": 5205, "score": 0.9681627154350281, "start": 5178, "tag": "KEY", "value": "10d7ce2f43e35fa57d1bbf8b1eB" }, { "context": "quals(card1, TransactionValidator.getCreditCard(\"10d7ce2f43e35fa57d1bbf8b1eB\", \"2014-04-29T13:15:54\", \"10.00\"));\r\n\r\n\t\tassertNo", "end": 5364, "score": 0.9754413366317749, "start": 5338, "tag": "KEY", "value": "0d7ce2f43e35fa57d1bbf8b1eB" }, { "context": "Equals(card1, TransactionValidator.getCreditCard(\"10d7ce2f43e35fa57d1bbf8b1eA\", \"2014-04-29T13:15:54\", \"10.00\"));\r\n\t\tassertNotE", "end": 5492, "score": 0.9676327109336853, "start": 5465, "tag": "KEY", "value": "10d7ce2f43e35fa57d1bbf8b1eA" }, { "context": "Equals(card1, TransactionValidator.getCreditCard(\"10d7ce2f43e35fa57d1bbf8b1eB\", \"2014-04-29T13:15:54\", \"11.00\"));\r\n\t\tassertNotE", "end": 5618, "score": 0.9707658290863037, "start": 5591, "tag": "KEY", "value": "10d7ce2f43e35fa57d1bbf8b1eB" }, { "context": "quals(card1, TransactionValidator.getCreditCard(\"10d7ce2f43e35fa57d1bbf8b1eB\", \"2014-04-29T13:15:53\", \"10.0", "end": 5725, "score": 0.9711758494377136, "start": 5718, "tag": "KEY", "value": "0d7ce2f" } ]
null
[]
package com.app.creditcard; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Assert; import org.junit.Test; public class TransactionValidatorTest { @Test public void testValidateTransaction() { String transactions[] = TestUtility.getSampleData(); Calendar transactionDate = Calendar.getInstance(); transactionDate.set(2014, 03, 22); Date date = transactionDate.getTime(); BigDecimal threshold = BigDecimal.valueOf(60.00); Set<String> fraudelentCards = TransactionValidator.validateTransaction(transactions, date, threshold); Assert.assertEquals(1, fraudelentCards.size()); for (String creditCardNumber : fraudelentCards) { Assert.assertEquals("10d7ce2f43e35fa57d1bbf8b1eA", creditCardNumber); } Set<String> fraudelentCards2 = TransactionValidator.validateTransaction(TestUtility.getSampleData2(), date, threshold); Assert.assertEquals(2, fraudelentCards2.size()); List<String> dataList = new ArrayList<String>(); dataList.addAll(fraudelentCards2); Assert.assertEquals("10d7ce2f43e35fa57d1bbf8b1eA", dataList.get(0)); Assert.assertEquals("10d7ce2f43e35fa57d1bbf8b1eC", dataList.get(1)); } @Test public void testGroupByCardNumber() { String datas[] = { "AA,2014-04-29T13:15:54,10.00", "BB,2014-04-29T13:15:54,50.00", "CC,2014-04-22T05:15:54,30.00", "AA,2014-04-22T11:15:54,40.00" }; List<CreditCard> cards = TransactionValidator.getCreditCards(datas); Map<String, List<CreditCard>> groupByCardNumber = TransactionValidator.groupByCardNumber(cards); assertEquals(3, groupByCardNumber.size()); String datas2[] = { "AA,2014-04-29T13:15:54,10.00", "AA,2014-03-29T13:15:54,10.00", "", null }; List<CreditCard> cards2 = TransactionValidator.getCreditCards(datas2); Map<String, List<CreditCard>> groupByCardNumber2 = TransactionValidator.groupByCardNumber(cards2); assertEquals(1, groupByCardNumber2.size()); } @Test public void testGroupAndFilterByDate() { String datas[] = TestUtility.getSampleData(); List<CreditCard> cards = TransactionValidator.getCreditCards(datas); Calendar transactionDate = Calendar.getInstance(); transactionDate.set(2014, 03, 22); Date date = transactionDate.getTime(); Map<Date, List<CreditCard>> groupAndFilterByDate = TransactionValidator.groupAndFilterByDate(cards, date); assertEquals(1, groupAndFilterByDate.size()); Calendar transactionDate2 = Calendar.getInstance(); transactionDate2.set(2014, 03, 21); groupAndFilterByDate = TransactionValidator.groupAndFilterByDate(cards, transactionDate2.getTime()); assertEquals(0, groupAndFilterByDate.size()); groupAndFilterByDate = TransactionValidator.groupAndFilterByDate(cards, null); assertEquals(0, groupAndFilterByDate.size()); } @Test public void testCompareAmount() { String datas[] = TestUtility.getSampleData(); List<CreditCard> cards = TransactionValidator.getCreditCards(datas); Calendar transactionDate = Calendar.getInstance(); transactionDate.set(2014, 03, 22); Date date = transactionDate.getTime(); Map<Date, List<CreditCard>> groupAndFilterByDate = TransactionValidator.groupAndFilterByDate(cards, date); assertEquals(1, groupAndFilterByDate.size()); Set<String> compareAmount = TransactionValidator.compareAmount(groupAndFilterByDate, BigDecimal.valueOf(60.00)); assertEquals(1, compareAmount.size()); compareAmount = TransactionValidator.compareAmount(groupAndFilterByDate, BigDecimal.valueOf(70.00)); assertEquals(0, compareAmount.size()); compareAmount = TransactionValidator.compareAmount(groupAndFilterByDate, BigDecimal.valueOf(71.00)); assertEquals(0, compareAmount.size()); compareAmount = TransactionValidator.compareAmount(groupAndFilterByDate, BigDecimal.valueOf(50.00)); assertEquals(1, compareAmount.size()); } @Test public void testGetCreditCards() { String datas[] = TestUtility.getSampleData(); List<CreditCard> creditCards = TransactionValidator.getCreditCards(datas); assertNotNull(creditCards); assertEquals(4, creditCards.size()); assertEquals("10d7ce2f43e35fa57d1bbf8b1eB", creditCards.get(0).getCardNumber()); assertEquals(BigDecimal.valueOf(40.00), creditCards.get(3).getAmount()); String datas2[] = { "10d7ce2f43e35fa57d1bbf8b1eB,2014-04-29T13:15:54", "10d7ce2f43e35fa57d1bbf8b1eA,2014-04-29,50.00", "10d7ce2f43e35fa57d1bbf8b1eA,2014-04-22T05:15:54,3", "", "10d7ce2f43e35fa57d1bbf8b1eA,2014-04-22T11:15:54,40.00" }; List<CreditCard> creditCards2 = creditCards = TransactionValidator.getCreditCards(datas2); assertNotNull(creditCards2); assertEquals(1, creditCards2.size()); assertEquals("10d7ce2f43e35fa57d1bbf8b1eA", creditCards2.get(0).getCardNumber()); } @Test public void testGetCreditCard() { CreditCard card1 = new CreditCard("10d7ce2f43e35fa57d1bbf8b1eB", Timestamp.valueOf("2014-04-29 13:15:54"), BigDecimal.valueOf(10.00)); assertEquals(card1, TransactionValidator.getCreditCard("10d7ce2f43e35fa57d1bbf8b1eB", "2014-04-29T13:15:54", "10.00")); assertNotEquals(card1, TransactionValidator.getCreditCard("10d7ce2f43e35fa57d1bbf8b1eA", "2014-04-29T13:15:54", "10.00")); assertNotEquals(card1, TransactionValidator.getCreditCard("10d7ce2f43e35fa57d1bbf8b1eB", "2014-04-29T13:15:54", "11.00")); assertNotEquals(card1, TransactionValidator.getCreditCard("10d7ce2f43e35fa57d1bbf8b1eB", "2014-04-29T13:15:53", "10.00")); assertNotEquals(card1, TransactionValidator.getCreditCard("", "", "")); assertNotEquals(card1, TransactionValidator.getCreditCard(null, null, null)); } }
5,955
0.755668
0.664987
150
37.686668
39.334488
177
false
false
0
0
0
0
0
0
2.306667
false
false
13
35c77ad5fc890619513238e901845676cc5c534c
51,539,637,396
72a7d36b1812869ee6e7b6f8af817a52e8e4e082
/yapin-api/src/main/java/com/lf/yapin/cms/service/MemberReportService.java
9ad88d4e4a6556ebb8eb8004232258c3b6cefd8e
[]
no_license
genuinefun/yapin-mall-admin
https://github.com/genuinefun/yapin-mall-admin
92a9a09c0c8bbd1e246e29c0e8b7d843f31f63b9
748dc228595dbbb21fb7cadbcb48fbccbee4429a
refs/heads/master
2022-07-12T19:51:19.457000
2020-03-20T15:43:59
2020-03-20T15:43:59
246,858,054
0
0
null
false
2022-06-21T03:01:36
2020-03-12T14:41:22
2020-03-20T15:45:14
2022-06-21T03:01:33
27,622
0
0
1
Java
false
false
package com.lf.yapin.cms.service; import com.lf.yapin.cms.entity.MemberReport; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 用户举报表 服务类 * </p> * * @author lf * @since 2020-03-12 */ public interface MemberReportService extends IService<MemberReport> { }
UTF-8
Java
304
java
MemberReportService.java
Java
[ { "context": "ce;\n\n/**\n * <p>\n * 用户举报表 服务类\n * </p>\n *\n * @author lf\n * @since 2020-03-12\n */\npublic interface MemberR", "end": 189, "score": 0.9992804527282715, "start": 187, "tag": "USERNAME", "value": "lf" } ]
null
[]
package com.lf.yapin.cms.service; import com.lf.yapin.cms.entity.MemberReport; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 用户举报表 服务类 * </p> * * @author lf * @since 2020-03-12 */ public interface MemberReportService extends IService<MemberReport> { }
304
0.722222
0.694444
16
17
21.598612
69
false
false
0
0
0
0
0
0
0.1875
false
false
13
c9a5aa8cbeef8ddb7a98288fddf7626d2e902fa7
29,695,403,928,082
6d1a2d9df9145ff1b25668fa9d1be3bf7306be7d
/src/ServiceLocator/ServeiPagament.java
db6bef22ebd0a444621e30ab6c789823bc245c39
[]
no_license
clarita/AS-Llu-s-i-Clara
https://github.com/clarita/AS-Llu-s-i-Clara
4fe6cc452fbaccac70b59c3152b2ce89c5b3afcd
082be4f5c48c44560898634bc6d468cc53277d62
refs/heads/master
2021-01-23T08:52:33.080000
2012-01-15T17:12:37
2012-01-15T17:12:37
3,145,027
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ServiceLocator; import java.util.Date; /** * * @author elena */ public class ServeiPagament { public String Id; public ServeiPagament(){}; public boolean autoritza(String numTarg, Date dCad, float preuTotal, Date d) { //throw new UnsupportedOperationException("Not yet implemented"); return true; } }
UTF-8
Java
466
java
ServeiPagament.java
Java
[ { "context": "ocator;\n\nimport java.util.Date;\n\n/**\n *\n * @author elena\n */\npublic class ServeiPagament {\n public Stri", "end": 172, "score": 0.9982553720474243, "start": 167, "tag": "USERNAME", "value": "elena" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ServiceLocator; import java.util.Date; /** * * @author elena */ public class ServeiPagament { public String Id; public ServeiPagament(){}; public boolean autoritza(String numTarg, Date dCad, float preuTotal, Date d) { //throw new UnsupportedOperationException("Not yet implemented"); return true; } }
466
0.65236
0.65236
24
18.416666
22.466488
82
false
false
0
0
0
0
0
0
0.458333
false
false
13
37ec1aac59b13e5554413d74833b09606ba6568e
6,451,040,923,305
b9dbccc72b440f4d595673e29b43566842499dda
/src/instructions/base/ClassInitLogic.java
61cb74d21a10a7f6bb32895f7cf38858c4894977
[]
no_license
hervewenjie/Hava
https://github.com/hervewenjie/Hava
92a299089a3890ed4c419678417761296afd8349
420e5082047a4ee27284ec92a633b515534f9420
refs/heads/master
2020-07-28T15:46:21.247000
2016-10-17T03:23:26
2016-10-17T03:23:26
67,907,582
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package instructions.base; import heap._Class; import heap._Method; import rtdata.Frame; import rtdata._Thread; public class ClassInitLogic { public static void initClass(_Thread thread,_Class _class){ _class.startInit(); scheduleClinit(thread, _class); initSuperClass(thread, _class); } public static void scheduleClinit(_Thread thread,_Class _class){ _Method clinit=_class.getClinitMethod(); if(clinit!=null){ Frame newFrame=thread.newFrame(clinit); thread.pushFrame(newFrame); } } public static void initSuperClass(_Thread thread,_Class _class){ if(!_class.isInterface()){ _Class superClass=_class.getSuperClass(); if(superClass!=null && !superClass.initStarted()){ initClass(thread, superClass); } } } }
UTF-8
Java
753
java
ClassInitLogic.java
Java
[]
null
[]
package instructions.base; import heap._Class; import heap._Method; import rtdata.Frame; import rtdata._Thread; public class ClassInitLogic { public static void initClass(_Thread thread,_Class _class){ _class.startInit(); scheduleClinit(thread, _class); initSuperClass(thread, _class); } public static void scheduleClinit(_Thread thread,_Class _class){ _Method clinit=_class.getClinitMethod(); if(clinit!=null){ Frame newFrame=thread.newFrame(clinit); thread.pushFrame(newFrame); } } public static void initSuperClass(_Thread thread,_Class _class){ if(!_class.isInterface()){ _Class superClass=_class.getSuperClass(); if(superClass!=null && !superClass.initStarted()){ initClass(thread, superClass); } } } }
753
0.719788
0.719788
30
24.1
19.940495
65
false
false
0
0
0
0
0
0
2.033333
false
false
13
53e49379238abe8ff1f0c8607e5c949a6e6a6c76
20,822,001,518,901
88f5fc8ce1662a456a6fb69693ffcf8f606bbd6f
/src/java/visitor/VisitorClient.java
ad0c4608e855783dd321f387160a19250bbc0879
[]
no_license
echisan/design-patterns-note
https://github.com/echisan/design-patterns-note
fd5c1262b03fd04a8da22580849cbe0080270bce
ec2edd2e93ac7a5c0ff1cecf8833b5524fc968f4
refs/heads/master
2020-04-27T00:40:40.865000
2019-03-10T07:42:42
2019-03-10T07:42:42
173,941,605
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package visitor; public class VisitorClient { public static void main(String[] args) { Visitor visitor = new ConcreteVisitor(); Element ea = new ElementA(); ea.accept(visitor); Element eb = new ElementB(); eb.accept(visitor); } }
UTF-8
Java
282
java
VisitorClient.java
Java
[]
null
[]
package visitor; public class VisitorClient { public static void main(String[] args) { Visitor visitor = new ConcreteVisitor(); Element ea = new ElementA(); ea.accept(visitor); Element eb = new ElementB(); eb.accept(visitor); } }
282
0.602837
0.602837
14
19.142857
17.373449
48
false
false
0
0
0
0
0
0
0.428571
false
false
13
543764f0c44b9569cfe860d091858a099de65c86
22,909,355,622,707
82539396c76ed55d85af653861b6ebf2d186e084
/Toy_project/src/main/java/com/alpha/toy/shop/mapper/ShopSQLMapper.java
c17908ffdef9c80bc084e8a7bee13d4e8e07b72c
[]
no_license
kyggg/toy_project
https://github.com/kyggg/toy_project
6d4bdb00fa82f109941f35b509e8f0b67c6131ce
fd8737d4b79da354b81553a77b9403c723133909
refs/heads/main
2023-08-15T09:06:36.156000
2021-10-01T07:08:31
2021-10-01T07:08:31
412,363,429
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.alpha.toy.shop.mapper; import java.util.ArrayList; import org.apache.ibatis.annotations.Param; import com.alpha.toy.vo.ToyBuyVo; import com.alpha.toy.vo.ToyProductVo; import com.alpha.toy.vo.ToyShopLikeVo; import com.alpha.toy.vo.ToyShopVo; public interface ShopSQLMapper { //총 가게 수 public int getShopCount(@Param("page_num") int page_num); //가게 등록하기 public void shopRegister(ToyShopVo vo); //가게관리 목록 public ArrayList<ToyShopVo> getShopList(@Param("page_num") int page_num); //가게 상세 보기 public ToyShopVo getShopByNo(int shop_no); //가게 삭제 public void deleteShop(int shop_no); //가게 수정 public void updateShop(ToyShopVo vo); //상품 등록 public void productRegister(ToyProductVo vo); //상품 목록 ArrayList<ToyProductVo> getProductList(ToyProductVo vo); ArrayList<ToyProductVo> getProductList2(ToyProductVo vo); //상품 상세 보기 public ToyProductVo getProductByNo(int shop_no); //물품 구매 public void buyProduct(ToyBuyVo vo); //남은 수량 - 구매 수량 0보다 커야 된다... public int canBuy(ToyBuyVo vo); //상점 찜하기 public void setLike(ToyShopLikeVo vo); public void deleteLike(ToyShopLikeVo vo); public ToyShopLikeVo getLike(ToyShopLikeVo vo); public int countLike(int shop_no); //구매내역------------------------------------- ToyProductVo purchaseProduct(int product_no); ArrayList<ToyBuyVo> purchaseBuy(int member_no); //찜목록보기 ArrayList<ToyShopLikeVo> likeList(int member_no); ToyShopVo likeShopInfo(int shop_no); }
UTF-8
Java
1,608
java
ShopSQLMapper.java
Java
[]
null
[]
package com.alpha.toy.shop.mapper; import java.util.ArrayList; import org.apache.ibatis.annotations.Param; import com.alpha.toy.vo.ToyBuyVo; import com.alpha.toy.vo.ToyProductVo; import com.alpha.toy.vo.ToyShopLikeVo; import com.alpha.toy.vo.ToyShopVo; public interface ShopSQLMapper { //총 가게 수 public int getShopCount(@Param("page_num") int page_num); //가게 등록하기 public void shopRegister(ToyShopVo vo); //가게관리 목록 public ArrayList<ToyShopVo> getShopList(@Param("page_num") int page_num); //가게 상세 보기 public ToyShopVo getShopByNo(int shop_no); //가게 삭제 public void deleteShop(int shop_no); //가게 수정 public void updateShop(ToyShopVo vo); //상품 등록 public void productRegister(ToyProductVo vo); //상품 목록 ArrayList<ToyProductVo> getProductList(ToyProductVo vo); ArrayList<ToyProductVo> getProductList2(ToyProductVo vo); //상품 상세 보기 public ToyProductVo getProductByNo(int shop_no); //물품 구매 public void buyProduct(ToyBuyVo vo); //남은 수량 - 구매 수량 0보다 커야 된다... public int canBuy(ToyBuyVo vo); //상점 찜하기 public void setLike(ToyShopLikeVo vo); public void deleteLike(ToyShopLikeVo vo); public ToyShopLikeVo getLike(ToyShopLikeVo vo); public int countLike(int shop_no); //구매내역------------------------------------- ToyProductVo purchaseProduct(int product_no); ArrayList<ToyBuyVo> purchaseBuy(int member_no); //찜목록보기 ArrayList<ToyShopLikeVo> likeList(int member_no); ToyShopVo likeShopInfo(int shop_no); }
1,608
0.725962
0.724588
66
21.060606
20.616909
74
false
false
0
0
0
0
0
0
1.166667
false
false
13
35589f22e1bb120f54360582305a58c6c0094f53
15,891,379,004,000
08909272d5599af7a89a470efd9ab067c120a8dc
/src/pithreads/examples/tutorial/tut3/async/Reader.java
6aa3a5691347f9bad2e5943fdb00808553ab7697
[ "MIT" ]
permissive
kstewart83/javapi
https://github.com/kstewart83/javapi
e00f01f52955f79730dfec375d827a385cf6d833
842d8fa04323bd887ea1ff007a99e7e10ebed7a9
refs/heads/master
2021-01-10T07:59:51.650000
2012-03-01T14:37:13
2012-03-01T14:37:13
48,659,689
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pithreads.examples.tutorial.tut3.async; import pithreads.framework.PiChannel; import pithreads.framework.RunException; import pithreads.framework.Task; public class Reader extends Task { private PiChannel<String> take; public Reader(PiChannel<String> take) { this.take = take; } @Override public void body() throws RunException { while(true) { String msg = receive(take); log("received: "+msg); } } }
UTF-8
Java
433
java
Reader.java
Java
[]
null
[]
package pithreads.examples.tutorial.tut3.async; import pithreads.framework.PiChannel; import pithreads.framework.RunException; import pithreads.framework.Task; public class Reader extends Task { private PiChannel<String> take; public Reader(PiChannel<String> take) { this.take = take; } @Override public void body() throws RunException { while(true) { String msg = receive(take); log("received: "+msg); } } }
433
0.734411
0.732102
21
19.619047
16.634663
47
false
false
0
0
0
0
0
0
1.333333
false
false
13
3d4c83ea9a002a73379ee3f8ccbc41037e519c70
22,256,520,536,832
4003b6ab1f83179c0eb744d2182c1a21aefbfeec
/tessera-core/src/main/java/com/quorum/tessera/core/api/ServiceFactoryImpl.java
0b61c92a18b3ef45aae09df70442cabde830ee8b
[ "Apache-2.0" ]
permissive
amanshr1729/tessera
https://github.com/amanshr1729/tessera
7ebc15720c111c6aa101403c063c8a7a126fbba2
02a51f82a16f108088a065d810a9ea986b27359f
refs/heads/master
2022-04-25T02:54:38.292000
2020-04-27T15:07:10
2020-04-27T15:07:10
259,633,917
2
0
NOASSERTION
true
2020-04-28T12:43:08
2020-04-28T12:43:07
2020-04-27T15:07:15
2020-04-28T12:42:45
162,048
0
0
0
null
false
false
package com.quorum.tessera.core.api; import com.quorum.tessera.enclave.Enclave; import com.quorum.tessera.partyinfo.PartyInfoService; import com.quorum.tessera.service.locator.ServiceLocator; import com.quorum.tessera.data.EncryptedRawTransactionDAO; import com.quorum.tessera.data.EncryptedTransactionDAO; import com.quorum.tessera.partyinfo.PartyInfoServiceFactory; import com.quorum.tessera.partyinfo.PayloadPublisher; import com.quorum.tessera.partyinfo.ResendManager; import com.quorum.tessera.transaction.TransactionManager; public class ServiceFactoryImpl implements ServiceFactory { private final ServiceLocator serviceLocator = ServiceLocator.create(); private final PartyInfoServiceFactory partyInfoServiceFactory = PartyInfoServiceFactory.create(); public ServiceFactoryImpl() {} @Override public PartyInfoService partyInfoService() { return partyInfoServiceFactory.partyInfoService(); } @Override public Enclave enclave() { return find(Enclave.class); } public <T> T find(Class<T> type) { return serviceLocator.getServices().stream() .filter(type::isInstance) .map(type::cast) .findAny() .orElseThrow(() -> new IllegalStateException("Unable to find service type :" + type)); } @Override public TransactionManager transactionManager() { return find(TransactionManager.class); } @Override public EncryptedTransactionDAO encryptedTransactionDAO() { return find(EncryptedTransactionDAO.class); } @Override public EncryptedRawTransactionDAO encryptedRawTransactionDAO() { return find(EncryptedRawTransactionDAO.class); } @Override public ResendManager resendManager() { return partyInfoServiceFactory.resendManager(); } @Override public PayloadPublisher payloadPublisher() { return partyInfoServiceFactory.payloadPublisher(); } }
UTF-8
Java
1,982
java
ServiceFactoryImpl.java
Java
[]
null
[]
package com.quorum.tessera.core.api; import com.quorum.tessera.enclave.Enclave; import com.quorum.tessera.partyinfo.PartyInfoService; import com.quorum.tessera.service.locator.ServiceLocator; import com.quorum.tessera.data.EncryptedRawTransactionDAO; import com.quorum.tessera.data.EncryptedTransactionDAO; import com.quorum.tessera.partyinfo.PartyInfoServiceFactory; import com.quorum.tessera.partyinfo.PayloadPublisher; import com.quorum.tessera.partyinfo.ResendManager; import com.quorum.tessera.transaction.TransactionManager; public class ServiceFactoryImpl implements ServiceFactory { private final ServiceLocator serviceLocator = ServiceLocator.create(); private final PartyInfoServiceFactory partyInfoServiceFactory = PartyInfoServiceFactory.create(); public ServiceFactoryImpl() {} @Override public PartyInfoService partyInfoService() { return partyInfoServiceFactory.partyInfoService(); } @Override public Enclave enclave() { return find(Enclave.class); } public <T> T find(Class<T> type) { return serviceLocator.getServices().stream() .filter(type::isInstance) .map(type::cast) .findAny() .orElseThrow(() -> new IllegalStateException("Unable to find service type :" + type)); } @Override public TransactionManager transactionManager() { return find(TransactionManager.class); } @Override public EncryptedTransactionDAO encryptedTransactionDAO() { return find(EncryptedTransactionDAO.class); } @Override public EncryptedRawTransactionDAO encryptedRawTransactionDAO() { return find(EncryptedRawTransactionDAO.class); } @Override public ResendManager resendManager() { return partyInfoServiceFactory.resendManager(); } @Override public PayloadPublisher payloadPublisher() { return partyInfoServiceFactory.payloadPublisher(); } }
1,982
0.729062
0.729062
63
30.460318
26.991371
102
false
false
0
0
0
0
0
0
0.31746
false
false
13
7fb7cb89464f213b59d7374b5ff338d60b2d626f
22,256,520,538,035
8740730743dae9763976805c2fa272fd08a5fd81
/ProjectEuler/src/Problem2.java
09b919b2fac1ab71356e62570550d0efb67533a6
[]
no_license
ThomasLewis1028/CS2133
https://github.com/ThomasLewis1028/CS2133
c9bfd43393b5b2f88560cb1449e110031329e326
b727c4dcf6bee8a2f1304acbb5bc4c762dcf485a
refs/heads/master
2020-03-27T06:36:00.761000
2018-08-25T18:21:12
2018-08-25T18:21:12
146,118,376
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Problem2 { public static void main(String[] args) { long fib1 = 1; long fib2 = 1; long fibEvenSum = 0; long fibTotal = 0; while (fibTotal < 4000000) { fibTotal = fib1 + fib2; fib1 = fib2; fib2 = fibTotal; if ((fibTotal % 2) == 0) { fibEvenSum += fibTotal; } } System.out.println(fibEvenSum); } }
UTF-8
Java
347
java
Problem2.java
Java
[]
null
[]
public class Problem2 { public static void main(String[] args) { long fib1 = 1; long fib2 = 1; long fibEvenSum = 0; long fibTotal = 0; while (fibTotal < 4000000) { fibTotal = fib1 + fib2; fib1 = fib2; fib2 = fibTotal; if ((fibTotal % 2) == 0) { fibEvenSum += fibTotal; } } System.out.println(fibEvenSum); } }
347
0.596542
0.536023
20
16.35
12.471066
41
false
false
0
0
0
0
0
0
2.2
false
false
13
9feaa1b811511e3ca379d7b716df3a144ac819a3
30,683,246,369,987
ac82c44a91362f66d49c9ffa2f798b9a47e75ab4
/yagi/src/main/java/org/raml/yagi/framework/grammar/rule/ArrayRule.java
f106a1cadd38bb62da575058fe496ba4013c9eb3
[ "Apache-2.0" ]
permissive
raml-org/raml-java-parser
https://github.com/raml-org/raml-java-parser
0d07a5b61211dc4c7b255b3e05094f8577ce3cfb
d2935eb7eec3aee4b5badd644d51f14e09eadb3d
refs/heads/master
2023-08-29T01:04:55.495000
2022-02-12T14:27:47
2022-02-12T14:27:47
11,036,770
148
135
NOASSERTION
false
2020-06-09T10:37:39
2013-06-28T20:09:34
2020-06-08T18:52:17
2020-06-09T10:37:38
5,514
169
133
140
Java
false
false
/* * Copyright 2013 (c) MuleSoft, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package org.raml.yagi.framework.grammar.rule; import org.raml.yagi.framework.nodes.ArrayNode; import org.raml.yagi.framework.nodes.Node; import org.raml.yagi.framework.nodes.NodeType; import org.raml.yagi.framework.nodes.NullNodeImpl; import org.raml.yagi.framework.suggester.ParsingContext; import org.raml.yagi.framework.suggester.ParsingContextType; import org.raml.yagi.framework.suggester.Suggestion; import org.raml.yagi.framework.util.NodeUtils; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ArrayRule extends Rule { private Rule of; private boolean strict = false; public ArrayRule(Rule of) { this.of = of; } public ArrayRule(Rule of, boolean strict) { this.of = of; this.strict = strict; } public Rule of() { return of; } public void of(Rule of) { this.of = of; } @Nonnull @Override public List<Suggestion> getSuggestions(Node node, ParsingContext context) { // Array does not have any children then we need to create a dummy one and inject into the tree final NullNodeImpl nullNode = new NullNodeImpl(); node.addChild(nullNode); final List<Suggestion> suggestions = of.getSuggestions(nullNode, context); final List<Suggestion> result = new ArrayList<>(); for (Suggestion suggestion : suggestions) { if (node instanceof ArrayNode && !((ArrayNode) node).isJsonStyle()) { result.add(suggestion); } else if (context.getContextType() == ParsingContextType.VALUE) { final String prefix = "\n" + NodeUtils.computeColumnForChild(node.getParent()); result.add(suggestion.withValue("- " + suggestion.getValue()).withPrefix(prefix)); } else { result.add(suggestion.withValue("- " + suggestion.getValue())); } } return result; } @Override public List<Suggestion> getSuggestions(List<Node> pathToRoot, ParsingContext context) { if (pathToRoot.isEmpty()) { return Collections.emptyList(); } else { final Node mappingNode = pathToRoot.get(0); switch (pathToRoot.size()) { case 1: return getSuggestions(mappingNode, context); default: return of.getSuggestions(pathToRoot.subList(1, pathToRoot.size()), context); } } } @Override public List<Rule> getChildren() { return Collections.singletonList(of); } @Override public boolean matches(@Nonnull Node node) { boolean matches = node instanceof ArrayNode; if (matches && strict) { for (Node child : node.getChildren()) { if (!of.matches(child)) { return false; } } } return matches; } @Override public Node apply(@Nonnull Node node) { if (!matches(node)) { return ErrorNodeFactory.createInvalidType(node, NodeType.Array); } else { Node result = createNodeUsingFactory(node); final List<Node> children = node.getChildren(); for (Node child : children) { if (of.matches(child)) { final Node transform = of.apply(child); child.replaceWith(transform); } else { child.replaceWith(ErrorNodeFactory.createInvalidArrayElement(child)); } } return result; } } @Override public String getDescription() { return "Array[" + of.getDescription() + "]"; } }
UTF-8
Java
4,631
java
ArrayRule.java
Java
[]
null
[]
/* * Copyright 2013 (c) MuleSoft, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package org.raml.yagi.framework.grammar.rule; import org.raml.yagi.framework.nodes.ArrayNode; import org.raml.yagi.framework.nodes.Node; import org.raml.yagi.framework.nodes.NodeType; import org.raml.yagi.framework.nodes.NullNodeImpl; import org.raml.yagi.framework.suggester.ParsingContext; import org.raml.yagi.framework.suggester.ParsingContextType; import org.raml.yagi.framework.suggester.Suggestion; import org.raml.yagi.framework.util.NodeUtils; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ArrayRule extends Rule { private Rule of; private boolean strict = false; public ArrayRule(Rule of) { this.of = of; } public ArrayRule(Rule of, boolean strict) { this.of = of; this.strict = strict; } public Rule of() { return of; } public void of(Rule of) { this.of = of; } @Nonnull @Override public List<Suggestion> getSuggestions(Node node, ParsingContext context) { // Array does not have any children then we need to create a dummy one and inject into the tree final NullNodeImpl nullNode = new NullNodeImpl(); node.addChild(nullNode); final List<Suggestion> suggestions = of.getSuggestions(nullNode, context); final List<Suggestion> result = new ArrayList<>(); for (Suggestion suggestion : suggestions) { if (node instanceof ArrayNode && !((ArrayNode) node).isJsonStyle()) { result.add(suggestion); } else if (context.getContextType() == ParsingContextType.VALUE) { final String prefix = "\n" + NodeUtils.computeColumnForChild(node.getParent()); result.add(suggestion.withValue("- " + suggestion.getValue()).withPrefix(prefix)); } else { result.add(suggestion.withValue("- " + suggestion.getValue())); } } return result; } @Override public List<Suggestion> getSuggestions(List<Node> pathToRoot, ParsingContext context) { if (pathToRoot.isEmpty()) { return Collections.emptyList(); } else { final Node mappingNode = pathToRoot.get(0); switch (pathToRoot.size()) { case 1: return getSuggestions(mappingNode, context); default: return of.getSuggestions(pathToRoot.subList(1, pathToRoot.size()), context); } } } @Override public List<Rule> getChildren() { return Collections.singletonList(of); } @Override public boolean matches(@Nonnull Node node) { boolean matches = node instanceof ArrayNode; if (matches && strict) { for (Node child : node.getChildren()) { if (!of.matches(child)) { return false; } } } return matches; } @Override public Node apply(@Nonnull Node node) { if (!matches(node)) { return ErrorNodeFactory.createInvalidType(node, NodeType.Array); } else { Node result = createNodeUsingFactory(node); final List<Node> children = node.getChildren(); for (Node child : children) { if (of.matches(child)) { final Node transform = of.apply(child); child.replaceWith(transform); } else { child.replaceWith(ErrorNodeFactory.createInvalidArrayElement(child)); } } return result; } } @Override public String getDescription() { return "Array[" + of.getDescription() + "]"; } }
4,631
0.583027
0.580652
164
27.237804
25.295778
103
false
false
0
0
0
0
0
0
0.359756
false
false
13
00a284d8d4598d8765730bd6543ee6528535f8e2
30,683,246,367,011
0335d23fefd35903a7788747e3a45188a45ce177
/app/src/main/java/com/example/nano/sidchat/Tab2.java
842b6e464027e72d500b85d67385718b6ff1d66b
[]
no_license
ajaygosh102/ChatScreen
https://github.com/ajaygosh102/ChatScreen
49239400765e4788158d3dbe03d3733afa4e375d
33d49937739d33a097ea1ee41ebad45bbbeaba96
refs/heads/master
2020-03-13T04:35:49.388000
2018-04-25T07:18:46
2018-04-25T07:18:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.nano.sidchat; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import java.util.ArrayList; public class Tab2 extends Fragment { private ListView listView; private ChatAdapter mAdapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.tab2, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setupTextDetails(view); } private void setupTextDetails(View view) { listView = (ListView)view.findViewById(R.id.movies_list); ArrayList<Chat> moviesList = new ArrayList<>(); moviesList.add(new Chat(R.mipmap.house_karakter, "Edward Livingston" , "Teacher" , "12:30 am")); moviesList.add(new Chat(R.mipmap.house_karakter, "Edward Livingston" , "Teacher", "12:35 am")); moviesList.add(new Chat(R.mipmap.house_karakter, "Edward Livingston" , "Teacher", "12:30 am")); moviesList.add(new Chat(R.mipmap.house_karakter, "Edward Livingston" , "Teacher", "12:30 am")); moviesList.add(new Chat(R.mipmap.house_karakter, "Edward Livingston" , "Teacher", "12:40 am")); moviesList.add(new Chat(R.mipmap.house_karakter, "Edward Livingston" , "Teacher", "12:50 am")); moviesList.add(new Chat(R.mipmap.house_karakter, "Edward Livingston" , "Teacher", "12:30 am")); moviesList.add(new Chat(R.mipmap.house_karakter, "Edward Livingston" , "Teacher", "12:20 am")); moviesList.add(new Chat(R.mipmap.house_karakter, "Edward Livingston" , "Teacher", "12:11 am")); mAdapter = new ChatAdapter(getContext(),moviesList); listView.setAdapter(mAdapter); } }
UTF-8
Java
2,054
java
Tab2.java
Java
[ { "context": "moviesList.add(new Chat(R.mipmap.house_karakter, \"Edward Livingston\" , \"Teacher\" , \"12:30 am\"));\n moviesList.a", "end": 1082, "score": 0.9995797872543335, "start": 1065, "tag": "NAME", "value": "Edward Livingston" }, { "context": "moviesList.add(new Chat(R.mipmap.house_karakter, \"Edward Livingston\" , \"Teacher\", \"12:35 am\"));\n moviesList.ad", "end": 1187, "score": 0.9995783567428589, "start": 1170, "tag": "NAME", "value": "Edward Livingston" }, { "context": "moviesList.add(new Chat(R.mipmap.house_karakter, \"Edward Livingston\" , \"Teacher\", \"12:30 am\"));\n moviesList.ad", "end": 1291, "score": 0.9994381070137024, "start": 1274, "tag": "NAME", "value": "Edward Livingston" }, { "context": "moviesList.add(new Chat(R.mipmap.house_karakter, \"Edward Livingston\" , \"Teacher\", \"12:30 am\"));\n moviesList.ad", "end": 1395, "score": 0.9995602369308472, "start": 1378, "tag": "NAME", "value": "Edward Livingston" }, { "context": "moviesList.add(new Chat(R.mipmap.house_karakter, \"Edward Livingston\" , \"Teacher\", \"12:40 am\"));\n moviesList.ad", "end": 1499, "score": 0.9995033144950867, "start": 1482, "tag": "NAME", "value": "Edward Livingston" }, { "context": "moviesList.add(new Chat(R.mipmap.house_karakter, \"Edward Livingston\" , \"Teacher\", \"12:50 am\"));\n moviesList.ad", "end": 1603, "score": 0.9993671178817749, "start": 1586, "tag": "NAME", "value": "Edward Livingston" }, { "context": "moviesList.add(new Chat(R.mipmap.house_karakter, \"Edward Livingston\" , \"Teacher\", \"12:30 am\"));\n moviesList.ad", "end": 1707, "score": 0.9991718530654907, "start": 1690, "tag": "NAME", "value": "Edward Livingston" }, { "context": "moviesList.add(new Chat(R.mipmap.house_karakter, \"Edward Livingston\" , \"Teacher\", \"12:20 am\"));\n moviesList.ad", "end": 1811, "score": 0.9998931884765625, "start": 1794, "tag": "NAME", "value": "Edward Livingston" }, { "context": "moviesList.add(new Chat(R.mipmap.house_karakter, \"Edward Livingston\" , \"Teacher\", \"12:11 am\"));\n\n mAdapter = n", "end": 1915, "score": 0.999890148639679, "start": 1898, "tag": "NAME", "value": "Edward Livingston" } ]
null
[]
package com.example.nano.sidchat; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import java.util.ArrayList; public class Tab2 extends Fragment { private ListView listView; private ChatAdapter mAdapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.tab2, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setupTextDetails(view); } private void setupTextDetails(View view) { listView = (ListView)view.findViewById(R.id.movies_list); ArrayList<Chat> moviesList = new ArrayList<>(); moviesList.add(new Chat(R.mipmap.house_karakter, "<NAME>" , "Teacher" , "12:30 am")); moviesList.add(new Chat(R.mipmap.house_karakter, "<NAME>" , "Teacher", "12:35 am")); moviesList.add(new Chat(R.mipmap.house_karakter, "<NAME>" , "Teacher", "12:30 am")); moviesList.add(new Chat(R.mipmap.house_karakter, "<NAME>" , "Teacher", "12:30 am")); moviesList.add(new Chat(R.mipmap.house_karakter, "<NAME>" , "Teacher", "12:40 am")); moviesList.add(new Chat(R.mipmap.house_karakter, "<NAME>" , "Teacher", "12:50 am")); moviesList.add(new Chat(R.mipmap.house_karakter, "<NAME>" , "Teacher", "12:30 am")); moviesList.add(new Chat(R.mipmap.house_karakter, "<NAME>" , "Teacher", "12:20 am")); moviesList.add(new Chat(R.mipmap.house_karakter, "<NAME>" , "Teacher", "12:11 am")); mAdapter = new ChatAdapter(getContext(),moviesList); listView.setAdapter(mAdapter); } }
1,955
0.703992
0.685005
51
39.294117
37.780216
104
false
false
0
0
0
0
0
0
1.215686
false
false
13
a4cd5e92d5c25cebf4a6995bdf3c1ef82e3b8684
18,691,697,732,613
7ccf2a616632e3b2b9c69c55fa98e6790161a142
/app/src/main/java/com/example/practice/SelfHelpActivity.java
74d6d1c8de4ebf4ce144f8dfeef270868e158684
[]
no_license
AzizbekRasulmetov/ReadBookApp
https://github.com/AzizbekRasulmetov/ReadBookApp
e38a6a37589afccff3ba0e3884f5c3daea4c049f
10c39f36989be853605decd6e759ceab7154d778
refs/heads/master
2023-02-10T10:24:33.642000
2021-01-13T05:53:25
2021-01-13T05:53:25
329,207,980
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.practice; import android.os.Bundle; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; public class SelfHelpActivity extends AppCompatActivity { private TextView title; private ImageView image; public static final String EXTRA_NAME = "extra"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.book_activity); title = (TextView) findViewById(R.id.title); image = (ImageView) findViewById(R.id.image); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); String extraName = getIntent().getStringExtra(EXTRA_NAME); if(extraName.equals(SelfHelpBook.SELF_HELP_BOOKS[0].toString())){ image.setImageResource(R.drawable.thinkandgrowrich); }else if(extraName.equals(SelfHelpBook.SELF_HELP_BOOKS[1].toString())){ image.setImageResource(R.drawable.powerofhabit); } title.setText(extraName); } }
UTF-8
Java
1,386
java
SelfHelpActivity.java
Java
[]
null
[]
package com.example.practice; import android.os.Bundle; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; public class SelfHelpActivity extends AppCompatActivity { private TextView title; private ImageView image; public static final String EXTRA_NAME = "extra"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.book_activity); title = (TextView) findViewById(R.id.title); image = (ImageView) findViewById(R.id.image); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); String extraName = getIntent().getStringExtra(EXTRA_NAME); if(extraName.equals(SelfHelpBook.SELF_HELP_BOOKS[0].toString())){ image.setImageResource(R.drawable.thinkandgrowrich); }else if(extraName.equals(SelfHelpBook.SELF_HELP_BOOKS[1].toString())){ image.setImageResource(R.drawable.powerofhabit); } title.setText(extraName); } }
1,386
0.722222
0.720779
43
31.232557
24.71685
79
false
false
0
0
0
0
0
0
0.55814
false
false
13
3f9fe57f0bd0d3f1d50633adf7dd3a0f9741bf2e
3,659,312,156,077
6de50a0b598843787a0d621854c44aad4619387f
/src/com/sunyard/cop/IF/spring/websocket/WebSocketHandler.java
c3871023853d3060cc4307867917b1c281231614
[]
no_license
zhangguozhan/WebProject
https://github.com/zhangguozhan/WebProject
6b81a23afa90eeb7f8a525606ab0c279274f0743
b13e5107317716890f81fbd05a500e1c16c5942a
refs/heads/master
2020-06-01T07:02:55.855000
2018-05-19T16:49:13
2018-05-19T16:49:13
94,066,514
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.sunyard.cop.IF.spring.websocket; import java.util.Map; import net.sf.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.BinaryWebSocketHandler; import org.springframework.web.socket.handler.TextWebSocketHandler; /** * 功能说明:WebSocket处理器 * 可以继承 {@link TextWebSocketHandler}/{@link BinaryWebSocketHandler}, * 或者简单的实现{@link WebSocketHandler}接口 * @author YZ * 2017年1月16日 上午10:20:27 */ public class WebSocketHandler extends TextWebSocketHandler{ private Logger logger = LoggerFactory.getLogger(WebSocketHandler.class); /** * 建立连接 * @param session * @throws Exception */ @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { Map map = session.getAttributes(); String webSocketId = (String)map.get("webSocketId"); String loginTag = (String)map.get("loginTag"); if(WebSocketSessionUtils.hasConnection(webSocketId, loginTag)){ WebSocketSessionUtils.sendMessage(webSocketId, loginTag, "您的账号已在其他地点登陆,请注意账号密码安全"); WebSocketSession closeSession = WebSocketSessionUtils.get(webSocketId, loginTag); closeSession.close(); } WebSocketSessionUtils.add(webSocketId, loginTag, session); logger.info(webSocketId+"_"+loginTag+" 加入Websocket连接"); } /** * 收到客户端消息 * @param session * @param message * @throws Exception */ @Override public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { Map map = session.getAttributes(); String webSocketId = (String)map.get("webSocketId"); String loginTag = (String)map.get("loginTag"); String bankNo = (String)map.get("bankNo"); String systemNo = (String)map.get("systemNo"); String projectNo = (String)map.get("projectNo"); String msg=message.getPayload().toString(); JSONObject json = JSONObject.fromObject(msg); String type=json.getString("type"); if("online_".equalsIgnoreCase(type)){ String mes=json.getString("mssage"); WebSocketSessionUtils.sendMessageAllOnline(mes); }else if("chat_one".equalsIgnoreCase(type)){//一对一聊天 String chatTo=json.getString("chatTo"); if(WebSocketSessionUtils.hasConnection(chatTo, "2")||WebSocketSessionUtils.hasConnection(chatTo, "1")){ String chatcontent=json.getString("chatcontent"); String chatId=insertChatHistory(json,bankNo,systemNo,projectNo); json.put("chatId", chatId); if(WebSocketSessionUtils.hasConnection(chatTo, "1")){ WebSocketSessionUtils.sendMessage(chatTo, "1", json.toString()); } if(WebSocketSessionUtils.hasConnection(chatTo, "2")){ WebSocketSessionUtils.sendMessage(chatTo, "2", json.toString()); } }else{//不在线,保存到消息列表(标为未读) insertChatHistory(json,bankNo,systemNo,projectNo); } }else if("chat_group".equalsIgnoreCase(type)){ this.insertGroupHistory(json, bankNo, systemNo, projectNo); } } /** * 出现异常 * @param session * @param exception * @throws Exception */ @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { Map map = session.getAttributes(); String webSocketId = (String)map.get("webSocketId"); String loginTag = (String)map.get("loginTag"); logger.error("Websocket 连接异常: " + WebSocketSessionUtils.getKey(webSocketId, loginTag)); logger.error(exception.getMessage(), exception); WebSocketSessionUtils.remove(webSocketId, loginTag); } /** * 连接关闭 * @param session * @param closeStatus * @throws Exception */ @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { Map map = session.getAttributes(); String webSocketId = (String)map.get("webSocketId"); String loginTag = (String)map.get("loginTag"); WebSocketSessionUtils.remove(webSocketId, loginTag); logger.info(webSocketId+"_"+loginTag+" 断开Websocket连接"); if(WebSocketSessionUtils.hasConnection(webSocketId, "1")||WebSocketSessionUtils.hasConnection(webSocketId, "2")){ }else{ String msg="close_"+webSocketId; if (WebSocketSessionUtils.getSize()!=0){ WebSocketSessionUtils.sendMessageAllOnline(msg); } } } /** * 是否分段发送消息 * @return */ @Override public boolean supportsPartialMessages() { return false; } /**\ * 插入数据库(sm_history_tb)标记消息为未读 * @param json * @param bankNo * @param systemNo * @param projectNo * @return */ private String insertChatHistory(JSONObject json,String bankNo,String systemNo,String projectNo){ // ChatHistory chathistory=new ChatHistory(); // String sendTime=json.getString("sendTime"); // String chatId=sendTime+SunIFCommonUtil.getRandomStrings(10); // chathistory.setChatId(chatId); // chathistory.setChatFrom(json.getString("chatFrom")); // chathistory.setChatTo(json.getString("chatTo")); // chathistory.setChatcontent(json.getString("chatcontent")); // chathistory.setStatus("0"); // chathistory.setSendTime(sendTime); // chathistory.setBankNo(bankNo); // chathistory.setProjectNo(projectNo); // chathistory.setSystemNo(systemNo); // chatHistoryService.insertHistory(chathistory); // return chatId; return json.getString("sendTime")+getRandomStrings(10); } /** * 群消息插入数据库(sm_group_history_tb),将消息发送给群里面其他成员 */ private void insertGroupHistory(JSONObject json,String bankNo,String systemNo,String projectNo){ // GroupHistory groupHistory = new GroupHistory(); // String sendTime=json.getString("sendTime"); // String chatId=sendTime+SunIFCommonUtil.getRandomStrings(10); // groupHistory.setChatId(chatId); // groupHistory.setChatFrom(json.getString("chatFrom")); // groupHistory.setGroupId(json.getString("chatTo")); // groupHistory.setChatContent(json.getString("chatcontent")); // groupHistory.setSendTime(sendTime); // groupHistory.setBankNo(bankNo); // groupHistory.setProjectNo(projectNo); // groupHistory.setSystemNo(systemNo); // grouopHistoryService.insertGroupHistory(groupHistory); } public static String getRandomStrings(int length) { StringBuffer result = new StringBuffer(length); int i = 0; while (i < length) { int f = (int)(Math.random() * 3.0D); if (f == 0) result.append((int)(65.0D + Math.random() * 26.0D)); else if (f == 1) result.append((int)(97.0D + Math.random() * 26.0D)); else { result.append((int)(48.0D + Math.random() * 10.0D)); } i++; } return result.toString(); } }
UTF-8
Java
7,773
java
WebSocketHandler.java
Java
[ { "context": "\r\n * 或者简单的实现{@link WebSocketHandler}接口\r\n * @author YZ\r\n * 2017年1月16日 上午10:20:27\r\n */\r\npublic class Web", "end": 634, "score": 0.9986652731895447, "start": 632, "tag": "USERNAME", "value": "YZ" } ]
null
[]
/** * */ package com.sunyard.cop.IF.spring.websocket; import java.util.Map; import net.sf.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.BinaryWebSocketHandler; import org.springframework.web.socket.handler.TextWebSocketHandler; /** * 功能说明:WebSocket处理器 * 可以继承 {@link TextWebSocketHandler}/{@link BinaryWebSocketHandler}, * 或者简单的实现{@link WebSocketHandler}接口 * @author YZ * 2017年1月16日 上午10:20:27 */ public class WebSocketHandler extends TextWebSocketHandler{ private Logger logger = LoggerFactory.getLogger(WebSocketHandler.class); /** * 建立连接 * @param session * @throws Exception */ @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { Map map = session.getAttributes(); String webSocketId = (String)map.get("webSocketId"); String loginTag = (String)map.get("loginTag"); if(WebSocketSessionUtils.hasConnection(webSocketId, loginTag)){ WebSocketSessionUtils.sendMessage(webSocketId, loginTag, "您的账号已在其他地点登陆,请注意账号密码安全"); WebSocketSession closeSession = WebSocketSessionUtils.get(webSocketId, loginTag); closeSession.close(); } WebSocketSessionUtils.add(webSocketId, loginTag, session); logger.info(webSocketId+"_"+loginTag+" 加入Websocket连接"); } /** * 收到客户端消息 * @param session * @param message * @throws Exception */ @Override public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { Map map = session.getAttributes(); String webSocketId = (String)map.get("webSocketId"); String loginTag = (String)map.get("loginTag"); String bankNo = (String)map.get("bankNo"); String systemNo = (String)map.get("systemNo"); String projectNo = (String)map.get("projectNo"); String msg=message.getPayload().toString(); JSONObject json = JSONObject.fromObject(msg); String type=json.getString("type"); if("online_".equalsIgnoreCase(type)){ String mes=json.getString("mssage"); WebSocketSessionUtils.sendMessageAllOnline(mes); }else if("chat_one".equalsIgnoreCase(type)){//一对一聊天 String chatTo=json.getString("chatTo"); if(WebSocketSessionUtils.hasConnection(chatTo, "2")||WebSocketSessionUtils.hasConnection(chatTo, "1")){ String chatcontent=json.getString("chatcontent"); String chatId=insertChatHistory(json,bankNo,systemNo,projectNo); json.put("chatId", chatId); if(WebSocketSessionUtils.hasConnection(chatTo, "1")){ WebSocketSessionUtils.sendMessage(chatTo, "1", json.toString()); } if(WebSocketSessionUtils.hasConnection(chatTo, "2")){ WebSocketSessionUtils.sendMessage(chatTo, "2", json.toString()); } }else{//不在线,保存到消息列表(标为未读) insertChatHistory(json,bankNo,systemNo,projectNo); } }else if("chat_group".equalsIgnoreCase(type)){ this.insertGroupHistory(json, bankNo, systemNo, projectNo); } } /** * 出现异常 * @param session * @param exception * @throws Exception */ @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { Map map = session.getAttributes(); String webSocketId = (String)map.get("webSocketId"); String loginTag = (String)map.get("loginTag"); logger.error("Websocket 连接异常: " + WebSocketSessionUtils.getKey(webSocketId, loginTag)); logger.error(exception.getMessage(), exception); WebSocketSessionUtils.remove(webSocketId, loginTag); } /** * 连接关闭 * @param session * @param closeStatus * @throws Exception */ @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { Map map = session.getAttributes(); String webSocketId = (String)map.get("webSocketId"); String loginTag = (String)map.get("loginTag"); WebSocketSessionUtils.remove(webSocketId, loginTag); logger.info(webSocketId+"_"+loginTag+" 断开Websocket连接"); if(WebSocketSessionUtils.hasConnection(webSocketId, "1")||WebSocketSessionUtils.hasConnection(webSocketId, "2")){ }else{ String msg="close_"+webSocketId; if (WebSocketSessionUtils.getSize()!=0){ WebSocketSessionUtils.sendMessageAllOnline(msg); } } } /** * 是否分段发送消息 * @return */ @Override public boolean supportsPartialMessages() { return false; } /**\ * 插入数据库(sm_history_tb)标记消息为未读 * @param json * @param bankNo * @param systemNo * @param projectNo * @return */ private String insertChatHistory(JSONObject json,String bankNo,String systemNo,String projectNo){ // ChatHistory chathistory=new ChatHistory(); // String sendTime=json.getString("sendTime"); // String chatId=sendTime+SunIFCommonUtil.getRandomStrings(10); // chathistory.setChatId(chatId); // chathistory.setChatFrom(json.getString("chatFrom")); // chathistory.setChatTo(json.getString("chatTo")); // chathistory.setChatcontent(json.getString("chatcontent")); // chathistory.setStatus("0"); // chathistory.setSendTime(sendTime); // chathistory.setBankNo(bankNo); // chathistory.setProjectNo(projectNo); // chathistory.setSystemNo(systemNo); // chatHistoryService.insertHistory(chathistory); // return chatId; return json.getString("sendTime")+getRandomStrings(10); } /** * 群消息插入数据库(sm_group_history_tb),将消息发送给群里面其他成员 */ private void insertGroupHistory(JSONObject json,String bankNo,String systemNo,String projectNo){ // GroupHistory groupHistory = new GroupHistory(); // String sendTime=json.getString("sendTime"); // String chatId=sendTime+SunIFCommonUtil.getRandomStrings(10); // groupHistory.setChatId(chatId); // groupHistory.setChatFrom(json.getString("chatFrom")); // groupHistory.setGroupId(json.getString("chatTo")); // groupHistory.setChatContent(json.getString("chatcontent")); // groupHistory.setSendTime(sendTime); // groupHistory.setBankNo(bankNo); // groupHistory.setProjectNo(projectNo); // groupHistory.setSystemNo(systemNo); // grouopHistoryService.insertGroupHistory(groupHistory); } public static String getRandomStrings(int length) { StringBuffer result = new StringBuffer(length); int i = 0; while (i < length) { int f = (int)(Math.random() * 3.0D); if (f == 0) result.append((int)(65.0D + Math.random() * 26.0D)); else if (f == 1) result.append((int)(97.0D + Math.random() * 26.0D)); else { result.append((int)(48.0D + Math.random() * 10.0D)); } i++; } return result.toString(); } }
7,773
0.641262
0.634042
201
35.208954
27.991402
130
false
false
0
0
0
0
0
0
1.079602
false
false
13
b38965a65cc534f05ffe1de7ddc8cd609afdb941
27,848,567,964,736
a3f1e6db6809c6904469d49def9b7b19175c3bea
/content/jcr_root/libs/mcm/salesforce/src/impl/src/main/java/com/adobe/cq/mcm/salesforce/SalesforceException.java
0256c4276746797b6a58f5839a18d104a8686d72
[]
no_license
tiennv90/SVN
https://github.com/tiennv90/SVN
bd9f0024df7760db093bb63321946ad017b02203
43b5ae4fe747800fc9cd57180ee741c426668756
refs/heads/master
2020-02-26T07:56:06.467000
2013-10-09T14:16:11
2013-10-09T14:16:11
41,090,927
2
0
null
true
2015-08-20T10:52:22
2015-08-20T10:52:22
2015-02-18T15:47:39
2013-10-09T14:19:37
212,652
0
0
0
null
null
null
/************************************************************************* * * ADOBE CONFIDENTIAL * ___________________ * * Copyright 2012 Adobe Systems Incorporated * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Adobe Systems Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Adobe Systems Incorporated and its * suppliers and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Adobe Systems Incorporated. **************************************************************************/ package com.adobe.cq.mcm.salesforce; import java.lang.Exception; public class SalesforceException extends Exception { static final long serialVersionUID = 548754621; public SalesforceException(String message) { super(message); } public SalesforceException(Throwable cause) { super(cause); } public SalesforceException(String message, Throwable cause) { super(message, cause); } }
UTF-8
Java
1,208
java
SalesforceException.java
Java
[]
null
[]
/************************************************************************* * * ADOBE CONFIDENTIAL * ___________________ * * Copyright 2012 Adobe Systems Incorporated * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Adobe Systems Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Adobe Systems Incorporated and its * suppliers and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Adobe Systems Incorporated. **************************************************************************/ package com.adobe.cq.mcm.salesforce; import java.lang.Exception; public class SalesforceException extends Exception { static final long serialVersionUID = 548754621; public SalesforceException(String message) { super(message); } public SalesforceException(Throwable cause) { super(cause); } public SalesforceException(String message, Throwable cause) { super(message, cause); } }
1,208
0.639073
0.628311
38
30.789474
26.687428
76
false
false
0
0
0
0
0
0
0.263158
false
false
13
f2eed39090ad366b22fc1f63a97d583da07614dd
9,328,668,990,085
7147ddee404cbe64118447c6dec9e1b017261bc1
/src/main/java/jp/co/rerere/process/channel/dto/Channel.java
78b8036b58a1e18b12379523565ab1147508bf67
[]
no_license
iz-j/ReReRe
https://github.com/iz-j/ReReRe
3dbc38a99adbd6dfc4ff6db8c882936e2c11b017
ff5e26dd02cabc0b2b6575774607824493436c77
refs/heads/master
2016-04-01T09:17:09.302000
2015-02-25T09:39:49
2015-02-25T09:39:49
31,001,391
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jp.co.rerere.process.channel.dto; import java.util.ArrayList; import java.util.List; public final class Channel { public Long id; public String name; public Boolean isDefault; public List<String> owners = new ArrayList<>(); @Override public String toString() { return "Channel [id=" + id + ", name=" + name + ", isDefault=" + isDefault + ", owners=" + owners + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((isDefault == null) ? 0 : isDefault.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((owners == null) ? 0 : owners.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; } Channel other = (Channel)obj; if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } if (isDefault == null) { if (other.isDefault != null) { return false; } } else if (!isDefault.equals(other.isDefault)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } if (owners == null) { if (other.owners != null) { return false; } } else if (!owners.equals(other.owners)) { return false; } return true; } }
UTF-8
Java
1,576
java
Channel.java
Java
[]
null
[]
package jp.co.rerere.process.channel.dto; import java.util.ArrayList; import java.util.List; public final class Channel { public Long id; public String name; public Boolean isDefault; public List<String> owners = new ArrayList<>(); @Override public String toString() { return "Channel [id=" + id + ", name=" + name + ", isDefault=" + isDefault + ", owners=" + owners + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((isDefault == null) ? 0 : isDefault.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((owners == null) ? 0 : owners.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; } Channel other = (Channel)obj; if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } if (isDefault == null) { if (other.isDefault != null) { return false; } } else if (!isDefault.equals(other.isDefault)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } if (owners == null) { if (other.owners != null) { return false; } } else if (!owners.equals(other.owners)) { return false; } return true; } }
1,576
0.593909
0.589467
70
21.514286
20.256741
106
false
false
0
0
0
0
0
0
2.3
false
false
13
bed99f1fa68d2c5525ac6227d6498231f100e7d6
16,200,616,667,659
930c38c3becee0da463fdfc3c3e0d232b7fe1e32
/src/main/java/com/leetcode/linkedlist/_ReverseLinkedListii.java
5e1f73af57e254fc74ea4c49d7c1cdca90e40de9
[]
no_license
Jemmm1992/jemmmCode
https://github.com/Jemmm1992/jemmmCode
58920f0de233c75555a444ae2688216ae78bed9a
415b89755959930baebdc674f277cd442cbe0085
refs/heads/master
2020-04-05T14:34:13.597000
2017-09-26T14:42:32
2017-09-26T14:42:32
94,686,638
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.leetcode.linkedlist; /** * Created by xu_zj on 2017/6/28. */ import com.modal.ListNode; /** Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: Given1->2->3->4->5->NULL, m = 2 and n = 4, return1->4->3->2->5->NULL. Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list. */ /**思路: * 第一步是找到m结点所在位置, * 第二步就是进行反转直到n结点。 * 反转的方法就是每读到一个结点,把它插入到m结点前面位置,然后m结点接到读到结点的下一个。 */ public class _ReverseLinkedListii { public ListNode reverseBetween(ListNode head, int m, int n) { if(head == null) return null; ListNode node = new ListNode(0); node.next = head; ListNode preNode = node; int i=1; while(preNode.next!=null && i<m) { preNode = preNode.next; i++; } if(i<m) return head; ListNode p1 = preNode.next; ListNode cur = p1.next; while(cur!=null && i<n) { ListNode next = cur.next; cur.next = preNode.next; preNode.next = cur; p1.next = next; cur = next; i++; } return node.next; } }
UTF-8
Java
1,333
java
_ReverseLinkedListii.java
Java
[ { "context": "ackage com.leetcode.linkedlist;\n\n/**\n * Created by xu_zj on 2017/6/28.\n */\n\nimport com.modal.ListNode;\n\n/*", "end": 57, "score": 0.9995410442352295, "start": 52, "tag": "USERNAME", "value": "xu_zj" } ]
null
[]
package com.leetcode.linkedlist; /** * Created by xu_zj on 2017/6/28. */ import com.modal.ListNode; /** Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: Given1->2->3->4->5->NULL, m = 2 and n = 4, return1->4->3->2->5->NULL. Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list. */ /**思路: * 第一步是找到m结点所在位置, * 第二步就是进行反转直到n结点。 * 反转的方法就是每读到一个结点,把它插入到m结点前面位置,然后m结点接到读到结点的下一个。 */ public class _ReverseLinkedListii { public ListNode reverseBetween(ListNode head, int m, int n) { if(head == null) return null; ListNode node = new ListNode(0); node.next = head; ListNode preNode = node; int i=1; while(preNode.next!=null && i<m) { preNode = preNode.next; i++; } if(i<m) return head; ListNode p1 = preNode.next; ListNode cur = p1.next; while(cur!=null && i<n) { ListNode next = cur.next; cur.next = preNode.next; preNode.next = cur; p1.next = next; cur = next; i++; } return node.next; } }
1,333
0.546915
0.525782
49
23.142857
17.010201
76
false
false
0
0
0
0
0
0
0.489796
false
false
13
25b64b8425a20ed19537d9c577322ca5c2378ff1
25,701,084,323,366
95e380c49b143fb7271254ec2cf7b0f2ba47e616
/ethereum/spec/src/main/java/tech/pegasys/teku/spec/logic/versions/altair/statetransition/epoch/EpochProcessorAltair.java
b2e8e15eef1b10282c1293ff361a737456c02fb6
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
Nashatyrev/artemis
https://github.com/Nashatyrev/artemis
a34515760b8e64c28ca07b7a87b0c3729299e0fc
de2b2801c89ef5abf983d6bf37867c37fc47121f
refs/heads/master
2022-09-17T01:28:08.612000
2022-06-06T14:19:07
2022-06-06T14:19:07
232,340,075
1
0
Apache-2.0
true
2021-04-15T15:49:45
2020-01-07T14:18:44
2020-10-22T22:50:26
2021-04-15T15:49:44
123,612
1
0
0
Java
false
false
/* * Copyright 2021 ConsenSys AG. * * 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 tech.pegasys.teku.spec.logic.versions.altair.statetransition.epoch; import java.util.List; import tech.pegasys.teku.infrastructure.ssz.collections.SszMutableUInt64List; import tech.pegasys.teku.infrastructure.ssz.primitive.SszByte; import tech.pegasys.teku.infrastructure.unsigned.UInt64; import tech.pegasys.teku.spec.config.SpecConfig; import tech.pegasys.teku.spec.config.SpecConfigAltair; import tech.pegasys.teku.spec.datastructures.state.beaconstate.BeaconState; import tech.pegasys.teku.spec.datastructures.state.beaconstate.MutableBeaconState; import tech.pegasys.teku.spec.datastructures.state.beaconstate.versions.altair.BeaconStateAltair; import tech.pegasys.teku.spec.datastructures.state.beaconstate.versions.altair.MutableBeaconStateAltair; import tech.pegasys.teku.spec.logic.common.helpers.BeaconStateMutators; import tech.pegasys.teku.spec.logic.common.statetransition.epoch.AbstractEpochProcessor; import tech.pegasys.teku.spec.logic.common.statetransition.epoch.RewardAndPenaltyDeltas; import tech.pegasys.teku.spec.logic.common.statetransition.epoch.status.ValidatorStatus; import tech.pegasys.teku.spec.logic.common.statetransition.epoch.status.ValidatorStatusFactory; import tech.pegasys.teku.spec.logic.common.statetransition.epoch.status.ValidatorStatuses; import tech.pegasys.teku.spec.logic.common.util.BeaconStateUtil; import tech.pegasys.teku.spec.logic.common.util.ValidatorsUtil; import tech.pegasys.teku.spec.logic.versions.altair.helpers.BeaconStateAccessorsAltair; import tech.pegasys.teku.spec.logic.versions.altair.helpers.MiscHelpersAltair; import tech.pegasys.teku.spec.schemas.SchemaDefinitions; public class EpochProcessorAltair extends AbstractEpochProcessor { private final SpecConfigAltair specConfigAltair; protected final MiscHelpersAltair miscHelpersAltair; protected final BeaconStateAccessorsAltair beaconStateAccessorsAltair; public EpochProcessorAltair( final SpecConfigAltair specConfig, final MiscHelpersAltair miscHelpers, final BeaconStateAccessorsAltair beaconStateAccessors, final BeaconStateMutators beaconStateMutators, final ValidatorsUtil validatorsUtil, final BeaconStateUtil beaconStateUtil, final ValidatorStatusFactory validatorStatusFactory, final SchemaDefinitions schemaDefinitions) { super( specConfig, miscHelpers, beaconStateAccessors, beaconStateMutators, validatorsUtil, beaconStateUtil, validatorStatusFactory, schemaDefinitions); this.specConfigAltair = specConfig; this.miscHelpersAltair = miscHelpers; this.beaconStateAccessorsAltair = beaconStateAccessors; } @Override public RewardAndPenaltyDeltas getRewardAndPenaltyDeltas( final BeaconState genericState, final ValidatorStatuses validatorStatuses) { final BeaconStateAltair state = BeaconStateAltair.required(genericState); final RewardsAndPenaltiesCalculatorAltair calculator = new RewardsAndPenaltiesCalculatorAltair( specConfigAltair, state, validatorStatuses, miscHelpersAltair, beaconStateAccessorsAltair); return calculator.getDeltas(); } /** * Corresponds to process_participation_flag_updates in beacon-chain spec * * @param genericState The state to process * @see <a * href="https://github.com/ethereum/eth2.0-specs/blob/master/specs/altair/beacon-chain.md#participation-flags-updates">Altair * Participation Flags updates</a> */ @Override public void processParticipationUpdates(final MutableBeaconState genericState) { final MutableBeaconStateAltair state = MutableBeaconStateAltair.required(genericState); state.setPreviousEpochParticipation(state.getCurrentEpochParticipation()); // Reset current epoch participation flags state.getCurrentEpochParticipation().clear(); state.getCurrentEpochParticipation().setAll(SszByte.ZERO, state.getValidators().size()); } @Override public void processSyncCommitteeUpdates(final MutableBeaconState genericState) { final UInt64 nextEpoch = beaconStateAccessors.getCurrentEpoch(genericState).increment(); if (nextEpoch.mod(specConfigAltair.getEpochsPerSyncCommitteePeriod()).isZero()) { final MutableBeaconStateAltair state = MutableBeaconStateAltair.required(genericState); state.setCurrentSyncCommittee(state.getNextSyncCommittee()); state.setNextSyncCommittee(beaconStateAccessorsAltair.getNextSyncCommittee(state)); } } @Override public void processInactivityUpdates( final MutableBeaconState baseState, final ValidatorStatuses validatorStatuses) { if (beaconStateAccessors.getCurrentEpoch(baseState).equals(SpecConfig.GENESIS_EPOCH)) { return; } final MutableBeaconStateAltair state = MutableBeaconStateAltair.required(baseState); final SszMutableUInt64List inactivityScores = state.getInactivityScores(); final List<ValidatorStatus> statuses = validatorStatuses.getStatuses(); final boolean isInInactivityLeak = beaconStateAccessors.isInactivityLeak(state); for (int i = 0; i < statuses.size(); i++) { final ValidatorStatus validatorStatus = statuses.get(i); if (!validatorStatus.isEligibleValidator()) { continue; } // Increase inactivity score of inactive validators final UInt64 currentScore = inactivityScores.getElement(i); UInt64 newScore; if (validatorStatus.isNotSlashed() && validatorStatus.isPreviousEpochTargetAttester()) { newScore = currentScore.minusMinZero(1); } else { newScore = currentScore.plus(specConfigAltair.getInactivityScoreBias()); } // Decrease the score of all validators for forgiveness when not during a leak if (!isInInactivityLeak) { newScore = newScore.minusMinZero(specConfigAltair.getInactivityScoreRecoveryRate()); } if (!currentScore.equals(newScore)) { inactivityScores.setElement(i, newScore); } } } @Override protected int getProportionalSlashingMultiplier() { return specConfigAltair.getProportionalSlashingMultiplierAltair(); } }
UTF-8
Java
6,769
java
EpochProcessorAltair.java
Java
[ { "context": "ss\n * @see <a\n * href=\"https://github.com/ethereum/eth2.0-specs/blob/master/specs/altair/beacon-chai", "end": 3992, "score": 0.9548224806785583, "start": 3984, "tag": "USERNAME", "value": "ethereum" } ]
null
[]
/* * Copyright 2021 ConsenSys AG. * * 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 tech.pegasys.teku.spec.logic.versions.altair.statetransition.epoch; import java.util.List; import tech.pegasys.teku.infrastructure.ssz.collections.SszMutableUInt64List; import tech.pegasys.teku.infrastructure.ssz.primitive.SszByte; import tech.pegasys.teku.infrastructure.unsigned.UInt64; import tech.pegasys.teku.spec.config.SpecConfig; import tech.pegasys.teku.spec.config.SpecConfigAltair; import tech.pegasys.teku.spec.datastructures.state.beaconstate.BeaconState; import tech.pegasys.teku.spec.datastructures.state.beaconstate.MutableBeaconState; import tech.pegasys.teku.spec.datastructures.state.beaconstate.versions.altair.BeaconStateAltair; import tech.pegasys.teku.spec.datastructures.state.beaconstate.versions.altair.MutableBeaconStateAltair; import tech.pegasys.teku.spec.logic.common.helpers.BeaconStateMutators; import tech.pegasys.teku.spec.logic.common.statetransition.epoch.AbstractEpochProcessor; import tech.pegasys.teku.spec.logic.common.statetransition.epoch.RewardAndPenaltyDeltas; import tech.pegasys.teku.spec.logic.common.statetransition.epoch.status.ValidatorStatus; import tech.pegasys.teku.spec.logic.common.statetransition.epoch.status.ValidatorStatusFactory; import tech.pegasys.teku.spec.logic.common.statetransition.epoch.status.ValidatorStatuses; import tech.pegasys.teku.spec.logic.common.util.BeaconStateUtil; import tech.pegasys.teku.spec.logic.common.util.ValidatorsUtil; import tech.pegasys.teku.spec.logic.versions.altair.helpers.BeaconStateAccessorsAltair; import tech.pegasys.teku.spec.logic.versions.altair.helpers.MiscHelpersAltair; import tech.pegasys.teku.spec.schemas.SchemaDefinitions; public class EpochProcessorAltair extends AbstractEpochProcessor { private final SpecConfigAltair specConfigAltair; protected final MiscHelpersAltair miscHelpersAltair; protected final BeaconStateAccessorsAltair beaconStateAccessorsAltair; public EpochProcessorAltair( final SpecConfigAltair specConfig, final MiscHelpersAltair miscHelpers, final BeaconStateAccessorsAltair beaconStateAccessors, final BeaconStateMutators beaconStateMutators, final ValidatorsUtil validatorsUtil, final BeaconStateUtil beaconStateUtil, final ValidatorStatusFactory validatorStatusFactory, final SchemaDefinitions schemaDefinitions) { super( specConfig, miscHelpers, beaconStateAccessors, beaconStateMutators, validatorsUtil, beaconStateUtil, validatorStatusFactory, schemaDefinitions); this.specConfigAltair = specConfig; this.miscHelpersAltair = miscHelpers; this.beaconStateAccessorsAltair = beaconStateAccessors; } @Override public RewardAndPenaltyDeltas getRewardAndPenaltyDeltas( final BeaconState genericState, final ValidatorStatuses validatorStatuses) { final BeaconStateAltair state = BeaconStateAltair.required(genericState); final RewardsAndPenaltiesCalculatorAltair calculator = new RewardsAndPenaltiesCalculatorAltair( specConfigAltair, state, validatorStatuses, miscHelpersAltair, beaconStateAccessorsAltair); return calculator.getDeltas(); } /** * Corresponds to process_participation_flag_updates in beacon-chain spec * * @param genericState The state to process * @see <a * href="https://github.com/ethereum/eth2.0-specs/blob/master/specs/altair/beacon-chain.md#participation-flags-updates">Altair * Participation Flags updates</a> */ @Override public void processParticipationUpdates(final MutableBeaconState genericState) { final MutableBeaconStateAltair state = MutableBeaconStateAltair.required(genericState); state.setPreviousEpochParticipation(state.getCurrentEpochParticipation()); // Reset current epoch participation flags state.getCurrentEpochParticipation().clear(); state.getCurrentEpochParticipation().setAll(SszByte.ZERO, state.getValidators().size()); } @Override public void processSyncCommitteeUpdates(final MutableBeaconState genericState) { final UInt64 nextEpoch = beaconStateAccessors.getCurrentEpoch(genericState).increment(); if (nextEpoch.mod(specConfigAltair.getEpochsPerSyncCommitteePeriod()).isZero()) { final MutableBeaconStateAltair state = MutableBeaconStateAltair.required(genericState); state.setCurrentSyncCommittee(state.getNextSyncCommittee()); state.setNextSyncCommittee(beaconStateAccessorsAltair.getNextSyncCommittee(state)); } } @Override public void processInactivityUpdates( final MutableBeaconState baseState, final ValidatorStatuses validatorStatuses) { if (beaconStateAccessors.getCurrentEpoch(baseState).equals(SpecConfig.GENESIS_EPOCH)) { return; } final MutableBeaconStateAltair state = MutableBeaconStateAltair.required(baseState); final SszMutableUInt64List inactivityScores = state.getInactivityScores(); final List<ValidatorStatus> statuses = validatorStatuses.getStatuses(); final boolean isInInactivityLeak = beaconStateAccessors.isInactivityLeak(state); for (int i = 0; i < statuses.size(); i++) { final ValidatorStatus validatorStatus = statuses.get(i); if (!validatorStatus.isEligibleValidator()) { continue; } // Increase inactivity score of inactive validators final UInt64 currentScore = inactivityScores.getElement(i); UInt64 newScore; if (validatorStatus.isNotSlashed() && validatorStatus.isPreviousEpochTargetAttester()) { newScore = currentScore.minusMinZero(1); } else { newScore = currentScore.plus(specConfigAltair.getInactivityScoreBias()); } // Decrease the score of all validators for forgiveness when not during a leak if (!isInInactivityLeak) { newScore = newScore.minusMinZero(specConfigAltair.getInactivityScoreRecoveryRate()); } if (!currentScore.equals(newScore)) { inactivityScores.setElement(i, newScore); } } } @Override protected int getProportionalSlashingMultiplier() { return specConfigAltair.getProportionalSlashingMultiplierAltair(); } }
6,769
0.778106
0.774561
149
44.429531
34.088367
132
false
false
0
0
0
0
0
0
0.557047
false
false
13
41719f8675e9b2058fde2c7e1c9e7d0a810fe788
19,241,453,492,922
188bec1e5fc36a198ea39472c05a65c517318f60
/baiyan-common-service/src/main/java/com/baiyan/common/service/event/demo/DemoEvent.java
5bf0f8463941a439b4f1c9089ea4e93169a43cf6
[]
no_license
louyanfeng25/common-frame
https://github.com/louyanfeng25/common-frame
c459607db0a28fa3f5c2282cf14c810096b123b8
67ceefe048af58ec64a574949d3cf3186a4fe414
refs/heads/master
2023-05-23T23:44:31.608000
2022-11-08T06:52:32
2022-11-08T06:52:32
358,146,323
36
22
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.baiyan.common.service.event.demo; import com.baiyan.common.base.model.event.BaseDomainEvent; import lombok.Getter; import lombok.NoArgsConstructor; /** * 领域事件示例 * * @author baiyan * @date 2021/02/21 */ @NoArgsConstructor @Getter public class DemoEvent extends BaseDomainEvent<String> { private String demoField; public DemoEvent(String data,String demoField) { super(data); this.demoField = demoField; } }
UTF-8
Java
467
java
DemoEvent.java
Java
[ { "context": "ok.NoArgsConstructor;\n\n/**\n * 领域事件示例\n *\n * @author baiyan\n * @date 2021/02/21\n */\n@NoArgsConstructor\n@Gette", "end": 196, "score": 0.9995667338371277, "start": 190, "tag": "USERNAME", "value": "baiyan" } ]
null
[]
package com.baiyan.common.service.event.demo; import com.baiyan.common.base.model.event.BaseDomainEvent; import lombok.Getter; import lombok.NoArgsConstructor; /** * 领域事件示例 * * @author baiyan * @date 2021/02/21 */ @NoArgsConstructor @Getter public class DemoEvent extends BaseDomainEvent<String> { private String demoField; public DemoEvent(String data,String demoField) { super(data); this.demoField = demoField; } }
467
0.723077
0.705495
24
18
18.859127
58
false
false
0
0
0
0
0
0
0.333333
false
false
13
b67f3fa5d10b993e00c8fb6e2e70594a0d2bf6fc
26,499,948,234,775
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/32/32_4b0ebd23866a64e21e2a781a1ead17aeed100c34/Flag/32_4b0ebd23866a64e21e2a781a1ead17aeed100c34_Flag_s.java
5d5627f7b525b536200094ce87fbb7348e3b7a43
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.util.List; /** * Write a description of class Flag here. * * @author (your name) * @version (a version number or a date) */ public class Flag extends Actor { private String nationality; public Flag(String nationality) { this.nationality = nationality; if (nationality.equals("British")) { setImage("british.png"); } else { setImage("german.png"); } } /** * Act - do whatever the Flag wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Want a cool wave animation if (isTouching(EnemyNPC.class)) { // end the game. } CheckTutorialWin(); } public void CheckTutorialWin() { try { List<WinstonCrowley> actors = getNeighbours(50, true, java.lang.Class.forName("WinstonCrowley")); //Actor actors = getOneIntersectingObject(java.lang.Class.forName("WinstonCrowley")); if (!actors.isEmpty() && this.nationality == "german") { ((TutorialInfamyWorld)this.getWorld()).TutorialWin(); } } catch (Exception e) { } } }
UTF-8
Java
1,503
java
32_4b0ebd23866a64e21e2a781a1ead17aeed100c34_Flag_s.java
Java
[]
null
[]
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.util.List; /** * Write a description of class Flag here. * * @author (your name) * @version (a version number or a date) */ public class Flag extends Actor { private String nationality; public Flag(String nationality) { this.nationality = nationality; if (nationality.equals("British")) { setImage("british.png"); } else { setImage("german.png"); } } /** * Act - do whatever the Flag wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Want a cool wave animation if (isTouching(EnemyNPC.class)) { // end the game. } CheckTutorialWin(); } public void CheckTutorialWin() { try { List<WinstonCrowley> actors = getNeighbours(50, true, java.lang.Class.forName("WinstonCrowley")); //Actor actors = getOneIntersectingObject(java.lang.Class.forName("WinstonCrowley")); if (!actors.isEmpty() && this.nationality == "german") { ((TutorialInfamyWorld)this.getWorld()).TutorialWin(); } } catch (Exception e) { } } }
1,503
0.51497
0.513639
54
25.814816
25.556093
110
false
false
0
0
0
0
0
0
0.277778
false
false
13
3da1ae42f6a3de76de01e60d948f08729cf5d079
32,830,730,028,956
f2f60c79a8373c17a1609cb4be85d5d9c73b120f
/src/jp/eclipcebook/Help.java
7057e9d1b2aa215e331d1c6ab91c44abe39c6264
[]
no_license
Koichi317/ManekkoDance
https://github.com/Koichi317/ManekkoDance
4a0095a98c7601aac78c3834d4927dd40fe332b2
135a085117e652fc8716f67b055012594a11a41f
refs/heads/master
2016-09-06T19:10:36.226000
2013-02-22T05:18:00
2013-02-22T05:18:00
8,350,938
1
0
null
false
2014-10-16T12:56:38
2013-02-22T05:13:13
2014-04-16T22:04:13
2013-02-22T05:24:22
10,430
1
1
2
Java
null
null
package jp.eclipcebook; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageView; public class Help extends Activity { private String lesson; private String text_data; private String message; private int pageNumber; private String page; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.help); Intent intent = getIntent(); lesson = intent.getStringExtra("lesson"); message = intent.getStringExtra("message"); text_data = intent.getStringExtra("text_data"); pageNumber = 1; page = " / 8"; ImageView helpImage = (ImageView) findViewById(R.id.helpImage); helpImage.setImageResource(R.drawable.tutorial1); EditText pageText = (EditText)findViewById(R.id.page); pageText.setText("1 / 8"); } public void next(View view) { if (pageNumber == 8) pageNumber = 0; pageNumber++; ImageView helpImage = (ImageView) findViewById(R.id.helpImage); EditText pageText = (EditText)findViewById(R.id.page); pageText.setText(String.valueOf(pageNumber) + page); switch (pageNumber) { case 1: helpImage.setImageResource(R.drawable.tutorial1); break; case 2: helpImage.setImageResource(R.drawable.tutorial2); break; case 3: helpImage.setImageResource(R.drawable.tutorial3); break; case 4: helpImage.setImageResource(R.drawable.tutorial4); break; case 5: helpImage.setImageResource(R.drawable.tutorial5); break; case 6: helpImage.setImageResource(R.drawable.helptext1); break; case 7: helpImage.setImageResource(R.drawable.helptext2); break; case 8: helpImage.setImageResource(R.drawable.helptext3); break; } } public void prev(View view) { if (pageNumber == 1) pageNumber = 9; pageNumber--; ImageView helpImage = (ImageView) findViewById(R.id.helpImage); EditText pageText = (EditText)findViewById(R.id.page); pageText.setText(String.valueOf(pageNumber) + page); switch (pageNumber) { case 1: helpImage.setImageResource(R.drawable.tutorial1); break; case 2: helpImage.setImageResource(R.drawable.tutorial2); break; case 3: helpImage.setImageResource(R.drawable.tutorial3); break; case 4: helpImage.setImageResource(R.drawable.tutorial4); break; case 5: helpImage.setImageResource(R.drawable.tutorial5); break; case 6: helpImage.setImageResource(R.drawable.helptext1); break; case 7: helpImage.setImageResource(R.drawable.helptext2); break; case 8: helpImage.setImageResource(R.drawable.helptext3); break; } } public void changeScreen(View view) { Intent intent = new Intent(); intent.putExtra("lesson", lesson); intent.putExtra("message", message); intent.putExtra("text_data", text_data); finish(); } }
UTF-8
Java
2,883
java
Help.java
Java
[]
null
[]
package jp.eclipcebook; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageView; public class Help extends Activity { private String lesson; private String text_data; private String message; private int pageNumber; private String page; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.help); Intent intent = getIntent(); lesson = intent.getStringExtra("lesson"); message = intent.getStringExtra("message"); text_data = intent.getStringExtra("text_data"); pageNumber = 1; page = " / 8"; ImageView helpImage = (ImageView) findViewById(R.id.helpImage); helpImage.setImageResource(R.drawable.tutorial1); EditText pageText = (EditText)findViewById(R.id.page); pageText.setText("1 / 8"); } public void next(View view) { if (pageNumber == 8) pageNumber = 0; pageNumber++; ImageView helpImage = (ImageView) findViewById(R.id.helpImage); EditText pageText = (EditText)findViewById(R.id.page); pageText.setText(String.valueOf(pageNumber) + page); switch (pageNumber) { case 1: helpImage.setImageResource(R.drawable.tutorial1); break; case 2: helpImage.setImageResource(R.drawable.tutorial2); break; case 3: helpImage.setImageResource(R.drawable.tutorial3); break; case 4: helpImage.setImageResource(R.drawable.tutorial4); break; case 5: helpImage.setImageResource(R.drawable.tutorial5); break; case 6: helpImage.setImageResource(R.drawable.helptext1); break; case 7: helpImage.setImageResource(R.drawable.helptext2); break; case 8: helpImage.setImageResource(R.drawable.helptext3); break; } } public void prev(View view) { if (pageNumber == 1) pageNumber = 9; pageNumber--; ImageView helpImage = (ImageView) findViewById(R.id.helpImage); EditText pageText = (EditText)findViewById(R.id.page); pageText.setText(String.valueOf(pageNumber) + page); switch (pageNumber) { case 1: helpImage.setImageResource(R.drawable.tutorial1); break; case 2: helpImage.setImageResource(R.drawable.tutorial2); break; case 3: helpImage.setImageResource(R.drawable.tutorial3); break; case 4: helpImage.setImageResource(R.drawable.tutorial4); break; case 5: helpImage.setImageResource(R.drawable.tutorial5); break; case 6: helpImage.setImageResource(R.drawable.helptext1); break; case 7: helpImage.setImageResource(R.drawable.helptext2); break; case 8: helpImage.setImageResource(R.drawable.helptext3); break; } } public void changeScreen(View view) { Intent intent = new Intent(); intent.putExtra("lesson", lesson); intent.putExtra("message", message); intent.putExtra("text_data", text_data); finish(); } }
2,883
0.724939
0.710718
118
23.432203
19.853479
65
false
false
0
0
0
0
0
0
2.40678
false
false
13
7a47f30a6a65f4eee0e0fb46c78009f8a167dc14
31,679,678,806,147
804f6fdcb7accde8f4edf986a4ba6cd2d97aa235
/src/model/Main.java
10acf6c7a4df56020a7319a2755883e868b738f7
[]
no_license
marcops/ModelledApplication_Modeller
https://github.com/marcops/ModelledApplication_Modeller
2bf06270a4fc56b5f90d37a44681e4eccf66ce53
41a04cbb657616e5fef3e16a8275336e7b06ca25
refs/heads/master
2016-06-01T04:12:09.916000
2015-09-02T12:45:56
2015-09-02T12:45:56
41,800,206
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package model; import javax.swing.UIManager; /** * * @author Aog007 */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { //MobileContainer.main(args); try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch(Exception e){ System.err.println("Error: " + e.getMessage()); } ModelFace.main(args); } }
UTF-8
Java
595
java
Main.java
Java
[ { "context": "\n\nimport javax.swing.UIManager;\n\n/**\n *\n * @author Aog007\n */\npublic class Main {\n\n /**\n * @param ar", "end": 172, "score": 0.999557375907898, "start": 166, "tag": "USERNAME", "value": "Aog007" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package model; import javax.swing.UIManager; /** * * @author Aog007 */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { //MobileContainer.main(args); try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch(Exception e){ System.err.println("Error: " + e.getMessage()); } ModelFace.main(args); } }
595
0.593277
0.588235
31
18.193548
19.30472
62
false
false
0
0
0
0
0
0
0.258065
false
false
13
14e7a6c429373fd648c587c72c9580e3ec3743ac
14,894,946,640,434
6e1e6b1afde6baecb913ccc53495d889310c43d9
/src/main/java/com/gqb/controller/UserController.java
ccb84e3eeaac34c553c579973432c758d87b8c5c
[]
no_license
GQBBBB/SSM
https://github.com/GQBBBB/SSM
b21370c7ce8be37143276710b60f1e80818ffbd8
014b90223976984e20f721aae2ee0eaf08a1a101
refs/heads/master
2020-05-25T19:50:50.920000
2019-11-13T12:44:33
2019-11-13T12:44:33
187,961,786
0
0
null
false
2021-02-18T21:21:13
2019-05-22T04:17:48
2019-11-13T12:44:36
2021-02-18T21:21:12
17,826
0
0
4
Java
false
false
package com.gqb.controller; import com.gqb.pojo.User; import com.gqb.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpSession; @Controller @RequestMapping("user") public class UserController { //自动注入Service @Autowired private UserService userService; @RequestMapping("get/{id}") public String get(@PathVariable("id") int id, HttpSession session){ User user = userService.getByID(id); if(user != null){ session.setAttribute("USER", user); }else{ return "redirect:/index.jsp"; } return "user"; } }
UTF-8
Java
836
java
UserController.java
Java
[]
null
[]
package com.gqb.controller; import com.gqb.pojo.User; import com.gqb.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpSession; @Controller @RequestMapping("user") public class UserController { //自动注入Service @Autowired private UserService userService; @RequestMapping("get/{id}") public String get(@PathVariable("id") int id, HttpSession session){ User user = userService.getByID(id); if(user != null){ session.setAttribute("USER", user); }else{ return "redirect:/index.jsp"; } return "user"; } }
836
0.708937
0.708937
30
26.6
20.814419
71
false
false
0
0
0
0
0
0
0.5
false
false
13
e275098cbbeb7560de4ff49e3df6d66d952c7886
32,590,211,862,141
bffc26d949cc593540ef7d80a1c5d68a5c2d1ec1
/src/main/java/com/hong/hakwon/web/validation/RegisterValidator.java
ca73fd3f958203e94935e9e78f91fbe2554d550f
[]
no_license
parkmuhyeun/study
https://github.com/parkmuhyeun/study
d6b62653ca2079535c51089c6d1294a9e8a1bfaa
198bfc9fc85e2788a887fb1dd058055e8deccd8e
refs/heads/master
2023-09-01T16:30:33.234000
2021-09-30T14:02:53
2021-09-30T14:02:53
400,123,039
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hong.hakwon.web.validation; import com.hong.hakwon.web.dto.UserSaveDto; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import java.util.regex.Matcher; import java.util.regex.Pattern; @Component public class RegisterValidator implements Validator { String id_chk = "^[a-zA-Z0-9~!@#$%^&*()_+|<>?:{}]*$"; //영문자 && 숫자 && 특수문자 String name_chk = "^[가-힣]*$"; //한글만 String email_chk = "^[_a-zA-Z0-9-\\.]+@[\\.a-zA-Z0-9-]+\\.[a-zA-Z]+$"; //표준 이메일 String pw_chk = "^[a-zA-Z0-9~!@#$%^&*()_+|<>?:{}]*$"; //영문자 && 숫자 && 특수문자 String number_chk = "^01(?:0|1|[6-9])-(?:\\d{3}|\\d{4})-\\d{4}$"; String sido_chk = "^[0-9]+$"; private Pattern idP = Pattern.compile(id_chk); private Pattern passP = Pattern.compile(pw_chk); private Pattern nameP = Pattern.compile(name_chk); private Pattern numberP = Pattern.compile(number_chk); private Pattern sidoP = Pattern.compile(sido_chk); private Pattern emailP = Pattern.compile(email_chk); @Override public boolean supports(Class<?> clazz) { return UserSaveDto.class.isAssignableFrom(clazz); } @Override public void validate(Object target, Errors errors) { UserSaveDto userSaveDto = (UserSaveDto) target; if(userSaveDto.getUserId() == null || userSaveDto.getUserId().length() < 8 || userSaveDto.getUserId().length() > 15){ errors.rejectValue("userId", null, "8 ~ 15 자리 영문 혹은 숫자 등(한글제외) 입력 해주세요"); } else { Matcher matcher = idP.matcher(userSaveDto.getUserId()); if(!matcher.matches()){ errors.rejectValue("userId", null, "올바르지 않는 형식입니다."); } } if(userSaveDto.getName() == null || userSaveDto.getName().length() < 2 || userSaveDto.getName().length() > 30){ errors.rejectValue("name", null, "2글자 이상 30글자 이하로 적어주세요."); }else { Matcher matcher = nameP.matcher(userSaveDto.getName()); if (!matcher.matches()) { errors.rejectValue("name", null, "올바르지 않는 형식입니다.(한글만 입력) "); } } String phoneNumber = userSaveDto.getF_number() +"-"+ userSaveDto.getM_number() +"-"+ userSaveDto.getE_number(); Matcher matcherNum = numberP.matcher(phoneNumber); if (!matcherNum.matches()) { errors.rejectValue("f_number", null, "올바르지 않은 형식입니다."); } //시도 시군구 두개다 null이면 오류 Matcher matchersi = sidoP.matcher(userSaveDto.getSido()); if (!matchersi.matches()) { errors.rejectValue("sido",null, "주소를 입력해주세요"); } Matcher matcherE = emailP.matcher(userSaveDto.getEmail()); if(userSaveDto.getEmail() == null || !matcherE.matches()) { errors.rejectValue("email", null, "올바르지 않는 형식입니다. ex) example@email.com"); } if(userSaveDto.getPassword() == null || userSaveDto.getPassword().length() < 8 || userSaveDto.getPassword().length() > 15){ errors.rejectValue("password", null, "8 ~ 15 자리 영문 혹은 숫자 입력 해주세요"); } else { Matcher matcher = passP.matcher(userSaveDto.getPassword()); if(!matcher.matches()){ errors.rejectValue("password", null, "올바르지 않는 형식입니다."); } } } }
UTF-8
Java
3,685
java
RegisterValidator.java
Java
[ { "context": "ors.rejectValue(\"email\", null, \"올바르지 않는 형식입니다. ex) example@email.com\");\n }\n\n if(userSaveDto.getPassword(", "end": 2915, "score": 0.9999216198921204, "start": 2898, "tag": "EMAIL", "value": "example@email.com" } ]
null
[]
package com.hong.hakwon.web.validation; import com.hong.hakwon.web.dto.UserSaveDto; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import java.util.regex.Matcher; import java.util.regex.Pattern; @Component public class RegisterValidator implements Validator { String id_chk = "^[a-zA-Z0-9~!@#$%^&*()_+|<>?:{}]*$"; //영문자 && 숫자 && 특수문자 String name_chk = "^[가-힣]*$"; //한글만 String email_chk = "^[_a-zA-Z0-9-\\.]+@[\\.a-zA-Z0-9-]+\\.[a-zA-Z]+$"; //표준 이메일 String pw_chk = "^[a-zA-Z0-9~!@#$%^&*()_+|<>?:{}]*$"; //영문자 && 숫자 && 특수문자 String number_chk = "^01(?:0|1|[6-9])-(?:\\d{3}|\\d{4})-\\d{4}$"; String sido_chk = "^[0-9]+$"; private Pattern idP = Pattern.compile(id_chk); private Pattern passP = Pattern.compile(pw_chk); private Pattern nameP = Pattern.compile(name_chk); private Pattern numberP = Pattern.compile(number_chk); private Pattern sidoP = Pattern.compile(sido_chk); private Pattern emailP = Pattern.compile(email_chk); @Override public boolean supports(Class<?> clazz) { return UserSaveDto.class.isAssignableFrom(clazz); } @Override public void validate(Object target, Errors errors) { UserSaveDto userSaveDto = (UserSaveDto) target; if(userSaveDto.getUserId() == null || userSaveDto.getUserId().length() < 8 || userSaveDto.getUserId().length() > 15){ errors.rejectValue("userId", null, "8 ~ 15 자리 영문 혹은 숫자 등(한글제외) 입력 해주세요"); } else { Matcher matcher = idP.matcher(userSaveDto.getUserId()); if(!matcher.matches()){ errors.rejectValue("userId", null, "올바르지 않는 형식입니다."); } } if(userSaveDto.getName() == null || userSaveDto.getName().length() < 2 || userSaveDto.getName().length() > 30){ errors.rejectValue("name", null, "2글자 이상 30글자 이하로 적어주세요."); }else { Matcher matcher = nameP.matcher(userSaveDto.getName()); if (!matcher.matches()) { errors.rejectValue("name", null, "올바르지 않는 형식입니다.(한글만 입력) "); } } String phoneNumber = userSaveDto.getF_number() +"-"+ userSaveDto.getM_number() +"-"+ userSaveDto.getE_number(); Matcher matcherNum = numberP.matcher(phoneNumber); if (!matcherNum.matches()) { errors.rejectValue("f_number", null, "올바르지 않은 형식입니다."); } //시도 시군구 두개다 null이면 오류 Matcher matchersi = sidoP.matcher(userSaveDto.getSido()); if (!matchersi.matches()) { errors.rejectValue("sido",null, "주소를 입력해주세요"); } Matcher matcherE = emailP.matcher(userSaveDto.getEmail()); if(userSaveDto.getEmail() == null || !matcherE.matches()) { errors.rejectValue("email", null, "올바르지 않는 형식입니다. ex) <EMAIL>"); } if(userSaveDto.getPassword() == null || userSaveDto.getPassword().length() < 8 || userSaveDto.getPassword().length() > 15){ errors.rejectValue("password", null, "8 ~ 15 자리 영문 혹은 숫자 입력 해주세요"); } else { Matcher matcher = passP.matcher(userSaveDto.getPassword()); if(!matcher.matches()){ errors.rejectValue("password", null, "올바르지 않는 형식입니다."); } } } }
3,675
0.590276
0.579306
87
37.770115
33.750504
131
false
false
0
0
0
0
0
0
0.862069
false
false
13
9dedf32b0dd326e56b9a5950cc040216e598bb8c
31,817,117,754,596
38c95a8e610a26e7cb0e2a0ad027df148b890210
/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_659.java
f096600fdbabc8b4cafbffccfcb117927945ce4f
[ "MIT" ]
permissive
guobinhit/myleetcode
https://github.com/guobinhit/myleetcode
b2f4b5f2c1fd7c26dd303be34c227a20c9bfa9b7
bf519a04dcf574419543f52fbe2bfcb430d981f1
refs/heads/master
2023-01-21T10:58:24.809000
2023-01-09T03:36:45
2023-01-09T03:36:45
145,631,771
56
29
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hit.basmath.learn.others; /** * 659. Split Array into Consecutive Subsequences * <p> * Given an array nums sorted in ascending order, return true if and only if you can split it into 1 or more subsequences such that each subsequence consists of consecutive integers and has length at least 3. * <p> * Example 1: * <p> * Input: [1,2,3,3,4,5] * Output: True * Explanation: * You can split them into two consecutive subsequences : * 1, 2, 3 * 3, 4, 5 * <p> * Example 2: * <p> * Input: [1,2,3,3,4,4,5,5] * Output: True * Explanation: * You can split them into two consecutive subsequences : * 1, 2, 3, 4, 5 * 3, 4, 5 * <p> * Example 3: * <p> * Input: [1,2,3,4,4,5] * Output: False * <p> * Constraints: * <p> * 1 <= nums.length <= 10000 */ public class _659 { public boolean isPossible(int[] nums) { int pre = Integer.MIN_VALUE, p1 = 0, p2 = 0, p3 = 0; int cur = 0, cnt = 0, c1 = 0, c2 = 0, c3 = 0; for (int i = 0; i < nums.length; pre = cur, p1 = c1, p2 = c2, p3 = c3) { for (cur = nums[i], cnt = 0; i < nums.length && cur == nums[i]; cnt++, i++) ; if (cur != pre + 1) { if (p1 != 0 || p2 != 0) return false; c1 = cnt; c2 = 0; c3 = 0; } else { if (cnt < p1 + p2) return false; c1 = Math.max(0, cnt - (p1 + p2 + p3)); c2 = p1; c3 = p2 + Math.min(p3, cnt - (p1 + p2)); } } return (p1 == 0 && p2 == 0); } }
UTF-8
Java
1,572
java
_659.java
Java
[]
null
[]
package com.hit.basmath.learn.others; /** * 659. Split Array into Consecutive Subsequences * <p> * Given an array nums sorted in ascending order, return true if and only if you can split it into 1 or more subsequences such that each subsequence consists of consecutive integers and has length at least 3. * <p> * Example 1: * <p> * Input: [1,2,3,3,4,5] * Output: True * Explanation: * You can split them into two consecutive subsequences : * 1, 2, 3 * 3, 4, 5 * <p> * Example 2: * <p> * Input: [1,2,3,3,4,4,5,5] * Output: True * Explanation: * You can split them into two consecutive subsequences : * 1, 2, 3, 4, 5 * 3, 4, 5 * <p> * Example 3: * <p> * Input: [1,2,3,4,4,5] * Output: False * <p> * Constraints: * <p> * 1 <= nums.length <= 10000 */ public class _659 { public boolean isPossible(int[] nums) { int pre = Integer.MIN_VALUE, p1 = 0, p2 = 0, p3 = 0; int cur = 0, cnt = 0, c1 = 0, c2 = 0, c3 = 0; for (int i = 0; i < nums.length; pre = cur, p1 = c1, p2 = c2, p3 = c3) { for (cur = nums[i], cnt = 0; i < nums.length && cur == nums[i]; cnt++, i++) ; if (cur != pre + 1) { if (p1 != 0 || p2 != 0) return false; c1 = cnt; c2 = 0; c3 = 0; } else { if (cnt < p1 + p2) return false; c1 = Math.max(0, cnt - (p1 + p2 + p3)); c2 = p1; c3 = p2 + Math.min(p3, cnt - (p1 + p2)); } } return (p1 == 0 && p2 == 0); } }
1,572
0.494275
0.430025
59
25.644068
31.789436
208
false
false
0
0
0
0
0
0
1.033898
false
false
13
4024579ae8f19373dd3074cef32e577cda8f5364
9,019,431,329,846
8b84e640cb76a22d066d72b54d7fee7749632ab1
/Q13.java
4efeb0f31e9c5e80621af1d8dbda3fe993ecb114
[]
no_license
MuhammadTahaAzam1997/OOP_2ndSemester
https://github.com/MuhammadTahaAzam1997/OOP_2ndSemester
8f6f3c682f553026a155bb02c03414763718f00d
9ab236351b227ddfbb90d54ad30a9cb27a815dcf
refs/heads/master
2020-04-06T11:58:30.052000
2018-11-13T20:00:26
2018-11-13T20:00:26
157,438,296
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; class creditDetails { String Name; int limit; String accountID; int sum=0; int initialBalance; int noitems; int amountSpent(int noitems) { Scanner sc=new Scanner(System.in); int[] price=new int[noitems]; for(int x=0;x<price.length;x++) { System.out.println("ENTER PRICE OF ITEM NO. "+(x+1)); price[x]=sc.nextInt(); sum=sum+price[x]; } return sum; } int amountRemaining() { int rem=this.initialBalance-sum; return rem; } boolean checkCreditLimit() { if(this.amountSpent(noitems)>this.limit) {System.out.println("LIMIT EXCEEDED"); return false;} else return true; } } class Q13{ public static void main(String args[]) { creditDetails Customer=new creditDetails(); Scanner scan=new Scanner(System.in); System.out.println("ENTER NAME:\t"); Customer.Name=scan.nextLine(); System.out.println("ENTER ACCOUNT ID"); Customer.accountID=scan.nextLine(); System.out.println("ENTER INITIAL BALANCE"); Customer.initialBalance=scan.nextInt(); System.out.println("ENTER LIMIT "); Customer.limit=scan.nextInt(); System.out.println("ENTER NO OF ITEMS PURCHASED"); int noitems=scan.nextInt(); int spent=Customer.amountSpent(noitems); if(Customer.checkCreditLimit()) { int remain=Customer.amountRemaining(); System.out.println("TOTAL AMOUNT SPENT IS:"+spent); System.out.println("TOTAL REMAINING AMOUNT IS: "+remain);} } }
UTF-8
Java
1,422
java
Q13.java
Java
[]
null
[]
import java.util.Scanner; class creditDetails { String Name; int limit; String accountID; int sum=0; int initialBalance; int noitems; int amountSpent(int noitems) { Scanner sc=new Scanner(System.in); int[] price=new int[noitems]; for(int x=0;x<price.length;x++) { System.out.println("ENTER PRICE OF ITEM NO. "+(x+1)); price[x]=sc.nextInt(); sum=sum+price[x]; } return sum; } int amountRemaining() { int rem=this.initialBalance-sum; return rem; } boolean checkCreditLimit() { if(this.amountSpent(noitems)>this.limit) {System.out.println("LIMIT EXCEEDED"); return false;} else return true; } } class Q13{ public static void main(String args[]) { creditDetails Customer=new creditDetails(); Scanner scan=new Scanner(System.in); System.out.println("ENTER NAME:\t"); Customer.Name=scan.nextLine(); System.out.println("ENTER ACCOUNT ID"); Customer.accountID=scan.nextLine(); System.out.println("ENTER INITIAL BALANCE"); Customer.initialBalance=scan.nextInt(); System.out.println("ENTER LIMIT "); Customer.limit=scan.nextInt(); System.out.println("ENTER NO OF ITEMS PURCHASED"); int noitems=scan.nextInt(); int spent=Customer.amountSpent(noitems); if(Customer.checkCreditLimit()) { int remain=Customer.amountRemaining(); System.out.println("TOTAL AMOUNT SPENT IS:"+spent); System.out.println("TOTAL REMAINING AMOUNT IS: "+remain);} } }
1,422
0.703938
0.700422
63
21.571428
17.35778
60
false
false
0
0
0
0
0
0
1.952381
false
false
13
040905dc747e5fc66e19e34e02e501015fd83040
24,232,205,493,401
8c11c0b139548c9c869f1e77e9ef5a882430863a
/src/main/java/factory_method/ChicagoPizzaStore.java
d8d787ac9ed10be38cac7bdffc2d88cbf7cde8c2
[]
no_license
Getthrough/DesignPatterns
https://github.com/Getthrough/DesignPatterns
dcb7cdbb468eafe77aa4f11755ed9376aa6740d2
52097fd57c35a1233ffcbfb2510701bb4b7ae162
refs/heads/master
2021-07-06T16:29:13.409000
2020-07-16T15:46:22
2020-07-16T15:46:22
140,735,419
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package factory_method; /** * 芝加哥风味披萨 * * @author getthrough * @date 2020/7/10 */ public class ChicagoPizzaStore extends PizzaStore { @Override protected Pizza createPizza(String type) { if ("cheese".equals(type)) { return new CCStyleCheesePizza(); } else if ("veggie".equals(type)) { return new CCStyleVeggiePizza(); } else { return new Pizza(); } } }
UTF-8
Java
455
java
ChicagoPizzaStore.java
Java
[ { "context": "kage factory_method;\n\n/**\n * 芝加哥风味披萨\n *\n * @author getthrough\n * @date 2020/7/10\n */\npublic class ChicagoPizzaS", "end": 64, "score": 0.9995290637016296, "start": 54, "tag": "USERNAME", "value": "getthrough" } ]
null
[]
package factory_method; /** * 芝加哥风味披萨 * * @author getthrough * @date 2020/7/10 */ public class ChicagoPizzaStore extends PizzaStore { @Override protected Pizza createPizza(String type) { if ("cheese".equals(type)) { return new CCStyleCheesePizza(); } else if ("veggie".equals(type)) { return new CCStyleVeggiePizza(); } else { return new Pizza(); } } }
455
0.575964
0.560091
22
19.045454
17.402918
51
false
false
0
0
0
0
0
0
0.181818
false
false
13
24791c1598ebcfd168e3e7022e6557b3fe81c578
10,368,051,105,135
1557fb2c7fe35acbf4983d0603ff2a9fcfc80f22
/strategy/example/java/Multiplication.java
2815a15669ae7a4a0624033264997f98ddc686a9
[]
no_license
manurampandit/design-patterns
https://github.com/manurampandit/design-patterns
041ee7fdb73dcbd77b7b535c96736ac5a6982340
a387f228eefa0edd205423b6538e2aa8711fcb8a
refs/heads/master
2016-09-06T14:17:19.602000
2014-07-31T17:24:45
2014-07-31T17:24:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package designpatterns.strategy.example.java; /** * @author manurampandit * */ public class Multiplication implements IOperation { /* (non-Javadoc) * @see designpattern.strategy.example.java.IOperation#execute(int, int) */ @Override public void execute(int a, int b) { System.out.println("Multiplication of a & b" + a*b); } }
UTF-8
Java
355
java
Multiplication.java
Java
[ { "context": "ignpatterns.strategy.example.java;\n\n/**\n * @author manurampandit\n *\n */\npublic class Multiplication implements IOp", "end": 87, "score": 0.8912439346313477, "start": 74, "tag": "USERNAME", "value": "manurampandit" } ]
null
[]
/** * */ package designpatterns.strategy.example.java; /** * @author manurampandit * */ public class Multiplication implements IOperation { /* (non-Javadoc) * @see designpattern.strategy.example.java.IOperation#execute(int, int) */ @Override public void execute(int a, int b) { System.out.println("Multiplication of a & b" + a*b); } }
355
0.678873
0.678873
21
15.904762
21.701229
73
false
false
0
0
0
0
0
0
0.571429
false
false
13
d200b15893451c9e428179238e68ca095c69e847
4,140,348,528,570
f43da1e90b58dd88f83b9534a96c61631280d66d
/src10/com/github/forax/blast_from_the_past10/Occurence.java
08f4061ab9260991911a7e67ad8d60a0d396b9cc
[ "MIT" ]
permissive
forax/blast_from_the_past
https://github.com/forax/blast_from_the_past
924172e2823352b67e5bd75fc5a7154e0e425bc4
559453ffd65528e9ae0a6220a94b0548f696b93b
refs/heads/master
2021-05-11T19:30:58.966000
2018-03-27T13:49:40
2018-03-27T13:49:40
117,877,167
12
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.forax.blast_from_the_past10; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Comparator; import java.util.Map; import java.util.regex.Pattern; import java.util.stream.Collectors; public class Occurence { public static void main(String[] args) throws IOException { var pattern = Pattern.compile(" "); var path = Paths.get("romeo_and_juliet.txt"); Map<String, Long> map; try(var lines = Files.lines(path)) { map = lines.flatMap(pattern::splitAsStream) .collect(Collectors.groupingBy(w -> w, Collectors.counting())); } var list = new ArrayList<>(map.entrySet()); list.sort(Map.Entry.comparingByValue(Comparator.reverseOrder())); System.out.println(list); } }
UTF-8
Java
827
java
Occurence.java
Java
[ { "context": "package com.github.forax.blast_from_the_past10;\n\nimport java.io.IOExceptio", "end": 24, "score": 0.9976531267166138, "start": 19, "tag": "USERNAME", "value": "forax" } ]
null
[]
package com.github.forax.blast_from_the_past10; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Comparator; import java.util.Map; import java.util.regex.Pattern; import java.util.stream.Collectors; public class Occurence { public static void main(String[] args) throws IOException { var pattern = Pattern.compile(" "); var path = Paths.get("romeo_and_juliet.txt"); Map<String, Long> map; try(var lines = Files.lines(path)) { map = lines.flatMap(pattern::splitAsStream) .collect(Collectors.groupingBy(w -> w, Collectors.counting())); } var list = new ArrayList<>(map.entrySet()); list.sort(Map.Entry.comparingByValue(Comparator.reverseOrder())); System.out.println(list); } }
827
0.696493
0.694075
27
29.629629
21.087381
80
false
false
0
0
0
0
0
0
0.666667
false
false
13
ab77a59207bad35379652faa1662006f8b42bfa3
1,005,022,354,460
8eec47a5ab5f4661bcb52014ee5b72882a2dfe2e
/src/main/java/nl/sogeti/com/domain/Colour.java
0a46dadde1d4bde2f7f30dc35eefccb68b2ce755
[]
no_license
sudeepkuma/umAngular2
https://github.com/sudeepkuma/umAngular2
55c4e74bc546e49bbf657a351213a7be4aa3826c
55a4e1ad73eb3bdbe4ef772fd1d53fdad4274126
refs/heads/master
2021-01-02T09:29:36.337000
2017-11-13T13:01:15
2017-11-13T13:01:15
97,930,541
0
0
null
false
2017-08-01T09:45:33
2017-07-21T09:26:15
2017-07-21T09:58:06
2017-08-01T09:45:33
3,931
0
0
0
JavaScript
null
null
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: himtiwar ** Copyright: (c) Feb 19, 2015 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ */ package nl.sogeti.com.domain; import java.util.Comparator; import javax.persistence.AttributeOverride; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; // TODO: Auto-generated Javadoc /** * ????. * * @author himtiwar (c) Feb 19, 2015, Sogeti B.V. * @version $Id:$ */ @Entity @Table(name = "colour") @AttributeOverride(name = "id", column = @Column(name = "colour_id")) public class Colour extends AbstractEntity { /** * <code>serialVersionUID</code> indicates/is used for. */ private static final long serialVersionUID = 3583049578134821535L; /** The colour code. */ private String colourCode; /** The colour name. */ private String colourName; /** * Constructor: create a new Colour. */ public Colour() { super(); // TODO Auto-generated constructor stub } /** * Get the colourCode. * * @return Returns the colourCode as a String. */ public String getColourCode() { return this.colourCode; } /** * Set the colourCode to the specified value. * * @param colourCode The colourCode to set. */ public void setColourCode(String colourCode) { this.colourCode = colourCode; } /** * Get the colourName. * * @return Returns the colourName as a String. */ public String getColourName() { return this.colourName; } /** * Set the colourName to the specified value. * * @param colourName The colourName to set. */ public void setColourName(String colourName) { this.colourName = colourName; } /** The name comparator. */ public static Comparator<Colour> NAME_COMPARATOR = new Comparator<Colour>() { @Override public int compare(Colour o1, Colour o2) { if (o1.colourName == null) { return -1; } if (o2.colourName == null) { return 1; } return o1.colourName.compareToIgnoreCase(o2.colourName); } }; }
UTF-8
Java
2,911
java
Colour.java
Java
[ { "context": " ** Ident: Delivery Center Java\n ** Author: himtiwar\n ** Copyright: (c) Feb 19, 2015 Sogeti Nederland ", "end": 140, "score": 0.9990203976631165, "start": 132, "tag": "USERNAME", "value": "himtiwar" }, { "context": "Auto-generated Javadoc\n/**\n * ????.\n * \n * @author himtiwar (c) Feb 19, 2015, Sogeti B.V.\n * @version $Id:$\n ", "end": 1065, "score": 0.9990989565849304, "start": 1057, "tag": "USERNAME", "value": "himtiwar" } ]
null
[]
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: himtiwar ** Copyright: (c) Feb 19, 2015 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ */ package nl.sogeti.com.domain; import java.util.Comparator; import javax.persistence.AttributeOverride; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; // TODO: Auto-generated Javadoc /** * ????. * * @author himtiwar (c) Feb 19, 2015, Sogeti B.V. * @version $Id:$ */ @Entity @Table(name = "colour") @AttributeOverride(name = "id", column = @Column(name = "colour_id")) public class Colour extends AbstractEntity { /** * <code>serialVersionUID</code> indicates/is used for. */ private static final long serialVersionUID = 3583049578134821535L; /** The colour code. */ private String colourCode; /** The colour name. */ private String colourName; /** * Constructor: create a new Colour. */ public Colour() { super(); // TODO Auto-generated constructor stub } /** * Get the colourCode. * * @return Returns the colourCode as a String. */ public String getColourCode() { return this.colourCode; } /** * Set the colourCode to the specified value. * * @param colourCode The colourCode to set. */ public void setColourCode(String colourCode) { this.colourCode = colourCode; } /** * Get the colourName. * * @return Returns the colourName as a String. */ public String getColourName() { return this.colourName; } /** * Set the colourName to the specified value. * * @param colourName The colourName to set. */ public void setColourName(String colourName) { this.colourName = colourName; } /** The name comparator. */ public static Comparator<Colour> NAME_COMPARATOR = new Comparator<Colour>() { @Override public int compare(Colour o1, Colour o2) { if (o1.colourName == null) { return -1; } if (o2.colourName == null) { return 1; } return o1.colourName.compareToIgnoreCase(o2.colourName); } }; }
2,911
0.545861
0.530402
112
24.991072
24.589304
86
false
false
0
0
0
0
0
0
0.276786
false
false
13
7dc8a3071bee54ee7f575333f07800d52cfa410f
7,224,134,997,750
4bd7a36d09ab4af540861d649b5fab8b02015c78
/app/src/main/java/com/stylet/nutronx/Activities/ui/Patients/PatientFragment.java
f32adad19090d1f7b54b1a48047458495d0d39d5
[]
no_license
oolayemi/NuTronX
https://github.com/oolayemi/NuTronX
ecb3cfeebc787967caecc0bc6880a76b8f1c1893
7162ff55affedd6df3c18f4be9ad72dc6a5e1df6
refs/heads/master
2022-07-28T19:58:52.155000
2020-05-29T00:35:17
2020-05-29T00:35:17
267,727,738
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.stylet.nutronx.Activities.ui.Patients; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.Toolbar; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.stylet.nutronx.Activities.AddNewPatient; import com.stylet.nutronx.R; import java.util.ArrayList; import java.util.List; public class PatientFragment extends Fragment { private PatientViewModel patientViewModel; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_patient, container, false); Toolbar toolbar = root.findViewById(R.id.all_patient_toolbar); final FloatingActionButton fab = root.findViewById(R.id.addpatientfab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent toAddPatient = new Intent(getContext(), AddNewPatient.class); startActivity(toAddPatient); } }); return root; } }
UTF-8
Java
1,435
java
PatientFragment.java
Java
[]
null
[]
package com.stylet.nutronx.Activities.ui.Patients; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.Toolbar; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.stylet.nutronx.Activities.AddNewPatient; import com.stylet.nutronx.R; import java.util.ArrayList; import java.util.List; public class PatientFragment extends Fragment { private PatientViewModel patientViewModel; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_patient, container, false); Toolbar toolbar = root.findViewById(R.id.all_patient_toolbar); final FloatingActionButton fab = root.findViewById(R.id.addpatientfab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent toAddPatient = new Intent(getContext(), AddNewPatient.class); startActivity(toAddPatient); } }); return root; } }
1,435
0.729617
0.729617
49
28.306122
25.876633
84
false
false
0
0
0
0
0
0
0.632653
false
false
13
7fa05d14234a409873462caeb63f5b2d5849102f
11,544,872,160,031
fc715d0a6b48bcc645ca6d87fb7ac4a794141976
/Interface/Animal.java
7300b1be827e68e7601f3767961d9751161b9017
[]
no_license
CSQ223/java-project-template
https://github.com/CSQ223/java-project-template
a3b61837cb904f61b10c5c60153642a13ac24569
1f90538d8ecdf436eaae03ee58e5909df33503a5
refs/heads/main
2023-07-21T15:18:21.464000
2021-09-04T03:20:54
2021-09-04T03:20:54
402,952,925
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Interface; public interface Animal { void Eat(); void Drink(); void Move(); void Shout(); }
UTF-8
Java
125
java
Animal.java
Java
[]
null
[]
package Interface; public interface Animal { void Eat(); void Drink(); void Move(); void Shout(); }
125
0.56
0.56
8
13.625
8.092241
25
false
false
0
0
0
0
0
0
0.625
false
false
13
95edfb40df89d90cee15fb3cbf8eb2766713cbb0
17,506,286,699,087
378c3e511a2b49a679b45a5f4ee8e1add80a4ef6
/src/main/java/uz/pdp/appwarehouse/service/ClientService.java
0ace278ee8b4dbea9e0e7ae48d953052ca2ba576
[]
no_license
sherzodbeek/app-warehouse
https://github.com/sherzodbeek/app-warehouse
6cd0eb58a9a6b51b511bf7c0e474614f24d3647c
62b518b3174eba2f548c066345a9011b6789a370
refs/heads/master
2023-06-02T18:57:42.772000
2021-06-20T20:27:45
2021-06-20T20:27:45
378,658,424
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package uz.pdp.appwarehouse.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import uz.pdp.appwarehouse.entity.Client; import uz.pdp.appwarehouse.payload.Result; import uz.pdp.appwarehouse.repository.ClientRepository; import java.util.List; import java.util.Optional; @Service public class ClientService { @Autowired ClientRepository clientRepository; public List<Client> getAllClientsService() { return clientRepository.findAll(); } public Client getClientService(Integer id) { return clientRepository.findById(id).orElseThrow(() -> new IllegalStateException("Bunday ID li CLient topilmadi!")); } public Result deleteClientService(Integer id) { Optional<Client> optionalClient = clientRepository.findById(id); if(!optionalClient.isPresent()) return new Result("Bunday ID li CLient topilmadi!", false); clientRepository.deleteById(id); return new Result("Client o'chirilid", true); } public Result addClientService(Client client) { Client newClient = new Client(); newClient.setPhoneNumber(client.getPhoneNumber()); newClient.setName(client.getName()); clientRepository.save(newClient); return new Result("Client qo'shildi", true); } public Result editClientService(Integer id, Client client) { Optional<Client> optionalClient = clientRepository.findById(id); if(!optionalClient.isPresent()) return new Result("Bunday ID li CLient topilmadi!", false); Client editingClient = optionalClient.get(); editingClient.setName(client.getName()); editingClient.setPhoneNumber(client.getPhoneNumber()); clientRepository.save(editingClient); return new Result("Client o'zgaritrildi!", true); } }
UTF-8
Java
1,880
java
ClientService.java
Java
[]
null
[]
package uz.pdp.appwarehouse.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import uz.pdp.appwarehouse.entity.Client; import uz.pdp.appwarehouse.payload.Result; import uz.pdp.appwarehouse.repository.ClientRepository; import java.util.List; import java.util.Optional; @Service public class ClientService { @Autowired ClientRepository clientRepository; public List<Client> getAllClientsService() { return clientRepository.findAll(); } public Client getClientService(Integer id) { return clientRepository.findById(id).orElseThrow(() -> new IllegalStateException("Bunday ID li CLient topilmadi!")); } public Result deleteClientService(Integer id) { Optional<Client> optionalClient = clientRepository.findById(id); if(!optionalClient.isPresent()) return new Result("Bunday ID li CLient topilmadi!", false); clientRepository.deleteById(id); return new Result("Client o'chirilid", true); } public Result addClientService(Client client) { Client newClient = new Client(); newClient.setPhoneNumber(client.getPhoneNumber()); newClient.setName(client.getName()); clientRepository.save(newClient); return new Result("Client qo'shildi", true); } public Result editClientService(Integer id, Client client) { Optional<Client> optionalClient = clientRepository.findById(id); if(!optionalClient.isPresent()) return new Result("Bunday ID li CLient topilmadi!", false); Client editingClient = optionalClient.get(); editingClient.setName(client.getName()); editingClient.setPhoneNumber(client.getPhoneNumber()); clientRepository.save(editingClient); return new Result("Client o'zgaritrildi!", true); } }
1,880
0.71117
0.71117
52
35.153847
26.888935
124
false
false
0
0
0
0
0
0
0.634615
false
false
13
58482fc7700d57315f26c0d2a54e8cfae398bae5
17,497,696,831,333
17cb1347a9f055980c25deb61e1300bba1d9d08f
/Test i git/src/hej1.java
e72fadcb0e61b2547363ea0e4edff49072d20941
[]
no_license
madsh93/gittest
https://github.com/madsh93/gittest
91675a3b0812c7bf440f6b4e704bfd6a9d4315a7
034520e92720aaad68052985511c68283b9fadba
refs/heads/master
2018-12-29T04:10:36.523000
2014-09-29T11:00:28
2014-09-29T11:00:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class hej1 { // test af java }
UTF-8
Java
39
java
hej1.java
Java
[]
null
[]
public class hej1 { // test af java }
39
0.641026
0.615385
3
11.666667
7.717225
19
false
false
0
0
0
0
0
0
0
false
false
13
85bbc8fc6c48278d696a463da934de32f2007196
24,232,205,547,781
77c49f4014490d6daa59baf334d21b970699943a
/src/main/java/eu/mihosoft/vfxwebkit/NativeBinding.java
0cb760af25ee7415e7b8ec438588c904191eec17
[ "BSD-2-Clause" ]
permissive
miho/VFXWebKit
https://github.com/miho/VFXWebKit
e3b759cefbfbac78ee25ed6ac90fbec9f9b62fee
6a0c907025997d72df5ea476b1d1f267fc0489d0
refs/heads/master
2020-12-12T08:47:13.455000
2020-02-04T04:48:28
2020-02-04T04:48:28
36,893,206
10
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package eu.mihosoft.vfxwebkit; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.util.HashMap; import java.util.Map; import javafx.scene.image.PixelFormat; /** * * @author Michael Hoffer &lt;info@michaelhoffer.de&gt; */ public enum NativeBinding { INSTANCE; final Map<Integer, VFXWebNode> nodes; private NativeBinding() { this.nodes = new HashMap<>(); } // // native void init(); // // native void newPage(int key); // // native void deletePage(int key); native byte[] pageBuffer(int key); native ByteBuffer pageBufferDirect(int key); // // native int pageBufferSize(int key); // // native void setSize(int key, int w, int h); // // native int getSizeX(int key); // // native int getSizeW(int key); // // native void resizePage(int key, int w, int h); public void redraw(int key, int x1, int y1, int w, int h) { System.out.println("JVM: redraw x1: " + x1 + ", y1: " + y1); VFXWebNode node = nodes.get(key); byte[] buffer = pageBuffer(key); node.redraw(buffer, x1, y1, w, h); System.out.println("- JVM: end -"); } native boolean isDirty(int key); native void setDirty(int key, boolean value); // TODO needs key, works with one node only native void load(String url); // TODO needs key, works with one node only native void init(); // TODO needs key, works with one node only native void lock(); // TODO needs key, works with one node only native void unlock(); }
UTF-8
Java
1,599
java
NativeBinding.java
Java
[ { "context": "javafx.scene.image.PixelFormat;\n\n/**\n *\n * @author Michael Hoffer &lt;info@michaelhoffer.de&gt;\n */\npublic enum Nat", "end": 207, "score": 0.9980749487876892, "start": 193, "tag": "NAME", "value": "Michael Hoffer" }, { "context": "ixelFormat;\n\n/**\n *\n * @author Michael Hoffer &lt;info@michaelhoffer.de&gt;\n */\npublic enum NativeBinding {\n \n INST", "end": 233, "score": 0.9999132752418518, "start": 212, "tag": "EMAIL", "value": "info@michaelhoffer.de" } ]
null
[]
package eu.mihosoft.vfxwebkit; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.util.HashMap; import java.util.Map; import javafx.scene.image.PixelFormat; /** * * @author <NAME> &lt;<EMAIL>&gt; */ public enum NativeBinding { INSTANCE; final Map<Integer, VFXWebNode> nodes; private NativeBinding() { this.nodes = new HashMap<>(); } // // native void init(); // // native void newPage(int key); // // native void deletePage(int key); native byte[] pageBuffer(int key); native ByteBuffer pageBufferDirect(int key); // // native int pageBufferSize(int key); // // native void setSize(int key, int w, int h); // // native int getSizeX(int key); // // native int getSizeW(int key); // // native void resizePage(int key, int w, int h); public void redraw(int key, int x1, int y1, int w, int h) { System.out.println("JVM: redraw x1: " + x1 + ", y1: " + y1); VFXWebNode node = nodes.get(key); byte[] buffer = pageBuffer(key); node.redraw(buffer, x1, y1, w, h); System.out.println("- JVM: end -"); } native boolean isDirty(int key); native void setDirty(int key, boolean value); // TODO needs key, works with one node only native void load(String url); // TODO needs key, works with one node only native void init(); // TODO needs key, works with one node only native void lock(); // TODO needs key, works with one node only native void unlock(); }
1,577
0.608505
0.603502
69
22.173914
19.491325
68
false
false
0
0
0
0
0
0
0.73913
false
false
13
082e42effd211bcd6c4980570e21c6824978f13d
4,569,845,214,940
798e3563930a7f5098a790d86cba09a53a9030bd
/src/com/uas/erp/service/hr/QuestionService.java
cadecf592aad35d148d42321f4ee2b50164f6f89
[]
no_license
dreamvalley/6.0.0
https://github.com/dreamvalley/6.0.0
c5cabed6f34cab783df16de9ff6ddfc118b7c4fe
12ed81bf7a46a649711bcf654bf9bcafe70054c2
refs/heads/master
2022-02-17T02:31:57.439000
2018-07-25T02:52:27
2018-07-25T02:52:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.uas.erp.service.hr; public interface QuestionService { void saveQuestion(String formStore, String caller); void updateQuestionById(String formStore, String caller); void deleteQuestion(int or_id, String caller); }
UTF-8
Java
237
java
QuestionService.java
Java
[]
null
[]
package com.uas.erp.service.hr; public interface QuestionService { void saveQuestion(String formStore, String caller); void updateQuestionById(String formStore, String caller); void deleteQuestion(int or_id, String caller); }
237
0.776371
0.776371
11
20.545454
22.872625
58
false
false
0
0
0
0
0
0
1.181818
false
false
13
14dcf9661abd22aa353a24866a03e99ef8befc5b
7,421,703,522,035
6c54d0f4b87467a0e8d4e443db1e801179c234a7
/webapp/utit/src/test/java/com/skronawi/cicd/webapp/ThingDaoIT.java
55d5e008dd045ad7128cf0d0be27897a117da41f
[]
no_license
sikron/cd-project
https://github.com/sikron/cd-project
250355d7015ca05f44c821c758c00baae770dd6c
707ac93ed411d83a3818c9f44199efce5c0a22ce
refs/heads/master
2020-04-01T20:27:56.121000
2016-06-26T15:11:43
2016-06-26T15:11:43
61,318,699
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.skronawi.cicd.webapp; import com.skronawi.cicd.webapp.persistence.PersistenceConfig; import com.skronawi.cicd.webapp.persistence.Thing; import com.skronawi.cicd.webapp.persistence.ThingDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Set; @ContextConfiguration(classes = PersistenceConfig.class) public class ThingDaoIT extends AbstractTestNGSpringContextTests { @Autowired private ThingDao thingDao; @Test public void createGetDelete() throws Exception{ Set<Thing> all = thingDao.getAll(); Assert.assertTrue(all.isEmpty()); Thing thing = new Thing(); thing.setValue("v"); Thing created = thingDao.create(thing); Assert.assertNotNull(created); Assert.assertEquals(created.getValue(), thing.getValue()); Assert.assertNotNull(created.getId()); Thing retrieved = thingDao.get(created.getId()); Assert.assertNotNull(retrieved); Assert.assertEquals(retrieved.getValue(), thing.getValue()); thingDao.delete(retrieved.getId()); Thing deleted = thingDao.get(retrieved.getId()); Assert.assertNull(deleted); } }
UTF-8
Java
1,397
java
ThingDaoIT.java
Java
[]
null
[]
package com.skronawi.cicd.webapp; import com.skronawi.cicd.webapp.persistence.PersistenceConfig; import com.skronawi.cicd.webapp.persistence.Thing; import com.skronawi.cicd.webapp.persistence.ThingDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Set; @ContextConfiguration(classes = PersistenceConfig.class) public class ThingDaoIT extends AbstractTestNGSpringContextTests { @Autowired private ThingDao thingDao; @Test public void createGetDelete() throws Exception{ Set<Thing> all = thingDao.getAll(); Assert.assertTrue(all.isEmpty()); Thing thing = new Thing(); thing.setValue("v"); Thing created = thingDao.create(thing); Assert.assertNotNull(created); Assert.assertEquals(created.getValue(), thing.getValue()); Assert.assertNotNull(created.getId()); Thing retrieved = thingDao.get(created.getId()); Assert.assertNotNull(retrieved); Assert.assertEquals(retrieved.getValue(), thing.getValue()); thingDao.delete(retrieved.getId()); Thing deleted = thingDao.get(retrieved.getId()); Assert.assertNull(deleted); } }
1,397
0.734431
0.734431
42
32.261906
24.516331
80
false
false
0
0
0
0
0
0
0.642857
false
false
13
b0c58496e007e3d7677d066a7e49694e0014c656
13,159,779,845,174
7e139bcbfd73a14cff46b334c8b1d4090bec4fc6
/src/javaNIO/nio/ClientSocketChannelDemo.java
e61e229ac4c620f557c82392c6cdc844cb1547b5
[]
no_license
hzqiuxm/privateproject
https://github.com/hzqiuxm/privateproject
6e8b27e447fc27f2e70801c12ff89d1d9480fab1
e1d3af380894b271f49048cbaddb33c031b9d267
refs/heads/master
2021-01-17T05:13:10.275000
2018-06-21T01:55:50
2018-06-21T01:55:50
47,237,540
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package javaNIO.nio; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; /** * Copyright © 2016年 author. All rights reserved. * * @Author 临江仙 hxqiuxm@163.com * @Date 2017/1/4 0004 21:02 */ public class ClientSocketChannelDemo { public static void startClient() throws Exception{ SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress("localhost",8999)); socketChannel.configureBlocking(false);//客户端读不到的情况下,改成阻塞就能读到了 String request = "hello ServerSocketChannel"; ByteBuffer byteBuffer = ByteBuffer.wrap(request.getBytes("UTF-8")); socketChannel.write(byteBuffer); ByteBuffer rbuf = ByteBuffer.allocate(64); int size = socketChannel.read(rbuf); while(size>0){ rbuf.flip(); Charset charset = Charset.forName("UTF-8"); System.out.println(charset.newDecoder().decode(rbuf)); rbuf.clear(); size = socketChannel.read(rbuf); } byteBuffer.clear(); rbuf.clear(); socketChannel.close(); Thread.sleep(50000); } public static void main(String[] args) throws Exception{ startClient(); } }
UTF-8
Java
1,365
java
ClientSocketChannelDemo.java
Java
[ { "context": " 2016年 author. All rights reserved.\n *\n * @Author 临江仙 hxqiuxm@163.com\n * @Date 2017/1/4 0004 21:02\n */\n", "end": 230, "score": 0.9998111724853516, "start": 227, "tag": "NAME", "value": "临江仙" }, { "context": "16年 author. All rights reserved.\n *\n * @Author 临江仙 hxqiuxm@163.com\n * @Date 2017/1/4 0004 21:02\n */\npublic class Cli", "end": 246, "score": 0.9998682141304016, "start": 231, "tag": "EMAIL", "value": "hxqiuxm@163.com" } ]
null
[]
package javaNIO.nio; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; /** * Copyright © 2016年 author. All rights reserved. * * @Author 临江仙 <EMAIL> * @Date 2017/1/4 0004 21:02 */ public class ClientSocketChannelDemo { public static void startClient() throws Exception{ SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress("localhost",8999)); socketChannel.configureBlocking(false);//客户端读不到的情况下,改成阻塞就能读到了 String request = "hello ServerSocketChannel"; ByteBuffer byteBuffer = ByteBuffer.wrap(request.getBytes("UTF-8")); socketChannel.write(byteBuffer); ByteBuffer rbuf = ByteBuffer.allocate(64); int size = socketChannel.read(rbuf); while(size>0){ rbuf.flip(); Charset charset = Charset.forName("UTF-8"); System.out.println(charset.newDecoder().decode(rbuf)); rbuf.clear(); size = socketChannel.read(rbuf); } byteBuffer.clear(); rbuf.clear(); socketChannel.close(); Thread.sleep(50000); } public static void main(String[] args) throws Exception{ startClient(); } }
1,357
0.649696
0.6231
51
24.803921
23.37505
75
false
false
0
0
0
0
0
0
0.470588
false
false
13
2ba3c91050f06a4dd7cf57753cf03fc6239eb273
19,799,799,282,437
6ef2e0b663eda56712495942ef1f8a091d3963f2
/src/tests/model/engine/physics/ForceTest.java
639089c2f37ebdfdfdf060020f810e8e852699fb
[ "MIT" ]
permissive
cboin/angrycanard
https://github.com/cboin/angrycanard
5e7b57d8780b1e00ac78a5a56beb4a40b4a88c5f
e714cc4184e3b615b46e051363f82f33a991bb84
refs/heads/master
2018-10-09T08:31:53.708000
2016-01-17T17:55:40
2016-01-17T17:56:29
43,363,769
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tests.model.engine.physics; import static org.junit.Assert.*; import model.engine.physics.Force; import model.engine.utils.Vector2; import org.junit.Test; public class ForceTest { Force fo=new Force(new Vector2(50,50)); @Test public void test1(){ assertTrue(new Vector2(0,-9.81).equals(fo.getAcceleration())); assertEquals(9.81,fo.getGravite(),0.01); assertTrue(fo.getSpeed().equals(new Vector2(50,50))); } @Test public void test2(){ fo.setGravite(1.62); assertFalse(new Vector2(0,-9.81).equals(fo.getAcceleration())); assertNotEquals(9.81,fo.getGravite(),0.01); // Yeah, you're in the moon now. assertTrue(fo.getSpeed().equals(new Vector2(50,50))); fo.setSpeed(new Vector2(30,30)); assertFalse(fo.getSpeed().equals(new Vector2(50,50))); } }
UTF-8
Java
865
java
ForceTest.java
Java
[]
null
[]
package tests.model.engine.physics; import static org.junit.Assert.*; import model.engine.physics.Force; import model.engine.utils.Vector2; import org.junit.Test; public class ForceTest { Force fo=new Force(new Vector2(50,50)); @Test public void test1(){ assertTrue(new Vector2(0,-9.81).equals(fo.getAcceleration())); assertEquals(9.81,fo.getGravite(),0.01); assertTrue(fo.getSpeed().equals(new Vector2(50,50))); } @Test public void test2(){ fo.setGravite(1.62); assertFalse(new Vector2(0,-9.81).equals(fo.getAcceleration())); assertNotEquals(9.81,fo.getGravite(),0.01); // Yeah, you're in the moon now. assertTrue(fo.getSpeed().equals(new Vector2(50,50))); fo.setSpeed(new Vector2(30,30)); assertFalse(fo.getSpeed().equals(new Vector2(50,50))); } }
865
0.645087
0.583815
29
28.827587
24.777727
84
false
false
0
0
0
0
0
0
0.931035
false
false
13
f90c0287031efee88b334bb0247fcfa22a76c76e
17,265,768,591,056
d54a168031385c0df0730eb4bbd8aa6df91c289e
/src/com/reefangel/evolution/GraphActivity.java
fe11bb9dfa675a91d806d7a4964e998b73c7d41d
[]
no_license
reefangel/Evolution
https://github.com/reefangel/Evolution
ab9a684761cf9878f802d080a20e4c47b19b3689
391219f6b8875bb20301a050d9def8407a72bf66
refs/heads/master
2021-01-01T15:51:10.285000
2012-12-29T03:49:37
2012-12-29T03:49:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.reefangel.evolution; import android.app.Activity; import android.graphics.Color; import android.graphics.DashPathEffect; import android.os.Bundle; import android.util.Log; import com.androidplot.Plot.BorderStyle; import com.androidplot.xy.BoundaryMode; import com.androidplot.xy.LineAndPointFormatter; import com.androidplot.xy.SimpleXYSeries; import com.androidplot.xy.XYStepMode; import com.androidplot.series.XYSeries; import java.text.FieldPosition; import java.text.Format; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.List; /** * The simplest possible example of using AndroidPlot to plot some data. */ public class GraphActivity extends Activity { private static final String TAG = "EvolutionGraphActivity"; EvolutionDB dh; int paramid=0; String paramlabel="Param"; int[] seriesColor = { Color.rgb( 236, 142, 142), Color.rgb( 236, 173, 117), Color.rgb( 198, 149, 219), Color.rgb( 162, 224, 165), Color.rgb( 138, 150, 214), Color.rgb( 160, 125, 92), Color.rgb( 83, 125, 82), Color.rgb( 156, 191, 218) }; int[] seriesDecimal = {10,10,10,100,10,1,100,1}; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.graph); Bundle extras = getIntent().getExtras(); if (extras != null) { paramid = extras.getInt("PARAM_ID"); paramlabel = extras.getString("PARAM_LABEL"); } Log.d(TAG,"Param ID: "+paramid); Log.d(TAG,"Param Label: "+paramlabel); MultitouchPlot multitouchPlot = (MultitouchPlot) findViewById(R.id.multitouchPlot); dh = new EvolutionDB(this); List<String[]> series =null ; series=dh.selectAll(); dh.finalize(); Log.d(TAG,"DB Dize: "+series.size()); Number[] Logdate = new Number[series.size()]; Double[] PARAM = new Double[series.size()]; int x=0; Double maxy=0.0; Double miny=10000.0; for (String[] row:series) { Logdate[x]=Integer.parseInt(row[0]); PARAM[x]=Double.parseDouble(row[paramid+1])/seriesDecimal[paramid]; if (PARAM[x]<miny) miny=PARAM[x]; if (PARAM[x]>maxy) maxy=PARAM[x]; x++; } multitouchPlot.addSeries(new SimpleXYSeries(Arrays.asList(Logdate),Arrays.asList(PARAM),paramlabel), new LineAndPointFormatter(seriesColor[paramid],null,null)); // XYSeries series1 = new SimpleXYSeries(Arrays.asList(Logdate),Arrays.asList(T1),paramlabel); // Turn the above arrays into XYSeries: // XYSeries series1 = new SimpleXYSeries( // Arrays.asList(Logdate), // SimpleXYSeries takes a List so turn our array into a List // SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, // Y_VALS_ONLY means use the element index as the x value // paramlabel); // Set the display title of the series // Same as above, for series2 // XYSeries series2 = new SimpleXYSeries(Arrays.asList(series2Numbers), SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, // "Series2"); // Create a formatter to use for drawing a series using LineAndPointRenderer: // LineAndPointFormatter series1Format = new LineAndPointFormatter( // Color.rgb(0, 200, 0), // line color // null, // point color // null); // fill color (optional) multitouchPlot.setDomainValueFormat(new Format() { // create a simple date format that draws on the year portion of our timestamp. // see http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html // for a full description of SimpleDateFormat. private SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa"); @Override public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { // because our timestamps are in seconds and SimpleDateFormat expects milliseconds // we multiply our timestamp by 1000: long timestamp = ((Number) obj).longValue() * 1000; Date date = new Date(timestamp); return dateFormat.format(date, toAppendTo, pos); } @Override public Object parseObject(String source, ParsePosition pos) { return null; } }); // Same as above, with series2: // multitouchPlot.addSeries(series2, new LineAndPointFormatter(Color.rgb(0, 0, 200), Color.rgb(0, 0, 100), // null)); // Reduce the number of range labels multitouchPlot.setTicksPerRangeLabel(1); // By default, AndroidPlot displays developer guides to aid in laying out your plot. // To get rid of them call disableAllMarkup(): multitouchPlot.disableAllMarkup(); multitouchPlot.getTitleWidget().getLabelPaint().setColor(Color.BLACK); multitouchPlot.getLegendWidget().getTextPaint().setColor(Color.BLACK); multitouchPlot.setRangeBoundaries(miny.intValue()-2, maxy.intValue()+2, BoundaryMode.FIXED); multitouchPlot.setRangeStep(XYStepMode.INCREMENT_BY_VAL, .5); multitouchPlot.setDomainBoundaries((new Date().getTime()/1000)-(3600*24), new Date().getTime()/1000, BoundaryMode.FIXED); multitouchPlot.setBorderStyle(BorderStyle.NONE, null, null); multitouchPlot.getBackgroundPaint().setColor(Color.BLACK); multitouchPlot.getGraphWidget().getGridBackgroundPaint().setColor(Color.rgb(230, 230, 255)); multitouchPlot.getGraphWidget().getGridLinePaint().setColor(Color.rgb(170, 170, 170)); multitouchPlot.getGraphWidget().getGridLinePaint().setPathEffect(new DashPathEffect(new float[]{2,2}, 1)); multitouchPlot.getGraphWidget().getDomainLabelPaint().setColor(Color.BLACK); multitouchPlot.getGraphWidget().getRangeLabelPaint().setColor(Color.BLACK); multitouchPlot.getGraphWidget().getRangeOriginLinePaint().setColor(Color.BLACK); multitouchPlot.getGraphWidget().getRangeOriginLabelPaint().setColor(Color.BLACK); multitouchPlot.getGraphWidget().getDomainOriginLabelPaint().setColor(Color.BLACK); multitouchPlot.getGraphWidget().getDomainOriginLinePaint().setColor(Color.BLACK); multitouchPlot.getGraphWidget().getBackgroundPaint().setColor(Color.WHITE); multitouchPlot.getGraphWidget().getDomainLabelPaint().setColor(Color.BLACK); } }
UTF-8
Java
6,584
java
GraphActivity.java
Java
[]
null
[]
package com.reefangel.evolution; import android.app.Activity; import android.graphics.Color; import android.graphics.DashPathEffect; import android.os.Bundle; import android.util.Log; import com.androidplot.Plot.BorderStyle; import com.androidplot.xy.BoundaryMode; import com.androidplot.xy.LineAndPointFormatter; import com.androidplot.xy.SimpleXYSeries; import com.androidplot.xy.XYStepMode; import com.androidplot.series.XYSeries; import java.text.FieldPosition; import java.text.Format; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.List; /** * The simplest possible example of using AndroidPlot to plot some data. */ public class GraphActivity extends Activity { private static final String TAG = "EvolutionGraphActivity"; EvolutionDB dh; int paramid=0; String paramlabel="Param"; int[] seriesColor = { Color.rgb( 236, 142, 142), Color.rgb( 236, 173, 117), Color.rgb( 198, 149, 219), Color.rgb( 162, 224, 165), Color.rgb( 138, 150, 214), Color.rgb( 160, 125, 92), Color.rgb( 83, 125, 82), Color.rgb( 156, 191, 218) }; int[] seriesDecimal = {10,10,10,100,10,1,100,1}; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.graph); Bundle extras = getIntent().getExtras(); if (extras != null) { paramid = extras.getInt("PARAM_ID"); paramlabel = extras.getString("PARAM_LABEL"); } Log.d(TAG,"Param ID: "+paramid); Log.d(TAG,"Param Label: "+paramlabel); MultitouchPlot multitouchPlot = (MultitouchPlot) findViewById(R.id.multitouchPlot); dh = new EvolutionDB(this); List<String[]> series =null ; series=dh.selectAll(); dh.finalize(); Log.d(TAG,"DB Dize: "+series.size()); Number[] Logdate = new Number[series.size()]; Double[] PARAM = new Double[series.size()]; int x=0; Double maxy=0.0; Double miny=10000.0; for (String[] row:series) { Logdate[x]=Integer.parseInt(row[0]); PARAM[x]=Double.parseDouble(row[paramid+1])/seriesDecimal[paramid]; if (PARAM[x]<miny) miny=PARAM[x]; if (PARAM[x]>maxy) maxy=PARAM[x]; x++; } multitouchPlot.addSeries(new SimpleXYSeries(Arrays.asList(Logdate),Arrays.asList(PARAM),paramlabel), new LineAndPointFormatter(seriesColor[paramid],null,null)); // XYSeries series1 = new SimpleXYSeries(Arrays.asList(Logdate),Arrays.asList(T1),paramlabel); // Turn the above arrays into XYSeries: // XYSeries series1 = new SimpleXYSeries( // Arrays.asList(Logdate), // SimpleXYSeries takes a List so turn our array into a List // SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, // Y_VALS_ONLY means use the element index as the x value // paramlabel); // Set the display title of the series // Same as above, for series2 // XYSeries series2 = new SimpleXYSeries(Arrays.asList(series2Numbers), SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, // "Series2"); // Create a formatter to use for drawing a series using LineAndPointRenderer: // LineAndPointFormatter series1Format = new LineAndPointFormatter( // Color.rgb(0, 200, 0), // line color // null, // point color // null); // fill color (optional) multitouchPlot.setDomainValueFormat(new Format() { // create a simple date format that draws on the year portion of our timestamp. // see http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html // for a full description of SimpleDateFormat. private SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa"); @Override public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { // because our timestamps are in seconds and SimpleDateFormat expects milliseconds // we multiply our timestamp by 1000: long timestamp = ((Number) obj).longValue() * 1000; Date date = new Date(timestamp); return dateFormat.format(date, toAppendTo, pos); } @Override public Object parseObject(String source, ParsePosition pos) { return null; } }); // Same as above, with series2: // multitouchPlot.addSeries(series2, new LineAndPointFormatter(Color.rgb(0, 0, 200), Color.rgb(0, 0, 100), // null)); // Reduce the number of range labels multitouchPlot.setTicksPerRangeLabel(1); // By default, AndroidPlot displays developer guides to aid in laying out your plot. // To get rid of them call disableAllMarkup(): multitouchPlot.disableAllMarkup(); multitouchPlot.getTitleWidget().getLabelPaint().setColor(Color.BLACK); multitouchPlot.getLegendWidget().getTextPaint().setColor(Color.BLACK); multitouchPlot.setRangeBoundaries(miny.intValue()-2, maxy.intValue()+2, BoundaryMode.FIXED); multitouchPlot.setRangeStep(XYStepMode.INCREMENT_BY_VAL, .5); multitouchPlot.setDomainBoundaries((new Date().getTime()/1000)-(3600*24), new Date().getTime()/1000, BoundaryMode.FIXED); multitouchPlot.setBorderStyle(BorderStyle.NONE, null, null); multitouchPlot.getBackgroundPaint().setColor(Color.BLACK); multitouchPlot.getGraphWidget().getGridBackgroundPaint().setColor(Color.rgb(230, 230, 255)); multitouchPlot.getGraphWidget().getGridLinePaint().setColor(Color.rgb(170, 170, 170)); multitouchPlot.getGraphWidget().getGridLinePaint().setPathEffect(new DashPathEffect(new float[]{2,2}, 1)); multitouchPlot.getGraphWidget().getDomainLabelPaint().setColor(Color.BLACK); multitouchPlot.getGraphWidget().getRangeLabelPaint().setColor(Color.BLACK); multitouchPlot.getGraphWidget().getRangeOriginLinePaint().setColor(Color.BLACK); multitouchPlot.getGraphWidget().getRangeOriginLabelPaint().setColor(Color.BLACK); multitouchPlot.getGraphWidget().getDomainOriginLabelPaint().setColor(Color.BLACK); multitouchPlot.getGraphWidget().getDomainOriginLinePaint().setColor(Color.BLACK); multitouchPlot.getGraphWidget().getBackgroundPaint().setColor(Color.WHITE); multitouchPlot.getGraphWidget().getDomainLabelPaint().setColor(Color.BLACK); } }
6,584
0.676488
0.650365
157
40.942677
33.609077
168
false
false
0
0
0
0
0
0
1.707006
false
false
13
0e9a7418acaae4b1a27e01b67bbb09fa6d8afd93
33,629,593,975,032
34108bf338f64e3452e480154d1a0073f4a5c84b
/javaWebWorkspace/JavaDesign/src/com/nocol/pattern/structure/Proxy/Test/UserServiceImpl.java
8859e07d970a91b51d7170c552fad1ac5574a33a
[]
no_license
nocol0609/nocol
https://github.com/nocol0609/nocol
4cc25b4ca19cbcacb604cea3f97571079f21e100
98457320af9eb307cb578149fbff77b52e1fdd3f
refs/heads/master
2020-12-02T16:23:35.626000
2017-08-26T13:25:21
2017-08-26T13:25:21
96,543,322
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nocol.pattern.structure.Proxy.Test; public class UserServiceImpl implements UserService{ @Override public void login(String name) { // TODO Auto-generated method stub System.out.println("login....."); } @Override public void register() { // TODO Auto-generated method stub System.out.println("register......."); } }
UTF-8
Java
347
java
UserServiceImpl.java
Java
[]
null
[]
package com.nocol.pattern.structure.Proxy.Test; public class UserServiceImpl implements UserService{ @Override public void login(String name) { // TODO Auto-generated method stub System.out.println("login....."); } @Override public void register() { // TODO Auto-generated method stub System.out.println("register......."); } }
347
0.706052
0.706052
17
19.411764
18.711617
53
false
false
0
0
0
0
0
0
1
false
false
13
f1d7b4f97c8fdf44ecf9c8a15bd12d0d47db4ed1
10,050,223,519,694
f2b4d3366d5aea4ee4e3635ad02a1bcfaa5fb6a9
/resseler/resseler-core/resseler-commons/src/main/java/br/com/rubyit/resseler/core/commons/exceptions/RetrieveCustomerException.java
973733d07853fd3a3c5af09afe7ca3598495e39a
[]
no_license
thiago-devel/java
https://github.com/thiago-devel/java
cec8f8d67084f71e8e328e2575a0fa98830a10df
c36e1f09ade73c8b28742509e7fa134af2268541
refs/heads/master
2022-12-23T00:17:16.189000
2019-06-10T23:32:34
2019-06-10T23:32:34
139,039,198
0
0
null
false
2022-12-16T10:32:03
2018-06-28T15:49:06
2019-06-10T23:32:46
2022-12-16T10:31:59
1,178
0
0
17
Java
false
false
package br.com.rubyit.resseler.core.commons.exceptions; import br.com.rubyit.resseler.core.enums.ErrorType; public class RetrieveCustomerException extends RawException { /** * Método de lançamento da exception RetrieveCustomerException * @param message * @param cause * @param code * @param errorType */ public RetrieveCustomerException(final String message, final Throwable cause, final String code, final ErrorType errorType) { super(message, cause, code, errorType); } }
UTF-8
Java
553
java
RetrieveCustomerException.java
Java
[]
null
[]
package br.com.rubyit.resseler.core.commons.exceptions; import br.com.rubyit.resseler.core.enums.ErrorType; public class RetrieveCustomerException extends RawException { /** * Método de lançamento da exception RetrieveCustomerException * @param message * @param cause * @param code * @param errorType */ public RetrieveCustomerException(final String message, final Throwable cause, final String code, final ErrorType errorType) { super(message, cause, code, errorType); } }
553
0.689655
0.689655
19
28
23.584116
66
false
false
0
0
0
0
0
0
0.473684
false
false
13
5885311ff94616962ccb068568e3f0766a90f7d3
27,127,013,490,500
52176bbcceb3b41796eff54b6487469add81b3dd
/src/main/java/pl/januszsoft/feature/round/RoundDTO.java
5dde841cd3b7b7b86af517a6facd4130b5b23b1f
[]
no_license
JanuszSoft/ebet
https://github.com/JanuszSoft/ebet
3a2ea10add5a5984e7b156a33351386f26af494c
749bf122c66ce5dcf38f1479f18670e32d174b52
refs/heads/master
2021-01-15T10:58:02.123000
2017-10-21T22:10:23
2017-10-21T22:10:23
99,604,864
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.januszsoft.feature.round; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.hateoas.ResourceSupport; import pl.januszsoft.feature.match.MatchDTO; import java.util.ArrayList; import java.util.List; @Data @NoArgsConstructor public class RoundDTO extends ResourceSupport { @JsonProperty("id") private long roundId; private long leagueId; @JsonProperty("matchList") private List<MatchDTO> matchDTOList = new ArrayList<>(); public RoundDTO(List<MatchDTO> matchDTOList) { this.matchDTOList = matchDTOList; } }
UTF-8
Java
644
java
RoundDTO.java
Java
[]
null
[]
package pl.januszsoft.feature.round; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.hateoas.ResourceSupport; import pl.januszsoft.feature.match.MatchDTO; import java.util.ArrayList; import java.util.List; @Data @NoArgsConstructor public class RoundDTO extends ResourceSupport { @JsonProperty("id") private long roundId; private long leagueId; @JsonProperty("matchList") private List<MatchDTO> matchDTOList = new ArrayList<>(); public RoundDTO(List<MatchDTO> matchDTOList) { this.matchDTOList = matchDTOList; } }
644
0.762422
0.762422
28
22
19.733944
61
false
false
0
0
0
0
0
0
0.428571
false
false
13
93e1fa66bcaaf79b2f582456b202dac7e4c22938
24,558,623,053,078
f3628df04f5b554976a23b39f8422bea16e9cfe3
/src/JavaSTART/Work_Presentation/Lesson_8_Pages_161_178/Page_170/Exercise_4/MyClass_Replace_1.java
1f27415c2bc496b652ebcc9acf046a69cef1a9b9
[ "Apache-2.0" ]
permissive
AlSidorenko/ProgKievUa
https://github.com/AlSidorenko/ProgKievUa
b2570ae979ed059095bf4e4e7b17a33c3459fe8d
79ae1c47c17eaae58700bf522b3feb9aee9a9d1e
refs/heads/master
2017-12-02T20:50:13.186000
2017-08-04T16:09:37
2017-08-04T16:09:37
95,046,495
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package JavaSTART.Work_Presentation.Lesson_8_Pages_161_178.Page_170.Exercise_4; /** * Created by Александр on 28.02.2017. */ public class MyClass_Replace_1 { public static void main(String[] args) { System.out.println(); } /*public static String replace (String s, char ch, char sub) { } */ }
UTF-8
Java
335
java
MyClass_Replace_1.java
Java
[ { "context": "es_161_178.Page_170.Exercise_4;\n\n/**\n * Created by Александр on 28.02.2017.\n */\npublic class MyClass_Replace_1", "end": 108, "score": 0.9998547434806824, "start": 99, "tag": "NAME", "value": "Александр" } ]
null
[]
package JavaSTART.Work_Presentation.Lesson_8_Pages_161_178.Page_170.Exercise_4; /** * Created by Александр on 28.02.2017. */ public class MyClass_Replace_1 { public static void main(String[] args) { System.out.println(); } /*public static String replace (String s, char ch, char sub) { } */ }
335
0.647239
0.58589
15
20.733334
25.164701
79
false
false
0
0
0
0
0
0
0.266667
false
false
13
66a36d28b5db77cba38a052505f259e22c65f1af
24,558,623,052,259
674f624872920dc84e9c2b26650afd1a0e16c7e2
/src/main/java/gd/rf/acro/walledkingdoms/Items/tool/ItemShovel.java
c568b458112c298a0b5ac9d3a397356eec8acf05
[]
no_license
JSJBDEV/WalledKingdoms
https://github.com/JSJBDEV/WalledKingdoms
480a855939e2f8c81ded37e68b1efb6015aef06a
47428e8d727c9ea877afc47aed37e50c6278ccf9
refs/heads/master
2022-04-12T07:17:31.973000
2020-03-30T20:13:21
2020-03-30T20:13:21
217,395,167
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gd.rf.acro.walledkingdoms.Items.tool; import gd.rf.acro.walledkingdoms.WalledKingdoms; import net.minecraft.item.ItemSpade; public class ItemShovel extends ItemSpade { private String name; public ItemShovel(ToolMaterial material, String name) { super(material); setRegistryName(name); setUnlocalizedName(name); this.name = name; setCreativeTab(WalledKingdoms.tab); } public void registerItemModel() { WalledKingdoms.proxy.registerItemRenderer(this, 0, name); } }
UTF-8
Java
543
java
ItemShovel.java
Java
[]
null
[]
package gd.rf.acro.walledkingdoms.Items.tool; import gd.rf.acro.walledkingdoms.WalledKingdoms; import net.minecraft.item.ItemSpade; public class ItemShovel extends ItemSpade { private String name; public ItemShovel(ToolMaterial material, String name) { super(material); setRegistryName(name); setUnlocalizedName(name); this.name = name; setCreativeTab(WalledKingdoms.tab); } public void registerItemModel() { WalledKingdoms.proxy.registerItemRenderer(this, 0, name); } }
543
0.705341
0.703499
20
26.15
20.662224
65
false
false
0
0
0
0
0
0
0.65
false
false
13
3c9f06af78c6403e3c50a8a6c37bcd8b7dbf38ca
13,116,830,193,445
4bb83687710716d91b5da55054c04f430474ee52
/dsrc/sku.0/sys.server/compiled/game/script/theme_park/meatlump/destroy_weapon_cachev2.java
dd2bcc704c5b41b1eff787f81008a8e8e6aa11a6
[]
no_license
geralex/SWG-NGE
https://github.com/geralex/SWG-NGE
0846566a44f4460c32d38078e0a1eb115a9b08b0
fa8ae0017f996e400fccc5ba3763e5bb1c8cdd1c
refs/heads/master
2020-04-06T11:18:36.110000
2018-03-19T15:42:32
2018-03-19T15:42:32
157,411,938
1
0
null
true
2018-11-13T16:35:01
2018-11-13T16:35:01
2018-03-19T15:42:35
2018-03-19T15:42:33
47,108
0
0
0
null
false
null
package script.theme_park.meatlump; import script.*; import script.base_class.*; import script.combat_engine.*; import java.util.Arrays; import java.util.Hashtable; import java.util.Vector; import script.base_script; import script.library.collection; import script.library.sui; import script.library.stealth; import script.library.utils; public class destroy_weapon_cachev2 extends script.base_script { public destroy_weapon_cachev2() { } public static final String VAR_PREFIX = "meatlump_weapon_cache"; public static final String PID_NAME = VAR_PREFIX + ".pid"; public static final String CURRENTLY_CALIBRATION = VAR_PREFIX + ".calibration"; public static final String CALIBRATION_GOAL = VAR_PREFIX + ".goal"; public static final String CALIBRATION_CURRENT = VAR_PREFIX + ".current"; public static final String CALIBRATION_TRIES = VAR_PREFIX + ".tries"; public static final String CALIBRATION_MAX_TRIES = VAR_PREFIX + ".max_tries"; public static final String STATUS_VAR = VAR_PREFIX + ".status"; public static final String COMPONENT_VAR = VAR_PREFIX + ".component"; public static final String CAPTION = "Calibrate Power Cell Abatement"; public static final String OBJVAR_SLOT_NAME = "collection.slotName"; public static final string_id SID_OPEN = new string_id("meatlump/meatlump", "weapon_calibration_use"); public static final String CALIBRATION_ATTEMPTS_REMAINING = "@meatlump/meatlump:weapon_calibration_attempts_remaining"; public static final String CALIBRATION_SUCCESS = "@meatlump/meatlump:weapon_calibration_success"; public static final String CALIBRATION_FAILURE = "@meatlump/meatlump:weapon_calibration_failure"; public static final String CALIBRATION_DESCRIPTION = "@meatlump/meatlump:weapon_calibration_description"; public static final string_id SID_ALREADY_FINISHED_COLLECTION = new string_id("collection", "already_finished_collection"); public static final string_id SID_NOT_CLOSE_ENOUGH = new string_id("collection", "not_close_enough"); public static final string_id SID_ALREADY_HAVE_SLOT = new string_id("collection", "already_have_slot"); public static final string_id SID_REPORT_CONSUME_ITEM_FAIL = new string_id("collection", "report_consume_item_fail"); public static final string_id MSG_CALIBRATION_ABORTED = new string_id("quest/force_sensitive/fs_crafting", "phase1_msg_calibration_aborted"); public static final int MAX_RANGE_TO_COLLECT = 3; public static final int DEFAULT_TRIES = 10; public static final String[] CONFIG_PLAYER_BUTTONS = { "top.triangles.player.right.1", "top.triangles.player.right.2", "top.triangles.player.right.3", "top.triangles.player.left.2", "top.triangles.player.left.3", "top.triangles.player.left.1" }; public static final String[] CONFIG_SERVER_BUTTONS = { "top.triangles.server.right.1", "top.triangles.server.right.2", "top.triangles.server.right.3", "top.triangles.server.left.2", "top.triangles.server.left.3", "top.triangles.server.left.1" }; public static final int[] DEFAULT_GOAL_CURRENT_ARRAY = { 0, 0, 0, 0, 0, 0 }; public int OnObjectMenuRequest(obj_id self, obj_id player, menu_info mi) throws InterruptedException { mi.addRootMenu(menu_info_types.ITEM_USE, SID_OPEN); return SCRIPT_CONTINUE; } public int OnObjectMenuSelect(obj_id self, obj_id player, int item) throws InterruptedException { if (!isIdValid(player) || !exists(player)) { return SCRIPT_CONTINUE; } obj_id collectionItem = self; if (!hasObjVar(collectionItem, OBJVAR_SLOT_NAME)) { return SCRIPT_CONTINUE; } if (item != menu_info_types.ITEM_USE) { return SCRIPT_CONTINUE; } String baseSlotName = getStringObjVar(collectionItem, OBJVAR_SLOT_NAME); String[] splitSlotNames = split(baseSlotName, ':'); String slotName = splitSlotNames[1]; String collectionName = splitSlotNames[0]; if (!hasCompletedCollectionSlotPrereq(player, slotName)) { sendSystemMessage(player, collection.SID_NEED_TO_ACTIVATE_COLLECTION); return SCRIPT_CONTINUE; } else if (hasCompletedCollection(player, collectionName)) { sendSystemMessage(player, SID_ALREADY_FINISHED_COLLECTION); return SCRIPT_CONTINUE; } else if ((slotName == null || slotName.equals("")) || hasCompletedCollectionSlot(player, slotName)) { sendSystemMessage(player, SID_ALREADY_HAVE_SLOT); return SCRIPT_CONTINUE; } closeOldWindow(player); blog("OnObjectMenuSelect"); createConfigUI(collectionItem, player); return SCRIPT_CONTINUE; } public boolean createConfigUI(obj_id collectionItem, obj_id player) throws InterruptedException { blog("createConfigUI - INIT"); if (!isValidId(collectionItem) || !isValidId(player)) { return false; } else if (!exists(collectionItem) || !exists(player)) { return false; } dictionary params = new dictionary(); int pid = createSUIPage("/Script.calibration.game4", collectionItem, player); sui.setPid(player, pid, PID_NAME); setSUIAssociatedLocation(pid, collectionItem); setSUIMaxRangeToObject(pid, 8); params.put("callingPid", pid); blog("createConfigUI - sending to initializeCalibration"); if (!initializeCalibration(collectionItem, player)) { return false; } setSUIProperty(pid, "bg.caption.lbltitle", "Text", CAPTION); setSUIProperty(pid, "top.description.desc", "Text", CALIBRATION_DESCRIPTION); setSUIProperty(pid, "top.description.attempts", "Text", CALIBRATION_ATTEMPTS_REMAINING + " 100%"); int[] goal = utils.getIntArrayScriptVar(player, CALIBRATION_GOAL); if (goal == null) { return false; } blog("createConfigUI - goal.length: " + goal.length); for (int i = 0; i < goal.length; i++) { if (goal[i] == 1) { setSUIProperty(pid, CONFIG_SERVER_BUTTONS[i], "Color", "#000000"); } setSUIProperty(pid, CONFIG_SERVER_BUTTONS[i], "IsCancelButton", "false"); setSUIProperty(pid, CONFIG_PLAYER_BUTTONS[i], "IsCancelButton", "false"); } setSUIProperty(pid, "bg.mmc.close", "IsCancelButton", "true"); for (int i = 0; i < CONFIG_PLAYER_BUTTONS.length; i++) { subscribeToSUIEvent(pid, sui_event_type.SET_onButton, CONFIG_PLAYER_BUTTONS[i], "configProcessorPuzzleCallback"); } setSUIAssociatedObject(pid, player); setSUIMaxRangeToObject(pid, 10.0f); showSUIPage(pid); return true; } public boolean initializeCalibration(obj_id collectionItem, obj_id player) throws InterruptedException { blog("initializeCalibration - INIT"); if (!isValidId(collectionItem) || !isValidId(player)) { return false; } blog("initializeCalibration - creating stuff"); int[] goal = DEFAULT_GOAL_CURRENT_ARRAY; int[] current = DEFAULT_GOAL_CURRENT_ARRAY; int lastr = -1; int r = -1; int tries = DEFAULT_TRIES; boolean mixed = false; while (!mixed) { for (int h = 0; h < 6; h++) { goal[h] = 0; } for (int i = 0; i < 6; i++) { do { r = rand(0, 5); } while (r == lastr); lastr = r; goal = toggleButton(goal, r); } for (int j = 0; j < 6; j++) { if (goal[j] != current[j]) { mixed = true; } } } blog("initializeCalibration - saving data"); utils.setScriptVar(player, CALIBRATION_GOAL, goal); utils.setScriptVar(player, CALIBRATION_CURRENT, current); utils.setScriptVar(player, CALIBRATION_TRIES, tries); utils.setScriptVar(player, CALIBRATION_MAX_TRIES, tries); return true; } public int[] toggleButton(int[] config, int button) throws InterruptedException { if (config == null || button < 0) { return null; } blog("toggleButton - init"); int secondary1 = -1; int secondary2 = -1; switch (button) { case 0: secondary1 = 3; secondary2 = 4; break; case 1: secondary1 = 4; secondary2 = 5; break; case 2: secondary1 = 3; secondary2 = 5; break; case 3: secondary1 = 0; secondary2 = 2; break; case 4: secondary1 = 0; secondary2 = 1; break; case 5: secondary1 = 1; secondary2 = 2; break; } if (secondary1 == -1 || secondary2 == -1) { return null; } if (config[button] == 0) { config[button] = 1; } else { config[button] = 0; } if (config[secondary1] == 0) { config[secondary1] = 1; } else { config[secondary1] = 0; } if (config[secondary2] == 0) { config[secondary2] = 1; } else { config[secondary2] = 0; } blog("toggleButton - returning config"); return config; } public int configProcessorPuzzleCallback(obj_id self, dictionary params) throws InterruptedException { blog("configProcessorPuzzleCallback - INIT"); obj_id player = sui.getPlayerId(params); if (!isValidId(player)) { blog("configProcessorPuzzleCallback - NO PLAYER"); return SCRIPT_CONTINUE; } String widgetName = params.getString("eventWidgetName"); blog("configProcessorPuzzleCallback widgetName - " + widgetName); int pid = sui.getPid(player, PID_NAME); if (pid <= 0) { blog("configProcessorPuzzleCallback pid FAILED " + pid); return SCRIPT_CONTINUE; } blog("configProcessorPuzzleCallback pid - " + pid); if (widgetName == null || widgetName.equals("")) { blog("configProcessorPuzzleCallback widgetName = null "); obj_id component = utils.getObjIdScriptVar(self, COMPONENT_VAR); if (!hasObjVar(component, STATUS_VAR)) { setObjVar(component, STATUS_VAR, -1); sendSystemMessage(self, MSG_CALIBRATION_ABORTED); } removePlayerVars(player); forceCloseSUIPage(pid); return SCRIPT_CONTINUE; } blog("configProcessorPuzzleCallback widget != null"); int index = -1; for (int i = 0; i < CONFIG_PLAYER_BUTTONS.length; i++) { setSUIProperty(pid, CONFIG_PLAYER_BUTTONS[i], "Color", "#FFFFFF"); if (widgetName.equalsIgnoreCase(CONFIG_PLAYER_BUTTONS[i])) { index = i; } } blog("configProcessorPuzzleCallback index: " + index); if (index < 0 || index > 5) { return SCRIPT_CONTINUE; } int[] current = utils.getIntArrayScriptVar(player, CALIBRATION_CURRENT); int[] goal = utils.getIntArrayScriptVar(player, CALIBRATION_GOAL); int tries = utils.getIntScriptVar(player, CALIBRATION_TRIES); int max_tries = utils.getIntScriptVar(player, CALIBRATION_MAX_TRIES); if (current == null || goal == null) { blog("configProcessorPuzzleCallback current or goal == null"); removePlayerVars(player); return SCRIPT_CONTINUE; } blog("configProcessorPuzzleCallback - About to toggle buttons"); current = toggleButton(current, index); if (current == null) { blog("configProcessorPuzzleCallback current is NULL"); return SCRIPT_CONTINUE; } for (int i = 0; i < CONFIG_PLAYER_BUTTONS.length; i++) { if (current[i] == 1) { blog("configProcessorPuzzleCallback setting to black: " + CONFIG_PLAYER_BUTTONS[i]); setSUIProperty(pid, CONFIG_PLAYER_BUTTONS[i], "Color", "#000000"); } } tries--; int integrity = (int)(((float)tries / (float)max_tries) * 100); blog("configProcessorPuzzleCallback integrity: " + integrity); boolean win = true; for (int i = 0; i < current.length; i++) { if (current[i] != goal[i]) { win = false; } } blog("configProcessorPuzzleCallback win: " + win); if (win) { blog("configProcessorPuzzleCallback THE WIN "); obj_id component = utils.getObjIdScriptVar(player, COMPONENT_VAR); setObjVar(component, STATUS_VAR, 1); setSUIProperty(pid, "top.description.desc", "Text", CALIBRATION_SUCCESS); for (int i = 0; i < CONFIG_PLAYER_BUTTONS.length; i++) { subscribeToSUIEvent(pid, sui_event_type.SET_onButton, CONFIG_PLAYER_BUTTONS[i], "noCallback"); setSUIProperty(pid, CONFIG_PLAYER_BUTTONS[i], "GetsInput", "false"); } rewardPlayer(self, player); } else if (tries <= 0) { blog("configProcessorPuzzleCallback YOU LOSE "); obj_id component = utils.getObjIdScriptVar(player, COMPONENT_VAR); setObjVar(component, STATUS_VAR, -1); setSUIProperty(pid, "top.description.attempts", "Text", CALIBRATION_ATTEMPTS_REMAINING + " " + integrity + "%"); setSUIProperty(pid, "top.description.desc", "Text", CALIBRATION_FAILURE); for (int i = 0; i < CONFIG_PLAYER_BUTTONS.length; i++) { subscribeToSUIEvent(pid, sui_event_type.SET_onButton, CONFIG_PLAYER_BUTTONS[i], "noCallback"); setSUIProperty(pid, CONFIG_PLAYER_BUTTONS[i], "GetsInput", "false"); } removePlayerVars(player); } else { blog("configProcessorPuzzleCallback DECREMENT "); setSUIProperty(pid, "top.description.attempts", "Text", CALIBRATION_ATTEMPTS_REMAINING + " " + integrity + "%"); } utils.setScriptVar(player, CALIBRATION_CURRENT, current); utils.setScriptVar(player, CALIBRATION_TRIES, tries); flushSUIPage(pid); return SCRIPT_CONTINUE; } public boolean rewardPlayer(obj_id collectionItem, obj_id player) throws InterruptedException { if (!isValidId(collectionItem) || !isValidId(player)) { return false; } String baseSlotName = getStringObjVar(collectionItem, OBJVAR_SLOT_NAME); String[] splitSlotNames = split(baseSlotName, ':'); String slotName = splitSlotNames[1]; String collectionName = splitSlotNames[0]; if (!hasCompletedCollectionSlotPrereq(player, slotName)) { sendSystemMessage(player, collection.SID_NEED_TO_ACTIVATE_COLLECTION); return false; } else if (hasCompletedCollection(player, collectionName)) { sendSystemMessage(player, SID_ALREADY_FINISHED_COLLECTION); return false; } else if ((slotName == null || slotName.equals("")) || hasCompletedCollectionSlot(player, slotName)) { sendSystemMessage(player, SID_ALREADY_HAVE_SLOT); return false; } boolean currentState = collection.checkState(player); if (!currentState) { return false; } boolean isCloseEnough = collection.checkDistance(collectionItem, player, MAX_RANGE_TO_COLLECT); if (!isCloseEnough) { blog("Not Close ENOUGH"); sendSystemMessage(player, SID_NOT_CLOSE_ENOUGH); return false; } blog("Player collecting " + slotName); stealth.testInvisNonCombatAction(player, collectionItem); collection.giveAreaMobsHate(collectionItem, player); closeOldWindow(player); removePlayerVars(player); if (modifyCollectionSlotValue(player, slotName, 1)) { CustomerServiceLog("CollectionConsume: ", "collectionItem (" + collectionItem + ")" + " was consumed into a collection, for player " + getFirstName(player) + "(" + player + ")."); return false; } else { CustomerServiceLog("CollectionConsume: ", "collectionItem (" + collectionItem + ")" + " was NOT consumed into a collection, for player " + getFirstName(player) + "(" + player + ")."); sendSystemMessage(player, SID_REPORT_CONSUME_ITEM_FAIL); } return false; } public void closeOldWindow(obj_id player) throws InterruptedException { blog("closeOldWindow - init"); int pid = sui.getPid(player, PID_NAME); blog("closeOldWindow - pid: " + pid); if (pid > -1) { blog("closeOldWindow - force closing: " + pid); forceCloseSUIPage(pid); sui.removePid(player, PID_NAME); } } public void removePlayerVars(obj_id player) throws InterruptedException { utils.removeScriptVarTree(player, VAR_PREFIX); utils.removeObjVar(player, VAR_PREFIX); } public boolean blog(String msg) throws InterruptedException { LOG("minigame", msg); return true; } }
UTF-8
Java
18,284
java
destroy_weapon_cachev2.java
Java
[]
null
[]
package script.theme_park.meatlump; import script.*; import script.base_class.*; import script.combat_engine.*; import java.util.Arrays; import java.util.Hashtable; import java.util.Vector; import script.base_script; import script.library.collection; import script.library.sui; import script.library.stealth; import script.library.utils; public class destroy_weapon_cachev2 extends script.base_script { public destroy_weapon_cachev2() { } public static final String VAR_PREFIX = "meatlump_weapon_cache"; public static final String PID_NAME = VAR_PREFIX + ".pid"; public static final String CURRENTLY_CALIBRATION = VAR_PREFIX + ".calibration"; public static final String CALIBRATION_GOAL = VAR_PREFIX + ".goal"; public static final String CALIBRATION_CURRENT = VAR_PREFIX + ".current"; public static final String CALIBRATION_TRIES = VAR_PREFIX + ".tries"; public static final String CALIBRATION_MAX_TRIES = VAR_PREFIX + ".max_tries"; public static final String STATUS_VAR = VAR_PREFIX + ".status"; public static final String COMPONENT_VAR = VAR_PREFIX + ".component"; public static final String CAPTION = "Calibrate Power Cell Abatement"; public static final String OBJVAR_SLOT_NAME = "collection.slotName"; public static final string_id SID_OPEN = new string_id("meatlump/meatlump", "weapon_calibration_use"); public static final String CALIBRATION_ATTEMPTS_REMAINING = "@meatlump/meatlump:weapon_calibration_attempts_remaining"; public static final String CALIBRATION_SUCCESS = "@meatlump/meatlump:weapon_calibration_success"; public static final String CALIBRATION_FAILURE = "@meatlump/meatlump:weapon_calibration_failure"; public static final String CALIBRATION_DESCRIPTION = "@meatlump/meatlump:weapon_calibration_description"; public static final string_id SID_ALREADY_FINISHED_COLLECTION = new string_id("collection", "already_finished_collection"); public static final string_id SID_NOT_CLOSE_ENOUGH = new string_id("collection", "not_close_enough"); public static final string_id SID_ALREADY_HAVE_SLOT = new string_id("collection", "already_have_slot"); public static final string_id SID_REPORT_CONSUME_ITEM_FAIL = new string_id("collection", "report_consume_item_fail"); public static final string_id MSG_CALIBRATION_ABORTED = new string_id("quest/force_sensitive/fs_crafting", "phase1_msg_calibration_aborted"); public static final int MAX_RANGE_TO_COLLECT = 3; public static final int DEFAULT_TRIES = 10; public static final String[] CONFIG_PLAYER_BUTTONS = { "top.triangles.player.right.1", "top.triangles.player.right.2", "top.triangles.player.right.3", "top.triangles.player.left.2", "top.triangles.player.left.3", "top.triangles.player.left.1" }; public static final String[] CONFIG_SERVER_BUTTONS = { "top.triangles.server.right.1", "top.triangles.server.right.2", "top.triangles.server.right.3", "top.triangles.server.left.2", "top.triangles.server.left.3", "top.triangles.server.left.1" }; public static final int[] DEFAULT_GOAL_CURRENT_ARRAY = { 0, 0, 0, 0, 0, 0 }; public int OnObjectMenuRequest(obj_id self, obj_id player, menu_info mi) throws InterruptedException { mi.addRootMenu(menu_info_types.ITEM_USE, SID_OPEN); return SCRIPT_CONTINUE; } public int OnObjectMenuSelect(obj_id self, obj_id player, int item) throws InterruptedException { if (!isIdValid(player) || !exists(player)) { return SCRIPT_CONTINUE; } obj_id collectionItem = self; if (!hasObjVar(collectionItem, OBJVAR_SLOT_NAME)) { return SCRIPT_CONTINUE; } if (item != menu_info_types.ITEM_USE) { return SCRIPT_CONTINUE; } String baseSlotName = getStringObjVar(collectionItem, OBJVAR_SLOT_NAME); String[] splitSlotNames = split(baseSlotName, ':'); String slotName = splitSlotNames[1]; String collectionName = splitSlotNames[0]; if (!hasCompletedCollectionSlotPrereq(player, slotName)) { sendSystemMessage(player, collection.SID_NEED_TO_ACTIVATE_COLLECTION); return SCRIPT_CONTINUE; } else if (hasCompletedCollection(player, collectionName)) { sendSystemMessage(player, SID_ALREADY_FINISHED_COLLECTION); return SCRIPT_CONTINUE; } else if ((slotName == null || slotName.equals("")) || hasCompletedCollectionSlot(player, slotName)) { sendSystemMessage(player, SID_ALREADY_HAVE_SLOT); return SCRIPT_CONTINUE; } closeOldWindow(player); blog("OnObjectMenuSelect"); createConfigUI(collectionItem, player); return SCRIPT_CONTINUE; } public boolean createConfigUI(obj_id collectionItem, obj_id player) throws InterruptedException { blog("createConfigUI - INIT"); if (!isValidId(collectionItem) || !isValidId(player)) { return false; } else if (!exists(collectionItem) || !exists(player)) { return false; } dictionary params = new dictionary(); int pid = createSUIPage("/Script.calibration.game4", collectionItem, player); sui.setPid(player, pid, PID_NAME); setSUIAssociatedLocation(pid, collectionItem); setSUIMaxRangeToObject(pid, 8); params.put("callingPid", pid); blog("createConfigUI - sending to initializeCalibration"); if (!initializeCalibration(collectionItem, player)) { return false; } setSUIProperty(pid, "bg.caption.lbltitle", "Text", CAPTION); setSUIProperty(pid, "top.description.desc", "Text", CALIBRATION_DESCRIPTION); setSUIProperty(pid, "top.description.attempts", "Text", CALIBRATION_ATTEMPTS_REMAINING + " 100%"); int[] goal = utils.getIntArrayScriptVar(player, CALIBRATION_GOAL); if (goal == null) { return false; } blog("createConfigUI - goal.length: " + goal.length); for (int i = 0; i < goal.length; i++) { if (goal[i] == 1) { setSUIProperty(pid, CONFIG_SERVER_BUTTONS[i], "Color", "#000000"); } setSUIProperty(pid, CONFIG_SERVER_BUTTONS[i], "IsCancelButton", "false"); setSUIProperty(pid, CONFIG_PLAYER_BUTTONS[i], "IsCancelButton", "false"); } setSUIProperty(pid, "bg.mmc.close", "IsCancelButton", "true"); for (int i = 0; i < CONFIG_PLAYER_BUTTONS.length; i++) { subscribeToSUIEvent(pid, sui_event_type.SET_onButton, CONFIG_PLAYER_BUTTONS[i], "configProcessorPuzzleCallback"); } setSUIAssociatedObject(pid, player); setSUIMaxRangeToObject(pid, 10.0f); showSUIPage(pid); return true; } public boolean initializeCalibration(obj_id collectionItem, obj_id player) throws InterruptedException { blog("initializeCalibration - INIT"); if (!isValidId(collectionItem) || !isValidId(player)) { return false; } blog("initializeCalibration - creating stuff"); int[] goal = DEFAULT_GOAL_CURRENT_ARRAY; int[] current = DEFAULT_GOAL_CURRENT_ARRAY; int lastr = -1; int r = -1; int tries = DEFAULT_TRIES; boolean mixed = false; while (!mixed) { for (int h = 0; h < 6; h++) { goal[h] = 0; } for (int i = 0; i < 6; i++) { do { r = rand(0, 5); } while (r == lastr); lastr = r; goal = toggleButton(goal, r); } for (int j = 0; j < 6; j++) { if (goal[j] != current[j]) { mixed = true; } } } blog("initializeCalibration - saving data"); utils.setScriptVar(player, CALIBRATION_GOAL, goal); utils.setScriptVar(player, CALIBRATION_CURRENT, current); utils.setScriptVar(player, CALIBRATION_TRIES, tries); utils.setScriptVar(player, CALIBRATION_MAX_TRIES, tries); return true; } public int[] toggleButton(int[] config, int button) throws InterruptedException { if (config == null || button < 0) { return null; } blog("toggleButton - init"); int secondary1 = -1; int secondary2 = -1; switch (button) { case 0: secondary1 = 3; secondary2 = 4; break; case 1: secondary1 = 4; secondary2 = 5; break; case 2: secondary1 = 3; secondary2 = 5; break; case 3: secondary1 = 0; secondary2 = 2; break; case 4: secondary1 = 0; secondary2 = 1; break; case 5: secondary1 = 1; secondary2 = 2; break; } if (secondary1 == -1 || secondary2 == -1) { return null; } if (config[button] == 0) { config[button] = 1; } else { config[button] = 0; } if (config[secondary1] == 0) { config[secondary1] = 1; } else { config[secondary1] = 0; } if (config[secondary2] == 0) { config[secondary2] = 1; } else { config[secondary2] = 0; } blog("toggleButton - returning config"); return config; } public int configProcessorPuzzleCallback(obj_id self, dictionary params) throws InterruptedException { blog("configProcessorPuzzleCallback - INIT"); obj_id player = sui.getPlayerId(params); if (!isValidId(player)) { blog("configProcessorPuzzleCallback - NO PLAYER"); return SCRIPT_CONTINUE; } String widgetName = params.getString("eventWidgetName"); blog("configProcessorPuzzleCallback widgetName - " + widgetName); int pid = sui.getPid(player, PID_NAME); if (pid <= 0) { blog("configProcessorPuzzleCallback pid FAILED " + pid); return SCRIPT_CONTINUE; } blog("configProcessorPuzzleCallback pid - " + pid); if (widgetName == null || widgetName.equals("")) { blog("configProcessorPuzzleCallback widgetName = null "); obj_id component = utils.getObjIdScriptVar(self, COMPONENT_VAR); if (!hasObjVar(component, STATUS_VAR)) { setObjVar(component, STATUS_VAR, -1); sendSystemMessage(self, MSG_CALIBRATION_ABORTED); } removePlayerVars(player); forceCloseSUIPage(pid); return SCRIPT_CONTINUE; } blog("configProcessorPuzzleCallback widget != null"); int index = -1; for (int i = 0; i < CONFIG_PLAYER_BUTTONS.length; i++) { setSUIProperty(pid, CONFIG_PLAYER_BUTTONS[i], "Color", "#FFFFFF"); if (widgetName.equalsIgnoreCase(CONFIG_PLAYER_BUTTONS[i])) { index = i; } } blog("configProcessorPuzzleCallback index: " + index); if (index < 0 || index > 5) { return SCRIPT_CONTINUE; } int[] current = utils.getIntArrayScriptVar(player, CALIBRATION_CURRENT); int[] goal = utils.getIntArrayScriptVar(player, CALIBRATION_GOAL); int tries = utils.getIntScriptVar(player, CALIBRATION_TRIES); int max_tries = utils.getIntScriptVar(player, CALIBRATION_MAX_TRIES); if (current == null || goal == null) { blog("configProcessorPuzzleCallback current or goal == null"); removePlayerVars(player); return SCRIPT_CONTINUE; } blog("configProcessorPuzzleCallback - About to toggle buttons"); current = toggleButton(current, index); if (current == null) { blog("configProcessorPuzzleCallback current is NULL"); return SCRIPT_CONTINUE; } for (int i = 0; i < CONFIG_PLAYER_BUTTONS.length; i++) { if (current[i] == 1) { blog("configProcessorPuzzleCallback setting to black: " + CONFIG_PLAYER_BUTTONS[i]); setSUIProperty(pid, CONFIG_PLAYER_BUTTONS[i], "Color", "#000000"); } } tries--; int integrity = (int)(((float)tries / (float)max_tries) * 100); blog("configProcessorPuzzleCallback integrity: " + integrity); boolean win = true; for (int i = 0; i < current.length; i++) { if (current[i] != goal[i]) { win = false; } } blog("configProcessorPuzzleCallback win: " + win); if (win) { blog("configProcessorPuzzleCallback THE WIN "); obj_id component = utils.getObjIdScriptVar(player, COMPONENT_VAR); setObjVar(component, STATUS_VAR, 1); setSUIProperty(pid, "top.description.desc", "Text", CALIBRATION_SUCCESS); for (int i = 0; i < CONFIG_PLAYER_BUTTONS.length; i++) { subscribeToSUIEvent(pid, sui_event_type.SET_onButton, CONFIG_PLAYER_BUTTONS[i], "noCallback"); setSUIProperty(pid, CONFIG_PLAYER_BUTTONS[i], "GetsInput", "false"); } rewardPlayer(self, player); } else if (tries <= 0) { blog("configProcessorPuzzleCallback YOU LOSE "); obj_id component = utils.getObjIdScriptVar(player, COMPONENT_VAR); setObjVar(component, STATUS_VAR, -1); setSUIProperty(pid, "top.description.attempts", "Text", CALIBRATION_ATTEMPTS_REMAINING + " " + integrity + "%"); setSUIProperty(pid, "top.description.desc", "Text", CALIBRATION_FAILURE); for (int i = 0; i < CONFIG_PLAYER_BUTTONS.length; i++) { subscribeToSUIEvent(pid, sui_event_type.SET_onButton, CONFIG_PLAYER_BUTTONS[i], "noCallback"); setSUIProperty(pid, CONFIG_PLAYER_BUTTONS[i], "GetsInput", "false"); } removePlayerVars(player); } else { blog("configProcessorPuzzleCallback DECREMENT "); setSUIProperty(pid, "top.description.attempts", "Text", CALIBRATION_ATTEMPTS_REMAINING + " " + integrity + "%"); } utils.setScriptVar(player, CALIBRATION_CURRENT, current); utils.setScriptVar(player, CALIBRATION_TRIES, tries); flushSUIPage(pid); return SCRIPT_CONTINUE; } public boolean rewardPlayer(obj_id collectionItem, obj_id player) throws InterruptedException { if (!isValidId(collectionItem) || !isValidId(player)) { return false; } String baseSlotName = getStringObjVar(collectionItem, OBJVAR_SLOT_NAME); String[] splitSlotNames = split(baseSlotName, ':'); String slotName = splitSlotNames[1]; String collectionName = splitSlotNames[0]; if (!hasCompletedCollectionSlotPrereq(player, slotName)) { sendSystemMessage(player, collection.SID_NEED_TO_ACTIVATE_COLLECTION); return false; } else if (hasCompletedCollection(player, collectionName)) { sendSystemMessage(player, SID_ALREADY_FINISHED_COLLECTION); return false; } else if ((slotName == null || slotName.equals("")) || hasCompletedCollectionSlot(player, slotName)) { sendSystemMessage(player, SID_ALREADY_HAVE_SLOT); return false; } boolean currentState = collection.checkState(player); if (!currentState) { return false; } boolean isCloseEnough = collection.checkDistance(collectionItem, player, MAX_RANGE_TO_COLLECT); if (!isCloseEnough) { blog("Not Close ENOUGH"); sendSystemMessage(player, SID_NOT_CLOSE_ENOUGH); return false; } blog("Player collecting " + slotName); stealth.testInvisNonCombatAction(player, collectionItem); collection.giveAreaMobsHate(collectionItem, player); closeOldWindow(player); removePlayerVars(player); if (modifyCollectionSlotValue(player, slotName, 1)) { CustomerServiceLog("CollectionConsume: ", "collectionItem (" + collectionItem + ")" + " was consumed into a collection, for player " + getFirstName(player) + "(" + player + ")."); return false; } else { CustomerServiceLog("CollectionConsume: ", "collectionItem (" + collectionItem + ")" + " was NOT consumed into a collection, for player " + getFirstName(player) + "(" + player + ")."); sendSystemMessage(player, SID_REPORT_CONSUME_ITEM_FAIL); } return false; } public void closeOldWindow(obj_id player) throws InterruptedException { blog("closeOldWindow - init"); int pid = sui.getPid(player, PID_NAME); blog("closeOldWindow - pid: " + pid); if (pid > -1) { blog("closeOldWindow - force closing: " + pid); forceCloseSUIPage(pid); sui.removePid(player, PID_NAME); } } public void removePlayerVars(obj_id player) throws InterruptedException { utils.removeScriptVarTree(player, VAR_PREFIX); utils.removeObjVar(player, VAR_PREFIX); } public boolean blog(String msg) throws InterruptedException { LOG("minigame", msg); return true; } }
18,284
0.582422
0.575038
472
37.737289
30.689583
195
false
false
0
0
0
0
0
0
0.947034
false
false
13
f3cf8d32377b5fbc4c296283c88f1bb5932035f5
18,081,812,372,476
8055853f4a5001f929fdcdabd2fc925bb08c3487
/day10_SpringBoot_SpringSecurity/src/main/java/org/bigjava/service/UserDetailsService.java
16129e7948c9eb095d446f14dbdc5526cd9467c8
[]
no_license
hualong-hu/SpringBoot
https://github.com/hualong-hu/SpringBoot
b3c35553b79a8856502d31299c64ad84e88df882
6b81a81acb5f062ef43039dafc7d4bc951ee6bea
refs/heads/master
2023-01-22T16:57:50.045000
2020-12-06T05:24:07
2020-12-06T05:24:07
318,958,181
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.bigjava.service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.bigjava.entity.Users; import org.bigjava.mapper.UsersMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import java.util.List; /** * @ProjectName: JavaEESenior * @ClassName: UserDetailsService * @Description: TODO * @Author: 洛笙 * @Date: 2020-10-30 16:50 * @Version v1.0 */ @Service("userDetailsService") public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService { @Autowired private UsersMapper usersMapper; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { QueryWrapper<Users> wrapper = new QueryWrapper<>(); wrapper.eq("username", s); Users users = usersMapper.selectOne(wrapper); if (users == null){ throw new UsernameNotFoundException("用户名不存在"); } List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("manager,ROLE_sale"); User user = new User(users.getUsername(), new BCryptPasswordEncoder().encode(users.getPassword()), authorities); return user; } }
UTF-8
Java
1,692
java
UserDetailsService.java
Java
[ { "context": "erDetailsService\n * @Description: TODO\n * @Author: 洛笙\n * @Date: 2020-10-30 16:50\n * @Version v1.0\n */\n@", "end": 813, "score": 0.957724392414093, "start": 811, "tag": "NAME", "value": "洛笙" } ]
null
[]
package org.bigjava.service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.bigjava.entity.Users; import org.bigjava.mapper.UsersMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import java.util.List; /** * @ProjectName: JavaEESenior * @ClassName: UserDetailsService * @Description: TODO * @Author: 洛笙 * @Date: 2020-10-30 16:50 * @Version v1.0 */ @Service("userDetailsService") public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService { @Autowired private UsersMapper usersMapper; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { QueryWrapper<Users> wrapper = new QueryWrapper<>(); wrapper.eq("username", s); Users users = usersMapper.selectOne(wrapper); if (users == null){ throw new UsernameNotFoundException("用户名不存在"); } List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("manager,ROLE_sale"); User user = new User(users.getUsername(), new BCryptPasswordEncoder().encode(users.getPassword()), authorities); return user; } }
1,692
0.770883
0.76253
47
34.659573
32.599621
120
false
false
0
0
0
0
0
0
0.531915
false
false
13
cefa17047275044f8d3f4343221a28b72698463c
32,246,614,485,308
3c0586bf25beecccf84141e2df042cd0b65dcd69
/src/main/java/org/charlie/chess/pieces/Knight.java
e04efe78b2bc456c80f72b46bae34a89be479248
[ "Apache-2.0" ]
permissive
charlieaustin/chess
https://github.com/charlieaustin/chess
f1c62bea1b88fa2c0865b52306575aaa9b92254d
f6ba8b811ea60682c0c1aa2b3d44ab7ac43eb916
refs/heads/master
2016-08-11T17:31:53.372000
2015-08-03T02:20:14
2015-08-03T02:20:14
36,437,202
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.charlie.chess.pieces; import org.charlie.chess.Board; import org.charlie.chess.moves.PossibleMoves; import org.charlie.chess.Square; import org.charlie.chess.moves.SimpleMove; import org.charlie.chess.players.Player; import java.util.LinkedList; import java.util.List; public class Knight extends BasePiece { private final List<Square> possibleDestinations = new LinkedList<>(); private Square upLeft; private Square upRight; private Square rightUp; private Square rightDown; private Square downLeft; private Square downRight; private Square leftUp; private Square leftDown; public Knight(Player owner, Square currentLocation) { super(owner, currentLocation); updateLocation(); } @Override public PossibleMoves getPossibleMoves(Board board) { PossibleMoves possibleMoves = new PossibleMoves(); for (Square possibleDest : possibleDestinations) { canMoveToSquare(possibleMoves, possibleDest, board); } return possibleMoves; } private void updateLocation() { upLeft = new Square(currentLocation.getX() - 2, currentLocation.getY() - 1); upRight = new Square(currentLocation.getX() - 2, currentLocation.getY() + 1); rightUp = new Square(currentLocation.getX() - 1, currentLocation.getY() + 2); rightDown = new Square(currentLocation.getX() + 1, currentLocation.getY() + 2); downLeft = new Square(currentLocation.getX() + 2, currentLocation.getY() - 1); downRight = new Square(currentLocation.getX() + 2, currentLocation.getY() + 1); leftUp = new Square(currentLocation.getX() - 1, currentLocation.getY() - 2); leftDown = new Square(currentLocation.getX() + 1, currentLocation.getY() - 2); possibleDestinations.clear(); possibleDestinations.add(upLeft); possibleDestinations.add(upRight); possibleDestinations.add(rightUp); possibleDestinations.add(rightDown); possibleDestinations.add(downLeft); possibleDestinations.add(downRight); possibleDestinations.add(leftUp); possibleDestinations.add(leftDown); } private void canMoveToSquare(PossibleMoves possibleMoves, Square dest, Board board) { if (board.squareIsEmptyOrHasOpponent(dest, owner)) { possibleMoves.addMove(new SimpleMove(currentLocation, dest, this)); } } @Override public String stringRepresentation() { return "n"; } @Override public void move(Square dest) { super.move(dest); updateLocation(); } }
UTF-8
Java
2,625
java
Knight.java
Java
[]
null
[]
package org.charlie.chess.pieces; import org.charlie.chess.Board; import org.charlie.chess.moves.PossibleMoves; import org.charlie.chess.Square; import org.charlie.chess.moves.SimpleMove; import org.charlie.chess.players.Player; import java.util.LinkedList; import java.util.List; public class Knight extends BasePiece { private final List<Square> possibleDestinations = new LinkedList<>(); private Square upLeft; private Square upRight; private Square rightUp; private Square rightDown; private Square downLeft; private Square downRight; private Square leftUp; private Square leftDown; public Knight(Player owner, Square currentLocation) { super(owner, currentLocation); updateLocation(); } @Override public PossibleMoves getPossibleMoves(Board board) { PossibleMoves possibleMoves = new PossibleMoves(); for (Square possibleDest : possibleDestinations) { canMoveToSquare(possibleMoves, possibleDest, board); } return possibleMoves; } private void updateLocation() { upLeft = new Square(currentLocation.getX() - 2, currentLocation.getY() - 1); upRight = new Square(currentLocation.getX() - 2, currentLocation.getY() + 1); rightUp = new Square(currentLocation.getX() - 1, currentLocation.getY() + 2); rightDown = new Square(currentLocation.getX() + 1, currentLocation.getY() + 2); downLeft = new Square(currentLocation.getX() + 2, currentLocation.getY() - 1); downRight = new Square(currentLocation.getX() + 2, currentLocation.getY() + 1); leftUp = new Square(currentLocation.getX() - 1, currentLocation.getY() - 2); leftDown = new Square(currentLocation.getX() + 1, currentLocation.getY() - 2); possibleDestinations.clear(); possibleDestinations.add(upLeft); possibleDestinations.add(upRight); possibleDestinations.add(rightUp); possibleDestinations.add(rightDown); possibleDestinations.add(downLeft); possibleDestinations.add(downRight); possibleDestinations.add(leftUp); possibleDestinations.add(leftDown); } private void canMoveToSquare(PossibleMoves possibleMoves, Square dest, Board board) { if (board.squareIsEmptyOrHasOpponent(dest, owner)) { possibleMoves.addMove(new SimpleMove(currentLocation, dest, this)); } } @Override public String stringRepresentation() { return "n"; } @Override public void move(Square dest) { super.move(dest); updateLocation(); } }
2,625
0.681524
0.675429
77
33.090908
27.248821
89
false
false
0
0
0
0
0
0
0.779221
false
false
13
9f29833ec2ad3370a35e2f13ed76cfab9e23c941
33,543,694,599,983
e7bb5dbb13ad53b0aec25b28b9c550561e50e58b
/driver-demo/src/main/java/com/demo/DriverRequestDemo.java
91eaa463065c44e9deeab75c7dafe724eb4ee20a
[]
no_license
gdrouet/pluggable-messaging-architecture
https://github.com/gdrouet/pluggable-messaging-architecture
91ad03353fd9bfe73b188a4fe2bcf978c7c915df
096e60880f1d060b796b641c126f01efd38d67ef
refs/heads/master
2021-01-11T19:14:56.629000
2017-01-18T14:02:38
2017-01-18T14:02:38
79,343,194
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.demo; /** * Example of parameter type passed to the driver implementation and that can be defined by the driver itself. */ public class DriverRequestDemo extends DriverRequest { }
UTF-8
Java
195
java
DriverRequestDemo.java
Java
[]
null
[]
package com.demo; /** * Example of parameter type passed to the driver implementation and that can be defined by the driver itself. */ public class DriverRequestDemo extends DriverRequest { }
195
0.774359
0.774359
7
26.857143
38.312359
110
false
false
0
0
0
0
0
0
0.142857
false
false
13
123b9499800fb34dffaf14d2cb65dc4773dd3979
26,645,977,144,373
71f02f65abed2b410f002918918a31dcb0d16601
/java/7 匿名对象/Test_girl.java
1e52585281ff80385353f5fe5ad48dd68f5901d5
[]
no_license
142296/-
https://github.com/142296/-
bd9db28e9000b3e01cba986716963c24e8bd24fc
23ba488189a797cea0e8fbda7e65a3274968ba80
refs/heads/master
2023-03-28T12:17:51.425000
2021-03-25T02:25:39
2021-03-25T02:25:39
351,279,304
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package demo; public class Test_girl { public static void main(String[]args) { new Girl().show(); //匿名对象,针对只使用一次的对象 } }
UTF-8
Java
159
java
Test_girl.java
Java
[]
null
[]
package demo; public class Test_girl { public static void main(String[]args) { new Girl().show(); //匿名对象,针对只使用一次的对象 } }
159
0.658915
0.658915
8
15.25
16.207638
42
false
false
0
0
0
0
0
0
0.875
false
false
13
dac1c9f2835c17eb146500a5c74fd91ce0fd7eda
30,648,886,629,098
d5b748e83fe120442757a47417c4793cd55ca6c4
/app/src/main/java/com/example/megacine/SegundaPregunta.java
574e5fd7329ded1612988dd0af94566f86472ac4
[]
no_license
cquisay/ExamenPractico1P
https://github.com/cquisay/ExamenPractico1P
6c36b757c6d85ce09dee039b5260c357429e642b
c5c3b2d1d206ab14f48795cc246eaf42a68c8e75
refs/heads/main
2023-01-20T09:48:40.279000
2020-11-27T21:20:07
2020-11-27T21:20:07
316,557,605
0
0
null
false
2020-11-27T21:20:08
2020-11-27T17:03:22
2020-11-27T17:26:58
2020-11-27T21:20:08
197
0
0
0
Java
false
false
package com.example.megacine; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class SegundaPregunta extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_segunda_pregunta); } //Respuesta COrrecta public void Correcto(View view){ Intent Correcto = new Intent(this, TerceraPregunta.class); startActivity(Correcto); } //Ir a pantalla de fallo public void Fallo(View view){ Intent Fallo = new Intent(this, HaPerdido.class); startActivity(Fallo); } }
UTF-8
Java
732
java
SegundaPregunta.java
Java
[]
null
[]
package com.example.megacine; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class SegundaPregunta extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_segunda_pregunta); } //Respuesta COrrecta public void Correcto(View view){ Intent Correcto = new Intent(this, TerceraPregunta.class); startActivity(Correcto); } //Ir a pantalla de fallo public void Fallo(View view){ Intent Fallo = new Intent(this, HaPerdido.class); startActivity(Fallo); } }
732
0.713115
0.713115
28
25.178572
21.218344
66
false
false
0
0
0
0
0
0
0.464286
false
false
13
54a614763335c80c360f82b3f1cb71862d85d758
4,930,622,487,317
3375b57cf97d7dde74ebb20ab5bad72c70c58997
/EasyHomeFramework/src/com/easyhome/framework/ui/window/BaseWindow.java
6f4062e23f5d9ea446cad27223b18e434867a7da
[]
no_license
zlkevinet/EasyhomeFramework
https://github.com/zlkevinet/EasyhomeFramework
0560b5b38150641eed1371f0fccb28b12df411d1
4a3d71b9bed2012b5f64282e92bd48cb40193daa
refs/heads/master
2021-05-27T18:27:22.292000
2012-12-01T01:34:41
2012-12-01T01:34:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright */ package com.easyhome.framework.ui.window; /** * * @author zhoulu * @since 2012-11-9-上午1:03:38 * @version 1.0 */ public abstract class BaseWindow implements IWindow{ //wait to be fill }
UTF-8
Java
231
java
BaseWindow.java
Java
[ { "context": "yhome.framework.ui.window;\r\n\r\n/**\r\n * \r\n * @author zhoulu\r\n * @since 2012-11-9-上午1:03:38\r\n * @version 1.0\r\n", "end": 96, "score": 0.8379747271537781, "start": 90, "tag": "USERNAME", "value": "zhoulu" } ]
null
[]
/** * Copyright */ package com.easyhome.framework.ui.window; /** * * @author zhoulu * @since 2012-11-9-上午1:03:38 * @version 1.0 */ public abstract class BaseWindow implements IWindow{ //wait to be fill }
231
0.625551
0.563877
14
14.214286
15.56176
52
false
false
0
0
0
0
0
0
0.071429
false
false
13
51ba101ab0fdd861deb2e206b60c0e778bb68c21
25,177,098,318,593
5cdb1dc41e5cb0817bd68f9d1695a1dea64b5cc6
/src/main/java/com/raychen518/study/java/datatypes/misc/numeric/Summary.java
048e5ea9410f832593e3b3942f89c08ff2545898
[]
no_license
raychen518/study-java
https://github.com/raychen518/study-java
c181d243fedd4d518427df6dc1f57020edbfcc32
07eb61be870609fe2df8e8b7d4122fb632689925
refs/heads/master
2020-07-20T18:58:52.325000
2017-08-13T07:46:54
2017-08-13T07:46:54
66,048,654
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.raychen518.study.java.datatypes.misc.numeric; import java.math.BigDecimal; import java.math.BigInteger; public class Summary { public static void main(String[] args) { System.out.println("========================================"); System.out.println("BigInteger & BigDecimal"); System.out.println("========================================"); System.out.println("BigInteger and BigDecimal can process numeric values in any length."); System.out.println(); System.out.println("e.g."); System.out.println("Long.MAX_VALUE\t\t\t\t\t\t\t: " + Long.MAX_VALUE); System.out.println("Long.MAX_VALUE + 1\t\t\t\t\t\t: " + (Long.MAX_VALUE + 1) + "\t\t// Wrong. Should be 9223372036854775808."); System.out.println("BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE)\t\t: " + BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE) + "\t\t// Correct."); System.out.println(); System.out.println("e.g."); System.out.println("Double.MAX_VALUE\t\t\t\t\t\t: " + Double.MAX_VALUE); System.out.println("Double.MAX_VALUE * 10\t\t\t\t\t\t: " + (Double.MAX_VALUE * 10) + "\t\t\t// Wrong. Should be 1.79769313486231570E+309."); System.out.println("BigDecimal.valueOf(Double.MAX_VALUE).multiply(BigDecimal.TEN)\t: " + BigDecimal.valueOf(Double.MAX_VALUE).multiply(BigDecimal.TEN) + "\t// Correct."); System.out.println(); } }
UTF-8
Java
1,370
java
Summary.java
Java
[ { "context": "package com.raychen518.study.java.datatypes.misc.numeric;\n\nimport java", "end": 20, "score": 0.6263065338134766, "start": 15, "tag": "USERNAME", "value": "chen5" } ]
null
[]
package com.raychen518.study.java.datatypes.misc.numeric; import java.math.BigDecimal; import java.math.BigInteger; public class Summary { public static void main(String[] args) { System.out.println("========================================"); System.out.println("BigInteger & BigDecimal"); System.out.println("========================================"); System.out.println("BigInteger and BigDecimal can process numeric values in any length."); System.out.println(); System.out.println("e.g."); System.out.println("Long.MAX_VALUE\t\t\t\t\t\t\t: " + Long.MAX_VALUE); System.out.println("Long.MAX_VALUE + 1\t\t\t\t\t\t: " + (Long.MAX_VALUE + 1) + "\t\t// Wrong. Should be 9223372036854775808."); System.out.println("BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE)\t\t: " + BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE) + "\t\t// Correct."); System.out.println(); System.out.println("e.g."); System.out.println("Double.MAX_VALUE\t\t\t\t\t\t: " + Double.MAX_VALUE); System.out.println("Double.MAX_VALUE * 10\t\t\t\t\t\t: " + (Double.MAX_VALUE * 10) + "\t\t\t// Wrong. Should be 1.79769313486231570E+309."); System.out.println("BigDecimal.valueOf(Double.MAX_VALUE).multiply(BigDecimal.TEN)\t: " + BigDecimal.valueOf(Double.MAX_VALUE).multiply(BigDecimal.TEN) + "\t// Correct."); System.out.println(); } }
1,370
0.647445
0.611679
32
41.84375
32.01963
92
false
false
0
0
0
0
0
0
2.0625
false
false
13
be1742b7e7f66476b7b4c92ddb887d9b1983fd60
15,410,342,680,422
7552efc9b8d37374b3f49390d9d958d0fa124dae
/src/application/graphics/item/gameObjects/PlayerBar.java
c59326f0cadf12122277f6eb148f2ddb6a7b7ad0
[]
no_license
dcaffo98/OOP_Project
https://github.com/dcaffo98/OOP_Project
c36daba6e27f54beed7cfa94683c91914bb4403f
d431853815636bdf73f258cec28c8e904a0eadbc
refs/heads/master
2020-07-03T09:37:44.436000
2019-09-16T22:27:23
2019-09-16T22:27:23
201,867,690
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package application.graphics.item.gameObjects; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.Parent; import javafx.scene.image.ImageView; import javafx.scene.layout.Pane; public class PlayerBar extends ImageView { private DoubleProperty speed; private double position; public PlayerBar(String url) { super(url); speed = new SimpleDoubleProperty(); position = getLayoutX() + (getFitWidth() / 2); // listener per impostare in modo dinamico le dimensioni della barra se viene allargata o diminuita la schermata parentProperty().addListener(new ChangeListener<Parent>() { @Override public void changed(ObservableValue<? extends Parent> observable, Parent oldValue, Parent newValue) { if(newValue != null) { fitWidthProperty().bind(((Pane) newValue).widthProperty().multiply(0.07)); fitHeightProperty().bind(((Pane) newValue).heightProperty().multiply(0.02)); setLayoutX((((Pane) newValue).getWidth() - getFitWidth()) / 2) ; setManaged(false); //altrimenti non fa fare il binding del layoutY layoutYProperty().bind(((Pane) newValue).heightProperty().subtract(getFitHeight() * 1.5)); speed.bind( ((Pane) newValue).widthProperty().multiply(0.01)); } } }); } public void moveRight() { if(getLayoutX() + getFitWidth() + speed.doubleValue() > ((Pane) getParent()).getWidth()) setLayoutX(((Pane) getParent()).getWidth() - getFitWidth()); else setLayoutX(getLayoutX() + speed.doubleValue()); } public void moveLeft() { if(getLayoutX() - speed.doubleValue() < 0) setLayoutX(0); else setLayoutX(getLayoutX() - speed.doubleValue()); } public double getPosition() { return position; } public void setPosition(double length) { this.position = position; } public void updatePosition() { position = getLayoutX() + (getFitWidth() / 2); } }
UTF-8
Java
2,295
java
PlayerBar.java
Java
[]
null
[]
package application.graphics.item.gameObjects; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.Parent; import javafx.scene.image.ImageView; import javafx.scene.layout.Pane; public class PlayerBar extends ImageView { private DoubleProperty speed; private double position; public PlayerBar(String url) { super(url); speed = new SimpleDoubleProperty(); position = getLayoutX() + (getFitWidth() / 2); // listener per impostare in modo dinamico le dimensioni della barra se viene allargata o diminuita la schermata parentProperty().addListener(new ChangeListener<Parent>() { @Override public void changed(ObservableValue<? extends Parent> observable, Parent oldValue, Parent newValue) { if(newValue != null) { fitWidthProperty().bind(((Pane) newValue).widthProperty().multiply(0.07)); fitHeightProperty().bind(((Pane) newValue).heightProperty().multiply(0.02)); setLayoutX((((Pane) newValue).getWidth() - getFitWidth()) / 2) ; setManaged(false); //altrimenti non fa fare il binding del layoutY layoutYProperty().bind(((Pane) newValue).heightProperty().subtract(getFitHeight() * 1.5)); speed.bind( ((Pane) newValue).widthProperty().multiply(0.01)); } } }); } public void moveRight() { if(getLayoutX() + getFitWidth() + speed.doubleValue() > ((Pane) getParent()).getWidth()) setLayoutX(((Pane) getParent()).getWidth() - getFitWidth()); else setLayoutX(getLayoutX() + speed.doubleValue()); } public void moveLeft() { if(getLayoutX() - speed.doubleValue() < 0) setLayoutX(0); else setLayoutX(getLayoutX() - speed.doubleValue()); } public double getPosition() { return position; } public void setPosition(double length) { this.position = position; } public void updatePosition() { position = getLayoutX() + (getFitWidth() / 2); } }
2,295
0.619608
0.612636
63
35.42857
32.557503
120
false
false
0
0
0
0
0
0
0.460317
false
false
13
c36235886121ed1651bdefe3df00307f02d142d1
15,410,342,680,511
f0927038e5c322e3508463f26d09733a47d24411
/unisco-core/src/main/java/com/unisco/entity/VideoEntity.java
4ff7bf5035d122d07cf5ce3549492334634dc690
[]
no_license
trivip002/project-sem-4
https://github.com/trivip002/project-sem-4
1ca3fba237b4ca7834fa5481ed9c3b5ef4814eb7
c2f6fc6730750435e56db944874f82bf2bd0b052
refs/heads/master
2021-02-15T10:40:59.050000
2020-07-15T06:23:13
2020-07-15T06:23:13
244,890,308
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.unisco.entity; import com.unisco.entity.base.BaseEntity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name = "video") @AllArgsConstructor @NoArgsConstructor @Getter @Setter public class VideoEntity extends BaseEntity implements Serializable { private static final long serialVersionUID = 928136466631731381L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "video_id") private Long videoId; @Column(name = "video_name") private String videoName; @Column(name = "video_url", columnDefinition = "TEXT") private String videoUrl; @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "section_id") private SectionEntity section; }
UTF-8
Java
959
java
VideoEntity.java
Java
[]
null
[]
package com.unisco.entity; import com.unisco.entity.base.BaseEntity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name = "video") @AllArgsConstructor @NoArgsConstructor @Getter @Setter public class VideoEntity extends BaseEntity implements Serializable { private static final long serialVersionUID = 928136466631731381L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "video_id") private Long videoId; @Column(name = "video_name") private String videoName; @Column(name = "video_url", columnDefinition = "TEXT") private String videoUrl; @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "section_id") private SectionEntity section; }
959
0.759124
0.740355
36
25.638889
19.832848
69
false
false
0
0
0
0
0
0
0.472222
false
false
13
ffd3c69e1fdb893079f6f65286cf19f297f9fecb
28,716,151,358,973
13bcb731080e5313bdf466097739ba59ad80756a
/src/com/fr/solution/plugin/chart/echarts/common/toolbox/EChartsToolbox.java
66f0661e7ce82317acac99fa280c5fa062b1e5cd
[]
no_license
carlhong/plugin-chart-echarts
https://github.com/carlhong/plugin-chart-echarts
4fe16e56b2c2027f35ffd16c9657c145fe23c128
7ca0b5c1975c4d6c0b5986dca7334e5981349248
refs/heads/master
2020-12-30T12:23:40.441000
2017-05-16T08:31:35
2017-05-16T08:31:35
91,431,844
0
0
null
true
2017-05-16T08:01:30
2017-05-16T08:01:30
2017-03-16T01:03:19
2017-03-21T03:05:49
2,823
0
0
0
null
null
null
package com.fr.solution.plugin.chart.echarts.common.toolbox; import com.fr.general.ComparatorUtils; import com.fr.json.JSONArray; import com.fr.json.JSONException; import com.fr.json.JSONObject; import com.fr.stable.web.Repository; import com.fr.stable.xml.XMLPrintWriter; import com.fr.stable.xml.XMLable; import com.fr.stable.xml.XMLableReader; import java.awt.*; public class EChartsToolbox implements XMLable { public static final String XML_TAG = "Toolbox"; private Boolean brushVisible = false; private Boolean isRectSelected = false; private Boolean isPolygonSelected = false; private Boolean isKeepSelected = false; private Boolean isLineXSelected = false; private Boolean isLineYSelected = false; private Boolean isClearSelected = false; private Boolean dataViewVisible = false; private Color bgColor; private Color textareaColor; private Color textareaBorderColor; private Color textColor; private Color buttonColor; private Color buttonTextColor; private Boolean dataZoomVisible = false; private Boolean magicTypeVisible = false; private Boolean isBarSelected = false; private Boolean isLineSelected = false; private Boolean isStackSelected = false; private Boolean isTiledSelected = false; private Boolean restoreVisible = false; private Boolean saveAsImageVisible = false; private String imageFormat; public EChartsToolbox() {} public boolean isBrushVisible() { return brushVisible; } public void setBrushVisible(boolean brushVisible) { this.brushVisible = brushVisible; } public boolean isRectSelected() { return isRectSelected; } public void setRectSelected(boolean isRectSelected) { this.isRectSelected = isRectSelected; } public boolean isPolygonSelected() { return isPolygonSelected; } public void setPolygonSelected(boolean isPolygonSelected) { this.isPolygonSelected = isPolygonSelected; } public boolean isKeepSelected() { return isKeepSelected; } public void setKeepSelected(boolean isKeepSelected) { this.isKeepSelected = isKeepSelected; } public boolean isLineXSelected() { return isLineXSelected; } public void setLineXSelected(boolean isLineXSelected) { this.isLineXSelected = isLineXSelected; } public boolean isLineYSelected() { return isLineYSelected; } public void setLineYSelected(boolean isLineYSelected) { this.isLineYSelected = isLineYSelected; } public boolean isClearSelected() { return isClearSelected; } public void setClearSelected(boolean isClearSelected) { this.isClearSelected = isClearSelected; } public boolean isDataViewVisible() { return dataViewVisible; } public void setDataViewVisible(boolean dataViewVisible) { this.dataViewVisible = dataViewVisible; } public boolean isDataZoomVisible() { return dataZoomVisible; } public String color2String(Color borderColor) { return String.format("#%02x%02x%02x", borderColor.getRed(), borderColor.getGreen(), borderColor.getBlue()); } public Color getBgColor() { return bgColor; } public void setBgColor(Color bgColor) { this.bgColor = bgColor; } public Color getTextareaColor() { return textareaColor; } public void setTextareaColor(Color textareaColor) { this.textareaColor = textareaColor; } public Color getTextareaBorderColor() { return textareaBorderColor; } public void setTextareaBorderColor(Color textareaBorderColor) { this.textareaBorderColor = textareaBorderColor; } public Color getTextColor() { return textColor; } public void setTextColor(Color textColor) { this.textColor = textColor; } public Color getButtonColor() { return buttonColor; } public void setButtonColor(Color buttonColor) { this.buttonColor = buttonColor; } public Color getButtonTextColor() { return buttonTextColor; } public void setButtonTextColor(Color buttonTextColor) { this.buttonTextColor = buttonTextColor; } public void setDataZoomVisible(boolean dataZoomVisible) { this.dataZoomVisible = dataZoomVisible; } public boolean isMagicTypeVisible() { return magicTypeVisible; } public void setMagicTypeVisible(boolean magicTypeVisible) { this.magicTypeVisible = magicTypeVisible; } public boolean isBarSelected() { return isBarSelected; } public void setBarSelected(boolean isBarSelected) { this.isBarSelected = isBarSelected; } public boolean isLineSelected() { return isLineSelected; } public void setLineSelected(boolean isLineSelected) { this.isLineSelected = isLineSelected; } public boolean isStackSelected() { return isStackSelected; } public void setStackSelected(boolean isStackSelected) { this.isStackSelected = isStackSelected; } public boolean isTiledSelected() { return isTiledSelected; } public void setTiledSelected(boolean isTiledSelected) { this.isTiledSelected = isTiledSelected; } public boolean isRestoreVisible() { return restoreVisible; } public void setRestoreVisible(boolean restoreVisible) { this.restoreVisible = restoreVisible; } public boolean isSaveAsImageVisible() { return saveAsImageVisible; } public void setSaveAsImageVisible(boolean saveAsImageVisible) { this.saveAsImageVisible = saveAsImageVisible; } public String getImageFormat() { return imageFormat; } public void setImageFormat(String imageFormat) { this.imageFormat = imageFormat; } public JSONObject toJSONObject(Repository repo) throws JSONException { JSONObject jo = JSONObject.create(); JSONObject wrapper = JSONObject.create(); jo.put("feature", wrapper); if (brushVisible) { JSONObject brushTypeWrapper = JSONObject.create(); wrapper.put("brush", brushTypeWrapper); JSONArray brushType = JSONArray.create(); brushTypeWrapper.put("type", brushType); if (isRectSelected) { brushType.put("rect"); } if (isPolygonSelected) { brushType.put("polygon"); } if (isKeepSelected) { brushType.put("keep"); } if (isLineXSelected) { brushType.put("lineX"); } if (isLineYSelected) { brushType.put("lineY"); } if (isClearSelected) { brushType.put("clear"); } } if (dataViewVisible) { JSONObject dataViewWrapper = JSONObject.create(); wrapper.put("dataView", dataViewWrapper); dataViewWrapper.put("backgroundColor", color2String(getBgColor())); dataViewWrapper.put("textareaColor", color2String(getTextareaColor())); dataViewWrapper.put("textareaBorderColor", color2String(getTextareaBorderColor())); dataViewWrapper.put("textColor", color2String(getTextColor())); dataViewWrapper.put("buttonColor", color2String(getButtonColor())); dataViewWrapper.put("buttonTextColor", color2String(getButtonTextColor())); } if (dataZoomVisible) { wrapper.put("dataZoom", JSONObject.create()); } if (magicTypeVisible) { JSONObject magicTypeWrapper = JSONObject.create(); wrapper.put("magicType", magicTypeWrapper); JSONArray magicType = JSONArray.create(); magicTypeWrapper.put("type", magicType); if (isBarSelected) { magicType.put("bar"); } if (isLineSelected) { magicType.put("line"); } if (isStackSelected) { magicType.put("stack"); } if (isTiledSelected) { magicType.put("tiled"); } } if (restoreVisible) { wrapper.put("restore", JSONObject.create()); } if (saveAsImageVisible) { JSONObject imageFormatWrapper = JSONObject.create(); wrapper.put("saveAsImage", imageFormatWrapper); imageFormatWrapper.put("type", imageFormat); } return jo; } @Override public boolean equals(Object obj) { return obj instanceof EChartsToolbox && ComparatorUtils.equals(brushVisible, ((EChartsToolbox) obj).brushVisible) && ComparatorUtils.equals(isRectSelected, ((EChartsToolbox) obj).isRectSelected) && ComparatorUtils.equals(isPolygonSelected, ((EChartsToolbox) obj).isPolygonSelected) && ComparatorUtils.equals(isKeepSelected, ((EChartsToolbox) obj).isKeepSelected) && ComparatorUtils.equals(isLineXSelected, ((EChartsToolbox) obj).isLineXSelected) && ComparatorUtils.equals(isLineYSelected, ((EChartsToolbox) obj).isLineYSelected) && ComparatorUtils.equals(isClearSelected, ((EChartsToolbox) obj).isClearSelected) && ComparatorUtils.equals(dataViewVisible, ((EChartsToolbox) obj).dataViewVisible) && ComparatorUtils.equals(bgColor, ((EChartsToolbox) obj).bgColor) && ComparatorUtils.equals(textareaColor, ((EChartsToolbox) obj).textareaColor) && ComparatorUtils.equals(textareaBorderColor, ((EChartsToolbox) obj).textareaBorderColor) && ComparatorUtils.equals(textColor, ((EChartsToolbox) obj).textColor) && ComparatorUtils.equals(buttonColor, ((EChartsToolbox) obj).buttonColor) && ComparatorUtils.equals(buttonTextColor, ((EChartsToolbox) obj).buttonTextColor) && ComparatorUtils.equals(dataZoomVisible, ((EChartsToolbox) obj).dataZoomVisible) && ComparatorUtils.equals(magicTypeVisible, ((EChartsToolbox) obj).magicTypeVisible) && ComparatorUtils.equals(isBarSelected, ((EChartsToolbox) obj).isBarSelected) && ComparatorUtils.equals(isLineSelected, ((EChartsToolbox) obj).isLineSelected) && ComparatorUtils.equals(isStackSelected, ((EChartsToolbox) obj).isStackSelected) && ComparatorUtils.equals(isTiledSelected, ((EChartsToolbox) obj).isTiledSelected) && ComparatorUtils.equals(restoreVisible, ((EChartsToolbox) obj).restoreVisible) && ComparatorUtils.equals(saveAsImageVisible, ((EChartsToolbox) obj).saveAsImageVisible) && ComparatorUtils.equals(imageFormat, ((EChartsToolbox) obj).imageFormat); } @Override public void readXML(XMLableReader reader) { if (reader.isChildNode()) { String tagName = reader.getTagName(); if (tagName.equals("ToolboxAttr")) { brushVisible = reader.getAttrAsBoolean("brushVisible", false); isRectSelected = reader.getAttrAsBoolean("isRectSelected", false); isPolygonSelected = reader.getAttrAsBoolean("isPolygonSelected", false); isKeepSelected = reader.getAttrAsBoolean("isKeepSelected", false); isLineXSelected = reader.getAttrAsBoolean("isLineXSelected", false); isLineYSelected = reader.getAttrAsBoolean("isLineYSelected", false); isClearSelected = reader.getAttrAsBoolean("isClearSelected", false); dataViewVisible = reader.getAttrAsBoolean("dataViewVisible", false); bgColor = reader.getAttrAsColor("bgColor", Color.white); textareaColor = reader.getAttrAsColor("textareaColor", Color.white); textareaBorderColor = reader.getAttrAsColor("textareaBorderColor", Color.black); textColor = reader.getAttrAsColor("textColor", Color.black); buttonColor = reader.getAttrAsColor("buttonColor", Color.red); buttonTextColor = reader.getAttrAsColor("buttonTextColor", Color.white); dataZoomVisible = reader.getAttrAsBoolean("dataZoomVisible", false); magicTypeVisible = reader.getAttrAsBoolean("magicTypeVisible", false); isBarSelected = reader.getAttrAsBoolean("isBarSelected", false); isLineSelected = reader.getAttrAsBoolean("isLineSelected", false); isStackSelected = reader.getAttrAsBoolean("isStackSelected", false); isTiledSelected = reader.getAttrAsBoolean("isTiledSelected", false); restoreVisible = reader.getAttrAsBoolean("restoreVisible", false); saveAsImageVisible = reader.getAttrAsBoolean("saveAsImageVisible", false); imageFormat = reader.getAttrAsString("imageFormat", "png"); } } } @Override public void writeXML(XMLPrintWriter writer) { writer.startTAG("ToolboxAttr"); writer.attr("brushVisible", String.valueOf(brushVisible)); writer.attr("isRectSelected", String.valueOf(isRectSelected)); writer.attr("isPolygonSelected", String.valueOf(isPolygonSelected)); writer.attr("isKeepSelected", String.valueOf(isKeepSelected)); writer.attr("isLineXSelected", String.valueOf(isLineXSelected)); writer.attr("isLineYSelected", String.valueOf(isLineYSelected)); writer.attr("isClearSelected", String.valueOf(isClearSelected)); writer.attr("dataViewVisible", String.valueOf(dataViewVisible)); if (bgColor != null) { writer.attr("bgColor", bgColor.getRGB()); } if (bgColor != null) { writer.attr("textareaColor", textareaColor.getRGB()); } if (bgColor != null) { writer.attr("textareaBorderColor", textareaBorderColor.getRGB()); } if (bgColor != null) { writer.attr("textColor", textColor.getRGB()); } if (bgColor != null) { writer.attr("buttonColor", buttonColor.getRGB()); } if (bgColor != null) { writer.attr("buttonTextColor", buttonTextColor.getRGB()); } writer.attr("dataZoomVisible", String.valueOf(dataZoomVisible)); writer.attr("magicTypeVisible", String.valueOf(magicTypeVisible)); writer.attr("isBarSelected", String.valueOf(isBarSelected)); writer.attr("isLineSelected", String.valueOf(isLineSelected)); writer.attr("isStackSelected", String.valueOf(isStackSelected)); writer.attr("isTiledSelected", String.valueOf(isTiledSelected)); writer.attr("restoreVisible", String.valueOf(restoreVisible)); writer.attr("saveAsImageVisible", String.valueOf(saveAsImageVisible)); writer.attr("imageFormat", imageFormat); writer.end(); } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
UTF-8
Java
15,344
java
EChartsToolbox.java
Java
[]
null
[]
package com.fr.solution.plugin.chart.echarts.common.toolbox; import com.fr.general.ComparatorUtils; import com.fr.json.JSONArray; import com.fr.json.JSONException; import com.fr.json.JSONObject; import com.fr.stable.web.Repository; import com.fr.stable.xml.XMLPrintWriter; import com.fr.stable.xml.XMLable; import com.fr.stable.xml.XMLableReader; import java.awt.*; public class EChartsToolbox implements XMLable { public static final String XML_TAG = "Toolbox"; private Boolean brushVisible = false; private Boolean isRectSelected = false; private Boolean isPolygonSelected = false; private Boolean isKeepSelected = false; private Boolean isLineXSelected = false; private Boolean isLineYSelected = false; private Boolean isClearSelected = false; private Boolean dataViewVisible = false; private Color bgColor; private Color textareaColor; private Color textareaBorderColor; private Color textColor; private Color buttonColor; private Color buttonTextColor; private Boolean dataZoomVisible = false; private Boolean magicTypeVisible = false; private Boolean isBarSelected = false; private Boolean isLineSelected = false; private Boolean isStackSelected = false; private Boolean isTiledSelected = false; private Boolean restoreVisible = false; private Boolean saveAsImageVisible = false; private String imageFormat; public EChartsToolbox() {} public boolean isBrushVisible() { return brushVisible; } public void setBrushVisible(boolean brushVisible) { this.brushVisible = brushVisible; } public boolean isRectSelected() { return isRectSelected; } public void setRectSelected(boolean isRectSelected) { this.isRectSelected = isRectSelected; } public boolean isPolygonSelected() { return isPolygonSelected; } public void setPolygonSelected(boolean isPolygonSelected) { this.isPolygonSelected = isPolygonSelected; } public boolean isKeepSelected() { return isKeepSelected; } public void setKeepSelected(boolean isKeepSelected) { this.isKeepSelected = isKeepSelected; } public boolean isLineXSelected() { return isLineXSelected; } public void setLineXSelected(boolean isLineXSelected) { this.isLineXSelected = isLineXSelected; } public boolean isLineYSelected() { return isLineYSelected; } public void setLineYSelected(boolean isLineYSelected) { this.isLineYSelected = isLineYSelected; } public boolean isClearSelected() { return isClearSelected; } public void setClearSelected(boolean isClearSelected) { this.isClearSelected = isClearSelected; } public boolean isDataViewVisible() { return dataViewVisible; } public void setDataViewVisible(boolean dataViewVisible) { this.dataViewVisible = dataViewVisible; } public boolean isDataZoomVisible() { return dataZoomVisible; } public String color2String(Color borderColor) { return String.format("#%02x%02x%02x", borderColor.getRed(), borderColor.getGreen(), borderColor.getBlue()); } public Color getBgColor() { return bgColor; } public void setBgColor(Color bgColor) { this.bgColor = bgColor; } public Color getTextareaColor() { return textareaColor; } public void setTextareaColor(Color textareaColor) { this.textareaColor = textareaColor; } public Color getTextareaBorderColor() { return textareaBorderColor; } public void setTextareaBorderColor(Color textareaBorderColor) { this.textareaBorderColor = textareaBorderColor; } public Color getTextColor() { return textColor; } public void setTextColor(Color textColor) { this.textColor = textColor; } public Color getButtonColor() { return buttonColor; } public void setButtonColor(Color buttonColor) { this.buttonColor = buttonColor; } public Color getButtonTextColor() { return buttonTextColor; } public void setButtonTextColor(Color buttonTextColor) { this.buttonTextColor = buttonTextColor; } public void setDataZoomVisible(boolean dataZoomVisible) { this.dataZoomVisible = dataZoomVisible; } public boolean isMagicTypeVisible() { return magicTypeVisible; } public void setMagicTypeVisible(boolean magicTypeVisible) { this.magicTypeVisible = magicTypeVisible; } public boolean isBarSelected() { return isBarSelected; } public void setBarSelected(boolean isBarSelected) { this.isBarSelected = isBarSelected; } public boolean isLineSelected() { return isLineSelected; } public void setLineSelected(boolean isLineSelected) { this.isLineSelected = isLineSelected; } public boolean isStackSelected() { return isStackSelected; } public void setStackSelected(boolean isStackSelected) { this.isStackSelected = isStackSelected; } public boolean isTiledSelected() { return isTiledSelected; } public void setTiledSelected(boolean isTiledSelected) { this.isTiledSelected = isTiledSelected; } public boolean isRestoreVisible() { return restoreVisible; } public void setRestoreVisible(boolean restoreVisible) { this.restoreVisible = restoreVisible; } public boolean isSaveAsImageVisible() { return saveAsImageVisible; } public void setSaveAsImageVisible(boolean saveAsImageVisible) { this.saveAsImageVisible = saveAsImageVisible; } public String getImageFormat() { return imageFormat; } public void setImageFormat(String imageFormat) { this.imageFormat = imageFormat; } public JSONObject toJSONObject(Repository repo) throws JSONException { JSONObject jo = JSONObject.create(); JSONObject wrapper = JSONObject.create(); jo.put("feature", wrapper); if (brushVisible) { JSONObject brushTypeWrapper = JSONObject.create(); wrapper.put("brush", brushTypeWrapper); JSONArray brushType = JSONArray.create(); brushTypeWrapper.put("type", brushType); if (isRectSelected) { brushType.put("rect"); } if (isPolygonSelected) { brushType.put("polygon"); } if (isKeepSelected) { brushType.put("keep"); } if (isLineXSelected) { brushType.put("lineX"); } if (isLineYSelected) { brushType.put("lineY"); } if (isClearSelected) { brushType.put("clear"); } } if (dataViewVisible) { JSONObject dataViewWrapper = JSONObject.create(); wrapper.put("dataView", dataViewWrapper); dataViewWrapper.put("backgroundColor", color2String(getBgColor())); dataViewWrapper.put("textareaColor", color2String(getTextareaColor())); dataViewWrapper.put("textareaBorderColor", color2String(getTextareaBorderColor())); dataViewWrapper.put("textColor", color2String(getTextColor())); dataViewWrapper.put("buttonColor", color2String(getButtonColor())); dataViewWrapper.put("buttonTextColor", color2String(getButtonTextColor())); } if (dataZoomVisible) { wrapper.put("dataZoom", JSONObject.create()); } if (magicTypeVisible) { JSONObject magicTypeWrapper = JSONObject.create(); wrapper.put("magicType", magicTypeWrapper); JSONArray magicType = JSONArray.create(); magicTypeWrapper.put("type", magicType); if (isBarSelected) { magicType.put("bar"); } if (isLineSelected) { magicType.put("line"); } if (isStackSelected) { magicType.put("stack"); } if (isTiledSelected) { magicType.put("tiled"); } } if (restoreVisible) { wrapper.put("restore", JSONObject.create()); } if (saveAsImageVisible) { JSONObject imageFormatWrapper = JSONObject.create(); wrapper.put("saveAsImage", imageFormatWrapper); imageFormatWrapper.put("type", imageFormat); } return jo; } @Override public boolean equals(Object obj) { return obj instanceof EChartsToolbox && ComparatorUtils.equals(brushVisible, ((EChartsToolbox) obj).brushVisible) && ComparatorUtils.equals(isRectSelected, ((EChartsToolbox) obj).isRectSelected) && ComparatorUtils.equals(isPolygonSelected, ((EChartsToolbox) obj).isPolygonSelected) && ComparatorUtils.equals(isKeepSelected, ((EChartsToolbox) obj).isKeepSelected) && ComparatorUtils.equals(isLineXSelected, ((EChartsToolbox) obj).isLineXSelected) && ComparatorUtils.equals(isLineYSelected, ((EChartsToolbox) obj).isLineYSelected) && ComparatorUtils.equals(isClearSelected, ((EChartsToolbox) obj).isClearSelected) && ComparatorUtils.equals(dataViewVisible, ((EChartsToolbox) obj).dataViewVisible) && ComparatorUtils.equals(bgColor, ((EChartsToolbox) obj).bgColor) && ComparatorUtils.equals(textareaColor, ((EChartsToolbox) obj).textareaColor) && ComparatorUtils.equals(textareaBorderColor, ((EChartsToolbox) obj).textareaBorderColor) && ComparatorUtils.equals(textColor, ((EChartsToolbox) obj).textColor) && ComparatorUtils.equals(buttonColor, ((EChartsToolbox) obj).buttonColor) && ComparatorUtils.equals(buttonTextColor, ((EChartsToolbox) obj).buttonTextColor) && ComparatorUtils.equals(dataZoomVisible, ((EChartsToolbox) obj).dataZoomVisible) && ComparatorUtils.equals(magicTypeVisible, ((EChartsToolbox) obj).magicTypeVisible) && ComparatorUtils.equals(isBarSelected, ((EChartsToolbox) obj).isBarSelected) && ComparatorUtils.equals(isLineSelected, ((EChartsToolbox) obj).isLineSelected) && ComparatorUtils.equals(isStackSelected, ((EChartsToolbox) obj).isStackSelected) && ComparatorUtils.equals(isTiledSelected, ((EChartsToolbox) obj).isTiledSelected) && ComparatorUtils.equals(restoreVisible, ((EChartsToolbox) obj).restoreVisible) && ComparatorUtils.equals(saveAsImageVisible, ((EChartsToolbox) obj).saveAsImageVisible) && ComparatorUtils.equals(imageFormat, ((EChartsToolbox) obj).imageFormat); } @Override public void readXML(XMLableReader reader) { if (reader.isChildNode()) { String tagName = reader.getTagName(); if (tagName.equals("ToolboxAttr")) { brushVisible = reader.getAttrAsBoolean("brushVisible", false); isRectSelected = reader.getAttrAsBoolean("isRectSelected", false); isPolygonSelected = reader.getAttrAsBoolean("isPolygonSelected", false); isKeepSelected = reader.getAttrAsBoolean("isKeepSelected", false); isLineXSelected = reader.getAttrAsBoolean("isLineXSelected", false); isLineYSelected = reader.getAttrAsBoolean("isLineYSelected", false); isClearSelected = reader.getAttrAsBoolean("isClearSelected", false); dataViewVisible = reader.getAttrAsBoolean("dataViewVisible", false); bgColor = reader.getAttrAsColor("bgColor", Color.white); textareaColor = reader.getAttrAsColor("textareaColor", Color.white); textareaBorderColor = reader.getAttrAsColor("textareaBorderColor", Color.black); textColor = reader.getAttrAsColor("textColor", Color.black); buttonColor = reader.getAttrAsColor("buttonColor", Color.red); buttonTextColor = reader.getAttrAsColor("buttonTextColor", Color.white); dataZoomVisible = reader.getAttrAsBoolean("dataZoomVisible", false); magicTypeVisible = reader.getAttrAsBoolean("magicTypeVisible", false); isBarSelected = reader.getAttrAsBoolean("isBarSelected", false); isLineSelected = reader.getAttrAsBoolean("isLineSelected", false); isStackSelected = reader.getAttrAsBoolean("isStackSelected", false); isTiledSelected = reader.getAttrAsBoolean("isTiledSelected", false); restoreVisible = reader.getAttrAsBoolean("restoreVisible", false); saveAsImageVisible = reader.getAttrAsBoolean("saveAsImageVisible", false); imageFormat = reader.getAttrAsString("imageFormat", "png"); } } } @Override public void writeXML(XMLPrintWriter writer) { writer.startTAG("ToolboxAttr"); writer.attr("brushVisible", String.valueOf(brushVisible)); writer.attr("isRectSelected", String.valueOf(isRectSelected)); writer.attr("isPolygonSelected", String.valueOf(isPolygonSelected)); writer.attr("isKeepSelected", String.valueOf(isKeepSelected)); writer.attr("isLineXSelected", String.valueOf(isLineXSelected)); writer.attr("isLineYSelected", String.valueOf(isLineYSelected)); writer.attr("isClearSelected", String.valueOf(isClearSelected)); writer.attr("dataViewVisible", String.valueOf(dataViewVisible)); if (bgColor != null) { writer.attr("bgColor", bgColor.getRGB()); } if (bgColor != null) { writer.attr("textareaColor", textareaColor.getRGB()); } if (bgColor != null) { writer.attr("textareaBorderColor", textareaBorderColor.getRGB()); } if (bgColor != null) { writer.attr("textColor", textColor.getRGB()); } if (bgColor != null) { writer.attr("buttonColor", buttonColor.getRGB()); } if (bgColor != null) { writer.attr("buttonTextColor", buttonTextColor.getRGB()); } writer.attr("dataZoomVisible", String.valueOf(dataZoomVisible)); writer.attr("magicTypeVisible", String.valueOf(magicTypeVisible)); writer.attr("isBarSelected", String.valueOf(isBarSelected)); writer.attr("isLineSelected", String.valueOf(isLineSelected)); writer.attr("isStackSelected", String.valueOf(isStackSelected)); writer.attr("isTiledSelected", String.valueOf(isTiledSelected)); writer.attr("restoreVisible", String.valueOf(restoreVisible)); writer.attr("saveAsImageVisible", String.valueOf(saveAsImageVisible)); writer.attr("imageFormat", imageFormat); writer.end(); } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
15,344
0.648266
0.647419
434
34.354839
29.447029
106
false
false
0
0
0
0
0
0
0.587558
false
false
13