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
ed02b5356a21482c51849e442cb2b715bfef6347
13,623,636,271,984
12922b5cf82fdb2ccb43eab486b5091a8879acd0
/app/src/main/java/com/cnh/bluetooth/view/impl/ICyBaseView.java
47ea11c05f3b2aae0bfc3274142644336a744d33
[]
no_license
CNHTT/PullListView
https://github.com/CNHTT/PullListView
1a2841d5bb4829937a67a63d19b5cff37b100fdb
dcc7609691f604f963bb878a5382bc2adfac62b6
refs/heads/master
2021-01-20T13:45:36.220000
2017-06-02T03:59:38
2017-06-02T03:59:38
90,525,679
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cnh.bluetooth.view.impl; /** * 项目名称:0505Bluetooth. * 创建人: CT. * 创建时间: 2017/5/4. * GitHub:https://github.com/CNHTT */ public interface ICyBaseView { }
UTF-8
Java
195
java
ICyBaseView.java
Java
[ { "context": ".\n * 创建时间: 2017/5/4.\n * GitHub:https://github.com/CNHTT\n */\n\npublic interface ICyBaseView {\n}\n", "end": 130, "score": 0.9987189173698425, "start": 125, "tag": "USERNAME", "value": "CNHTT" } ]
null
[]
package com.cnh.bluetooth.view.impl; /** * 项目名称:0505Bluetooth. * 创建人: CT. * 创建时间: 2017/5/4. * GitHub:https://github.com/CNHTT */ public interface ICyBaseView { }
195
0.668639
0.609467
11
14.363636
13.586576
36
false
false
0
0
0
0
0
0
0.090909
false
false
5
b321d4121d1784cd6b0bcda06def1b213b4588a6
28,973,849,386,899
f73428651296cc7755e490340998fa2c87696510
/webapp/src/main/java/com/omchlstats/web/controller/teams/TeamAssembler.java
2a17cbde4b42114ad3b915e44e0ac5d8eee0b81c
[]
no_license
abenak/omchlstats
https://github.com/abenak/omchlstats
5037b9cc938a7cea67bde80942a4f1f9b0691e97
5813c513e285b56b7f8a29dedd27a0332d836566
refs/heads/master
2018-01-08T11:24:36.960000
2017-11-05T23:00:43
2017-11-05T23:00:43
53,997,913
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.omchlstats.web.controller.teams; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import com.omchlstats.data.dataobject.Player; import com.omchlstats.data.dataobject.Team; import com.omchlstats.data.services.GenericService; import com.omchlstats.web.controller.assembler.AbstractResourceAssembler; import com.omchlstats.web.controller.league.LeagueController; import com.omchlstats.web.controller.players.PlayerAssembler; import com.omchlstats.web.controller.seasons.SeasonsController; import com.omchlstats.web.models.OmchlResource; import com.omchlstats.web.models.OmchlResourceCollection; /** * Assembles links and child resources for a {@link Team} * * <pre> * * HISTORY * Date Author Description * ------------ ----------- --------------------- * Oct 14, 2017 abenak Creation * * </pre> * * @author abenak * @version 1.0 */ public class TeamAssembler extends AbstractResourceAssembler<Team> { public TeamAssembler(GenericService service) { super(Team.class, service); } @Override protected OmchlResource buildResource(Team entity, boolean isRootEntity) { if (isRootEntity) { AbstractResourceAssembler<Player> playerAssembler = new PlayerAssembler(service); OmchlResourceCollection rscs = new OmchlResourceCollection(); for (Player player : entity.getPlayers()) { rscs.addResource(playerAssembler.toResource(player, false, false)); } entity.setData(rscs); } OmchlResource rsc = new OmchlResource(entity); rsc.add(linkTo(methodOn(SeasonsController.class).get(entity.getLeague().getSeason().getId())) .withRel("season")); rsc.add(linkTo(methodOn(LeagueController.class).get(entity.getLeague().getId())).withRel("league")); rsc.add(linkTo(methodOn(TeamController.class).get(entity.getId())).withSelfRel()); return rsc; } }
UTF-8
Java
2,111
java
TeamAssembler.java
Java
[ { "context": "------ \t---------------------\r\n * Oct 14, 2017 abenak \t Creation\r\n *\r\n * </pre>\r\n *\r\n * @author ", "end": 934, "score": 0.9978256225585938, "start": 928, "tag": "USERNAME", "value": "abenak" }, { "context": "k \t Creation\r\n *\r\n * </pre>\r\n *\r\n * @author abenak\r\n * @version 1.0\r\n */\r\npublic class TeamAssembler", "end": 990, "score": 0.9945845007896423, "start": 984, "tag": "USERNAME", "value": "abenak" } ]
null
[]
package com.omchlstats.web.controller.teams; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import com.omchlstats.data.dataobject.Player; import com.omchlstats.data.dataobject.Team; import com.omchlstats.data.services.GenericService; import com.omchlstats.web.controller.assembler.AbstractResourceAssembler; import com.omchlstats.web.controller.league.LeagueController; import com.omchlstats.web.controller.players.PlayerAssembler; import com.omchlstats.web.controller.seasons.SeasonsController; import com.omchlstats.web.models.OmchlResource; import com.omchlstats.web.models.OmchlResourceCollection; /** * Assembles links and child resources for a {@link Team} * * <pre> * * HISTORY * Date Author Description * ------------ ----------- --------------------- * Oct 14, 2017 abenak Creation * * </pre> * * @author abenak * @version 1.0 */ public class TeamAssembler extends AbstractResourceAssembler<Team> { public TeamAssembler(GenericService service) { super(Team.class, service); } @Override protected OmchlResource buildResource(Team entity, boolean isRootEntity) { if (isRootEntity) { AbstractResourceAssembler<Player> playerAssembler = new PlayerAssembler(service); OmchlResourceCollection rscs = new OmchlResourceCollection(); for (Player player : entity.getPlayers()) { rscs.addResource(playerAssembler.toResource(player, false, false)); } entity.setData(rscs); } OmchlResource rsc = new OmchlResource(entity); rsc.add(linkTo(methodOn(SeasonsController.class).get(entity.getLeague().getSeason().getId())) .withRel("season")); rsc.add(linkTo(methodOn(LeagueController.class).get(entity.getLeague().getId())).withRel("league")); rsc.add(linkTo(methodOn(TeamController.class).get(entity.getId())).withSelfRel()); return rsc; } }
2,111
0.685931
0.682141
54
37.092594
31.199043
108
false
false
0
0
0
0
0
0
0.685185
false
false
5
aa89bd875fed1983a130f6c99435a8bee7af6a9e
9,251,359,568,075
bc87a3c49a11828af8456f6301d38a2e6e96f190
/src/main/java/org/kids/controller/login/UserController.java
5e5a6b718e3c113cfd251cfdd853de18eaf6b99c
[]
no_license
KiD-repo/pipe
https://github.com/KiD-repo/pipe
4f7c032447dcc492de8b429dbcce6a42ebb27932
478ed32406c3a196619d56de1604f77945f398a7
refs/heads/master
2016-09-07T03:24:55.626000
2015-01-21T08:46:34
2015-01-21T08:46:34
28,477,892
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.kids.controller.login; import javax.inject.Inject; import org.kids.service.login.UserService; import org.kids.vo.UserVO; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/user/*") public class UserController { @Inject private UserService service; @RequestMapping(value="/view", method= RequestMethod.GET) public void view(Model model, int user_no) throws Exception{ model.addAttribute("view", service.view(user_no)); } @RequestMapping(value="/view", method= RequestMethod.POST) public void viewPost(Model model, int user_no) throws Exception{ model.addAttribute("view", service.view(user_no)); } @RequestMapping(value="/regist", method= RequestMethod.GET) public void regist() throws Exception{ } @RequestMapping(value="/regist", method= RequestMethod.POST) public String registPost(UserVO vo, Model model) throws Exception{ service.regist(vo); if(vo.getBand_no() == 1){ model.addAttribute("user_no", service.max(vo.getUser_no())); return "/user/band/regist"; }else{ return "redirect:/radio"; } } @RequestMapping(value="/remove", method= RequestMethod.POST) public void removePost(int user_no) throws Exception{ service.remove(user_no); } @RequestMapping(value="/modify", method= RequestMethod.GET) public void modify(Model model, int user_no) throws Exception{ model.addAttribute("view", service.view(user_no)); } @RequestMapping(value="/modify", method= RequestMethod.POST) public void modifyPost(UserVO vo) throws Exception{ service.modify(vo); } }
UTF-8
Java
1,766
java
UserController.java
Java
[]
null
[]
package org.kids.controller.login; import javax.inject.Inject; import org.kids.service.login.UserService; import org.kids.vo.UserVO; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/user/*") public class UserController { @Inject private UserService service; @RequestMapping(value="/view", method= RequestMethod.GET) public void view(Model model, int user_no) throws Exception{ model.addAttribute("view", service.view(user_no)); } @RequestMapping(value="/view", method= RequestMethod.POST) public void viewPost(Model model, int user_no) throws Exception{ model.addAttribute("view", service.view(user_no)); } @RequestMapping(value="/regist", method= RequestMethod.GET) public void regist() throws Exception{ } @RequestMapping(value="/regist", method= RequestMethod.POST) public String registPost(UserVO vo, Model model) throws Exception{ service.regist(vo); if(vo.getBand_no() == 1){ model.addAttribute("user_no", service.max(vo.getUser_no())); return "/user/band/regist"; }else{ return "redirect:/radio"; } } @RequestMapping(value="/remove", method= RequestMethod.POST) public void removePost(int user_no) throws Exception{ service.remove(user_no); } @RequestMapping(value="/modify", method= RequestMethod.GET) public void modify(Model model, int user_no) throws Exception{ model.addAttribute("view", service.view(user_no)); } @RequestMapping(value="/modify", method= RequestMethod.POST) public void modifyPost(UserVO vo) throws Exception{ service.modify(vo); } }
1,766
0.732163
0.731597
71
23.87324
24.508654
67
false
false
0
0
0
0
0
0
1.676056
false
false
5
5b49695b4583c4ac62f6e52d9d55de7b9d2d88a8
9,251,359,566,684
83a570d7ba853dc135e24e9608cdf489333ba9bc
/web-services/src/com/winsafe/drp/dao/AppPriceOrganLog.java
7327e9c6c5c5685c84d359944e840126c3f0343e
[]
no_license
marcncs/platform-svc
https://github.com/marcncs/platform-svc
2498f509b2117e8c7487e1d4f923a46783fc92df
8be007fde58e2e7bdcdd83109c636b3afcb0b42c
refs/heads/master
2021-05-21T15:48:46.283000
2020-03-25T11:44:46
2020-03-25T11:44:46
252,697,532
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.winsafe.drp.dao; import java.util.List; import com.winsafe.drp.entity.EntityManager; public class AppPriceOrganLog { public void addPriceOrganLog(PriceOrganLog p) throws Exception{ EntityManager.save(p); } public void updPriceOrganLog(PriceOrganLog p) throws Exception{ EntityManager.saveOrUpdate(p); } public void delPriceOrganLogByPid(String productid) throws Exception{ String sql="delete from Price_Organ_Log where productid='"+productid+"'"; EntityManager.updateOrdelete(sql); } public List getPriceOrganLogByPid(String pid) throws Exception{ List list = null; String sql = "from PriceOrganLog where productid='"+pid+"'"; list = EntityManager.getAllByHql(sql); return list; } }
UTF-8
Java
751
java
AppPriceOrganLog.java
Java
[]
null
[]
package com.winsafe.drp.dao; import java.util.List; import com.winsafe.drp.entity.EntityManager; public class AppPriceOrganLog { public void addPriceOrganLog(PriceOrganLog p) throws Exception{ EntityManager.save(p); } public void updPriceOrganLog(PriceOrganLog p) throws Exception{ EntityManager.saveOrUpdate(p); } public void delPriceOrganLogByPid(String productid) throws Exception{ String sql="delete from Price_Organ_Log where productid='"+productid+"'"; EntityManager.updateOrdelete(sql); } public List getPriceOrganLogByPid(String pid) throws Exception{ List list = null; String sql = "from PriceOrganLog where productid='"+pid+"'"; list = EntityManager.getAllByHql(sql); return list; } }
751
0.741678
0.741678
36
19.861111
24.563017
75
false
false
0
0
0
0
0
0
1.444444
false
false
5
237bc08db8382f89b9b0c9b678cb268425db52d5
412,316,870,646
dffe9135efef927c0b2a0df57b649f61380132be
/src/spt/seo/ui/FrmMain.java
16495492f70cfdaac0159c48ce6b5d1e27657f5d
[]
no_license
nguyenductamlhp/SEO
https://github.com/nguyenductamlhp/SEO
c0b87d7d8577d075399f2230f47d5f94e9434074
4ec6a526d838998f22acb64bb8b941f9f6afe0cb
refs/heads/master
2021-01-10T06:22:04.974000
2016-03-05T13:53:40
2016-03-05T13:53:40
53,203,364
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package spt.seo.ui; import java.awt.EventQueue; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.text.Normalizer; import java.util.regex.Pattern; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class FrmMain extends JFrame { /** * */ private static final long serialVersionUID = 1L; private JPanel contentPane; private JTextField txtCountWord; private JTextField txtCountChar; private JTextField txtSelectFolder; private JTextArea txtInput = new JTextArea(); private JTextArea txtKeyWord; @SuppressWarnings("rawtypes") private static JComboBox cbxChangeChar = new JComboBox(); @SuppressWarnings("rawtypes") private static JComboBox cbxByChar = new JComboBox(); @SuppressWarnings("rawtypes") private static JComboBox cbxChangeCharF = new JComboBox(); @SuppressWarnings("rawtypes") private static JComboBox cbxByCharF = new JComboBox(); private static String[] listItem = { " ", "-","_", ",", ";", ":", "(", ")" }; private JTextField txtSuccess; private JTextField txtFail; private JTextField txtSum; private JTextField txtURL; // private File getLatestFilefromDir(String dirPath){ // File dir = new File(dirPath); // File[] files = dir.listFiles(); // if (files == null || files.length == 0) { // return null; // } // // File lastModifiedFile = files[0]; // for (int i = 1; i < files.length; i++) { // if (lastModifiedFile.lastModified() < files[i].lastModified()) { // lastModifiedFile = files[i]; // } // } // return lastModifiedFile; // } private String getHTMLCodeByURL(String url) throws IOException { String source = ""; try { URL u = new URL(url); HttpURLConnection urlConnection = (HttpURLConnection)u.openConnection(); InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); char[] buffer = new char[8192]; int read = 0; StringBuilder builder = new StringBuilder(); while ((read = reader.read(buffer)) != -1) { builder.append(buffer, 0, read); } source = builder.toString(); } catch (MalformedURLException ex) { ex.printStackTrace(); } return source; } private String findKeyWord(String Src) { int pos = Src.indexOf("\"keywords\":\"", 0); System.out.println("pos: " + pos); System.out.println("pos: " + pos); char ch = Src.charAt(pos + 11); String temp = ""; while (ch != '"') { temp = temp + ch; } System.out.println("temp: " + temp); return temp; } private class SelectFolderAction implements ActionListener { JFileChooser finalJF = new JFileChooser("C:\\"); @Override public void actionPerformed(ActionEvent arg0) { JFileChooser fileChooser = new JFileChooser(); fileChooser = finalJF; int value = fileChooser.showOpenDialog(null); if (value == JFileChooser.APPROVE_OPTION) { File f = fileChooser.getCurrentDirectory(); txtSelectFolder.setText(f.getAbsolutePath()); finalJF = new JFileChooser(f.getAbsolutePath()); } } } private class ChangeFileName implements ActionListener { @Override public void actionPerformed(ActionEvent arg0) { File root = new File(txtSelectFolder.getText()); File[] listFile = root.listFiles(); int Success = 0; int Fail = 0; for (int i = 0; i < listFile.length; i++) { if (listFile[i].isFile()) { // String temp = Normalizer.normalize(s, Normalizer.Form.NFD); // Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); // return pattern.matcher(temp).replaceAll(""); // return pattern.matcher(temp).replaceAll("").replaceAll("Đ", "D").replaceAll("đ", "d"); String S = Normalizer.normalize(listFile[i].getName().trim(), Normalizer.Form.NFD);; Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); S = pattern.matcher(S).replaceAll("").replaceAll("Đ", "D").replaceAll("đ", "d"); String R = ""; String changeChar = cbxChangeCharF.getSelectedItem().toString(); String byChar = cbxByCharF.getSelectedItem().toString(); String R1 = S.replaceAll(changeChar, byChar); R = R1.replaceAll("[()]", ""); File oldFile = listFile[i]; File newFile = new File(oldFile.getAbsolutePath().replace(oldFile.getName(), R)); if (oldFile.renameTo(newFile)) { Success++; } else { Fail++; } } } txtSuccess.setText(Integer.toString(Success)); txtFail.setText(Integer.toString(Fail)); txtSum.setText(Integer.toString(Fail + Success)); JOptionPane.showMessageDialog(null, "Đã đổi xong"); } } private class ConvertTextAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String S = txtInput.getText(); int limit = S.length(); String s = ""; try { File f = new File("E:/config.xml"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(f); Element root = document.getDocumentElement(); NodeList list = root.getElementsByTagName("limitchar"); s = list.item(0).getTextContent(); limit = Integer.parseInt(s); } catch (ParserConfigurationException e1) { e1.printStackTrace(); } catch (SAXException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } S = S.substring(0, limit); txtInput.setText(S); String changeChar = cbxChangeChar.getSelectedItem().toString(); String byChar = cbxByChar.getSelectedItem().toString(); String R = S.replaceAll(changeChar, byChar); txtInput.setText(R); } } private class countWordAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String S = txtInput.getText().trim(); String[] arrS = S.split("[\\ \\,\\.\\\\\\/\\|\\:\\;\\'\\?\\(\\)\\\r\n\\_\\-]+"); txtCountWord.setText(Integer.toString(arrS.length)); } } private class countCharAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String S = new String(); S = txtInput.getText(); txtCountChar.setText(Integer.toString(S.length())); } } private class getKeyWordAction implements ActionListener { @Override public void actionPerformed(ActionEvent arg0) { String url = txtURL.getText().trim(); System.out.println(url); String S = ""; String Re = ""; try { S = getHTMLCodeByURL(url); //System.out.println("S: " + S); Re = findKeyWord(S); System.out.println("Key: " + Re); txtKeyWord.setText(Re); } catch (IOException e) { e.printStackTrace(); } } } /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { FrmMain frame = new FrmMain(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ @SuppressWarnings({ "rawtypes", "unchecked" }) public FrmMain() { setTitle("SEO"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 592, 355); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu mnOption = new JMenu("Lựa chọn"); menuBar.add(mnOption); JMenuItem mntmCharLimit = new JMenuItem("Giới hạn kí tự"); mntmCharLimit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String inp = ""; inp = JOptionPane.showInputDialog(null, "Nhập số ký tự tối đa", inp); System.out.println(inp); try { File f = new File("E:/config.xml"); //f.canWrite(); if (f.createNewFile()) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder build = factory.newDocumentBuilder(); Document doc = build.newDocument(); Element root = doc.createElement("root"); doc.appendChild(root); Node limitchar = doc.createElement("limitchar"); limitchar.setTextContent(inp); root.appendChild(limitchar); Transformer tr = TransformerFactory.newInstance().newTransformer(); DOMSource src = new DOMSource(doc); StreamResult re = new StreamResult(f); tr.transform(src, re); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ; } }); mnOption.add(mntmCharLimit); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JTabbedPane containTab = new JTabbedPane(JTabbedPane.TOP); containTab.setBounds(0, 0, 576, 295); contentPane.add(containTab); JPanel panelRenameFile = new JPanel(); containTab.addTab("Đổi tên file", null, panelRenameFile, null); panelRenameFile.setLayout(null); JLabel lblSelectFolder = new JLabel("Chọn thư mục"); lblSelectFolder.setBounds(10, 10, 80, 20); panelRenameFile.add(lblSelectFolder); txtSelectFolder = new JTextField(); txtSelectFolder.setBounds(116, 10, 305, 20); panelRenameFile.add(txtSelectFolder); txtSelectFolder.setColumns(10); JButton btnSelectFolder = new JButton("..."); btnSelectFolder.addActionListener(new SelectFolderAction()); btnSelectFolder.setBounds(447, 9, 89, 23); panelRenameFile.add(btnSelectFolder); JLabel lbli = new JLabel("Đổi"); lbli.setBounds(10, 63, 80, 20); panelRenameFile.add(lbli); cbxChangeCharF.setModel(new DefaultComboBoxModel(listItem)); cbxChangeCharF.setBounds(116, 63, 89, 20); panelRenameFile.add(cbxChangeCharF); JLabel lblBng_1 = new JLabel("bằng"); lblBng_1.setBounds(227, 63, 61, 20); panelRenameFile.add(lblBng_1); cbxByCharF.setModel(new DefaultComboBoxModel(listItem)); cbxByCharF.setBounds(324, 63, 97, 20); panelRenameFile.add(cbxByCharF); JButton btniTn = new JButton("Đổi tên"); btniTn.setFont(new Font("Times New Roman", Font.BOLD, 14)); btniTn.addActionListener(new ChangeFileName()); btniTn.setBounds(173, 107, 189, 29); panelRenameFile.add(btniTn); JLabel lblSuccess = new JLabel("Thành công"); lblSuccess.setBounds(10, 160, 80, 20); panelRenameFile.add(lblSuccess); txtSuccess = new JTextField(); txtSuccess.setEditable(false); txtSuccess.setBounds(116, 160, 86, 20); panelRenameFile.add(txtSuccess); txtSuccess.setColumns(10); JLabel lblFail = new JLabel("Thất bại"); lblFail.setBounds(245, 162, 80, 17); panelRenameFile.add(lblFail); txtFail = new JTextField(); txtFail.setEditable(false); txtFail.setBounds(353, 160, 86, 20); panelRenameFile.add(txtFail); txtFail.setColumns(10); JLabel lblSum = new JLabel("Tổng"); lblSum.setBounds(52, 218, 80, 20); panelRenameFile.add(lblSum); txtSum = new JTextField(); txtSum.setEditable(false); txtSum.setBounds(218, 218, 86, 20); panelRenameFile.add(txtSum); txtSum.setColumns(10); JPanel panelConvertText = new JPanel(); containTab.addTab("Đổi ký tự", null, panelConvertText, null); panelConvertText.setLayout(null); JLabel lblInput = new JLabel("Nhập văn bản"); lblInput.setBounds(10, 10, 80, 20); panelConvertText.add(lblInput); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(117, 8, 418, 135); panelConvertText.add(scrollPane); scrollPane.setViewportView(txtInput); txtCountWord = new JTextField(); txtCountWord.setEditable(false); txtCountWord.setBounds(117, 234, 118, 20); panelConvertText.add(txtCountWord); txtCountWord.setColumns(10); JButton btnCountWord = new JButton("Số từ"); btnCountWord.addActionListener(new countWordAction()); btnCountWord.setBounds(10, 233, 80, 23); panelConvertText.add(btnCountWord); JButton btnConvert = new JButton("Đổi kí tự"); btnConvert.addActionListener(new ConvertTextAction()); btnConvert.setBounds(229, 200, 89, 23); panelConvertText.add(btnConvert); JLabel lblThay = new JLabel("Thay"); lblThay.setBounds(10, 160, 80, 20); panelConvertText.add(lblThay); cbxChangeChar.setModel(new DefaultComboBoxModel(listItem)); cbxChangeChar.setBounds(117, 160, 70, 20); panelConvertText.add(cbxChangeChar); JLabel lblBng = new JLabel("bằng"); lblBng.setBounds(243, 160, 80, 20); panelConvertText.add(lblBng); cbxByChar.setModel(new DefaultComboBoxModel(listItem)); cbxByChar.setBounds(368, 160, 70, 20); panelConvertText.add(cbxByChar); JButton btnCountChar = new JButton("Số ký tự"); btnCountChar.addActionListener(new countCharAction()); btnCountChar.setBounds(269, 233, 89, 23); panelConvertText.add(btnCountChar); txtCountChar = new JTextField(); txtCountChar.setEditable(false); txtCountChar.setBounds(378, 234, 137, 20); panelConvertText.add(txtCountChar); txtCountChar.setColumns(10); JPanel panelGetKeyWord = new JPanel(); containTab.addTab("Tìm Keyword", null, panelGetKeyWord, null); panelGetKeyWord.setLayout(null); JLabel lblURL = new JLabel("Nhập URL"); lblURL.setBounds(10, 10, 80, 20); panelGetKeyWord.add(lblURL); txtURL = new JTextField(); txtURL.setBounds(110, 10, 419, 20); panelGetKeyWord.add(txtURL); txtURL.setColumns(10); JLabel lblKeyword = new JLabel("KeyWord"); lblKeyword.setBounds(10, 100, 80, 20); panelGetKeyWord.add(lblKeyword); JScrollPane scrollPane_1 = new JScrollPane(); scrollPane_1.setBounds(110, 98, 419, 143); panelGetKeyWord.add(scrollPane_1); txtKeyWord = new JTextArea(); scrollPane_1.setViewportView(txtKeyWord); JButton btnFind = new JButton("Tìm"); btnFind.addActionListener(new getKeyWordAction()); btnFind.setBounds(264, 52, 89, 23); panelGetKeyWord.add(btnFind); } }
UTF-8
Java
15,952
java
FrmMain.java
Java
[]
null
[]
package spt.seo.ui; import java.awt.EventQueue; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.text.Normalizer; import java.util.regex.Pattern; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class FrmMain extends JFrame { /** * */ private static final long serialVersionUID = 1L; private JPanel contentPane; private JTextField txtCountWord; private JTextField txtCountChar; private JTextField txtSelectFolder; private JTextArea txtInput = new JTextArea(); private JTextArea txtKeyWord; @SuppressWarnings("rawtypes") private static JComboBox cbxChangeChar = new JComboBox(); @SuppressWarnings("rawtypes") private static JComboBox cbxByChar = new JComboBox(); @SuppressWarnings("rawtypes") private static JComboBox cbxChangeCharF = new JComboBox(); @SuppressWarnings("rawtypes") private static JComboBox cbxByCharF = new JComboBox(); private static String[] listItem = { " ", "-","_", ",", ";", ":", "(", ")" }; private JTextField txtSuccess; private JTextField txtFail; private JTextField txtSum; private JTextField txtURL; // private File getLatestFilefromDir(String dirPath){ // File dir = new File(dirPath); // File[] files = dir.listFiles(); // if (files == null || files.length == 0) { // return null; // } // // File lastModifiedFile = files[0]; // for (int i = 1; i < files.length; i++) { // if (lastModifiedFile.lastModified() < files[i].lastModified()) { // lastModifiedFile = files[i]; // } // } // return lastModifiedFile; // } private String getHTMLCodeByURL(String url) throws IOException { String source = ""; try { URL u = new URL(url); HttpURLConnection urlConnection = (HttpURLConnection)u.openConnection(); InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); char[] buffer = new char[8192]; int read = 0; StringBuilder builder = new StringBuilder(); while ((read = reader.read(buffer)) != -1) { builder.append(buffer, 0, read); } source = builder.toString(); } catch (MalformedURLException ex) { ex.printStackTrace(); } return source; } private String findKeyWord(String Src) { int pos = Src.indexOf("\"keywords\":\"", 0); System.out.println("pos: " + pos); System.out.println("pos: " + pos); char ch = Src.charAt(pos + 11); String temp = ""; while (ch != '"') { temp = temp + ch; } System.out.println("temp: " + temp); return temp; } private class SelectFolderAction implements ActionListener { JFileChooser finalJF = new JFileChooser("C:\\"); @Override public void actionPerformed(ActionEvent arg0) { JFileChooser fileChooser = new JFileChooser(); fileChooser = finalJF; int value = fileChooser.showOpenDialog(null); if (value == JFileChooser.APPROVE_OPTION) { File f = fileChooser.getCurrentDirectory(); txtSelectFolder.setText(f.getAbsolutePath()); finalJF = new JFileChooser(f.getAbsolutePath()); } } } private class ChangeFileName implements ActionListener { @Override public void actionPerformed(ActionEvent arg0) { File root = new File(txtSelectFolder.getText()); File[] listFile = root.listFiles(); int Success = 0; int Fail = 0; for (int i = 0; i < listFile.length; i++) { if (listFile[i].isFile()) { // String temp = Normalizer.normalize(s, Normalizer.Form.NFD); // Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); // return pattern.matcher(temp).replaceAll(""); // return pattern.matcher(temp).replaceAll("").replaceAll("Đ", "D").replaceAll("đ", "d"); String S = Normalizer.normalize(listFile[i].getName().trim(), Normalizer.Form.NFD);; Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); S = pattern.matcher(S).replaceAll("").replaceAll("Đ", "D").replaceAll("đ", "d"); String R = ""; String changeChar = cbxChangeCharF.getSelectedItem().toString(); String byChar = cbxByCharF.getSelectedItem().toString(); String R1 = S.replaceAll(changeChar, byChar); R = R1.replaceAll("[()]", ""); File oldFile = listFile[i]; File newFile = new File(oldFile.getAbsolutePath().replace(oldFile.getName(), R)); if (oldFile.renameTo(newFile)) { Success++; } else { Fail++; } } } txtSuccess.setText(Integer.toString(Success)); txtFail.setText(Integer.toString(Fail)); txtSum.setText(Integer.toString(Fail + Success)); JOptionPane.showMessageDialog(null, "Đã đổi xong"); } } private class ConvertTextAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String S = txtInput.getText(); int limit = S.length(); String s = ""; try { File f = new File("E:/config.xml"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(f); Element root = document.getDocumentElement(); NodeList list = root.getElementsByTagName("limitchar"); s = list.item(0).getTextContent(); limit = Integer.parseInt(s); } catch (ParserConfigurationException e1) { e1.printStackTrace(); } catch (SAXException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } S = S.substring(0, limit); txtInput.setText(S); String changeChar = cbxChangeChar.getSelectedItem().toString(); String byChar = cbxByChar.getSelectedItem().toString(); String R = S.replaceAll(changeChar, byChar); txtInput.setText(R); } } private class countWordAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String S = txtInput.getText().trim(); String[] arrS = S.split("[\\ \\,\\.\\\\\\/\\|\\:\\;\\'\\?\\(\\)\\\r\n\\_\\-]+"); txtCountWord.setText(Integer.toString(arrS.length)); } } private class countCharAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String S = new String(); S = txtInput.getText(); txtCountChar.setText(Integer.toString(S.length())); } } private class getKeyWordAction implements ActionListener { @Override public void actionPerformed(ActionEvent arg0) { String url = txtURL.getText().trim(); System.out.println(url); String S = ""; String Re = ""; try { S = getHTMLCodeByURL(url); //System.out.println("S: " + S); Re = findKeyWord(S); System.out.println("Key: " + Re); txtKeyWord.setText(Re); } catch (IOException e) { e.printStackTrace(); } } } /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { FrmMain frame = new FrmMain(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ @SuppressWarnings({ "rawtypes", "unchecked" }) public FrmMain() { setTitle("SEO"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 592, 355); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu mnOption = new JMenu("Lựa chọn"); menuBar.add(mnOption); JMenuItem mntmCharLimit = new JMenuItem("Giới hạn kí tự"); mntmCharLimit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String inp = ""; inp = JOptionPane.showInputDialog(null, "Nhập số ký tự tối đa", inp); System.out.println(inp); try { File f = new File("E:/config.xml"); //f.canWrite(); if (f.createNewFile()) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder build = factory.newDocumentBuilder(); Document doc = build.newDocument(); Element root = doc.createElement("root"); doc.appendChild(root); Node limitchar = doc.createElement("limitchar"); limitchar.setTextContent(inp); root.appendChild(limitchar); Transformer tr = TransformerFactory.newInstance().newTransformer(); DOMSource src = new DOMSource(doc); StreamResult re = new StreamResult(f); tr.transform(src, re); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ; } }); mnOption.add(mntmCharLimit); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JTabbedPane containTab = new JTabbedPane(JTabbedPane.TOP); containTab.setBounds(0, 0, 576, 295); contentPane.add(containTab); JPanel panelRenameFile = new JPanel(); containTab.addTab("Đổi tên file", null, panelRenameFile, null); panelRenameFile.setLayout(null); JLabel lblSelectFolder = new JLabel("Chọn thư mục"); lblSelectFolder.setBounds(10, 10, 80, 20); panelRenameFile.add(lblSelectFolder); txtSelectFolder = new JTextField(); txtSelectFolder.setBounds(116, 10, 305, 20); panelRenameFile.add(txtSelectFolder); txtSelectFolder.setColumns(10); JButton btnSelectFolder = new JButton("..."); btnSelectFolder.addActionListener(new SelectFolderAction()); btnSelectFolder.setBounds(447, 9, 89, 23); panelRenameFile.add(btnSelectFolder); JLabel lbli = new JLabel("Đổi"); lbli.setBounds(10, 63, 80, 20); panelRenameFile.add(lbli); cbxChangeCharF.setModel(new DefaultComboBoxModel(listItem)); cbxChangeCharF.setBounds(116, 63, 89, 20); panelRenameFile.add(cbxChangeCharF); JLabel lblBng_1 = new JLabel("bằng"); lblBng_1.setBounds(227, 63, 61, 20); panelRenameFile.add(lblBng_1); cbxByCharF.setModel(new DefaultComboBoxModel(listItem)); cbxByCharF.setBounds(324, 63, 97, 20); panelRenameFile.add(cbxByCharF); JButton btniTn = new JButton("Đổi tên"); btniTn.setFont(new Font("Times New Roman", Font.BOLD, 14)); btniTn.addActionListener(new ChangeFileName()); btniTn.setBounds(173, 107, 189, 29); panelRenameFile.add(btniTn); JLabel lblSuccess = new JLabel("Thành công"); lblSuccess.setBounds(10, 160, 80, 20); panelRenameFile.add(lblSuccess); txtSuccess = new JTextField(); txtSuccess.setEditable(false); txtSuccess.setBounds(116, 160, 86, 20); panelRenameFile.add(txtSuccess); txtSuccess.setColumns(10); JLabel lblFail = new JLabel("Thất bại"); lblFail.setBounds(245, 162, 80, 17); panelRenameFile.add(lblFail); txtFail = new JTextField(); txtFail.setEditable(false); txtFail.setBounds(353, 160, 86, 20); panelRenameFile.add(txtFail); txtFail.setColumns(10); JLabel lblSum = new JLabel("Tổng"); lblSum.setBounds(52, 218, 80, 20); panelRenameFile.add(lblSum); txtSum = new JTextField(); txtSum.setEditable(false); txtSum.setBounds(218, 218, 86, 20); panelRenameFile.add(txtSum); txtSum.setColumns(10); JPanel panelConvertText = new JPanel(); containTab.addTab("Đổi ký tự", null, panelConvertText, null); panelConvertText.setLayout(null); JLabel lblInput = new JLabel("Nhập văn bản"); lblInput.setBounds(10, 10, 80, 20); panelConvertText.add(lblInput); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(117, 8, 418, 135); panelConvertText.add(scrollPane); scrollPane.setViewportView(txtInput); txtCountWord = new JTextField(); txtCountWord.setEditable(false); txtCountWord.setBounds(117, 234, 118, 20); panelConvertText.add(txtCountWord); txtCountWord.setColumns(10); JButton btnCountWord = new JButton("Số từ"); btnCountWord.addActionListener(new countWordAction()); btnCountWord.setBounds(10, 233, 80, 23); panelConvertText.add(btnCountWord); JButton btnConvert = new JButton("Đổi kí tự"); btnConvert.addActionListener(new ConvertTextAction()); btnConvert.setBounds(229, 200, 89, 23); panelConvertText.add(btnConvert); JLabel lblThay = new JLabel("Thay"); lblThay.setBounds(10, 160, 80, 20); panelConvertText.add(lblThay); cbxChangeChar.setModel(new DefaultComboBoxModel(listItem)); cbxChangeChar.setBounds(117, 160, 70, 20); panelConvertText.add(cbxChangeChar); JLabel lblBng = new JLabel("bằng"); lblBng.setBounds(243, 160, 80, 20); panelConvertText.add(lblBng); cbxByChar.setModel(new DefaultComboBoxModel(listItem)); cbxByChar.setBounds(368, 160, 70, 20); panelConvertText.add(cbxByChar); JButton btnCountChar = new JButton("Số ký tự"); btnCountChar.addActionListener(new countCharAction()); btnCountChar.setBounds(269, 233, 89, 23); panelConvertText.add(btnCountChar); txtCountChar = new JTextField(); txtCountChar.setEditable(false); txtCountChar.setBounds(378, 234, 137, 20); panelConvertText.add(txtCountChar); txtCountChar.setColumns(10); JPanel panelGetKeyWord = new JPanel(); containTab.addTab("Tìm Keyword", null, panelGetKeyWord, null); panelGetKeyWord.setLayout(null); JLabel lblURL = new JLabel("Nhập URL"); lblURL.setBounds(10, 10, 80, 20); panelGetKeyWord.add(lblURL); txtURL = new JTextField(); txtURL.setBounds(110, 10, 419, 20); panelGetKeyWord.add(txtURL); txtURL.setColumns(10); JLabel lblKeyword = new JLabel("KeyWord"); lblKeyword.setBounds(10, 100, 80, 20); panelGetKeyWord.add(lblKeyword); JScrollPane scrollPane_1 = new JScrollPane(); scrollPane_1.setBounds(110, 98, 419, 143); panelGetKeyWord.add(scrollPane_1); txtKeyWord = new JTextArea(); scrollPane_1.setViewportView(txtKeyWord); JButton btnFind = new JButton("Tìm"); btnFind.addActionListener(new getKeyWordAction()); btnFind.setBounds(264, 52, 89, 23); panelGetKeyWord.add(btnFind); } }
15,952
0.689549
0.666414
550
27.843636
20.757322
93
false
false
0
0
0
0
0
0
3.209091
false
false
5
b2945801d59d78a5c01be2b92ba799d49d93cfb5
4,913,442,604,048
ae076bfdeac3a3b1b04d6ab78e4323ee23edbda6
/app/src/main/java/org/lunapark/dev/war4peace1/managers/SoundManager.java
87131d9325276d264bfb574c76981e1e3074e327
[]
no_license
luna-park/War4peace1
https://github.com/luna-park/War4peace1
8f4f7a9c2e22fc32017db2f205a2bac5a3a295b0
b0ce272238327bd2ca015d0a125f839b209db1ba
refs/heads/master
2021-01-23T06:35:14.368000
2017-04-05T22:22:13
2017-04-05T22:22:13
86,379,912
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.lunapark.dev.war4peace1.managers; import android.content.Context; import android.media.AudioManager; import android.media.SoundPool; import org.lunapark.dev.war4peace1.R; /** * Sound manager * Created by znak on 27.03.2017. */ public class SoundManager { private SoundPool soundPool; private Context context; public static int sfxShot, sfxImpact, sfxStep; public SoundManager(Context context) { this.context = context; soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0); soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() { @Override public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { } }); loadSounds(); } private void loadSounds() { sfxShot = soundPool.load(context, R.raw.sfx_shot, 1); sfxImpact = soundPool.load(context, R.raw.sfx_impact, 1); sfxStep = soundPool.load(context, R.raw.sfx_step, 1); } public void playSoundMono(int id) { soundPool.play(id, 0.5f, 0.5f, 1, 0, 1); } public void dispose() { soundPool.release(); } }
UTF-8
Java
1,173
java
SoundManager.java
Java
[ { "context": ".war4peace1.R;\n\n/**\n * Sound manager\n * Created by znak on 27.03.2017.\n */\n\npublic class SoundManager {\n\n", "end": 225, "score": 0.9996652603149414, "start": 221, "tag": "USERNAME", "value": "znak" } ]
null
[]
package org.lunapark.dev.war4peace1.managers; import android.content.Context; import android.media.AudioManager; import android.media.SoundPool; import org.lunapark.dev.war4peace1.R; /** * Sound manager * Created by znak on 27.03.2017. */ public class SoundManager { private SoundPool soundPool; private Context context; public static int sfxShot, sfxImpact, sfxStep; public SoundManager(Context context) { this.context = context; soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0); soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() { @Override public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { } }); loadSounds(); } private void loadSounds() { sfxShot = soundPool.load(context, R.raw.sfx_shot, 1); sfxImpact = soundPool.load(context, R.raw.sfx_impact, 1); sfxStep = soundPool.load(context, R.raw.sfx_step, 1); } public void playSoundMono(int id) { soundPool.play(id, 0.5f, 0.5f, 1, 0, 1); } public void dispose() { soundPool.release(); } }
1,173
0.653879
0.633419
45
25.066668
23.886211
87
false
false
0
0
0
0
0
0
0.755556
false
false
5
5d5aa539f0ff25d2443f12c41b2c22de716c6f4e
32,813,550,152,680
51c233397c419e06bab5a54b24ecf1b47ad3ae3e
/BaseUtils/src/main/java/com/mill/utils/hideapi/HideApiHelper.java
907baa9cc6062ef65df4855b4cbcc3eb2169a265
[ "Apache-2.0" ]
permissive
miLLlulei/BasicLibrary
https://github.com/miLLlulei/BasicLibrary
cfd224697ee847dd53ed6c5b77c784c29d7ed314
6845deac4e2e483d09e5baf16c3685ab0d246ec7
refs/heads/master
2020-03-25T01:27:30.171000
2018-08-03T10:01:44
2018-08-03T10:01:44
143,238,949
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mill.utils.hideapi; import android.annotation.TargetApi; import android.app.Application; import android.content.Context; import android.os.Binder; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.util.DisplayMetrics; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class HideApiHelper { // android.util.DisplayMetrics public static final int DENSITY_DEVICE; static { DENSITY_DEVICE = getDeviceDensity(); } private static int getDeviceDensity() { return HideApiHelper.SystemProperties.getInt("qemu.sf.lcd_density", HideApiHelper.SystemProperties.getInt("ro.sf.lcd_density", 160)); } public static class ServiceManager { public static void addService(String serviceName, IBinder service) { try { Class.forName("android.os.ServiceManager") .getDeclaredMethod("addService", String.class, IBinder.class) .invoke(null, serviceName, service); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public static IBinder getService(String serviceName) { try { return (IBinder) Class.forName("android.os.ServiceManager") .getDeclaredMethod("getService", String.class) .invoke(null, serviceName); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public static IBinder checkService(String serviceName) { try { return (IBinder) Class.forName("android.os.ServiceManager") .getDeclaredMethod("checkService", String.class) .invoke(null, serviceName); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } public static class SystemProperties { public static int getInt(String key) { try { return (Integer) Class.forName("android.os.SystemProperties") .getDeclaredMethod("get", String.class) .invoke(null, key); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public static int getInt(String key, int def) { try { return (Integer) Class.forName("android.os.SystemProperties") .getDeclaredMethod("getInt", String.class, int.class) .invoke(null, key, def); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public static String get(String key) { try { return (String) Class.forName("android.os.SystemProperties") .getDeclaredMethod("get", String.class) .invoke(null, key); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public static String get(String key, String def) { try { return (String) Class.forName("android.os.SystemProperties") .getDeclaredMethod("get", String.class, String.class) .invoke(null, key, def); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } public static class Threads { public static long getOrCreateThreadId(Context context, String address) { try { return (Long) Class.forName(ReflectUtils.CLASSNAME_THREADS) .getDeclaredMethod("getOrCreateThreadId", Context.class, String.class) .invoke(null, context, address); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } public static class ActivityManagerNative { public static Object getDefault() { try { return Class.forName("android.app.ActivityManagerNative") .getMethod("getDefault") .invoke(null); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } /** * 只是对API>=18以上rom有效 */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public static Object getContentProviderExternal(String providerName, int userId, IBinder token) { try { Class clazz = Class.forName("android.app.ActivityManagerNative"); Method getContentProviderExternal = clazz. getMethod("getContentProviderExternal", String.class, int.class, IBinder.class); return getContentProviderExternal.invoke(getDefault(), providerName, userId, token); } catch (Exception e) { throw new RuntimeException(e); } } /** * 只是对API>=18以上rom有效 */ public static void removeContentProviderExternal(String providerName, IBinder token) { try { Class clazz = Class.forName("android.app.ActivityManagerNative"); Method removeContentProviderExternal = clazz. getMethod("removeContentProviderExternal", String.class, IBinder.class); removeContentProviderExternal.invoke(getDefault(), providerName, token); } catch (Exception e) { throw new RuntimeException(e); } } } public static class QuotedPrintableCodec { public static byte[] decodeQuotedPrintable(byte[] bytes) { try { return (byte[]) Class.forName("org.apache.commons.codec.net.QuotedPrintableCodec") .getDeclaredMethod("decodeQuotedPrintable", byte[].class) .invoke(null, (Object) bytes); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } public static File getSharedPrefsFile(Object context, String sharedPrefsFileName) { try { Method method = context.getClass().getMethod("getSharedPrefsFile", String.class); method.setAccessible(true); return (File) method.invoke(context, sharedPrefsFileName); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } public static Object currentActivityThread() { try { return Class.forName("android.app.ActivityThread") .getDeclaredMethod("currentActivityThread") .invoke(null); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public static Context getSystemContext(Object activityThread) { try { return (Context) activityThread.getClass() .getDeclaredMethod("getSystemContext") .invoke(activityThread); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } public static Class getActivityThreadClass() { try { return Class.forName("android.app.ActivityThread"); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public static Application currentApplication() { try { return (Application) Class.forName("android.app.ActivityThread") .getDeclaredMethod("currentApplication") .invoke(null); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } // android.content.pm.IPackageManager Helper Methods // 5.0.2 r1 // public int checkUidPermission(java.lang.String permName, int uid) throws android.os.RemoteException; public static int checkUidPermission(Object pm, String permName, int uid) { try { return (Integer) Class.forName(ReflectUtils.CLASSNAME_IPACKAGEMANAGER) .getMethod("checkUidPermission", String.class, int.class) .invoke(pm, permName, uid); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } //2.3 r1 //public abstract String[] getPackagesForUid(int uid); //2.3.1 //public abstract String[] getPackagesForUid(int uid); //2.3.3 r1 //public abstract String[] getPackagesForUid(int uid); //2.3.6 r1 //public abstract String[] getPackagesForUid(int uid); //4.4.4 r1 //public abstract String[] getPackagesForUid(int uid); //5.0.1 r1 //public abstract String[] getPackagesForUid(int uid); public static String[] getPackagesForUid(Object pm, int uid) { try { return (String[]) Class.forName(ReflectUtils.CLASSNAME_IPACKAGEMANAGER) .getMethod("getPackagesForUid", int.class) .invoke(pm, uid); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } // android.conent.pm.PackagePaser Helper Methods // 此API仅适用于 API<21 的版本,助手的原本代码,没有改动过 public static Object parsePackage(Object packageParser, File sourceFile, String destCodePath, DisplayMetrics metrics, int flags) { try { return packageParser.getClass() .getDeclaredMethod("packageParser", File.class, String.class, DisplayMetrics.class, int.class) .invoke(packageParser, sourceFile, destCodePath, metrics, flags); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } // 此API仅适用于 API<21 的版本,助手的原本代码,没有改动过 public static boolean collectCertificates(Object packageParser, Object pkg, int flags) { try { return (Boolean) packageParser.getClass() .getDeclaredMethod("collectCertificates", pkg.getClass(), int.class) .invoke(packageParser, pkg, flags); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } // IActivityManager Helper Methods //TODO 需要做版本适配 public static Object getServicesFromIActivityManager(Object tar, int arg0, int arg1) { try { return tar.getClass() .getMethod("getServices", int.class, int.class) .invoke(tar, arg0, arg1); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } public static class Content { /** * 只是对API>=18以上rom有效 */ public static void call(String authority, String callingPkg, String method, String arg, Bundle extras) throws Exception { //android.content.IContentProvider Object provider = null; IBinder token = new Binder(); try { Object holder = HideApiHelper.ActivityManagerNative.getContentProviderExternal( authority, 0, token); if (holder == null) { throw new IllegalStateException("Could not find provider: " + authority); } Field field = holder.getClass().getField("provider"); provider = field.get(holder); //public Bundle call(String callingPkg, String method, String arg, Bundle extras) Method call = Class.forName("android.content.IContentProvider").getMethod("call", String.class, String.class, String.class, Bundle.class); call.invoke(provider, callingPkg, method, arg, extras); } finally { if (provider != null) { HideApiHelper.ActivityManagerNative.removeContentProviderExternal(authority, token); } } } } }
UTF-8
Java
17,173
java
HideApiHelper.java
Java
[]
null
[]
package com.mill.utils.hideapi; import android.annotation.TargetApi; import android.app.Application; import android.content.Context; import android.os.Binder; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.util.DisplayMetrics; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class HideApiHelper { // android.util.DisplayMetrics public static final int DENSITY_DEVICE; static { DENSITY_DEVICE = getDeviceDensity(); } private static int getDeviceDensity() { return HideApiHelper.SystemProperties.getInt("qemu.sf.lcd_density", HideApiHelper.SystemProperties.getInt("ro.sf.lcd_density", 160)); } public static class ServiceManager { public static void addService(String serviceName, IBinder service) { try { Class.forName("android.os.ServiceManager") .getDeclaredMethod("addService", String.class, IBinder.class) .invoke(null, serviceName, service); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public static IBinder getService(String serviceName) { try { return (IBinder) Class.forName("android.os.ServiceManager") .getDeclaredMethod("getService", String.class) .invoke(null, serviceName); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public static IBinder checkService(String serviceName) { try { return (IBinder) Class.forName("android.os.ServiceManager") .getDeclaredMethod("checkService", String.class) .invoke(null, serviceName); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } public static class SystemProperties { public static int getInt(String key) { try { return (Integer) Class.forName("android.os.SystemProperties") .getDeclaredMethod("get", String.class) .invoke(null, key); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public static int getInt(String key, int def) { try { return (Integer) Class.forName("android.os.SystemProperties") .getDeclaredMethod("getInt", String.class, int.class) .invoke(null, key, def); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public static String get(String key) { try { return (String) Class.forName("android.os.SystemProperties") .getDeclaredMethod("get", String.class) .invoke(null, key); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public static String get(String key, String def) { try { return (String) Class.forName("android.os.SystemProperties") .getDeclaredMethod("get", String.class, String.class) .invoke(null, key, def); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } public static class Threads { public static long getOrCreateThreadId(Context context, String address) { try { return (Long) Class.forName(ReflectUtils.CLASSNAME_THREADS) .getDeclaredMethod("getOrCreateThreadId", Context.class, String.class) .invoke(null, context, address); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } public static class ActivityManagerNative { public static Object getDefault() { try { return Class.forName("android.app.ActivityManagerNative") .getMethod("getDefault") .invoke(null); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } /** * 只是对API>=18以上rom有效 */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public static Object getContentProviderExternal(String providerName, int userId, IBinder token) { try { Class clazz = Class.forName("android.app.ActivityManagerNative"); Method getContentProviderExternal = clazz. getMethod("getContentProviderExternal", String.class, int.class, IBinder.class); return getContentProviderExternal.invoke(getDefault(), providerName, userId, token); } catch (Exception e) { throw new RuntimeException(e); } } /** * 只是对API>=18以上rom有效 */ public static void removeContentProviderExternal(String providerName, IBinder token) { try { Class clazz = Class.forName("android.app.ActivityManagerNative"); Method removeContentProviderExternal = clazz. getMethod("removeContentProviderExternal", String.class, IBinder.class); removeContentProviderExternal.invoke(getDefault(), providerName, token); } catch (Exception e) { throw new RuntimeException(e); } } } public static class QuotedPrintableCodec { public static byte[] decodeQuotedPrintable(byte[] bytes) { try { return (byte[]) Class.forName("org.apache.commons.codec.net.QuotedPrintableCodec") .getDeclaredMethod("decodeQuotedPrintable", byte[].class) .invoke(null, (Object) bytes); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } public static File getSharedPrefsFile(Object context, String sharedPrefsFileName) { try { Method method = context.getClass().getMethod("getSharedPrefsFile", String.class); method.setAccessible(true); return (File) method.invoke(context, sharedPrefsFileName); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } public static Object currentActivityThread() { try { return Class.forName("android.app.ActivityThread") .getDeclaredMethod("currentActivityThread") .invoke(null); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public static Context getSystemContext(Object activityThread) { try { return (Context) activityThread.getClass() .getDeclaredMethod("getSystemContext") .invoke(activityThread); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } public static Class getActivityThreadClass() { try { return Class.forName("android.app.ActivityThread"); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public static Application currentApplication() { try { return (Application) Class.forName("android.app.ActivityThread") .getDeclaredMethod("currentApplication") .invoke(null); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } // android.content.pm.IPackageManager Helper Methods // 5.0.2 r1 // public int checkUidPermission(java.lang.String permName, int uid) throws android.os.RemoteException; public static int checkUidPermission(Object pm, String permName, int uid) { try { return (Integer) Class.forName(ReflectUtils.CLASSNAME_IPACKAGEMANAGER) .getMethod("checkUidPermission", String.class, int.class) .invoke(pm, permName, uid); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } //2.3 r1 //public abstract String[] getPackagesForUid(int uid); //2.3.1 //public abstract String[] getPackagesForUid(int uid); //2.3.3 r1 //public abstract String[] getPackagesForUid(int uid); //2.3.6 r1 //public abstract String[] getPackagesForUid(int uid); //4.4.4 r1 //public abstract String[] getPackagesForUid(int uid); //5.0.1 r1 //public abstract String[] getPackagesForUid(int uid); public static String[] getPackagesForUid(Object pm, int uid) { try { return (String[]) Class.forName(ReflectUtils.CLASSNAME_IPACKAGEMANAGER) .getMethod("getPackagesForUid", int.class) .invoke(pm, uid); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } // android.conent.pm.PackagePaser Helper Methods // 此API仅适用于 API<21 的版本,助手的原本代码,没有改动过 public static Object parsePackage(Object packageParser, File sourceFile, String destCodePath, DisplayMetrics metrics, int flags) { try { return packageParser.getClass() .getDeclaredMethod("packageParser", File.class, String.class, DisplayMetrics.class, int.class) .invoke(packageParser, sourceFile, destCodePath, metrics, flags); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } // 此API仅适用于 API<21 的版本,助手的原本代码,没有改动过 public static boolean collectCertificates(Object packageParser, Object pkg, int flags) { try { return (Boolean) packageParser.getClass() .getDeclaredMethod("collectCertificates", pkg.getClass(), int.class) .invoke(packageParser, pkg, flags); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } // IActivityManager Helper Methods //TODO 需要做版本适配 public static Object getServicesFromIActivityManager(Object tar, int arg0, int arg1) { try { return tar.getClass() .getMethod("getServices", int.class, int.class) .invoke(tar, arg0, arg1); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } public static class Content { /** * 只是对API>=18以上rom有效 */ public static void call(String authority, String callingPkg, String method, String arg, Bundle extras) throws Exception { //android.content.IContentProvider Object provider = null; IBinder token = new Binder(); try { Object holder = HideApiHelper.ActivityManagerNative.getContentProviderExternal( authority, 0, token); if (holder == null) { throw new IllegalStateException("Could not find provider: " + authority); } Field field = holder.getClass().getField("provider"); provider = field.get(holder); //public Bundle call(String callingPkg, String method, String arg, Bundle extras) Method call = Class.forName("android.content.IContentProvider").getMethod("call", String.class, String.class, String.class, Bundle.class); call.invoke(provider, callingPkg, method, arg, extras); } finally { if (provider != null) { HideApiHelper.ActivityManagerNative.removeContentProviderExternal(authority, token); } } } } }
17,173
0.579541
0.576898
426
38.974178
26.732403
154
false
false
0
0
0
0
0
0
0.549296
false
false
5
2d60529c218e4b622b78a55b13081db87f7978b3
33,139,967,666,221
30de73875e84ec36e7cde25f35c7bba39782d3e9
/src/controller/MainViewControllerSiemens.java
94b4c139b155d86c2b5800382b7a9ed9ecb4ab9f
[]
no_license
davideCerutti-git/TagMaker
https://github.com/davideCerutti-git/TagMaker
71d7cdd05cee4af9c1300c4ddb9083095189fde9
a5827a5a5e00d0c27a2eb37a047a426a51c02186
refs/heads/main
2023-08-08T19:10:47.280000
2023-08-01T09:33:15
2023-08-01T09:33:15
296,359,043
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Sample Skeleton for 'MainViewSiemens.fxml' Controller Class */ package controller; import java.io.*; import java.nio.channels.*; import org.controlsfx.control.*; import org.controlsfx.validation.*; import javafx.stage.*; import java.net.URL; import java.nio.file.*; import java.util.*; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.fxml.*; import javafx.geometry.Insets; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.image.*; import javafx.scene.layout.*; import javafx.stage.FileChooser.ExtensionFilter; import model.siemens.ModelSiemens; import settings.Settings; public class MainViewControllerSiemens extends ViewController implements Initializable { private ModelSiemens model; private ValidationSupport validationSupportDb = new ValidationSupport(); private ValidationSupport validationSupportXlsx = new ValidationSupport(); private static List<File> selectedDbFiles; private static List<File> selectedXlsxFiles; private Settings properties; private MaskerPane masker = new MaskerPane(); @FXML // ResourceBundle that was given to the FXMLLoader private ResourceBundle resources; @FXML // URL location of the FXML file that was given to the FXMLLoader private URL location; @FXML // fx:id="buttonBack" private Button buttonBack; // Value injected by FXMLLoader @FXML // fx:id="buttonChooseDb" private Button buttonChooseDb; // Value injected by FXMLLoader @FXML // fx:id="buttonChooseXlsx" private Button buttonChooseXlsx; // Value injected by FXMLLoader @FXML // fx:id="buttonDbToXls" private Button buttonDbToXls; // Value injected by FXMLLoader @FXML // fx:id="buttonXlsxToCsv" private Button buttonXlsxToCsv; // Value injected by FXMLLoader @FXML // fx:id="imageViewButtonDbToXls" private ImageView imageViewButtonDbToXls; // Value injected by FXMLLoader @FXML // fx:id="imageViewButtonFileChooserDb" private ImageView imageViewButtonFileChooserDb; // Value injected by FXMLLoader @FXML // fx:id="imageViewButtonFileChooserXls" private ImageView imageViewButtonFileChooserXls; // Value injected by FXMLLoader @FXML // fx:id="imageViewButtonXlsToCsv" private ImageView imageViewButtonXlsToCsv; // Value injected by FXMLLoader @FXML // fx:id="imageViewMenuItemAbout" private ImageView imageViewMenuItemAbout; // Value injected by FXMLLoader @FXML // fx:id="imageViewMenuItemClose" private ImageView imageViewMenuItemClose; // Value injected by FXMLLoader @FXML // fx:id="imageViewMenuItemSettings" private ImageView imageViewMenuItemSettings; // Value injected by FXMLLoader @FXML // fx:id="labelLocationDb" private Label labelLocationDb; // Value injected by FXMLLoader @FXML // fx:id="labelLocationXls" private Label labelLocationXls; // Value injected by FXMLLoader @FXML // fx:id="labelPrefixDriver" private Label labelPrefixDriver; // Value injected by FXMLLoader @FXML // fx:id="mainPane" private BorderPane mainPane; // Value injected by FXMLLoader @FXML // fx:id="mainStackPane" private StackPane mainStackPane; // Value injected by FXMLLoader @FXML // fx:id="mbPrefixDriver" private MenuButton mbPrefixDriver; // Value injected by FXMLLoader @FXML // fx:id="menuBar" private MenuBar menuBar; // Value injected by FXMLLoader @FXML // fx:id="menuItemSettingsSiemens" private MenuItem menuItemSettingsSiemens; // Value injected by FXMLLoader @FXML // fx:id="textFieldChooseDb" private TextField textFieldChooseDb; // Value injected by FXMLLoader @FXML // fx:id="textFieldChooseXlsx" private TextField textFieldChooseXlsx; // Value injected by FXMLLoader @FXML // fx:id="txtFieldPrefixDriver" private TextField txtFieldPrefixDriver; // Value injected by FXMLLoader @FXML // fx:id="rbAbsolute" private RadioButton rbAbsolute; // Value injected by FXMLLoader @FXML // fx:id="rbSymbolic" private RadioButton rbSymbolic; // Value injected by FXMLLoader public MainViewControllerSiemens() { model = new ModelSiemens(null); properties = ModelSiemens.getProp(); } @FXML void openSettingsSiemens(ActionEvent event) throws IOException { Stage stage = new Stage(); FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("/fxml/SettingsSiemens.fxml")); Parent root = loader.load(); SettingsControllerSiemens settingsSiemensController = (SettingsControllerSiemens) loader.getController(); settingsSiemensController.setModel(model); Image icon = new Image(getClass().getResourceAsStream("/images/tagIcon48.png")); stage.getIcons().add(icon); stage.setTitle("settings Siemens importer"); stage.setScene(new Scene(root)); stage.show(); } public void setModel(ModelSiemens modelSiemens) { model = modelSiemens; properties = ModelSiemens.getProp(); } /** * ######################## DB files * ############################################## **/ @FXML void openChooseFileDb(ActionEvent event) { ValidationSupport.setRequired(textFieldChooseDb, false); String filePath = ""; ModelSiemens.readProperties(); FileChooser fc = new FileChooser(); fc.setTitle("Open db File"); fc.getExtensionFilters().addAll(new ExtensionFilter("db Files", "*.db")); if (Files.exists(Paths.get(properties.getProperty("filePath"))) && !properties.getProperty("filePath").isBlank() && !properties.getProperty("filePath").isEmpty() && !properties.getProperty("filePath").isBlank()) { fc.setInitialDirectory(new File(properties.getProperty("filePath"))); } else { fc.setInitialDirectory(new File(System.getProperty("user.home") + "\\Desktop\\")); } selectedDbFiles = fc.showOpenMultipleDialog(buttonDbToXls.getParent().getScene().getWindow()); String s = ""; if (selectedDbFiles == null) { return; } for (File f : selectedDbFiles) { if (selectedDbFiles.size() > 1) { s = s + f.getName() + " ; "; } else { s = s + f.getName(); } filePath = f.getParentFile().getAbsolutePath(); } properties.setProperty("filePath", filePath); storePropertiesOnFile(); textFieldChooseDb.setText(s); } private void storePropertiesOnFile() { try { properties.store(new FileOutputStream("properties/siemensImporterSettings.cfg"), null); } catch (IOException e) { ModelSiemens.logSiem.error("IOException"); } } @FXML void dbToXls(ActionEvent event) throws IOException, CloneNotSupportedException { if (selectedDbFiles == null) { ValidationSupport.setRequired(textFieldChooseDb, true); } else { ConvertDb task = new ConvertDb(event); setDisable(true); new Thread(task).start(); } } public class ConvertDb extends Task<Void> { public ConvertDb(ActionEvent event) { } @Override protected Void call() throws Exception { if (selectedDbFiles != null) { File file = null; for (File f : selectedDbFiles) { if (!ModelSiemens.readDBFile(f)) { ModelSiemens.logSiem.error("Errore lettura file " + f.getName()); this.cancel(); return null; } file = f; } model.generateXlsx(file.getAbsolutePath().replace(".db", ".xlsx")); } return null; } @Override protected void succeeded() { selectedDbFiles = null; textFieldChooseDb.setText("select a file..."); model.clearDbList(); setDisable(false); } @Override protected void cancelled() { selectedDbFiles = null; textFieldChooseDb.setText("select a file..."); model.clearDbList(); setDisable(false); new Alert(Alert.AlertType.ERROR, "Errore converisone file .db ").showAndWait(); } } /** * ######################################################################################## **/ /** * ######################## XLS files * ############################################## **/ @FXML void openChooseFileXlsx(ActionEvent event) { ValidationSupport.setRequired(textFieldChooseXlsx, false); ValidationSupport.setRequired(txtFieldPrefixDriver, false); String filePath = ""; ModelSiemens.readProperties(); FileChooser fc = new FileChooser(); fc.setTitle("Open xlsx File"); fc.getExtensionFilters().addAll(new ExtensionFilter("xlsx Files", "*.xlsx")); if (Files.exists(Paths.get(properties.getProperty("filePath"))) && !properties.getProperty("filePath").isBlank() && !properties.getProperty("filePath").isEmpty() && !properties.getProperty("filePath").isBlank()) { fc.setInitialDirectory(new File(properties.getProperty("filePath"))); } else { fc.setInitialDirectory(new File(System.getProperty("user.home") + "\\Desktop\\")); } selectedXlsxFiles = fc.showOpenMultipleDialog(buttonXlsxToCsv.getParent().getScene().getWindow()); String s = ""; if (selectedXlsxFiles == null) { return; } for (File f : selectedXlsxFiles) { if (selectedXlsxFiles.size() > 1) { s = s + f.getName() + " ; "; } else { s = s + f.getName(); } filePath = f.getParentFile().getAbsolutePath(); } properties.setProperty("filePath", filePath); try { properties.store(new FileOutputStream("properties/siemensImporterSettings.cfg"), null); } catch (IOException e) { ModelSiemens.logSiem.error("IOException"); } textFieldChooseXlsx.setText(s); } @FXML void xlsxToCsv(ActionEvent event) throws IOException, CloneNotSupportedException { boolean error = false; if (selectedXlsxFiles == null) { ValidationSupport.setRequired(textFieldChooseXlsx, true); error = true; } if (txtFieldPrefixDriver.getText().isEmpty()) { ValidationSupport.setRequired(txtFieldPrefixDriver, true); error = true; } if (!error) { ConvertXlsx task = new ConvertXlsx(event); setDisable(true); new Thread(task).start(); } } public class ConvertXlsx extends Task<Void> { public ConvertXlsx(ActionEvent event) { } @Override protected Void call() throws Exception { if (selectedXlsxFiles != null) { File file = null; for (File f : selectedXlsxFiles) { if (!model.readXlsxFile(f)) { ModelSiemens.logSiem.error("Errore lettura file " + f.getName()); this.cancel(); return null; } file = f; } model.getCsvGenerator().generateCSV(file.getAbsolutePath().replace(".xlsx", ".csv"), rbSymbolic.isSelected(), false); model.clearListEntry(); } return null; } @Override protected void succeeded() { selectedXlsxFiles = null; textFieldChooseXlsx.setText("select a file..."); txtFieldPrefixDriver.setText(""); model.clearDbList(); setDisable(false); } @Override protected void cancelled() { selectedXlsxFiles = null; textFieldChooseXlsx.setText("select a file..."); txtFieldPrefixDriver.setText(""); model.clearDbList(); setDisable(false); new Alert(Alert.AlertType.ERROR, "Errore converisone file .xlsx ").showAndWait(); } } /** * ######################################################################################## **/ private void setDisable(boolean b) { for (Node n : mainStackPane.getChildren()) { n.setDisable(b); } if (b) { masker.setVisible(b); masker.setProgress(ProgressBar.INDETERMINATE_PROGRESS); masker.setText("Please wait..."); mainStackPane.getChildren().add(masker); } else mainStackPane.getChildren().remove(masker); } @FXML // This method is called by the FXMLLoader when initialization is complete void initialize() { assert buttonBack != null : "fx:id=\"buttonBack\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert buttonChooseDb != null : "fx:id=\"buttonChooseDb\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert buttonChooseXlsx != null : "fx:id=\"buttonChooseXlsx\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert buttonDbToXls != null : "fx:id=\"buttonDbToXls\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert buttonXlsxToCsv != null : "fx:id=\"buttonXlsxToCsv\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert imageViewButtonDbToXls != null : "fx:id=\"imageViewButtonDbToXls\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert imageViewButtonFileChooserDb != null : "fx:id=\"imageViewButtonFileChooserDb\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert imageViewButtonFileChooserXls != null : "fx:id=\"imageViewButtonFileChooserXls\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert imageViewButtonXlsToCsv != null : "fx:id=\"imageViewButtonXlsToCsv\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert imageViewMenuItemAbout != null : "fx:id=\"imageViewMenuItemAbout\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert imageViewMenuItemClose != null : "fx:id=\"imageViewMenuItemClose\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert imageViewMenuItemSettings != null : "fx:id=\"imageViewMenuItemSettings\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert labelLocationDb != null : "fx:id=\"labelLocationDb\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert labelLocationXls != null : "fx:id=\"labelLocationXls\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert labelPrefixDriver != null : "fx:id=\"labelPrefixDriver\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert mainPane != null : "fx:id=\"mainPane\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert mainStackPane != null : "fx:id=\"mainStackPane\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert mbPrefixDriver != null : "fx:id=\"mbPrefixDriver\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert menuBar != null : "fx:id=\"menuBar\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert menuItemSettingsSiemens != null : "fx:id=\"menuItemSettingsSiemens\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert textFieldChooseDb != null : "fx:id=\"textFieldChooseDb\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert textFieldChooseXlsx != null : "fx:id=\"textFieldChooseXlsx\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert txtFieldPrefixDriver != null : "fx:id=\"txtFieldPrefixDriver\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert rbAbsolute != null : "fx:id=\"rbAbsolute\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert rbSymbolic != null : "fx:id=\"rbSymbolic\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; } @Override public void initialize(URL location, ResourceBundle resources) { String[] menuItemStringsList = properties.getProperty("listOfPrefixes").split(";"); for (String s : menuItemStringsList) { s = s.trim(); } validationSupportDb.registerValidator(textFieldChooseDb, Validator.createEmptyValidator("Field required")); ValidationSupport.setRequired(textFieldChooseDb, false); validationSupportXlsx.registerValidator(textFieldChooseXlsx, Validator.createEmptyValidator("Field required")); ValidationSupport.setRequired(textFieldChooseXlsx, false); validationSupportXlsx.registerValidator(txtFieldPrefixDriver, Validator.createEmptyValidator("Field required")); ValidationSupport.setRequired(txtFieldPrefixDriver, false); makePopOverInfo(buttonDbToXls, "Converte un file db (creato con TIA) in file xlsx (formato Bottero)\n" + "- I file db non hanno informazione del numero DB, quindi è necessario\n" + "mettere nella cartella in cui si trova i/il file .db anche il file indexDBs.cfg\n" + "questo è un file di testo con il seguente contenuto (esempio):\n" + " DB_Fix write bit=185\n" + " DB_FixManComConv=189\n" + " DB_FixReadBit=181\n" + " DB_FixReadDint=183\n" + " DB_FixReadInt=182\n" + " DB_FixReadReal=184\n" + " DB_FixWrite_Real=188\n" + " DB_FixWriteDint=187\n" + " DB_FixWriteInt=186\n" + " FixReadCap=330\n" + " FixReadCap_copy=331\n" + "in questo file viene indicato a sinistra dell'uguale il nome simbolico della db e a destra il numero della db"); makePopOverInfo(buttonXlsxToCsv, "Converte un file xlsx (formato Bottero) in \nfile csv (formato importabile in iFix)"); ToggleGroup tg = new ToggleGroup(); rbAbsolute.setSelected(Boolean.parseBoolean(properties.getProperty("absoluteAddressSelected"))); rbSymbolic.setSelected(!Boolean.parseBoolean(properties.getProperty("absoluteAddressSelected"))); rbAbsolute.setToggleGroup(tg); rbSymbolic.setToggleGroup(tg); rbAbsolute.selectedProperty().addListener((observable, oldValue, newValue) -> { properties.setProperty("absoluteAddressSelected", "" + rbAbsolute.isSelected()); storePropertiesOnFile(); }); } private void makePopOverInfo(Button button, String string) { PopOver popOver = new PopOver(createPopOverinfo(string)); button.setOnMouseEntered(mouseEvent -> { // Show PopOver when mouse enters label popOver.show(button); }); button.setOnMouseExited(mouseEvent -> { // Show PopOver when mouse enters label popOver.hide(); }); } private VBox createPopOverinfo(String str) { Label lblName = new Label(str); VBox vBox = new VBox(lblName); VBox.setMargin(lblName, new Insets(10.0, 10.0, 10.0, 10.0)); return vBox; } @FXML void closeProgram(ActionEvent event) { System.exit(0); } @FXML void backToMainView(ActionEvent event) throws IOException { Node source = (Node) event.getSource(); Stage stage = (Stage) source.getScene().getWindow(); FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("/fxml/MainView.fxml")); Parent root = loader.load(); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("TagMaker"); stage.show(); } private boolean isFileClosed(File file) { try (FileChannel channel = new RandomAccessFile(file, "rw").getChannel()) { FileLock lock = channel.tryLock(); if (lock == null) { return false; } else { lock.release(); return true; } } catch (IOException e) { ModelSiemens.logSiem.warn("File gia' aperto in un altro processo!!!!"); } return false; } public String getPrefixSelected() { return txtFieldPrefixDriver.getText(); } public ModelSiemens getModel() { return this.model; } }
WINDOWS-1252
Java
18,396
java
MainViewControllerSiemens.java
Java
[]
null
[]
/** * Sample Skeleton for 'MainViewSiemens.fxml' Controller Class */ package controller; import java.io.*; import java.nio.channels.*; import org.controlsfx.control.*; import org.controlsfx.validation.*; import javafx.stage.*; import java.net.URL; import java.nio.file.*; import java.util.*; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.fxml.*; import javafx.geometry.Insets; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.image.*; import javafx.scene.layout.*; import javafx.stage.FileChooser.ExtensionFilter; import model.siemens.ModelSiemens; import settings.Settings; public class MainViewControllerSiemens extends ViewController implements Initializable { private ModelSiemens model; private ValidationSupport validationSupportDb = new ValidationSupport(); private ValidationSupport validationSupportXlsx = new ValidationSupport(); private static List<File> selectedDbFiles; private static List<File> selectedXlsxFiles; private Settings properties; private MaskerPane masker = new MaskerPane(); @FXML // ResourceBundle that was given to the FXMLLoader private ResourceBundle resources; @FXML // URL location of the FXML file that was given to the FXMLLoader private URL location; @FXML // fx:id="buttonBack" private Button buttonBack; // Value injected by FXMLLoader @FXML // fx:id="buttonChooseDb" private Button buttonChooseDb; // Value injected by FXMLLoader @FXML // fx:id="buttonChooseXlsx" private Button buttonChooseXlsx; // Value injected by FXMLLoader @FXML // fx:id="buttonDbToXls" private Button buttonDbToXls; // Value injected by FXMLLoader @FXML // fx:id="buttonXlsxToCsv" private Button buttonXlsxToCsv; // Value injected by FXMLLoader @FXML // fx:id="imageViewButtonDbToXls" private ImageView imageViewButtonDbToXls; // Value injected by FXMLLoader @FXML // fx:id="imageViewButtonFileChooserDb" private ImageView imageViewButtonFileChooserDb; // Value injected by FXMLLoader @FXML // fx:id="imageViewButtonFileChooserXls" private ImageView imageViewButtonFileChooserXls; // Value injected by FXMLLoader @FXML // fx:id="imageViewButtonXlsToCsv" private ImageView imageViewButtonXlsToCsv; // Value injected by FXMLLoader @FXML // fx:id="imageViewMenuItemAbout" private ImageView imageViewMenuItemAbout; // Value injected by FXMLLoader @FXML // fx:id="imageViewMenuItemClose" private ImageView imageViewMenuItemClose; // Value injected by FXMLLoader @FXML // fx:id="imageViewMenuItemSettings" private ImageView imageViewMenuItemSettings; // Value injected by FXMLLoader @FXML // fx:id="labelLocationDb" private Label labelLocationDb; // Value injected by FXMLLoader @FXML // fx:id="labelLocationXls" private Label labelLocationXls; // Value injected by FXMLLoader @FXML // fx:id="labelPrefixDriver" private Label labelPrefixDriver; // Value injected by FXMLLoader @FXML // fx:id="mainPane" private BorderPane mainPane; // Value injected by FXMLLoader @FXML // fx:id="mainStackPane" private StackPane mainStackPane; // Value injected by FXMLLoader @FXML // fx:id="mbPrefixDriver" private MenuButton mbPrefixDriver; // Value injected by FXMLLoader @FXML // fx:id="menuBar" private MenuBar menuBar; // Value injected by FXMLLoader @FXML // fx:id="menuItemSettingsSiemens" private MenuItem menuItemSettingsSiemens; // Value injected by FXMLLoader @FXML // fx:id="textFieldChooseDb" private TextField textFieldChooseDb; // Value injected by FXMLLoader @FXML // fx:id="textFieldChooseXlsx" private TextField textFieldChooseXlsx; // Value injected by FXMLLoader @FXML // fx:id="txtFieldPrefixDriver" private TextField txtFieldPrefixDriver; // Value injected by FXMLLoader @FXML // fx:id="rbAbsolute" private RadioButton rbAbsolute; // Value injected by FXMLLoader @FXML // fx:id="rbSymbolic" private RadioButton rbSymbolic; // Value injected by FXMLLoader public MainViewControllerSiemens() { model = new ModelSiemens(null); properties = ModelSiemens.getProp(); } @FXML void openSettingsSiemens(ActionEvent event) throws IOException { Stage stage = new Stage(); FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("/fxml/SettingsSiemens.fxml")); Parent root = loader.load(); SettingsControllerSiemens settingsSiemensController = (SettingsControllerSiemens) loader.getController(); settingsSiemensController.setModel(model); Image icon = new Image(getClass().getResourceAsStream("/images/tagIcon48.png")); stage.getIcons().add(icon); stage.setTitle("settings Siemens importer"); stage.setScene(new Scene(root)); stage.show(); } public void setModel(ModelSiemens modelSiemens) { model = modelSiemens; properties = ModelSiemens.getProp(); } /** * ######################## DB files * ############################################## **/ @FXML void openChooseFileDb(ActionEvent event) { ValidationSupport.setRequired(textFieldChooseDb, false); String filePath = ""; ModelSiemens.readProperties(); FileChooser fc = new FileChooser(); fc.setTitle("Open db File"); fc.getExtensionFilters().addAll(new ExtensionFilter("db Files", "*.db")); if (Files.exists(Paths.get(properties.getProperty("filePath"))) && !properties.getProperty("filePath").isBlank() && !properties.getProperty("filePath").isEmpty() && !properties.getProperty("filePath").isBlank()) { fc.setInitialDirectory(new File(properties.getProperty("filePath"))); } else { fc.setInitialDirectory(new File(System.getProperty("user.home") + "\\Desktop\\")); } selectedDbFiles = fc.showOpenMultipleDialog(buttonDbToXls.getParent().getScene().getWindow()); String s = ""; if (selectedDbFiles == null) { return; } for (File f : selectedDbFiles) { if (selectedDbFiles.size() > 1) { s = s + f.getName() + " ; "; } else { s = s + f.getName(); } filePath = f.getParentFile().getAbsolutePath(); } properties.setProperty("filePath", filePath); storePropertiesOnFile(); textFieldChooseDb.setText(s); } private void storePropertiesOnFile() { try { properties.store(new FileOutputStream("properties/siemensImporterSettings.cfg"), null); } catch (IOException e) { ModelSiemens.logSiem.error("IOException"); } } @FXML void dbToXls(ActionEvent event) throws IOException, CloneNotSupportedException { if (selectedDbFiles == null) { ValidationSupport.setRequired(textFieldChooseDb, true); } else { ConvertDb task = new ConvertDb(event); setDisable(true); new Thread(task).start(); } } public class ConvertDb extends Task<Void> { public ConvertDb(ActionEvent event) { } @Override protected Void call() throws Exception { if (selectedDbFiles != null) { File file = null; for (File f : selectedDbFiles) { if (!ModelSiemens.readDBFile(f)) { ModelSiemens.logSiem.error("Errore lettura file " + f.getName()); this.cancel(); return null; } file = f; } model.generateXlsx(file.getAbsolutePath().replace(".db", ".xlsx")); } return null; } @Override protected void succeeded() { selectedDbFiles = null; textFieldChooseDb.setText("select a file..."); model.clearDbList(); setDisable(false); } @Override protected void cancelled() { selectedDbFiles = null; textFieldChooseDb.setText("select a file..."); model.clearDbList(); setDisable(false); new Alert(Alert.AlertType.ERROR, "Errore converisone file .db ").showAndWait(); } } /** * ######################################################################################## **/ /** * ######################## XLS files * ############################################## **/ @FXML void openChooseFileXlsx(ActionEvent event) { ValidationSupport.setRequired(textFieldChooseXlsx, false); ValidationSupport.setRequired(txtFieldPrefixDriver, false); String filePath = ""; ModelSiemens.readProperties(); FileChooser fc = new FileChooser(); fc.setTitle("Open xlsx File"); fc.getExtensionFilters().addAll(new ExtensionFilter("xlsx Files", "*.xlsx")); if (Files.exists(Paths.get(properties.getProperty("filePath"))) && !properties.getProperty("filePath").isBlank() && !properties.getProperty("filePath").isEmpty() && !properties.getProperty("filePath").isBlank()) { fc.setInitialDirectory(new File(properties.getProperty("filePath"))); } else { fc.setInitialDirectory(new File(System.getProperty("user.home") + "\\Desktop\\")); } selectedXlsxFiles = fc.showOpenMultipleDialog(buttonXlsxToCsv.getParent().getScene().getWindow()); String s = ""; if (selectedXlsxFiles == null) { return; } for (File f : selectedXlsxFiles) { if (selectedXlsxFiles.size() > 1) { s = s + f.getName() + " ; "; } else { s = s + f.getName(); } filePath = f.getParentFile().getAbsolutePath(); } properties.setProperty("filePath", filePath); try { properties.store(new FileOutputStream("properties/siemensImporterSettings.cfg"), null); } catch (IOException e) { ModelSiemens.logSiem.error("IOException"); } textFieldChooseXlsx.setText(s); } @FXML void xlsxToCsv(ActionEvent event) throws IOException, CloneNotSupportedException { boolean error = false; if (selectedXlsxFiles == null) { ValidationSupport.setRequired(textFieldChooseXlsx, true); error = true; } if (txtFieldPrefixDriver.getText().isEmpty()) { ValidationSupport.setRequired(txtFieldPrefixDriver, true); error = true; } if (!error) { ConvertXlsx task = new ConvertXlsx(event); setDisable(true); new Thread(task).start(); } } public class ConvertXlsx extends Task<Void> { public ConvertXlsx(ActionEvent event) { } @Override protected Void call() throws Exception { if (selectedXlsxFiles != null) { File file = null; for (File f : selectedXlsxFiles) { if (!model.readXlsxFile(f)) { ModelSiemens.logSiem.error("Errore lettura file " + f.getName()); this.cancel(); return null; } file = f; } model.getCsvGenerator().generateCSV(file.getAbsolutePath().replace(".xlsx", ".csv"), rbSymbolic.isSelected(), false); model.clearListEntry(); } return null; } @Override protected void succeeded() { selectedXlsxFiles = null; textFieldChooseXlsx.setText("select a file..."); txtFieldPrefixDriver.setText(""); model.clearDbList(); setDisable(false); } @Override protected void cancelled() { selectedXlsxFiles = null; textFieldChooseXlsx.setText("select a file..."); txtFieldPrefixDriver.setText(""); model.clearDbList(); setDisable(false); new Alert(Alert.AlertType.ERROR, "Errore converisone file .xlsx ").showAndWait(); } } /** * ######################################################################################## **/ private void setDisable(boolean b) { for (Node n : mainStackPane.getChildren()) { n.setDisable(b); } if (b) { masker.setVisible(b); masker.setProgress(ProgressBar.INDETERMINATE_PROGRESS); masker.setText("Please wait..."); mainStackPane.getChildren().add(masker); } else mainStackPane.getChildren().remove(masker); } @FXML // This method is called by the FXMLLoader when initialization is complete void initialize() { assert buttonBack != null : "fx:id=\"buttonBack\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert buttonChooseDb != null : "fx:id=\"buttonChooseDb\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert buttonChooseXlsx != null : "fx:id=\"buttonChooseXlsx\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert buttonDbToXls != null : "fx:id=\"buttonDbToXls\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert buttonXlsxToCsv != null : "fx:id=\"buttonXlsxToCsv\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert imageViewButtonDbToXls != null : "fx:id=\"imageViewButtonDbToXls\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert imageViewButtonFileChooserDb != null : "fx:id=\"imageViewButtonFileChooserDb\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert imageViewButtonFileChooserXls != null : "fx:id=\"imageViewButtonFileChooserXls\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert imageViewButtonXlsToCsv != null : "fx:id=\"imageViewButtonXlsToCsv\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert imageViewMenuItemAbout != null : "fx:id=\"imageViewMenuItemAbout\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert imageViewMenuItemClose != null : "fx:id=\"imageViewMenuItemClose\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert imageViewMenuItemSettings != null : "fx:id=\"imageViewMenuItemSettings\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert labelLocationDb != null : "fx:id=\"labelLocationDb\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert labelLocationXls != null : "fx:id=\"labelLocationXls\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert labelPrefixDriver != null : "fx:id=\"labelPrefixDriver\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert mainPane != null : "fx:id=\"mainPane\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert mainStackPane != null : "fx:id=\"mainStackPane\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert mbPrefixDriver != null : "fx:id=\"mbPrefixDriver\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert menuBar != null : "fx:id=\"menuBar\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert menuItemSettingsSiemens != null : "fx:id=\"menuItemSettingsSiemens\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert textFieldChooseDb != null : "fx:id=\"textFieldChooseDb\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert textFieldChooseXlsx != null : "fx:id=\"textFieldChooseXlsx\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert txtFieldPrefixDriver != null : "fx:id=\"txtFieldPrefixDriver\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert rbAbsolute != null : "fx:id=\"rbAbsolute\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; assert rbSymbolic != null : "fx:id=\"rbSymbolic\" was not injected: check your FXML file 'MainViewSiemens.fxml'."; } @Override public void initialize(URL location, ResourceBundle resources) { String[] menuItemStringsList = properties.getProperty("listOfPrefixes").split(";"); for (String s : menuItemStringsList) { s = s.trim(); } validationSupportDb.registerValidator(textFieldChooseDb, Validator.createEmptyValidator("Field required")); ValidationSupport.setRequired(textFieldChooseDb, false); validationSupportXlsx.registerValidator(textFieldChooseXlsx, Validator.createEmptyValidator("Field required")); ValidationSupport.setRequired(textFieldChooseXlsx, false); validationSupportXlsx.registerValidator(txtFieldPrefixDriver, Validator.createEmptyValidator("Field required")); ValidationSupport.setRequired(txtFieldPrefixDriver, false); makePopOverInfo(buttonDbToXls, "Converte un file db (creato con TIA) in file xlsx (formato Bottero)\n" + "- I file db non hanno informazione del numero DB, quindi è necessario\n" + "mettere nella cartella in cui si trova i/il file .db anche il file indexDBs.cfg\n" + "questo è un file di testo con il seguente contenuto (esempio):\n" + " DB_Fix write bit=185\n" + " DB_FixManComConv=189\n" + " DB_FixReadBit=181\n" + " DB_FixReadDint=183\n" + " DB_FixReadInt=182\n" + " DB_FixReadReal=184\n" + " DB_FixWrite_Real=188\n" + " DB_FixWriteDint=187\n" + " DB_FixWriteInt=186\n" + " FixReadCap=330\n" + " FixReadCap_copy=331\n" + "in questo file viene indicato a sinistra dell'uguale il nome simbolico della db e a destra il numero della db"); makePopOverInfo(buttonXlsxToCsv, "Converte un file xlsx (formato Bottero) in \nfile csv (formato importabile in iFix)"); ToggleGroup tg = new ToggleGroup(); rbAbsolute.setSelected(Boolean.parseBoolean(properties.getProperty("absoluteAddressSelected"))); rbSymbolic.setSelected(!Boolean.parseBoolean(properties.getProperty("absoluteAddressSelected"))); rbAbsolute.setToggleGroup(tg); rbSymbolic.setToggleGroup(tg); rbAbsolute.selectedProperty().addListener((observable, oldValue, newValue) -> { properties.setProperty("absoluteAddressSelected", "" + rbAbsolute.isSelected()); storePropertiesOnFile(); }); } private void makePopOverInfo(Button button, String string) { PopOver popOver = new PopOver(createPopOverinfo(string)); button.setOnMouseEntered(mouseEvent -> { // Show PopOver when mouse enters label popOver.show(button); }); button.setOnMouseExited(mouseEvent -> { // Show PopOver when mouse enters label popOver.hide(); }); } private VBox createPopOverinfo(String str) { Label lblName = new Label(str); VBox vBox = new VBox(lblName); VBox.setMargin(lblName, new Insets(10.0, 10.0, 10.0, 10.0)); return vBox; } @FXML void closeProgram(ActionEvent event) { System.exit(0); } @FXML void backToMainView(ActionEvent event) throws IOException { Node source = (Node) event.getSource(); Stage stage = (Stage) source.getScene().getWindow(); FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("/fxml/MainView.fxml")); Parent root = loader.load(); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("TagMaker"); stage.show(); } private boolean isFileClosed(File file) { try (FileChannel channel = new RandomAccessFile(file, "rw").getChannel()) { FileLock lock = channel.tryLock(); if (lock == null) { return false; } else { lock.release(); return true; } } catch (IOException e) { ModelSiemens.logSiem.warn("File gia' aperto in un altro processo!!!!"); } return false; } public String getPrefixSelected() { return txtFieldPrefixDriver.getText(); } public ModelSiemens getModel() { return this.model; } }
18,396
0.710449
0.707731
482
37.161827
30.433908
119
false
false
0
0
0
0
0
0
2.639004
false
false
5
3e886b0dccb5c3449a43eb11f33cab4f342a96b6
5,961,414,626,998
3240347837b586b85306cdb61d46c2aac4781dcd
/2.JavaCore/src/com/javarush/task/task18/task1825/Solution.java
be4a5bf2c2df6522ce1c552edba605fbf8a91da7
[]
no_license
TjavaistT/JavaRushTasks
https://github.com/TjavaistT/JavaRushTasks
0ad6e37b7bde4e69c19e53ca90128ad533158e07
af02c24fa548b12fca2af3bae67341e75f2c7075
refs/heads/master
2020-06-04T14:03:12.773000
2019-09-30T09:18:44
2019-09-30T09:18:44
192,051,471
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.javarush.task.task18.task1825; import java.io.*; import java.util.*; import java.lang.*; /* Собираем файл */ public class Solution { public static void main(String[] args) { // Э: отсортировать имена файлов - TreeSet TreeSet<String> filesNames = new TreeSet<>(); // Э: считать имена файлов в список с автозакрытием потока try (Scanner scan = new Scanner(new InputStreamReader(System.in))) { String element; while (!(element = scan.next()).equals("end")) { filesNames.add(element); } } catch (Exception e) { e.printStackTrace(); } // Э: отделить имя файла от суффикса String[] splitedFilename = filesNames.first().split(".part"); String generalFilename = splitedFilename[0]; String suffix = ".part" + splitedFilename[1]; // Э: Создать файл с найденным именем в той же папке и открыть поток, что и считываемые файлы (буффер)(автозакрытие) try ( BufferedOutputStream writeGeneralFileStream = new BufferedOutputStream(new FileOutputStream(generalFilename, true)) ) { filesNames.stream() // получить содержимое всех файлов .map(Solution::getFileContent) //записать содержимое в основной файл .forEach(fileContent -> { boolean result = false; try { writeGeneralFileStream.write(fileContent); } catch (IOException e) { e.printStackTrace(); } }); } catch (IOException e) { e.printStackTrace(); } } //вернуть содержимое файла в массиве байт private static byte[] getFileContent(String filename) { byte[] fileContent = null; // Э:массив потоков файлов на чтение (автозакрытие) try (BufferedInputStream buf = new BufferedInputStream(new FileInputStream(filename))){ fileContent = new byte[buf.available()]; buf.read(fileContent); } catch (IOException e) { e.printStackTrace(); } return fileContent; } }
UTF-8
Java
2,586
java
Solution.java
Java
[]
null
[]
package com.javarush.task.task18.task1825; import java.io.*; import java.util.*; import java.lang.*; /* Собираем файл */ public class Solution { public static void main(String[] args) { // Э: отсортировать имена файлов - TreeSet TreeSet<String> filesNames = new TreeSet<>(); // Э: считать имена файлов в список с автозакрытием потока try (Scanner scan = new Scanner(new InputStreamReader(System.in))) { String element; while (!(element = scan.next()).equals("end")) { filesNames.add(element); } } catch (Exception e) { e.printStackTrace(); } // Э: отделить имя файла от суффикса String[] splitedFilename = filesNames.first().split(".part"); String generalFilename = splitedFilename[0]; String suffix = ".part" + splitedFilename[1]; // Э: Создать файл с найденным именем в той же папке и открыть поток, что и считываемые файлы (буффер)(автозакрытие) try ( BufferedOutputStream writeGeneralFileStream = new BufferedOutputStream(new FileOutputStream(generalFilename, true)) ) { filesNames.stream() // получить содержимое всех файлов .map(Solution::getFileContent) //записать содержимое в основной файл .forEach(fileContent -> { boolean result = false; try { writeGeneralFileStream.write(fileContent); } catch (IOException e) { e.printStackTrace(); } }); } catch (IOException e) { e.printStackTrace(); } } //вернуть содержимое файла в массиве байт private static byte[] getFileContent(String filename) { byte[] fileContent = null; // Э:массив потоков файлов на чтение (автозакрытие) try (BufferedInputStream buf = new BufferedInputStream(new FileInputStream(filename))){ fileContent = new byte[buf.available()]; buf.read(fileContent); } catch (IOException e) { e.printStackTrace(); } return fileContent; } }
2,586
0.569019
0.565468
68
32.10294
28.075077
131
false
false
0
0
0
0
0
0
0.338235
false
false
5
7aed1755e0ab1986f22426d8684a9b425acdef58
31,198,642,452,449
94b98fff7ef699e85ad65a7bfbd7d7fda5c39ac1
/src/test/java/org/es4j/eventstore/core/conversiontests/EventUpconverterPipelineHook/NonConvertingEvent.java
0a548889f1ba58ff6e06d6904eb43bca63ea922b
[]
no_license
es4j/es4j-eventstore-core
https://github.com/es4j/es4j-eventstore-core
0e692347801b7f2fd8a58b9267d0481e61047df7
651b433b262f0873e159f9334c42d03d4911f0c3
refs/heads/master
2021-01-15T19:46:04.625000
2012-08-11T19:17:47
2012-08-11T19:17:47
5,073,079
1
0
null
false
2020-10-13T06:40:30
2012-07-16T20:33:20
2016-04-10T15:15:45
2020-10-13T06:40:29
272
4
0
1
Java
false
false
package org.es4j.eventstore.core.conversiontests.EventUpconverterPipelineHook; /** * * @author Esfand */ public class NonConvertingEvent { }
UTF-8
Java
146
java
NonConvertingEvent.java
Java
[ { "context": "s.EventUpconverterPipelineHook;\n\n/**\n *\n * @author Esfand\n */\npublic class NonConvertingEvent {\n\n}\n", "end": 104, "score": 0.9701535105705261, "start": 98, "tag": "NAME", "value": "Esfand" } ]
null
[]
package org.es4j.eventstore.core.conversiontests.EventUpconverterPipelineHook; /** * * @author Esfand */ public class NonConvertingEvent { }
146
0.767123
0.760274
9
15.222222
24.493889
78
false
false
0
0
0
0
0
0
0.111111
false
false
5
87f26755ed88722212bae8c75f6135d079de5954
34,213,709,483,602
b3094fec74a901ef9746bd581debb7b5f4356cf3
/src/main/java/sk/eea/test/ambrosia/server/entity/EuropeanaObjectEntity.java
77251d5a39857b2038ebcdbdc6b0a5e5768460d1
[]
no_license
murphySk/ambrosiaTest
https://github.com/murphySk/ambrosiaTest
7843275bfca0509a4b57c9328329672cd278c9e5
a02a476bf4a7c4b28eaa3c3a0a298f334e07c439
refs/heads/master
2021-01-19T04:52:53.336000
2014-04-02T11:09:28
2014-04-02T11:09:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sk.eea.test.ambrosia.server.entity; /** * Created by murphy on 3/27/14. */ public class EuropeanaObjectEntity { private String objectId; private String title; private String description; }
UTF-8
Java
216
java
EuropeanaObjectEntity.java
Java
[ { "context": "ea.test.ambrosia.server.entity;\n\n/**\n * Created by murphy on 3/27/14.\n */\npublic class EuropeanaObjectEntit", "end": 69, "score": 0.996823787689209, "start": 63, "tag": "USERNAME", "value": "murphy" } ]
null
[]
package sk.eea.test.ambrosia.server.entity; /** * Created by murphy on 3/27/14. */ public class EuropeanaObjectEntity { private String objectId; private String title; private String description; }
216
0.708333
0.685185
14
14.428572
16.132107
43
false
false
0
0
0
0
0
0
0.285714
false
false
5
298b5407c04f09e168990782da39844751f31036
33,792,802,689,466
7f06fb2b771001b8f82188f1cd6b58c27ae40ba4
/src/test/java/com/yc/olshop/test/TestCart.java
6365eccd87b8eed7015ee2f0e1721c6ee54fbbd0
[]
no_license
HaloHan2017/OnlineShop
https://github.com/HaloHan2017/OnlineShop
7b463c5cad4cae694d2a3989576a746bbd650295
053be40aab0f52815faa0b530f31cd3308dadb2b
refs/heads/master
2022-12-22T08:09:33.879000
2020-10-11T12:51:06
2020-10-11T12:51:06
200,004,159
1
0
null
false
2022-12-10T03:27:23
2019-08-01T07:52:42
2020-10-11T12:51:10
2022-12-10T03:27:23
12,294
0
0
12
JavaScript
false
false
package com.yc.olshop.test; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.yc.olshop.bean.Comment; import com.yc.olshop.bean.User; import com.yc.olshop.biz.CartBiz; import com.yc.olshop.biz.CommentBiz; import com.yc.olshop.pojo.Cart; import com.yc.olshop.pojo.CartItem; @RunWith(SpringRunner.class) @ContextConfiguration("/beans.xml") public class TestCart { @SuppressWarnings("rawtypes") @Autowired private CartBiz cz; @Autowired private CommentBiz cb; @Test public void testName5() throws Exception { List<Integer> like = cb.selectLike(1); System.out.println(like.size()); } @Test public void testcomm() { int pid = 10; List<Comment> lst = cb.selectAllComment(pid); System.out.println(lst.get(0).toString()); } @Test public void testAdd() throws Exception { User user = new User(); user.setUid(1); user.setUsername("zhangsan"); int pid = 1; int pcount = 1; int ret = cz.addToCart(pid, pcount, user.getUsername() + "-" + user.getUid()); Assert.assertEquals(1, ret); } @Test public void testAdd2() throws Exception { User user = new User(); user.setUid(1); user.setUsername("zhangsan"); int pid = 2; int pcount = 2; int ret = cz.addToCart(pid, pcount, user.getUsername() + "-" + user.getUid()); Assert.assertEquals(1, ret); } @Test public void testDel() throws Exception { User user = new User(); user.setUid(1); user.setUsername("zhangsan"); int pid = 1; int ret = cz.delFromCart(pid, user.getUsername() + "-" + user.getUid()); Assert.assertEquals(1, ret); } @Test public void testDelAll() throws Exception { User user = new User(); user.setUid(1); user.setUsername("zhangsan"); int pid = 1; int ret = cz.delCart(user.getUsername() + "-" + user.getUid()); Assert.assertEquals(1, ret); } @Test public void testQuery() throws Exception { User user = new User(); user.setUid(1); user.setUsername("zhangsan"); Cart cart = cz.queryCart(user.getUsername() + "-" + user.getUid()); System.out.println(cart.getTotalMoney()); List<CartItem> citemList = cart.getCitemList(); for (CartItem cartItem : citemList) { System.out.println(cartItem.getProduct().getPname() + "--" + cartItem.getPcount()); } } }
UTF-8
Java
2,576
java
TestCart.java
Java
[ { "context": "w User();\r\n\t\tuser.setUid(1);\r\n\t\tuser.setUsername(\"zhangsan\");\r\n\r\n\t\tint pid = 1;\r\n\t\tint pcount = 1;\r\n\r\n\t\tint ", "end": 1162, "score": 0.9996176958084106, "start": 1154, "tag": "USERNAME", "value": "zhangsan" }, { "context": "w User();\r\n\t\tuser.setUid(1);\r\n\t\tuser.setUsername(\"zhangsan\");\r\n\r\n\t\tint pid = 2;\r\n\t\tint pcount = 2;\r\n\r\n\t\tint ", "end": 1452, "score": 0.999626636505127, "start": 1444, "tag": "USERNAME", "value": "zhangsan" }, { "context": "w User();\r\n\t\tuser.setUid(1);\r\n\t\tuser.setUsername(\"zhangsan\");\r\n\r\n\t\tint pid = 1;\r\n\t\tint ret = cz.delFromCart(", "end": 1741, "score": 0.9996240139007568, "start": 1733, "tag": "USERNAME", "value": "zhangsan" }, { "context": "w User();\r\n\t\tuser.setUid(1);\r\n\t\tuser.setUsername(\"zhangsan\");\r\n\r\n\t\tint pid = 1;\r\n\t\tint ret = cz.delCart(user", "end": 2006, "score": 0.9996249675750732, "start": 1998, "tag": "USERNAME", "value": "zhangsan" }, { "context": "w User();\r\n\t\tuser.setUid(1);\r\n\t\tuser.setUsername(\"zhangsan\");\r\n\r\n\t\tCart cart = cz.queryCart(user.getUsername", "end": 2261, "score": 0.9996128082275391, "start": 2253, "tag": "USERNAME", "value": "zhangsan" } ]
null
[]
package com.yc.olshop.test; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.yc.olshop.bean.Comment; import com.yc.olshop.bean.User; import com.yc.olshop.biz.CartBiz; import com.yc.olshop.biz.CommentBiz; import com.yc.olshop.pojo.Cart; import com.yc.olshop.pojo.CartItem; @RunWith(SpringRunner.class) @ContextConfiguration("/beans.xml") public class TestCart { @SuppressWarnings("rawtypes") @Autowired private CartBiz cz; @Autowired private CommentBiz cb; @Test public void testName5() throws Exception { List<Integer> like = cb.selectLike(1); System.out.println(like.size()); } @Test public void testcomm() { int pid = 10; List<Comment> lst = cb.selectAllComment(pid); System.out.println(lst.get(0).toString()); } @Test public void testAdd() throws Exception { User user = new User(); user.setUid(1); user.setUsername("zhangsan"); int pid = 1; int pcount = 1; int ret = cz.addToCart(pid, pcount, user.getUsername() + "-" + user.getUid()); Assert.assertEquals(1, ret); } @Test public void testAdd2() throws Exception { User user = new User(); user.setUid(1); user.setUsername("zhangsan"); int pid = 2; int pcount = 2; int ret = cz.addToCart(pid, pcount, user.getUsername() + "-" + user.getUid()); Assert.assertEquals(1, ret); } @Test public void testDel() throws Exception { User user = new User(); user.setUid(1); user.setUsername("zhangsan"); int pid = 1; int ret = cz.delFromCart(pid, user.getUsername() + "-" + user.getUid()); Assert.assertEquals(1, ret); } @Test public void testDelAll() throws Exception { User user = new User(); user.setUid(1); user.setUsername("zhangsan"); int pid = 1; int ret = cz.delCart(user.getUsername() + "-" + user.getUid()); Assert.assertEquals(1, ret); } @Test public void testQuery() throws Exception { User user = new User(); user.setUid(1); user.setUsername("zhangsan"); Cart cart = cz.queryCart(user.getUsername() + "-" + user.getUid()); System.out.println(cart.getTotalMoney()); List<CartItem> citemList = cart.getCitemList(); for (CartItem cartItem : citemList) { System.out.println(cartItem.getProduct().getPname() + "--" + cartItem.getPcount()); } } }
2,576
0.668866
0.660326
103
23.009708
20.853859
86
false
false
0
0
0
0
0
0
1.650485
false
false
5
ab849f3e833c65d9e3b653d2673a0fd7055ddad8
34,041,910,794,580
4dc1fbb943712a3c0b073054e90452071b57425a
/src/main/java/ssm/ConfigurationFile.java
df1b6d191133b74a388f8cebb8194d0a4449e88f
[ "MIT" ]
permissive
matheus-bongiorno/ssm
https://github.com/matheus-bongiorno/ssm
19ba12258c5df854d9973b90cda968f18704c6ef
27e691cb36a1398d2a0996f3da7218434dfb14d6
refs/heads/master
2022-04-06T01:36:14.968000
2018-10-18T19:44:40
2018-10-25T18:19:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ssm; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.stream.JsonReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; public class ConfigurationFile extends HashMapParameterStore { public ConfigurationFile(InputStream inputStream) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); JsonReader jsonReader = new JsonReader(inputStreamReader); Gson gson = new Gson(); Parameter[] parameters; try { parameters = gson.fromJson(jsonReader, Parameter[].class); } catch (JsonSyntaxException e) { Parameter[] examples = new Parameter[2]; examples[0] = new Parameter("name1", Environment.TEST, "value1"); examples[1] = new Parameter("name2", Environment.PRODUCTION, "value2"); throw new IllegalArgumentException(e.getMessage() + "\nExample syntax: " + Arrays.toString(examples)); } for (Parameter parameter : parameters) { if (parameter.getName() == null) { throw new IllegalArgumentException("Parameter name is missing."); } if (parameter.getEnvironment() == null) { throw new IllegalArgumentException("Parameter environment is missing."); } addParameter(parameter); } } }
UTF-8
Java
1,421
java
ConfigurationFile.java
Java
[]
null
[]
package ssm; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.stream.JsonReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; public class ConfigurationFile extends HashMapParameterStore { public ConfigurationFile(InputStream inputStream) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); JsonReader jsonReader = new JsonReader(inputStreamReader); Gson gson = new Gson(); Parameter[] parameters; try { parameters = gson.fromJson(jsonReader, Parameter[].class); } catch (JsonSyntaxException e) { Parameter[] examples = new Parameter[2]; examples[0] = new Parameter("name1", Environment.TEST, "value1"); examples[1] = new Parameter("name2", Environment.PRODUCTION, "value2"); throw new IllegalArgumentException(e.getMessage() + "\nExample syntax: " + Arrays.toString(examples)); } for (Parameter parameter : parameters) { if (parameter.getName() == null) { throw new IllegalArgumentException("Parameter name is missing."); } if (parameter.getEnvironment() == null) { throw new IllegalArgumentException("Parameter environment is missing."); } addParameter(parameter); } } }
1,421
0.653765
0.648839
35
39.599998
29.422247
114
false
false
0
0
0
0
0
0
0.685714
false
false
5
849ffeac14a3179d7c66ffa6c8c14e1c692d096a
32,083,405,718,417
b4a0eacd19fe6b6ca4849e2248e35d44638b9780
/Back End/Servlets/mywebapp/src/main/java/com/capgemini/mywebapp/servlets/LoginServlet.java
ceeb7d07abe17916e4def0b6708447b5f1b1adaf
[]
no_license
AbhayaAdarsh/TY_CG_HTD_BANGLORENOVEMBER_JFS_ABHAYAADARSH
https://github.com/AbhayaAdarsh/TY_CG_HTD_BANGLORENOVEMBER_JFS_ABHAYAADARSH
8eacea56dc0a0edd4d6d1aa4f54fadedcb31e0fc
fb5e5796bff2df32632e4b6225c0ee6da6a7d8de
refs/heads/master
2021-08-22T05:18:15.521000
2020-09-25T18:04:30
2020-09-25T18:04:30
225,846,160
0
0
null
false
2020-09-25T18:06:38
2019-12-04T11:01:11
2020-09-25T18:06:07
2020-09-25T18:06:36
66,924
0
0
20
JavaScript
false
false
package com.capgemini.mywebapp.servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.capgemini.mywebapp.bean.EmployeeInfoBean; import com.capgemini.mywebapp.services.EmployeeServiceImpl; import com.capgemini.mywebapp.services.EmployeeServices; @WebServlet("/Login") public class LoginServlet extends HttpServlet { private EmployeeServices service = new EmployeeServiceImpl() ; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Get the form data String empIdVal=req.getParameter("empId"); String password=req.getParameter("password"); int empId=Integer.parseInt(empIdVal); EmployeeInfoBean employeeInfoBean=service.authenticate(empId, password); PrintWriter out=resp.getWriter(); out.println("<html>"); out.println("<body>"); if(employeeInfoBean !=null) { //Valid credentials HttpSession session=req.getSession(true); session.setAttribute("employeeInfoBean",employeeInfoBean); out.println("<h2 style='color:blue'>Welcome "+ employeeInfoBean.getName() +"!</h2>"); out.println("<br><a href='./addEmpJspForm.html'>Add Employee</a>"); out.println("<br><a href='./updateEmpJsp'>Update Employee</a>"); out.println("<br><a href='./searchEmpForm.html'>Search Employee</a>"); out.println("<br><a href='./deleteEmployee.html'>Delete Employee</a>"); out.println("<br><a href='./seeAllEmployee'>Set All Employee</a>"); out.println("<br><br><a href='./logout'>Logout</a>"); } else { //Invalid credentials out.println("<h3 style='color:red'>Invalid Credentials</h3>"); req.getRequestDispatcher("./loginPage.html").include(req, resp); } out.println("</body>"); out.println("</html>"); }//end of doPost }//end of class
UTF-8
Java
2,060
java
LoginServlet.java
Java
[]
null
[]
package com.capgemini.mywebapp.servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.capgemini.mywebapp.bean.EmployeeInfoBean; import com.capgemini.mywebapp.services.EmployeeServiceImpl; import com.capgemini.mywebapp.services.EmployeeServices; @WebServlet("/Login") public class LoginServlet extends HttpServlet { private EmployeeServices service = new EmployeeServiceImpl() ; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Get the form data String empIdVal=req.getParameter("empId"); String password=req.getParameter("password"); int empId=Integer.parseInt(empIdVal); EmployeeInfoBean employeeInfoBean=service.authenticate(empId, password); PrintWriter out=resp.getWriter(); out.println("<html>"); out.println("<body>"); if(employeeInfoBean !=null) { //Valid credentials HttpSession session=req.getSession(true); session.setAttribute("employeeInfoBean",employeeInfoBean); out.println("<h2 style='color:blue'>Welcome "+ employeeInfoBean.getName() +"!</h2>"); out.println("<br><a href='./addEmpJspForm.html'>Add Employee</a>"); out.println("<br><a href='./updateEmpJsp'>Update Employee</a>"); out.println("<br><a href='./searchEmpForm.html'>Search Employee</a>"); out.println("<br><a href='./deleteEmployee.html'>Delete Employee</a>"); out.println("<br><a href='./seeAllEmployee'>Set All Employee</a>"); out.println("<br><br><a href='./logout'>Logout</a>"); } else { //Invalid credentials out.println("<h3 style='color:red'>Invalid Credentials</h3>"); req.getRequestDispatcher("./loginPage.html").include(req, resp); } out.println("</body>"); out.println("</html>"); }//end of doPost }//end of class
2,060
0.733495
0.731553
63
31.698412
27.180546
111
false
false
0
0
0
0
0
0
2.063492
false
false
5
5c8e971050a89c9eaf2cc3fd3b8ea037e054ac20
21,182,778,761,690
81d6369dfa382110c1a97d4d459469b7a6b86679
/app/src/main/java/com/iliubei/android/entity/commonEntity/LatestDailyEntity.java
1e378aa16ddb2e29b585b6e6e198375584b410d6
[]
no_license
Eaway2009/iliubei-android
https://github.com/Eaway2009/iliubei-android
87e734e31db3015324a814ca8f31faa93953cb89
2369b187e16a7af93f9c7f5a8a27df70da61d439
refs/heads/master
2021-01-19T00:23:59.035000
2017-07-17T05:12:58
2017-07-17T05:12:58
87,167,615
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.iliubei.android.entity.commonEntity; import java.util.List; /** * Created by eaway on 2016/12/27. */ public class LatestDailyEntity { // { // "webdes": "爱刘备电影网致力于为大家提供稀缺的百度云电影在线看,百度云电影高清下载,百度云资源,让大家告别视频网站无节操的收费,并为大家提供百度云论坛,让大家把自己所藏的百度云电影资源分享给别人。爱刘备电影网,值得你拥有。记住我们的网址:www.iliubei.com 。", // "errcode": 0, // "allPager": [ // { // "path": "/dapian/dongzuo/", // "img": "http://iliubei.com/uploads/allimg/170318/1_031Q010511142.jpg", // "sendDate": "2017-03-18", // "typeid": 11, // "id": 3329, // "title": "金刚狼3:殊死一战", // "url": "/dapian/dongzuo/3329.html", // "desc": "百度云电影金刚狼3:殊死一战基本简介: 导演: 詹姆斯曼高德" // } // ], // "webtitle": "百度云电影在线看_百度云电影高清下载_百度云资源_爱刘备电影网", // "tuijian": [ // { // "img": "http://iliubei.com/uploads/allimg/170316/1_0316214913M12.png", // "sendDate": "2017-03-16", // "title": "新娘", // "url": "/dapian/jingsong/3325.html", // "desc": "百度云电影新娘基本简介: 导演: Svyatoslav Po" // } // ], // "webkeywords": "百度云电影,百度云资源,百度云论坛,看片网站", // "hot5": [ // { // "path": "/flash/", // "img": "http://7xwpy5.com1.z0.glb.clouddn.com/uploads/allimg/170312/1-1F312230U1Q3.jpg?imageMogr2/thumbnail/!300x300r|imageView2/1/w/300/h/200", // "typeid": 32, // "id": 3310, // "title": "年轻的嫂子2", // "url": "/flash/3310.html" // } // ], // "banner": [ // { // "path": "/flash/", // "img": "http://7xwpy5.com1.z0.glb.clouddn.com/uploads/allimg/170317/1-1F31H2050M29.jpg?imageMogr2/thumbnail/!300x300r|imageView2/1/w/300/h/200", // "typeid": 32, // "id": 3327, // "title": "朋友夫妇交换", // "url": "/flash/3327.html" // } // ], // "errmsg": "", // "toutiao": [ // { // "img": "http://iliubei.com/uploads/allimg/170318/1_031Q010511142.jpg", // "sendDate": "2017-03-18", // "title": "金刚狼3:殊死一战", // "url": "/dapian/dongzuo/3329.html", // "desc": "百度云电影金刚狼3:殊死一战基本简介: 导演: 詹姆斯曼高德" // } // ] // } private String webdes; private int errcode; private List<StoriesEntity> allPager; private String webtitle; private List<BaseStoriesEntity> tuijian; private String webkeywords; private List<TopStoriesEntity> hot5; private List<BannerEntity> banner; private String errmsg; private List<BaseStoriesEntity> toutiao; public String getWebdes() { return webdes; } public void setWebdes(String webdes) { this.webdes = webdes; } public String getWebtitle() { return webtitle; } public void setWebtitle(String webtitle) { this.webtitle = webtitle; } public String getWebkeywords() { return webkeywords; } public void setWebkeywords(String webkeywords) { this.webkeywords = webkeywords; } public String getErrmsg() { return errmsg; } public void setErrmsg(String errmsg) { this.errmsg = errmsg; } public int getErrcode() { return errcode; } public void setErrcode(int errcode) { this.errcode = errcode; } public List<StoriesEntity> getAllPager() { return allPager; } public void setAllPager(List<StoriesEntity> allPager) { this.allPager = allPager; } public List<BaseStoriesEntity> getTuijian() { return tuijian; } public void setTuijian(List<BaseStoriesEntity> tuijian) { this.tuijian = tuijian; } public List<TopStoriesEntity> getHot5() { return hot5; } public void setHot5(List<TopStoriesEntity> hot5) { this.hot5 = hot5; } public List<BannerEntity> getBanner() { return banner; } public void setBanner(List<BannerEntity> banner) { this.banner = banner; } public List<BaseStoriesEntity> getToutiao() { return toutiao; } public void setToutiao(List<BaseStoriesEntity> toutiao) { this.toutiao = toutiao; } @Override public String toString() { return "LatestDailyEntity{" + "webdes='" + webdes + '\'' + ", webtitle='" + webtitle + '\'' + ", webkeywords='" + webkeywords + '\'' + ", errmsg='" + errmsg + '\'' + ", errcode=" + errcode + ", allPager=" + allPager + ", tuijian=" + tuijian + ", hot5=" + hot5 + ", banner=" + banner + ", toutiao=" + toutiao + '}'; } }
UTF-8
Java
5,448
java
LatestDailyEntity.java
Java
[ { "context": "Entity;\n\nimport java.util.List;\n\n/**\n * Created by eaway on 2016/12/27.\n */\n\npublic class LatestDailyEntit", "end": 97, "score": 0.9993422031402588, "start": 92, "tag": "USERNAME", "value": "eaway" }, { "context": "/ \"desc\": \"百度云电影金刚狼3:殊死一战基本简介: 导演: 詹姆斯曼高德\"\n// }\n// ],\n// \"webtitle\"", "end": 759, "score": 0.608008086681366, "start": 756, "tag": "NAME", "value": "詹姆斯" }, { "context": "html\",\n// \"desc\": \"百度云电影新娘基本简介: 导演: Svyatoslav Po\"\n// }\n// ],\n// \"webkeywords\"", "end": 1156, "score": 0.9989203214645386, "start": 1143, "tag": "NAME", "value": "Svyatoslav Po" }, { "context": "/ \"desc\": \"百度云电影金刚狼3:殊死一战基本简介: 导演: 詹姆斯曼高德\"\n// }\n// ]\n// }\n private Stri", "end": 2367, "score": 0.7502256035804749, "start": 2361, "tag": "NAME", "value": "詹姆斯曼高德" } ]
null
[]
package com.iliubei.android.entity.commonEntity; import java.util.List; /** * Created by eaway on 2016/12/27. */ public class LatestDailyEntity { // { // "webdes": "爱刘备电影网致力于为大家提供稀缺的百度云电影在线看,百度云电影高清下载,百度云资源,让大家告别视频网站无节操的收费,并为大家提供百度云论坛,让大家把自己所藏的百度云电影资源分享给别人。爱刘备电影网,值得你拥有。记住我们的网址:www.iliubei.com 。", // "errcode": 0, // "allPager": [ // { // "path": "/dapian/dongzuo/", // "img": "http://iliubei.com/uploads/allimg/170318/1_031Q010511142.jpg", // "sendDate": "2017-03-18", // "typeid": 11, // "id": 3329, // "title": "金刚狼3:殊死一战", // "url": "/dapian/dongzuo/3329.html", // "desc": "百度云电影金刚狼3:殊死一战基本简介: 导演: 詹姆斯曼高德" // } // ], // "webtitle": "百度云电影在线看_百度云电影高清下载_百度云资源_爱刘备电影网", // "tuijian": [ // { // "img": "http://iliubei.com/uploads/allimg/170316/1_0316214913M12.png", // "sendDate": "2017-03-16", // "title": "新娘", // "url": "/dapian/jingsong/3325.html", // "desc": "百度云电影新娘基本简介: 导演: <NAME>" // } // ], // "webkeywords": "百度云电影,百度云资源,百度云论坛,看片网站", // "hot5": [ // { // "path": "/flash/", // "img": "http://7xwpy5.com1.z0.glb.clouddn.com/uploads/allimg/170312/1-1F312230U1Q3.jpg?imageMogr2/thumbnail/!300x300r|imageView2/1/w/300/h/200", // "typeid": 32, // "id": 3310, // "title": "年轻的嫂子2", // "url": "/flash/3310.html" // } // ], // "banner": [ // { // "path": "/flash/", // "img": "http://7xwpy5.com1.z0.glb.clouddn.com/uploads/allimg/170317/1-1F31H2050M29.jpg?imageMogr2/thumbnail/!300x300r|imageView2/1/w/300/h/200", // "typeid": 32, // "id": 3327, // "title": "朋友夫妇交换", // "url": "/flash/3327.html" // } // ], // "errmsg": "", // "toutiao": [ // { // "img": "http://iliubei.com/uploads/allimg/170318/1_031Q010511142.jpg", // "sendDate": "2017-03-18", // "title": "金刚狼3:殊死一战", // "url": "/dapian/dongzuo/3329.html", // "desc": "百度云电影金刚狼3:殊死一战基本简介: 导演: 詹姆斯曼高德" // } // ] // } private String webdes; private int errcode; private List<StoriesEntity> allPager; private String webtitle; private List<BaseStoriesEntity> tuijian; private String webkeywords; private List<TopStoriesEntity> hot5; private List<BannerEntity> banner; private String errmsg; private List<BaseStoriesEntity> toutiao; public String getWebdes() { return webdes; } public void setWebdes(String webdes) { this.webdes = webdes; } public String getWebtitle() { return webtitle; } public void setWebtitle(String webtitle) { this.webtitle = webtitle; } public String getWebkeywords() { return webkeywords; } public void setWebkeywords(String webkeywords) { this.webkeywords = webkeywords; } public String getErrmsg() { return errmsg; } public void setErrmsg(String errmsg) { this.errmsg = errmsg; } public int getErrcode() { return errcode; } public void setErrcode(int errcode) { this.errcode = errcode; } public List<StoriesEntity> getAllPager() { return allPager; } public void setAllPager(List<StoriesEntity> allPager) { this.allPager = allPager; } public List<BaseStoriesEntity> getTuijian() { return tuijian; } public void setTuijian(List<BaseStoriesEntity> tuijian) { this.tuijian = tuijian; } public List<TopStoriesEntity> getHot5() { return hot5; } public void setHot5(List<TopStoriesEntity> hot5) { this.hot5 = hot5; } public List<BannerEntity> getBanner() { return banner; } public void setBanner(List<BannerEntity> banner) { this.banner = banner; } public List<BaseStoriesEntity> getToutiao() { return toutiao; } public void setToutiao(List<BaseStoriesEntity> toutiao) { this.toutiao = toutiao; } @Override public String toString() { return "LatestDailyEntity{" + "webdes='" + webdes + '\'' + ", webtitle='" + webtitle + '\'' + ", webkeywords='" + webkeywords + '\'' + ", errmsg='" + errmsg + '\'' + ", errcode=" + errcode + ", allPager=" + allPager + ", tuijian=" + tuijian + ", hot5=" + hot5 + ", banner=" + banner + ", toutiao=" + toutiao + '}'; } }
5,441
0.515416
0.472211
174
27.333334
26.229389
162
false
false
0
0
0
0
0
0
0.448276
false
false
5
88cc83158bf68d554ccdad1fe79ac2fec9270d6a
4,535,485,486,140
a2dd2e17a364e8945422bee8a6ffb4d599b6bf0a
/src/main/java/com/mn/amway/storeservice/model/Journal.java
a1b0d794dc1e005a717d396fb20a406777bc3e4a
[]
no_license
Ankhbayarp/amway-store-service
https://github.com/Ankhbayarp/amway-store-service
dae958d27fcc249390c05938d1433c2452cbc8ff
6c2a6a02ad10508f8c4f2dc2940c2453f4643b9d
refs/heads/master
2023-01-01T15:42:00.160000
2020-10-19T16:24:31
2020-10-19T16:24:31
305,025,206
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mn.amway.storeservice.model; import java.sql.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import lombok.Data; @Entity @Data @Table(name = "journal") public class Journal { @Id @GeneratedValue private Integer id; private Date date; @Column(name = "product_id") private Integer productId; private Integer income; // orlogo too shirheg private Integer expenditure; // zarlaga too shirhed @Column(name = "customer_id") private Integer customerId; public Journal() { } }
UTF-8
Java
662
java
Journal.java
Java
[]
null
[]
package com.mn.amway.storeservice.model; import java.sql.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import lombok.Data; @Entity @Data @Table(name = "journal") public class Journal { @Id @GeneratedValue private Integer id; private Date date; @Column(name = "product_id") private Integer productId; private Integer income; // orlogo too shirheg private Integer expenditure; // zarlaga too shirhed @Column(name = "customer_id") private Integer customerId; public Journal() { } }
662
0.722054
0.722054
33
19.09091
15.796746
55
false
false
0
0
0
0
0
0
0.424242
false
false
5
3935cd516eec317253a32a0583650a71d7f0a757
7,155,415,550,736
c53abd755f7f6163743b6dec0064da1b56d08161
/User/src/main/java/poc/projectmgt/user/controllers/AuthenticationController.java
edd6f54dc3d6ccf194ed42226d436b1c5ee8625c
[ "MIT" ]
permissive
abhimanyu1990/Microservice-Starter
https://github.com/abhimanyu1990/Microservice-Starter
f77ffaba31e6e9b356ed920ebfda5c7860062547
18622ae305da17405745a1f7db3c24ecf475ca37
refs/heads/master
2022-12-19T06:44:46.428000
2020-09-30T07:08:17
2020-09-30T07:08:17
299,835,225
0
0
null
false
2020-09-30T07:08:18
2020-09-30T07:00:15
2020-09-30T07:07:00
2020-09-30T07:08:18
0
0
0
0
Java
false
false
package poc.projectmgt.user.controllers; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import poc.projectmgt.customexceptions.GenericAuthenticationException; import poc.projectmgt.user.dto.AuthorizationTokenDTO; import poc.projectmgt.user.dto.LoginDTO; import poc.projectmgt.user.services.UserService; @RestController @RequestMapping("/api/v1") public class AuthenticationController { @Autowired private UserService userService; @PostMapping("/signin") public AuthorizationTokenDTO signin(@Valid @RequestBody LoginDTO login) { String authToken = userService.signin(login.getEmail(), login.getPassword()); if(authToken != null) { return new AuthorizationTokenDTO(login.getEmail(),authToken); } throw new GenericAuthenticationException("Email or password doesn't exist."); } }
UTF-8
Java
1,120
java
AuthenticationController.java
Java
[]
null
[]
package poc.projectmgt.user.controllers; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import poc.projectmgt.customexceptions.GenericAuthenticationException; import poc.projectmgt.user.dto.AuthorizationTokenDTO; import poc.projectmgt.user.dto.LoginDTO; import poc.projectmgt.user.services.UserService; @RestController @RequestMapping("/api/v1") public class AuthenticationController { @Autowired private UserService userService; @PostMapping("/signin") public AuthorizationTokenDTO signin(@Valid @RequestBody LoginDTO login) { String authToken = userService.signin(login.getEmail(), login.getPassword()); if(authToken != null) { return new AuthorizationTokenDTO(login.getEmail(),authToken); } throw new GenericAuthenticationException("Email or password doesn't exist."); } }
1,120
0.799107
0.798214
32
34
27.700407
84
false
false
0
0
0
0
0
0
1.15625
false
false
5
15245a50470b89df214ce3254f3acb02b7403077
15,642,270,892,421
48068844f6c397993a4fbf6a573093eeeaef185e
/dlapiservice-hivegrpc-client/src/main/java/com/treasuremountain/datalake/dlapiservice/service/grpc/client/GrpcClientMananer.java
9c953f7f41477bf818548cc0fc8a4ce3fb9123e7
[]
no_license
chenjian-520/yunzhihui_project_SparkSDK
https://github.com/chenjian-520/yunzhihui_project_SparkSDK
2310007f4a6a8e97303d8311cf49aaf378d061d8
a2256a0d7ee65c81856d36557ed33015777ebcb5
refs/heads/master
2022-12-22T02:13:40.882000
2019-11-28T08:21:30
2019-11-28T08:21:30
224,603,204
0
0
null
false
2022-12-16T04:32:47
2019-11-28T08:17:05
2019-11-28T08:25:34
2022-12-16T04:32:43
8,116
0
0
19
Java
false
false
package com.treasuremountain.datalake.dlapiservice.service.grpc.client; import io.grpc.ManagedChannel; import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; import io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2SecurityUtil; import io.grpc.netty.shaded.io.netty.handler.ssl.*; import io.grpc.netty.shaded.io.netty.handler.ssl.util.InsecureTrustManagerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.net.ssl.SSLException; import java.util.concurrent.TimeUnit; /** * Description: * <p> * Created by ref.tian on 2019/5/13. * Company: Foxconn * Project: TreasureMountain */ @Component public class GrpcClientMananer { @Value("${grpc.client.host}") private String host; @Value("${grpc.client.port}") private Integer port; public ManagedChannel getChannel() { NettyChannelBuilder ncb = null; try { ncb = NettyChannelBuilder.forAddress(host, port).sslContext(SslContextBuilder.forClient() .sslProvider(OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .trustManager(InsecureTrustManagerFactory.INSTANCE) .applicationProtocolConfig( new ApplicationProtocolConfig( ApplicationProtocolConfig.Protocol.ALPN, ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build()) .keepAliveWithoutCalls(false); } catch (SSLException e) { e.printStackTrace(); System.out.println("建立grpc连接发现异常!" + e.getMessage()); } return ncb.build(); } }
UTF-8
Java
2,112
java
GrpcClientMananer.java
Java
[ { "context": "imeUnit;\n\n/**\n * Description:\n * <p>\n * Created by ref.tian on 2019/5/13.\n * Company: Foxconn\n * Project: Tre", "end": 611, "score": 0.9953789710998535, "start": 603, "tag": "USERNAME", "value": "ref.tian" } ]
null
[]
package com.treasuremountain.datalake.dlapiservice.service.grpc.client; import io.grpc.ManagedChannel; import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; import io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2SecurityUtil; import io.grpc.netty.shaded.io.netty.handler.ssl.*; import io.grpc.netty.shaded.io.netty.handler.ssl.util.InsecureTrustManagerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.net.ssl.SSLException; import java.util.concurrent.TimeUnit; /** * Description: * <p> * Created by ref.tian on 2019/5/13. * Company: Foxconn * Project: TreasureMountain */ @Component public class GrpcClientMananer { @Value("${grpc.client.host}") private String host; @Value("${grpc.client.port}") private Integer port; public ManagedChannel getChannel() { NettyChannelBuilder ncb = null; try { ncb = NettyChannelBuilder.forAddress(host, port).sslContext(SslContextBuilder.forClient() .sslProvider(OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .trustManager(InsecureTrustManagerFactory.INSTANCE) .applicationProtocolConfig( new ApplicationProtocolConfig( ApplicationProtocolConfig.Protocol.ALPN, ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build()) .keepAliveWithoutCalls(false); } catch (SSLException e) { e.printStackTrace(); System.out.println("建立grpc连接发现异常!" + e.getMessage()); } return ncb.build(); } }
2,112
0.647564
0.641356
52
39.26923
30.495344
101
false
false
0
0
0
0
0
0
0.442308
false
false
5
e7957d5f95229fa2cd7e7a70e3404880c6fccd4a
12,738,873,032,420
309fe0d12f0c72c270b6cc716548db6a60030c27
/src/com/exp/dao/LogisticsDao.java
72189c8d40f82b86464ad4dddee06e1fedc4646c
[]
no_license
frankppeng/exp
https://github.com/frankppeng/exp
b26ff81c9320556bffd26e1f6e1065294365b128
a3fafd2a9df0ed72aebe01ca2381e5b75d8d5f2f
refs/heads/master
2020-03-28T08:58:11.102000
2018-09-09T08:18:19
2018-09-09T08:18:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.exp.dao; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.exp.modle.Logistics; import com.exp.util.SqlUtil; public class LogisticsDao { public List Query() { String sql = "select * from logistics order by log_id desc"; ArrayList<HashMap<String, Object>> list = SqlUtil.excuteQuery(sql, null); return list; } public List QueryOrderId(String orderId) { String sql = "select * from logistics where order_id = ? order by log_id desc"; ArrayList<HashMap<String, Object>> list = SqlUtil.excuteQuery(sql, new Object[]{orderId}); return list; } public int Add(Logistics log){ String sql = "insert into logistics values (?,?,?,?,?,?)"; return SqlUtil.excuteUpdate(sql, new Object[]{"0",log.getOrderId(),log.getCourId(),log.getLogAddress(),log.getLogDate(),log.getLogStatus()}); } public int Edit(Logistics log){ String sql = "update logistics set order_id = ?,cour_id = ?,log_address = ?,log_date = ?,log_status = ? where log_id = ?"; return SqlUtil.excuteUpdate(sql, new Object[]{log.getOrderId(),log.getCourId(),log.getLogAddress(),log.getLogDate(),log.getLogStatus(),log.getLogId()}); } public void Remove(String LogId){ String sql = "delete from logistics where log_id = ?"; SqlUtil.excuteUpdate(sql, new Object[]{LogId}); } }
UTF-8
Java
1,322
java
LogisticsDao.java
Java
[]
null
[]
package com.exp.dao; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.exp.modle.Logistics; import com.exp.util.SqlUtil; public class LogisticsDao { public List Query() { String sql = "select * from logistics order by log_id desc"; ArrayList<HashMap<String, Object>> list = SqlUtil.excuteQuery(sql, null); return list; } public List QueryOrderId(String orderId) { String sql = "select * from logistics where order_id = ? order by log_id desc"; ArrayList<HashMap<String, Object>> list = SqlUtil.excuteQuery(sql, new Object[]{orderId}); return list; } public int Add(Logistics log){ String sql = "insert into logistics values (?,?,?,?,?,?)"; return SqlUtil.excuteUpdate(sql, new Object[]{"0",log.getOrderId(),log.getCourId(),log.getLogAddress(),log.getLogDate(),log.getLogStatus()}); } public int Edit(Logistics log){ String sql = "update logistics set order_id = ?,cour_id = ?,log_address = ?,log_date = ?,log_status = ? where log_id = ?"; return SqlUtil.excuteUpdate(sql, new Object[]{log.getOrderId(),log.getCourId(),log.getLogAddress(),log.getLogDate(),log.getLogStatus(),log.getLogId()}); } public void Remove(String LogId){ String sql = "delete from logistics where log_id = ?"; SqlUtil.excuteUpdate(sql, new Object[]{LogId}); } }
1,322
0.70348
0.702723
39
32.923077
39.918755
155
false
false
0
0
0
0
0
0
2.102564
false
false
5
f0c8387e90ede6c89de3f7bf26620875afc0f748
927,712,992,875
0af8b92686a58eb0b64e319b22411432aca7a8f3
/large-multiproject/project75/src/test/java/org/gradle/test/performance75_5/Test75_445.java
598b04760e434fd58272755ed75a9f93c4ce7f86
[]
no_license
gradle/performance-comparisons
https://github.com/gradle/performance-comparisons
b0d38db37c326e0ce271abebdb3c91769b860799
e53dc7182fafcf9fedf07920cbbea8b40ee4eef4
refs/heads/master
2023-08-14T19:24:39.164000
2022-11-24T05:18:33
2022-11-24T05:18:33
80,121,268
17
15
null
false
2022-09-30T08:04:35
2017-01-26T14:25:33
2022-09-09T14:38:38
2022-09-30T08:04:34
19,731
14
13
103
null
false
false
package org.gradle.test.performance75_5; import static org.junit.Assert.*; public class Test75_445 { private final Production75_445 production = new Production75_445("value"); @org.junit.Test public void test() { assertEquals(production.getProperty(), "value"); } }
UTF-8
Java
292
java
Test75_445.java
Java
[]
null
[]
package org.gradle.test.performance75_5; import static org.junit.Assert.*; public class Test75_445 { private final Production75_445 production = new Production75_445("value"); @org.junit.Test public void test() { assertEquals(production.getProperty(), "value"); } }
292
0.69863
0.636986
12
23.416666
24.008533
78
false
false
0
0
0
0
0
0
0.416667
false
false
5
3713add4981cb03cd0164615de6d67b1102901db
23,931,557,784,302
741fcc6b028e31777d04212cabac5fc376a9460e
/chapter_002/src/main/java/ru/job4j/oop/DummyDic.java
02e90f213031ff06135811396cdd1da86a13e3c4
[]
no_license
AndreyGorbunov/job4j
https://github.com/AndreyGorbunov/job4j
dc8f55ba291901f2fe287ccbb148d3badc5628a8
30c08a8e1e98b8c39251d6d52d4e7dd4217afb6e
refs/heads/master
2021-07-25T09:37:38.298000
2020-09-28T18:45:58
2020-09-28T18:45:58
226,559,775
0
0
null
false
2020-10-13T18:02:52
2019-12-07T18:40:38
2020-09-28T16:44:14
2020-10-13T18:02:51
669
0
0
1
Java
false
false
package ru.job4j.oop; public class DummyDic { public String engToRus(String eng) { String output = "Неизвестное слово. " + eng; return output; } public static void main(String[] args) { DummyDic word = new DummyDic(); String say = word.engToRus("sun"); System.out.println(say); } }
UTF-8
Java
355
java
DummyDic.java
Java
[]
null
[]
package ru.job4j.oop; public class DummyDic { public String engToRus(String eng) { String output = "Неизвестное слово. " + eng; return output; } public static void main(String[] args) { DummyDic word = new DummyDic(); String say = word.engToRus("sun"); System.out.println(say); } }
355
0.60177
0.59882
13
25.076923
17.273642
52
false
false
0
0
0
0
0
0
0.461538
false
false
5
c888d52f7ec7541fbf85fe36fdadc6b0b4b6fb88
5,102,421,202,140
d9063263787511c96cdf86f628c610eb4663bf50
/src/main/java/validator/EmailValidator.java
3b1c397687212beb8b54117e7e17a9b67808a435
[]
no_license
web-2-utfpr/instaclone
https://github.com/web-2-utfpr/instaclone
d2c41bb5d8d96450e2dbeb74203dcd316744eeab
832b528ca1b0cedaef7e11e424cbc31bf4f31666
refs/heads/master
2021-06-11T03:37:49.949000
2018-06-28T23:14:22
2018-06-28T23:14:22
128,283,943
4
2
null
true
2018-11-07T23:38:06
2018-04-06T01:32:25
2018-07-14T21:47:31
2018-11-07T23:38:06
1,176
4
3
14
Java
false
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package validator; import exception.InvalidEmailException; /** * * @author rafae */ public class EmailValidator { public static void isValid(String email) throws InvalidEmailException { if (email == null || !(email.matches("[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$"))) { throw new InvalidEmailException("Invalid Email"); } } }
UTF-8
Java
554
java
EmailValidator.java
Java
[ { "context": "xception.InvalidEmailException;\n\n/**\n *\n * @author rafae\n */\npublic class EmailValidator {\n\n public sta", "end": 269, "score": 0.9989522099494934, "start": 264, "tag": "USERNAME", "value": "rafae" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package validator; import exception.InvalidEmailException; /** * * @author rafae */ public class EmailValidator { public static void isValid(String email) throws InvalidEmailException { if (email == null || !(email.matches("[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$"))) { throw new InvalidEmailException("Invalid Email"); } } }
554
0.65343
0.642599
21
25.380953
29.58197
92
false
false
0
0
0
0
0
0
0.428571
false
false
5
17d939e8fe3a854f175234689797b9d4d822d2bd
16,217,796,562,539
51110a688f8030cd9a7daa137f8a8b86e556a735
/14-1 剪绳子/src/Solution3.java
aed3bd56e0df085efee7afbeb065f67473978ede
[]
no_license
Sningning/CodingInterviewChinese2
https://github.com/Sningning/CodingInterviewChinese2
7b421a5aef44783c9ad49dac90b55157751775f1
d3b5a7c83634b90987e0e92b4f78ea7d8c777ac6
refs/heads/master
2023-01-19T01:09:19.876000
2020-11-24T02:57:14
2020-11-24T02:57:14
267,775,656
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * @author: Song Ningning * @date: 2020-05-28 15:09 */ public class Solution3 { public static int cuttingRope(int n) { /* * 根据暴力递归可知,对于确定的一个数 n,将他分割后的最大乘积是固定不变的,即不管怎么分,最大值是一定的,因此无后效性; * 递归时可变参数 i 变化范围是 [1,n-1] (至少划分为2份),所以对于每个 i,它的结果都可以确定地填在一维数组 dp[n+1] 中; * 最终想要的状态是 dp[n] * 递归终止条件是 if (n == 1) { return 1; },因此 dp[1] 是不依赖其他位置的,即初始化 dp[1] = 1; * 对于某个 i,dp[i] 所依赖的状态有:dp[i-j] (1<= j <= i-1),即所有 i 前面的状态,又因为 dp[1] 已知了,所以,可以依次求出 * dp[2]、dp[3]... * * 动态规划 * 状态:dp[i] 表示把长度为 i 的绳子剪成若干段之后各段长度乘积的最大值 * 初始化:dp[1] = 1 * 状态转移:要计算 dp[i],就要计算 dp[i-1]、dp[i-2]... * 结果返回:dp[n] */ // Time:O(N^2) 两层循环 // Space:O(N) int[] dp = new int[n + 1]; dp[1] = 1; for (int i = 2; i <= n; i++) { // 对于每一个 i,还要分解为 j + (i - j),来计算出 dp[i] for (int j = 1; j <= i - 1; j++) { // 获得最大乘积的一种方式 j * (i - j) // 另一种方式 (i - j) 分割后的最大乘积 * j,而 (i - j) 分割后的最大乘积就是 dp[i - j] // 因为 (i - j) < i,因此之前已经求出了 dp[i] = Math.max(dp[i], Math.max(j * (i - j), j * dp[i - j])); } } return dp[n]; } public static void main(String[] args) { System.out.println(cuttingRope(10)); // 36 System.out.println(cuttingRope(31)); // 78732 } }
UTF-8
Java
2,000
java
Solution3.java
Java
[ { "context": "/**\n * @author: Song Ningning\n * @date: 2020-05-28 15:09\n */\npublic class Solut", "end": 29, "score": 0.9998582601547241, "start": 16, "tag": "NAME", "value": "Song Ningning" } ]
null
[]
/** * @author: <NAME> * @date: 2020-05-28 15:09 */ public class Solution3 { public static int cuttingRope(int n) { /* * 根据暴力递归可知,对于确定的一个数 n,将他分割后的最大乘积是固定不变的,即不管怎么分,最大值是一定的,因此无后效性; * 递归时可变参数 i 变化范围是 [1,n-1] (至少划分为2份),所以对于每个 i,它的结果都可以确定地填在一维数组 dp[n+1] 中; * 最终想要的状态是 dp[n] * 递归终止条件是 if (n == 1) { return 1; },因此 dp[1] 是不依赖其他位置的,即初始化 dp[1] = 1; * 对于某个 i,dp[i] 所依赖的状态有:dp[i-j] (1<= j <= i-1),即所有 i 前面的状态,又因为 dp[1] 已知了,所以,可以依次求出 * dp[2]、dp[3]... * * 动态规划 * 状态:dp[i] 表示把长度为 i 的绳子剪成若干段之后各段长度乘积的最大值 * 初始化:dp[1] = 1 * 状态转移:要计算 dp[i],就要计算 dp[i-1]、dp[i-2]... * 结果返回:dp[n] */ // Time:O(N^2) 两层循环 // Space:O(N) int[] dp = new int[n + 1]; dp[1] = 1; for (int i = 2; i <= n; i++) { // 对于每一个 i,还要分解为 j + (i - j),来计算出 dp[i] for (int j = 1; j <= i - 1; j++) { // 获得最大乘积的一种方式 j * (i - j) // 另一种方式 (i - j) 分割后的最大乘积 * j,而 (i - j) 分割后的最大乘积就是 dp[i - j] // 因为 (i - j) < i,因此之前已经求出了 dp[i] = Math.max(dp[i], Math.max(j * (i - j), j * dp[i - j])); } } return dp[n]; } public static void main(String[] args) { System.out.println(cuttingRope(10)); // 36 System.out.println(cuttingRope(31)); // 78732 } }
1,993
0.453704
0.418803
45
30.200001
25.171942
90
false
false
0
0
0
0
0
0
0.355556
false
false
5
071e4b595a830f6f8d774c8071d18a882abcd72c
14,396,730,389,631
e514efb45cba9fb75cdd466d5488f8ea0633a8e3
/app/src/main/java/com/plaze/PlacaActivity.java
192d197713567cc7c1718a6ff692049190c97f34
[]
no_license
uc-web/Plaze-Android
https://github.com/uc-web/Plaze-Android
0662bdf134e698fa1b19ce74d33052225d24c326
110f5a6b42439442db189dc950bd93b68c001602
refs/heads/master
2018-10-14T06:31:16.114000
2018-10-05T23:30:02
2018-10-05T23:30:02
132,768,063
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.plaze; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AlertDialog; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.plaze.adapter.PlateAdapter; import com.plaze.application.BaseActivity; import com.plaze.application.Configuration; import com.plaze.application.CustomJsonObjectRequest; import com.plaze.model.Plate; import com.plaze.util.ConnectionBroadcastReceiver; import com.plaze.util.Constantes; import com.plaze.util.Preferences; import com.plaze.util.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Objects; import butterknife.BindView; import butterknife.OnClick; public class PlacaActivity extends BaseActivity implements IAdapter { public static final String TAG = PlacaActivity.class.getSimpleName(); @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.tv_title) TextView tv_title; private ArrayList<Plate> pla_list = new ArrayList<>(); @BindView(R.id.rv_vehiculos_placas) RecyclerView rv_vehiculos_placas; private String placa_new; @BindView(R.id.refreshLayout_placas) SwipeRefreshLayout refreshLayout_placas; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_placa); setToolbar(this, toolbar, true); tv_title.setText("Mis Placas"); requestListPlate(); if (refreshLayout_placas != null) { refreshLayout_placas.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refreshLayout_placas.post(new Runnable() { @Override public void run() { requestListPlate(); } }); } }); } } private void requestListPlate() { if (ConnectionBroadcastReceiver.isConnect()) { //showDialog(this,"Cargando"); //BaseActivity.showFragmentDialog(pDialog); if (refreshLayout_placas != null) { refreshLayout_placas.setRefreshing(true); } final Preferences prefs = new Preferences(Objects.requireNonNull(this)); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("user_id", prefs.getUser_id()); } catch (JSONException e) { e.printStackTrace(); } CustomJsonObjectRequest request = new CustomJsonObjectRequest( Request.Method.POST, Constantes.url_plate, jsonObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { pla_list.clear(); String msg = response.getString("message"); if (response.getBoolean("status")) { JSONArray jArray = response.getJSONArray("data"); for (int i = 0; i < jArray.length(); i++) { Plate pla = new Plate(); pla.setId(jArray.getJSONObject(i).getInt("pla_id")); pla.setPlate(jArray.getJSONObject(i).getString("pla_number")); pla.setStatus(jArray.getJSONObject(i).getInt("pla_status")); pla_list.add(pla); } //BaseActivity.hideFragmentpDialog(pDialog); if (refreshLayout_placas != null) { refreshLayout_placas.setRefreshing(false); } if (pla_list.size() == 0) { simpleDialog(PlacaActivity.this, "Aùn no tiene una placa asignada a su cuenta. Acérquese a cualquiera de nuestros serenos con su vehículo y solicite que vinculen su placa.", true, false); } } else { //BaseActivity.hideFragmentpDialog(pDialog); refreshLayout_placas.setRefreshing(false); Toast.makeText(PlacaActivity.this, msg, Toast.LENGTH_SHORT).show(); } showPlateList(); } catch (JSONException e) { e.printStackTrace(); //BaseActivity.hideFragmentpDialog(pDialog); refreshLayout_placas.setRefreshing(false); Toast.makeText(PlacaActivity.this, "Ocurrió un error", Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); //BaseActivity.hideFragmentpDialog(pDialog); refreshLayout_placas.setRefreshing(false); Toast.makeText(PlacaActivity.this, "Ocurrió un error", Toast.LENGTH_SHORT).show(); } } ); request.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); Configuration.getInstance().addToRequestQueue(request, TAG); } else { ConnectionBroadcastReceiver.showSnack(findViewById(R.id.activity_placa), this); refreshLayout_placas.setRefreshing(false); } } private void showPlateList() { PlateAdapter adapter = new PlateAdapter(this, pla_list, this); rv_vehiculos_placas.setHasFixedSize(true); rv_vehiculos_placas.setLayoutManager(new LinearLayoutManager(this)); rv_vehiculos_placas.setAdapter(adapter); adapter.notifyDataSetChanged(); } @OnClick(R.id.iv_placa_agregar) public void plateAdd() { @SuppressLint("InflateParams") View view = LayoutInflater.from(this).inflate(R.layout.popup_plate_remove, null); final AlertDialog.Builder dialog = new AlertDialog.Builder(Objects.requireNonNull(this)); dialog.setView(view); //aqui puedes cambiar los valores de tus otros controladores como los textview o buttons, etc Button btn_Cerrar = view.findViewById(R.id.btn_placa_remove_cancelar); Button btn_Aceptar = view.findViewById(R.id.btn_placa_remove_aceptar); TextView question = view.findViewById(R.id.tv_popup_plate_question); question.setText("Para evitar que su placa se duplique, le recomendamos validarla con la ayuda de un sereno."); btn_Aceptar.setText("Aceptar"); dialog.create(); final AlertDialog ad = dialog.show(); btn_Cerrar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ad.dismiss(); } }); btn_Aceptar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showInPopUp(); ad.dismiss(); } }); } private void showInPopUp() { @SuppressLint("InflateParams") View view = LayoutInflater.from(this).inflate(R.layout.popup_plate_add, null); final AlertDialog.Builder dialog = new AlertDialog.Builder(Objects.requireNonNull(this)); dialog.setView(view); Button btn_Cerrar = view.findViewById(R.id.btn_placa_add_cancelar); Button btn_Aceptar = view.findViewById(R.id.btn_placa_add_aceptar); final EditText new_placa = view.findViewById(R.id.et_placa_add_name); dialog.create(); final AlertDialog ad = dialog.show(); btn_Cerrar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ad.dismiss(); } }); btn_Aceptar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { placa_new = new_placa.getText().toString().trim(); if (Utils.isValidInput(new_placa, "Ingrese una placa")) { if (placa_new.length() == 6) { ad.dismiss(); requestPlateAdd(); } else { Toast.makeText(PlacaActivity.this, "Estimado usuario, verifique el nro. de placa ingresado", Toast.LENGTH_SHORT).show(); } } } }); } private void requestPlateAdd() { if (ConnectionBroadcastReceiver.isConnect()) { showLoading(this); final Preferences prefs = new Preferences(Objects.requireNonNull(this)); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("user_id", prefs.getUser_id()); jsonObject.put("pla_number", placa_new); } catch (JSONException e) { e.printStackTrace(); } CustomJsonObjectRequest request = new CustomJsonObjectRequest( Request.Method.POST, Constantes.url_plate_add, jsonObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { String msg = response.getString("message"); if (response.getBoolean("status")) { requestListPlate(); hideLoading(); } else { hideLoading(); simpleDialog(PlacaActivity.this, msg, true, false); } showPlateList(); } catch (JSONException e) { e.printStackTrace(); hideLoading(); Toast.makeText(PlacaActivity.this, "Ocurrió un error", Toast.LENGTH_SHORT).show(); //connectionError(AdminActivity.this, false); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); hideLoading(); Toast.makeText(PlacaActivity.this, "Ocurrió un error", Toast.LENGTH_SHORT).show(); } } ); request.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); Configuration.getInstance().addToRequestQueue(request, TAG); } else { ConnectionBroadcastReceiver.showSnack(findViewById(R.id.activity_placa), this); } } public void deletePlate(final String id) { @SuppressLint("InflateParams") View view = LayoutInflater.from(this).inflate(R.layout.popup_plate_remove, null); final AlertDialog.Builder dialog = new AlertDialog.Builder(Objects.requireNonNull(this)); dialog.setView(view); //aqui puedes cambiar los valores de tus otros controladores como los textview o buttons, etc Button btn_Cerrar = view.findViewById(R.id.btn_placa_remove_cancelar); Button btn_Aceptar = view.findViewById(R.id.btn_placa_remove_aceptar); TextView question = view.findViewById(R.id.tv_popup_plate_question); question.setText("¿Desea eliminar la placa " + id + " ?"); dialog.create(); final AlertDialog ad = dialog.show(); btn_Cerrar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ad.dismiss(); } }); btn_Aceptar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { requestPlateRemove(id); ad.dismiss(); } }); } private void requestPlateRemove(final String plateName) { if (ConnectionBroadcastReceiver.isConnect()) { showLoading(this); final Preferences prefs = new Preferences(Objects.requireNonNull(this)); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("user_id", prefs.getUser_id()); jsonObject.put("pla_number", String.valueOf(plateName)); } catch (JSONException e) { e.printStackTrace(); } CustomJsonObjectRequest request = new CustomJsonObjectRequest( Request.Method.POST, Constantes.url_plate_remove, jsonObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { String msg = response.getString("message"); if (response.getBoolean("status")) { Toast.makeText(PlacaActivity.this, msg, Toast.LENGTH_SHORT).show(); requestListPlate(); hideLoading(); } else { hideLoading(); //Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show(); simpleDialog(PlacaActivity.this, msg, true, false); //simpleDialog(AdminActivity.this, server_msg, true, false); } showPlateList(); } catch (JSONException e) { e.printStackTrace(); hideLoading(); Toast.makeText(PlacaActivity.this, "Ocurrió un error", Toast.LENGTH_SHORT).show(); //connectionError(AdminActivity.this, false); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); hideLoading(); Toast.makeText(PlacaActivity.this, "Ocurrió un error", Toast.LENGTH_SHORT).show(); // connectionError(AdminActivity.this, false); } } ); request.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); Configuration.getInstance().addToRequestQueue(request, TAG); } else { ConnectionBroadcastReceiver.showSnack(findViewById(R.id.activity_placa), this); } } }
UTF-8
Java
16,599
java
PlacaActivity.java
Java
[]
null
[]
package com.plaze; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AlertDialog; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.plaze.adapter.PlateAdapter; import com.plaze.application.BaseActivity; import com.plaze.application.Configuration; import com.plaze.application.CustomJsonObjectRequest; import com.plaze.model.Plate; import com.plaze.util.ConnectionBroadcastReceiver; import com.plaze.util.Constantes; import com.plaze.util.Preferences; import com.plaze.util.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Objects; import butterknife.BindView; import butterknife.OnClick; public class PlacaActivity extends BaseActivity implements IAdapter { public static final String TAG = PlacaActivity.class.getSimpleName(); @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.tv_title) TextView tv_title; private ArrayList<Plate> pla_list = new ArrayList<>(); @BindView(R.id.rv_vehiculos_placas) RecyclerView rv_vehiculos_placas; private String placa_new; @BindView(R.id.refreshLayout_placas) SwipeRefreshLayout refreshLayout_placas; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_placa); setToolbar(this, toolbar, true); tv_title.setText("Mis Placas"); requestListPlate(); if (refreshLayout_placas != null) { refreshLayout_placas.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refreshLayout_placas.post(new Runnable() { @Override public void run() { requestListPlate(); } }); } }); } } private void requestListPlate() { if (ConnectionBroadcastReceiver.isConnect()) { //showDialog(this,"Cargando"); //BaseActivity.showFragmentDialog(pDialog); if (refreshLayout_placas != null) { refreshLayout_placas.setRefreshing(true); } final Preferences prefs = new Preferences(Objects.requireNonNull(this)); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("user_id", prefs.getUser_id()); } catch (JSONException e) { e.printStackTrace(); } CustomJsonObjectRequest request = new CustomJsonObjectRequest( Request.Method.POST, Constantes.url_plate, jsonObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { pla_list.clear(); String msg = response.getString("message"); if (response.getBoolean("status")) { JSONArray jArray = response.getJSONArray("data"); for (int i = 0; i < jArray.length(); i++) { Plate pla = new Plate(); pla.setId(jArray.getJSONObject(i).getInt("pla_id")); pla.setPlate(jArray.getJSONObject(i).getString("pla_number")); pla.setStatus(jArray.getJSONObject(i).getInt("pla_status")); pla_list.add(pla); } //BaseActivity.hideFragmentpDialog(pDialog); if (refreshLayout_placas != null) { refreshLayout_placas.setRefreshing(false); } if (pla_list.size() == 0) { simpleDialog(PlacaActivity.this, "Aùn no tiene una placa asignada a su cuenta. Acérquese a cualquiera de nuestros serenos con su vehículo y solicite que vinculen su placa.", true, false); } } else { //BaseActivity.hideFragmentpDialog(pDialog); refreshLayout_placas.setRefreshing(false); Toast.makeText(PlacaActivity.this, msg, Toast.LENGTH_SHORT).show(); } showPlateList(); } catch (JSONException e) { e.printStackTrace(); //BaseActivity.hideFragmentpDialog(pDialog); refreshLayout_placas.setRefreshing(false); Toast.makeText(PlacaActivity.this, "Ocurrió un error", Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); //BaseActivity.hideFragmentpDialog(pDialog); refreshLayout_placas.setRefreshing(false); Toast.makeText(PlacaActivity.this, "Ocurrió un error", Toast.LENGTH_SHORT).show(); } } ); request.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); Configuration.getInstance().addToRequestQueue(request, TAG); } else { ConnectionBroadcastReceiver.showSnack(findViewById(R.id.activity_placa), this); refreshLayout_placas.setRefreshing(false); } } private void showPlateList() { PlateAdapter adapter = new PlateAdapter(this, pla_list, this); rv_vehiculos_placas.setHasFixedSize(true); rv_vehiculos_placas.setLayoutManager(new LinearLayoutManager(this)); rv_vehiculos_placas.setAdapter(adapter); adapter.notifyDataSetChanged(); } @OnClick(R.id.iv_placa_agregar) public void plateAdd() { @SuppressLint("InflateParams") View view = LayoutInflater.from(this).inflate(R.layout.popup_plate_remove, null); final AlertDialog.Builder dialog = new AlertDialog.Builder(Objects.requireNonNull(this)); dialog.setView(view); //aqui puedes cambiar los valores de tus otros controladores como los textview o buttons, etc Button btn_Cerrar = view.findViewById(R.id.btn_placa_remove_cancelar); Button btn_Aceptar = view.findViewById(R.id.btn_placa_remove_aceptar); TextView question = view.findViewById(R.id.tv_popup_plate_question); question.setText("Para evitar que su placa se duplique, le recomendamos validarla con la ayuda de un sereno."); btn_Aceptar.setText("Aceptar"); dialog.create(); final AlertDialog ad = dialog.show(); btn_Cerrar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ad.dismiss(); } }); btn_Aceptar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showInPopUp(); ad.dismiss(); } }); } private void showInPopUp() { @SuppressLint("InflateParams") View view = LayoutInflater.from(this).inflate(R.layout.popup_plate_add, null); final AlertDialog.Builder dialog = new AlertDialog.Builder(Objects.requireNonNull(this)); dialog.setView(view); Button btn_Cerrar = view.findViewById(R.id.btn_placa_add_cancelar); Button btn_Aceptar = view.findViewById(R.id.btn_placa_add_aceptar); final EditText new_placa = view.findViewById(R.id.et_placa_add_name); dialog.create(); final AlertDialog ad = dialog.show(); btn_Cerrar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ad.dismiss(); } }); btn_Aceptar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { placa_new = new_placa.getText().toString().trim(); if (Utils.isValidInput(new_placa, "Ingrese una placa")) { if (placa_new.length() == 6) { ad.dismiss(); requestPlateAdd(); } else { Toast.makeText(PlacaActivity.this, "Estimado usuario, verifique el nro. de placa ingresado", Toast.LENGTH_SHORT).show(); } } } }); } private void requestPlateAdd() { if (ConnectionBroadcastReceiver.isConnect()) { showLoading(this); final Preferences prefs = new Preferences(Objects.requireNonNull(this)); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("user_id", prefs.getUser_id()); jsonObject.put("pla_number", placa_new); } catch (JSONException e) { e.printStackTrace(); } CustomJsonObjectRequest request = new CustomJsonObjectRequest( Request.Method.POST, Constantes.url_plate_add, jsonObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { String msg = response.getString("message"); if (response.getBoolean("status")) { requestListPlate(); hideLoading(); } else { hideLoading(); simpleDialog(PlacaActivity.this, msg, true, false); } showPlateList(); } catch (JSONException e) { e.printStackTrace(); hideLoading(); Toast.makeText(PlacaActivity.this, "Ocurrió un error", Toast.LENGTH_SHORT).show(); //connectionError(AdminActivity.this, false); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); hideLoading(); Toast.makeText(PlacaActivity.this, "Ocurrió un error", Toast.LENGTH_SHORT).show(); } } ); request.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); Configuration.getInstance().addToRequestQueue(request, TAG); } else { ConnectionBroadcastReceiver.showSnack(findViewById(R.id.activity_placa), this); } } public void deletePlate(final String id) { @SuppressLint("InflateParams") View view = LayoutInflater.from(this).inflate(R.layout.popup_plate_remove, null); final AlertDialog.Builder dialog = new AlertDialog.Builder(Objects.requireNonNull(this)); dialog.setView(view); //aqui puedes cambiar los valores de tus otros controladores como los textview o buttons, etc Button btn_Cerrar = view.findViewById(R.id.btn_placa_remove_cancelar); Button btn_Aceptar = view.findViewById(R.id.btn_placa_remove_aceptar); TextView question = view.findViewById(R.id.tv_popup_plate_question); question.setText("¿Desea eliminar la placa " + id + " ?"); dialog.create(); final AlertDialog ad = dialog.show(); btn_Cerrar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ad.dismiss(); } }); btn_Aceptar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { requestPlateRemove(id); ad.dismiss(); } }); } private void requestPlateRemove(final String plateName) { if (ConnectionBroadcastReceiver.isConnect()) { showLoading(this); final Preferences prefs = new Preferences(Objects.requireNonNull(this)); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("user_id", prefs.getUser_id()); jsonObject.put("pla_number", String.valueOf(plateName)); } catch (JSONException e) { e.printStackTrace(); } CustomJsonObjectRequest request = new CustomJsonObjectRequest( Request.Method.POST, Constantes.url_plate_remove, jsonObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { String msg = response.getString("message"); if (response.getBoolean("status")) { Toast.makeText(PlacaActivity.this, msg, Toast.LENGTH_SHORT).show(); requestListPlate(); hideLoading(); } else { hideLoading(); //Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show(); simpleDialog(PlacaActivity.this, msg, true, false); //simpleDialog(AdminActivity.this, server_msg, true, false); } showPlateList(); } catch (JSONException e) { e.printStackTrace(); hideLoading(); Toast.makeText(PlacaActivity.this, "Ocurrió un error", Toast.LENGTH_SHORT).show(); //connectionError(AdminActivity.this, false); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); hideLoading(); Toast.makeText(PlacaActivity.this, "Ocurrió un error", Toast.LENGTH_SHORT).show(); // connectionError(AdminActivity.this, false); } } ); request.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); Configuration.getInstance().addToRequestQueue(request, TAG); } else { ConnectionBroadcastReceiver.showSnack(findViewById(R.id.activity_placa), this); } } }
16,599
0.531497
0.53011
361
44.952908
31.456791
227
false
false
0
0
0
0
0
0
0.725762
false
false
5
81847f4f36624f928082ed0ff6285af603a861e9
14,396,730,391,886
0f6a018d6c78a29f5147859e348128fe8e529360
/IPProjekat/src/net/etfbl/project/bean/LogBean.java
677cb94445e9f94e29ef69404c0bb4ddfef4892b
[]
no_license
dejanbunic/InternetProgramiranje
https://github.com/dejanbunic/InternetProgramiranje
f070eb3e333ac907ad60b07a81f69e808e154167
42b9be8af7937f8675ab0c024402ba58d49cacb8
refs/heads/master
2022-11-19T20:11:02.736000
2020-07-21T15:52:19
2020-07-21T15:52:19
281,430,796
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.etfbl.project.bean; import net.etfbl.project.dao.LogDAO; public class LogBean { public int getUserNumberLogs(int id) { return LogDAO.getUserNumberLogs(id); } }
UTF-8
Java
181
java
LogBean.java
Java
[]
null
[]
package net.etfbl.project.bean; import net.etfbl.project.dao.LogDAO; public class LogBean { public int getUserNumberLogs(int id) { return LogDAO.getUserNumberLogs(id); } }
181
0.751381
0.751381
9
19.111111
16.947268
40
false
false
0
0
0
0
0
0
0.444444
false
false
5
b6ba3a7169e91410992ec9500e2bc845aa8eb483
2,980,707,361,591
caba7a547f30fb64b22bfdd4bfe36371f2539651
/src/modele/Cellule.java
d1bebbdae1b3a669313635782f15f5c8c32b2200
[]
no_license
pierremarieB/Natural-Selection-Simulation
https://github.com/pierremarieB/Natural-Selection-Simulation
34d18627e651eef8f37f6bf354e5710406a80c77
cc04a3b47e20533b49e2ada6dd4e4a0735304f3f
refs/heads/master
2020-04-06T15:52:16.621000
2018-11-14T18:58:43
2018-11-14T18:58:43
157,596,007
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package modele; import java.util.ArrayList; import java.util.Random; import java.util.Hashtable; public class Cellule { public static Random rand = new Random(); /** * Probabilite de reproduction */ protected double pReprod; /** * Caracteristique arbitraire 1 */ protected double firstCarac; /** * Caracterisitque arbitraire 2 */ protected double secondCarac; /** * Caracteristique arbitraire 3 */ protected double thirdCarac; /** * Tableau des caracteristique */ protected double[] caracArray; /** * Booleen pour savoir si la cellule vient de naitre a une iteration donne */ protected boolean recentNaissance = false; /** * Caracteristique d'une cellule qui definira la facon dont l'environnement agit sur elle */ protected double caracteristique; /** * Valeur permettetant de savoir si la cellule est plus ou moins vieille */ protected double pMortVieillesse; /** * Constructeur logique * * @param microE micro environnement dans laquelle est notre cellule */ public Cellule(double carac1, double carac2 ,double carac3, double pReprod){ //Caracteristique qui seront interpretes pas le MicroEnv this.firstCarac = carac1; this.secondCarac = carac2; this.thirdCarac = carac3; //Tableau des trois caracteristiques this.caracArray = new double[]{carac1,carac2,carac3}; //Probabilite de reprod et de mort par vieillissement this.pReprod = pReprod; this.pMortVieillesse = 0.1; } public boolean getRecentNaissance(){ return this.recentNaissance; } public void setRecentNaissance(boolean bool){ this.recentNaissance = bool; } public double getPMortVieillesse(){ return pMortVieillesse; } public void setPMortVieillesse(double value){ pMortVieillesse = value; } public double getPReprod(){ return pReprod; } public void setPReprod(double pReprod){ this.pReprod = pReprod; } public double getFirstCarac() { return this.firstCarac; } public void setFirstCarac(double carac) { this.firstCarac = carac; } public double getSecondCarac() { return this.secondCarac; } public void setSecondCarac(double carac) { this.secondCarac = carac; } public double getThirdCarac() { return this.thirdCarac; } public void setThirdCarac(double carac) { this.thirdCarac = carac; } /** * @return une cellule enfante */ public Cellule genererEnfant(){ Random rand = new Random(); double factorCarac1 = rand.nextGaussian()/200; double factorCarac2 = rand.nextGaussian()/200; double factorCarac3 = rand.nextGaussian()/200; double caracUpdate1 = normalizeCaracteristic(this.firstCarac+factorCarac1); double caracUpdate2 = normalizeCaracteristic(this.secondCarac+factorCarac2); double caracUpdate3 = normalizeCaracteristic(this.thirdCarac+factorCarac3); Cellule cell = new Cellule(caracUpdate1, caracUpdate2, caracUpdate3, this.pReprod); return cell; } public double normalizeCaracteristic(double caracteristic) { if(caracteristic < 0){ return (double) 0; } else if (caracteristic > 1) { return (double) 1; } else { return caracteristic; } } }
UTF-8
Java
3,139
java
Cellule.java
Java
[]
null
[]
package modele; import java.util.ArrayList; import java.util.Random; import java.util.Hashtable; public class Cellule { public static Random rand = new Random(); /** * Probabilite de reproduction */ protected double pReprod; /** * Caracteristique arbitraire 1 */ protected double firstCarac; /** * Caracterisitque arbitraire 2 */ protected double secondCarac; /** * Caracteristique arbitraire 3 */ protected double thirdCarac; /** * Tableau des caracteristique */ protected double[] caracArray; /** * Booleen pour savoir si la cellule vient de naitre a une iteration donne */ protected boolean recentNaissance = false; /** * Caracteristique d'une cellule qui definira la facon dont l'environnement agit sur elle */ protected double caracteristique; /** * Valeur permettetant de savoir si la cellule est plus ou moins vieille */ protected double pMortVieillesse; /** * Constructeur logique * * @param microE micro environnement dans laquelle est notre cellule */ public Cellule(double carac1, double carac2 ,double carac3, double pReprod){ //Caracteristique qui seront interpretes pas le MicroEnv this.firstCarac = carac1; this.secondCarac = carac2; this.thirdCarac = carac3; //Tableau des trois caracteristiques this.caracArray = new double[]{carac1,carac2,carac3}; //Probabilite de reprod et de mort par vieillissement this.pReprod = pReprod; this.pMortVieillesse = 0.1; } public boolean getRecentNaissance(){ return this.recentNaissance; } public void setRecentNaissance(boolean bool){ this.recentNaissance = bool; } public double getPMortVieillesse(){ return pMortVieillesse; } public void setPMortVieillesse(double value){ pMortVieillesse = value; } public double getPReprod(){ return pReprod; } public void setPReprod(double pReprod){ this.pReprod = pReprod; } public double getFirstCarac() { return this.firstCarac; } public void setFirstCarac(double carac) { this.firstCarac = carac; } public double getSecondCarac() { return this.secondCarac; } public void setSecondCarac(double carac) { this.secondCarac = carac; } public double getThirdCarac() { return this.thirdCarac; } public void setThirdCarac(double carac) { this.thirdCarac = carac; } /** * @return une cellule enfante */ public Cellule genererEnfant(){ Random rand = new Random(); double factorCarac1 = rand.nextGaussian()/200; double factorCarac2 = rand.nextGaussian()/200; double factorCarac3 = rand.nextGaussian()/200; double caracUpdate1 = normalizeCaracteristic(this.firstCarac+factorCarac1); double caracUpdate2 = normalizeCaracteristic(this.secondCarac+factorCarac2); double caracUpdate3 = normalizeCaracteristic(this.thirdCarac+factorCarac3); Cellule cell = new Cellule(caracUpdate1, caracUpdate2, caracUpdate3, this.pReprod); return cell; } public double normalizeCaracteristic(double caracteristic) { if(caracteristic < 0){ return (double) 0; } else if (caracteristic > 1) { return (double) 1; } else { return caracteristic; } } }
3,139
0.723797
0.711373
143
20.944056
21.874012
90
false
false
0
0
0
0
0
0
1.594406
false
false
5
cf13291fb038b144da3243c4cec650d0d65a0ec4
11,751,030,582,830
a5ebeaf0cd63c892033e7444aea9e651982d59d1
/src/C212/extra/MidtermPrep/Cutoffs.java
4eb96c066970f4f23bcf88d31ef0af9201b6d854
[]
no_license
jsisaacs/C212
https://github.com/jsisaacs/C212
ce2dcbfe4cd34a22d3795afb77569e750b671698
dd2d2a69a6b7eb002236059d9c7643746e60694c
refs/heads/master
2021-08-29T15:49:53.244000
2017-12-14T06:41:20
2017-12-14T06:41:20
105,238,143
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//Joshua Isaacson, jsisaacs, October 10, 2017 package C212.extra.MidtermPrep; /* The original US income tax of 1913 */ import java.util.Scanner; public class Cutoffs { //variables private static double incomeTax; public static double tax(double income) { if (income <= 50000) { incomeTax = income * 0.01; } if (income > 50000 && income <= 75000) { incomeTax = income * 0.02; } if (income > 75000 && income <= 100000) { incomeTax = income * 0.03; } if (income > 100000 && income <= 250000) { incomeTax = income * 0.04; } if (income > 250000 && income <= 500000) { incomeTax = income * 0.05; } if (income > 500000) { incomeTax = income * 0.06; } return incomeTax; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); double income; System.out.println("What is your income?"); income = scan.nextDouble(); System.out.println("Your income tax is: " + tax(income)); } }
UTF-8
Java
1,141
java
Cutoffs.java
Java
[ { "context": "//Joshua Isaacson, jsisaacs, October 10, 2017\n\npackage C212.extra.M", "end": 17, "score": 0.9998804330825806, "start": 2, "tag": "NAME", "value": "Joshua Isaacson" }, { "context": "//Joshua Isaacson, jsisaacs, October 10, 2017\n\npackage C212.extra.MidtermPrep", "end": 27, "score": 0.9995260238647461, "start": 19, "tag": "USERNAME", "value": "jsisaacs" } ]
null
[]
//<NAME>, jsisaacs, October 10, 2017 package C212.extra.MidtermPrep; /* The original US income tax of 1913 */ import java.util.Scanner; public class Cutoffs { //variables private static double incomeTax; public static double tax(double income) { if (income <= 50000) { incomeTax = income * 0.01; } if (income > 50000 && income <= 75000) { incomeTax = income * 0.02; } if (income > 75000 && income <= 100000) { incomeTax = income * 0.03; } if (income > 100000 && income <= 250000) { incomeTax = income * 0.04; } if (income > 250000 && income <= 500000) { incomeTax = income * 0.05; } if (income > 500000) { incomeTax = income * 0.06; } return incomeTax; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); double income; System.out.println("What is your income?"); income = scan.nextDouble(); System.out.println("Your income tax is: " + tax(income)); } }
1,132
0.537248
0.460999
45
24.355556
18.876389
65
false
false
0
0
0
0
0
0
0.4
false
false
5
d0de84a794bfb789bea41f530fc56362b68f9ab3
23,321,672,450,177
05ef1f27b39d47897bd61bfee25de6e83c4bc10d
/src/main/java/io/testAi/controller/MainController.java
699802d333334c54b10dffab61e83793d3e18be2
[]
no_license
sumsup/testAi
https://github.com/sumsup/testAi
1cc95ad7c045a61fddede20e503b0c745bc034ba
db1f69a692409b46f1a88a6bb0885d909cbc79da
refs/heads/master
2020-06-29T04:58:19.560000
2019-08-04T04:10:36
2019-08-04T04:10:36
200,448,025
0
0
null
false
2020-10-13T15:05:02
2019-08-04T04:08:17
2019-08-04T04:10:56
2020-10-13T15:05:00
12
0
0
3
Java
false
false
package io.testAi.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MainController { // 메인화면 컨트롤러 @RequestMapping(value="testMain") public void testMain() { } // 테스트 시작. @RequestMapping(value="testHealth") public void testHealth() { } // 테스트 결과. @RequestMapping(value="testHealthResult") public void testHealthResult() { } // 테스트 추가 및 변경. @RequestMapping(value="testHealthManagement") public void testHealthManagement() { } }
UTF-8
Java
648
java
MainController.java
Java
[]
null
[]
package io.testAi.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MainController { // 메인화면 컨트롤러 @RequestMapping(value="testMain") public void testMain() { } // 테스트 시작. @RequestMapping(value="testHealth") public void testHealth() { } // 테스트 결과. @RequestMapping(value="testHealthResult") public void testHealthResult() { } // 테스트 추가 및 변경. @RequestMapping(value="testHealthManagement") public void testHealthManagement() { } }
648
0.686242
0.686242
33
16.121212
17.683681
62
false
false
0
0
0
0
0
0
0.939394
false
false
5
902957823caf51a793c1df0e04c49cb7ae3a11bd
4,114,578,696,149
417a6403b1423fea9bac20ab272fab02ad4ce4e3
/Thuvien/src/GUI/selectNXB.java
c06c1855621eee843e40aa88bd0f97f6244f74c9
[]
no_license
PhuongNam03092000/ThuVien
https://github.com/PhuongNam03092000/ThuVien
3b98c53750a4aa27812ac9b44913b33e067b9659
e5d7000b212f20ce0a3dd8b193ac035e945650bf
refs/heads/master
2023-07-18T20:35:07.220000
2021-09-07T04:20:53
2021-09-07T04:20:53
308,191,412
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package GUI; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import BUS.nxbBUS; import DTO.nxbDTO; import java.util.Vector; import javax.swing.JTextField; public class selectNXB extends selectID { private JPanel contentPane; private DefaultTableModel model; private JTable tbTG; public selectNXB() throws Exception { super(); Vector header = new Vector(); header.add("Mã NXB"); header.add("Tên NXB"); header.add("SDT NXB"); header.add("Email NXB"); model = new DefaultTableModel(header, 0) { @Override public boolean isCellEditable(int row, int col) { return false; } }; tbTG = new JTable(model); JScrollPane scrollPane = new JScrollPane(tbTG); scrollPane.setBounds(12, 98, 404, 126); getContentPane().add(scrollPane); } public void loaddata() { nxbBUS bus = new nxbBUS(); bus.getNXBList(); for (nxbDTO nxb : nxbBUS.dsnxb) { Vector a = new Vector(); a.add(nxb.getManxb()); a.add(nxb.getTenxb()); a.add(nxb.getSdt()); a.add(nxb.getEmail()); model.addRow(a); } tbTG.setModel(model); } @Override public int kiemtra(JTextField a) { super.select(a); int i = tbTG.getSelectedRow(); if (i < 0) { a.setText(null); return 0; } else { String temp = (String) tbTG.getValueAt(i, 0); a.setText(temp); return 1; } } }
UTF-8
Java
1,700
java
selectNXB.java
Java
[]
null
[]
package GUI; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import BUS.nxbBUS; import DTO.nxbDTO; import java.util.Vector; import javax.swing.JTextField; public class selectNXB extends selectID { private JPanel contentPane; private DefaultTableModel model; private JTable tbTG; public selectNXB() throws Exception { super(); Vector header = new Vector(); header.add("Mã NXB"); header.add("Tên NXB"); header.add("SDT NXB"); header.add("Email NXB"); model = new DefaultTableModel(header, 0) { @Override public boolean isCellEditable(int row, int col) { return false; } }; tbTG = new JTable(model); JScrollPane scrollPane = new JScrollPane(tbTG); scrollPane.setBounds(12, 98, 404, 126); getContentPane().add(scrollPane); } public void loaddata() { nxbBUS bus = new nxbBUS(); bus.getNXBList(); for (nxbDTO nxb : nxbBUS.dsnxb) { Vector a = new Vector(); a.add(nxb.getManxb()); a.add(nxb.getTenxb()); a.add(nxb.getSdt()); a.add(nxb.getEmail()); model.addRow(a); } tbTG.setModel(model); } @Override public int kiemtra(JTextField a) { super.select(a); int i = tbTG.getSelectedRow(); if (i < 0) { a.setText(null); return 0; } else { String temp = (String) tbTG.getValueAt(i, 0); a.setText(temp); return 1; } } }
1,700
0.55477
0.545936
70
23.257143
15.907488
61
false
false
0
0
0
0
0
0
0.657143
false
false
5
bf6f0b8e339bf4ef18de7d3c2ffab983880b47bc
1,417,339,250,761
635c344550534c100e0a86ab318905734c95390d
/wpimath/src/main/java/edu/wpi/first/math/controller/LinearPlantInversionFeedforward.java
a7628512afee9ec461a78e8891cdccb3907e16fc
[ "BSD-3-Clause" ]
permissive
wpilibsuite/allwpilib
https://github.com/wpilibsuite/allwpilib
2435cd2f5c16fb5431afe158a5b8fd84da62da24
8f3d6a1d4b1713693abc888ded06023cab3cab3a
refs/heads/main
2023-08-23T21:04:26.896000
2023-08-23T17:47:32
2023-08-23T17:47:32
24,655,143
986
769
NOASSERTION
false
2023-09-14T03:51:22
2014-09-30T20:51:33
2023-09-13T20:40:52
2023-09-14T03:51:22
112,130
869
535
386
C++
false
false
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package edu.wpi.first.math.controller; import edu.wpi.first.math.Matrix; import edu.wpi.first.math.Num; import edu.wpi.first.math.numbers.N1; import edu.wpi.first.math.system.Discretization; import edu.wpi.first.math.system.LinearSystem; import org.ejml.simple.SimpleMatrix; /** * Constructs a plant inversion model-based feedforward from a {@link LinearSystem}. * * <p>The feedforward is calculated as <strong> u_ff = B<sup>+</sup> (r_k+1 - A r_k) </strong>, * where <strong> B<sup>+</sup> </strong> is the pseudoinverse of B. * * <p>For more on the underlying math, read * https://file.tavsys.net/control/controls-engineering-in-frc.pdf. */ public class LinearPlantInversionFeedforward< States extends Num, Inputs extends Num, Outputs extends Num> { /** The current reference state. */ private Matrix<States, N1> m_r; /** The computed feedforward. */ private Matrix<Inputs, N1> m_uff; private final Matrix<States, Inputs> m_B; private final Matrix<States, States> m_A; /** * Constructs a feedforward with the given plant. * * @param plant The plant being controlled. * @param dtSeconds Discretization timestep. */ public LinearPlantInversionFeedforward( LinearSystem<States, Inputs, Outputs> plant, double dtSeconds) { this(plant.getA(), plant.getB(), dtSeconds); } /** * Constructs a feedforward with the given coefficients. * * @param A Continuous system matrix of the plant being controlled. * @param B Continuous input matrix of the plant being controlled. * @param dtSeconds Discretization timestep. */ public LinearPlantInversionFeedforward( Matrix<States, States> A, Matrix<States, Inputs> B, double dtSeconds) { var discABPair = Discretization.discretizeAB(A, B, dtSeconds); this.m_A = discABPair.getFirst(); this.m_B = discABPair.getSecond(); m_r = new Matrix<>(new SimpleMatrix(B.getNumRows(), 1)); m_uff = new Matrix<>(new SimpleMatrix(B.getNumCols(), 1)); reset(); } /** * Returns the previously calculated feedforward as an input vector. * * @return The calculated feedforward. */ public Matrix<Inputs, N1> getUff() { return m_uff; } /** * Returns an element of the previously calculated feedforward. * * @param row Row of uff. * @return The row of the calculated feedforward. */ public double getUff(int row) { return m_uff.get(row, 0); } /** * Returns the current reference vector r. * * @return The current reference vector. */ public Matrix<States, N1> getR() { return m_r; } /** * Returns an element of the current reference vector r. * * @param row Row of r. * @return The row of the current reference vector. */ public double getR(int row) { return m_r.get(row, 0); } /** * Resets the feedforward with a specified initial state vector. * * @param initialState The initial state vector. */ public void reset(Matrix<States, N1> initialState) { m_r = initialState; m_uff.fill(0.0); } /** Resets the feedforward with a zero initial state vector. */ public void reset() { m_r.fill(0.0); m_uff.fill(0.0); } /** * Calculate the feedforward with only the desired future reference. This uses the internally * stored "current" reference. * * <p>If this method is used the initial state of the system is the one set using {@link * LinearPlantInversionFeedforward#reset(Matrix)}. If the initial state is not set it defaults to * a zero vector. * * @param nextR The reference state of the future timestep (k + dt). * @return The calculated feedforward. */ public Matrix<Inputs, N1> calculate(Matrix<States, N1> nextR) { return calculate(m_r, nextR); } /** * Calculate the feedforward with current and future reference vectors. * * @param r The reference state of the current timestep (k). * @param nextR The reference state of the future timestep (k + dt). * @return The calculated feedforward. */ public Matrix<Inputs, N1> calculate(Matrix<States, N1> r, Matrix<States, N1> nextR) { m_uff = new Matrix<>(m_B.solve(nextR.minus(m_A.times(r)))); m_r = nextR; return m_uff; } }
UTF-8
Java
4,421
java
LinearPlantInversionFeedforward.java
Java
[]
null
[]
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package edu.wpi.first.math.controller; import edu.wpi.first.math.Matrix; import edu.wpi.first.math.Num; import edu.wpi.first.math.numbers.N1; import edu.wpi.first.math.system.Discretization; import edu.wpi.first.math.system.LinearSystem; import org.ejml.simple.SimpleMatrix; /** * Constructs a plant inversion model-based feedforward from a {@link LinearSystem}. * * <p>The feedforward is calculated as <strong> u_ff = B<sup>+</sup> (r_k+1 - A r_k) </strong>, * where <strong> B<sup>+</sup> </strong> is the pseudoinverse of B. * * <p>For more on the underlying math, read * https://file.tavsys.net/control/controls-engineering-in-frc.pdf. */ public class LinearPlantInversionFeedforward< States extends Num, Inputs extends Num, Outputs extends Num> { /** The current reference state. */ private Matrix<States, N1> m_r; /** The computed feedforward. */ private Matrix<Inputs, N1> m_uff; private final Matrix<States, Inputs> m_B; private final Matrix<States, States> m_A; /** * Constructs a feedforward with the given plant. * * @param plant The plant being controlled. * @param dtSeconds Discretization timestep. */ public LinearPlantInversionFeedforward( LinearSystem<States, Inputs, Outputs> plant, double dtSeconds) { this(plant.getA(), plant.getB(), dtSeconds); } /** * Constructs a feedforward with the given coefficients. * * @param A Continuous system matrix of the plant being controlled. * @param B Continuous input matrix of the plant being controlled. * @param dtSeconds Discretization timestep. */ public LinearPlantInversionFeedforward( Matrix<States, States> A, Matrix<States, Inputs> B, double dtSeconds) { var discABPair = Discretization.discretizeAB(A, B, dtSeconds); this.m_A = discABPair.getFirst(); this.m_B = discABPair.getSecond(); m_r = new Matrix<>(new SimpleMatrix(B.getNumRows(), 1)); m_uff = new Matrix<>(new SimpleMatrix(B.getNumCols(), 1)); reset(); } /** * Returns the previously calculated feedforward as an input vector. * * @return The calculated feedforward. */ public Matrix<Inputs, N1> getUff() { return m_uff; } /** * Returns an element of the previously calculated feedforward. * * @param row Row of uff. * @return The row of the calculated feedforward. */ public double getUff(int row) { return m_uff.get(row, 0); } /** * Returns the current reference vector r. * * @return The current reference vector. */ public Matrix<States, N1> getR() { return m_r; } /** * Returns an element of the current reference vector r. * * @param row Row of r. * @return The row of the current reference vector. */ public double getR(int row) { return m_r.get(row, 0); } /** * Resets the feedforward with a specified initial state vector. * * @param initialState The initial state vector. */ public void reset(Matrix<States, N1> initialState) { m_r = initialState; m_uff.fill(0.0); } /** Resets the feedforward with a zero initial state vector. */ public void reset() { m_r.fill(0.0); m_uff.fill(0.0); } /** * Calculate the feedforward with only the desired future reference. This uses the internally * stored "current" reference. * * <p>If this method is used the initial state of the system is the one set using {@link * LinearPlantInversionFeedforward#reset(Matrix)}. If the initial state is not set it defaults to * a zero vector. * * @param nextR The reference state of the future timestep (k + dt). * @return The calculated feedforward. */ public Matrix<Inputs, N1> calculate(Matrix<States, N1> nextR) { return calculate(m_r, nextR); } /** * Calculate the feedforward with current and future reference vectors. * * @param r The reference state of the current timestep (k). * @param nextR The reference state of the future timestep (k + dt). * @return The calculated feedforward. */ public Matrix<Inputs, N1> calculate(Matrix<States, N1> r, Matrix<States, N1> nextR) { m_uff = new Matrix<>(m_B.solve(nextR.minus(m_A.times(r)))); m_r = nextR; return m_uff; } }
4,421
0.67858
0.673603
147
29.074829
27.396332
99
false
false
0
0
0
0
0
0
0.435374
false
false
5
932535082a1088c3825a763be397842873d8eacf
33,157,147,546,012
418e8d5bdbca976a479ddb3ee4179948c1ec84bb
/Battleship Game Using Various Design Patterns/battleship/Constants.java
433dd6fc19fd8b539caaef316d9c7d063fdff172
[]
no_license
SnehaDighe/Software-Design-Pattern
https://github.com/SnehaDighe/Software-Design-Pattern
f6ee633cfd5ed99ed3751d5f20bc6d912a417db1
2b34d670c45fed79c53ff979c179fcef97105cbb
refs/heads/master
2021-02-26T10:05:56.013000
2020-03-06T21:21:34
2020-03-06T21:21:34
245,518,632
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package battleship; public class Constants { public static final int nRows = 5; //no. of rows on board game public static final int nCols = 5; //no. of columns on board game. public static final int random_integer_bound = 5;//limit for the random integers. static final String[][] grid = new String[nRows][nCols]; //grid matrix for the board. static final int[][] missedGuesses = new int[nRows][nCols]; //counter to maintain missed moves. public static final int playerShipsCount = 3; //counter to maintain player ships on the board. public static final int computerShipsCount = 3; //counter to maintain computer ships on the board. }
UTF-8
Java
661
java
Constants.java
Java
[]
null
[]
package battleship; public class Constants { public static final int nRows = 5; //no. of rows on board game public static final int nCols = 5; //no. of columns on board game. public static final int random_integer_bound = 5;//limit for the random integers. static final String[][] grid = new String[nRows][nCols]; //grid matrix for the board. static final int[][] missedGuesses = new int[nRows][nCols]; //counter to maintain missed moves. public static final int playerShipsCount = 3; //counter to maintain player ships on the board. public static final int computerShipsCount = 3; //counter to maintain computer ships on the board. }
661
0.726172
0.718608
11
58.090908
37.683983
100
false
false
0
0
0
0
0
0
0.727273
false
false
5
c90743d77067f55cff78f050b20c950b793cff9b
21,019,570,011,099
0be0a0140bf33f7e9eef611ee9a014e08f8ce564
/server/src/test-fast/java/com/thoughtworks/go/server/dao/PluginSqlMapDaoTest.java
de744c48917a01112df112983f5667b39f5a5de8
[ "Apache-2.0" ]
permissive
gocd/gocd
https://github.com/gocd/gocd
d332cffef6d98ec6f88e1d0d96d8f31b999ef7ff
1a1e291a65d4a893bfdd83008ef61d57a98ba43c
refs/heads/master
2023-08-18T03:36:11.909000
2023-08-18T02:17:49
2023-08-18T02:17:49
15,155,534
6,443
1,074
Apache-2.0
false
2023-09-14T14:11:32
2013-12-13T05:26:16
2023-09-14T14:00:45
2023-09-14T14:11:31
366,925
6,892
988
72
Java
false
false
/* * Copyright 2023 Thoughtworks, 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 com.thoughtworks.go.server.dao; import org.assertj.core.api.Assertions; import org.hibernate.SessionFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; class PluginSqlMapDaoTest { private PluginSqlMapDao pluginSqlMapDao; @BeforeEach void setUp() { pluginSqlMapDao = new PluginSqlMapDao(mock(SessionFactory.class), null, null); } @Test void shouldGenerateCacheKeyForPluginId() { Assertions.assertThat(pluginSqlMapDao.cacheKeyForPluginSettings("cd.go.docker")) .isEqualTo("com.thoughtworks.go.server.dao.PluginSqlMapDao.$plugin_settings.$cd.go.docker"); } }
UTF-8
Java
1,305
java
PluginSqlMapDaoTest.java
Java
[]
null
[]
/* * Copyright 2023 Thoughtworks, 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 com.thoughtworks.go.server.dao; import org.assertj.core.api.Assertions; import org.hibernate.SessionFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; class PluginSqlMapDaoTest { private PluginSqlMapDao pluginSqlMapDao; @BeforeEach void setUp() { pluginSqlMapDao = new PluginSqlMapDao(mock(SessionFactory.class), null, null); } @Test void shouldGenerateCacheKeyForPluginId() { Assertions.assertThat(pluginSqlMapDao.cacheKeyForPluginSettings("cd.go.docker")) .isEqualTo("com.thoughtworks.go.server.dao.PluginSqlMapDao.$plugin_settings.$cd.go.docker"); } }
1,305
0.74023
0.7341
39
32.46154
30.065609
108
false
false
0
0
0
0
0
0
0.435897
false
false
5
143dd26caf625392f4bf9315c7275c0ee8a79483
21,019,570,007,740
d82451d18cca1fbe641058098bbeb40e4e44e08f
/day08-code/src/cn/itcast/day08/demo04/Demo04MathPractise.java
99d7471421908c4dcb85f48085328aa56a6e99df
[]
no_license
NeilyoSummer/JavaNotes
https://github.com/NeilyoSummer/JavaNotes
54fc3fdadb5444af96b0364490a12c11342510cc
0952b703a03899c43e5dfa4d550184b8009c1240
refs/heads/master
2020-04-06T16:43:01.721000
2018-11-24T09:34:44
2018-11-24T09:34:44
157,631,452
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.itcast.day08.demo04; /* 题目: 计算在-10.8到5.9之间, 绝对值大于6或者小于2.1的整数有多少个? 分析: 1. 既然已经确定范围,for循环 2. 起点位置-10.8应该转换成为-10, 两种方法: 2.1 可以使用Math.ceil方法, 向上(向正方向)取整 2.2 强转成为int, 自动舍弃所有小数位 3. 每一个数字都是整数, 所以步进表达式应该是num++, 这样每次都是+1的. 4. 如何拿到绝对值: Math.abs方法. 5. 一旦发现一个数字,需要让计数器++进行统计. */ public class Demo04MathPractise { public static void main(String[] args) { int count = 0; double min = -10.8; double max = 5.9; // 这样处理,变量i就是区间内所有的整数 for (int i = (int) min; i < max; i++) { int abs = Math.abs(i); if (abs > 6 || abs < 2.1) { count++; } } System.out.println("总共有:" + count); } }
UTF-8
Java
1,003
java
Demo04MathPractise.java
Java
[]
null
[]
package cn.itcast.day08.demo04; /* 题目: 计算在-10.8到5.9之间, 绝对值大于6或者小于2.1的整数有多少个? 分析: 1. 既然已经确定范围,for循环 2. 起点位置-10.8应该转换成为-10, 两种方法: 2.1 可以使用Math.ceil方法, 向上(向正方向)取整 2.2 强转成为int, 自动舍弃所有小数位 3. 每一个数字都是整数, 所以步进表达式应该是num++, 这样每次都是+1的. 4. 如何拿到绝对值: Math.abs方法. 5. 一旦发现一个数字,需要让计数器++进行统计. */ public class Demo04MathPractise { public static void main(String[] args) { int count = 0; double min = -10.8; double max = 5.9; // 这样处理,变量i就是区间内所有的整数 for (int i = (int) min; i < max; i++) { int abs = Math.abs(i); if (abs > 6 || abs < 2.1) { count++; } } System.out.println("总共有:" + count); } }
1,003
0.543262
0.489362
32
21.03125
15.430255
47
false
false
0
0
0
0
0
0
0.625
false
false
5
8e52663f5f06bf5afcec9545602faf281cd72a0d
22,763,326,695,445
9013a8712c2d9a233f700c1eb35118b2d1df14a8
/app/src/main/java/com/zxy/androidsample/ui/md/cardview/CardViewActivity.java
7f5ee155f060ecbabc960d8124bc078abf7cc624
[]
no_license
zxy816/AndroidSample
https://github.com/zxy816/AndroidSample
4c61066a11f272824414360b39915287326ab852
423ef3816155b8674cc49d214ddbb8ec46f692a4
refs/heads/master
2021-06-03T02:26:57.673000
2020-09-11T09:24:04
2020-09-11T09:24:04
82,264,612
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zxy.androidsample.ui.md.cardview; import android.os.Bundle; import com.zxy.androidsample.R; import com.zxy.common_library.BaseActivity; public class CardViewActivity extends BaseActivity { @Override public int getLayout() { return R.layout.activity_card_view; } @Override public void initView(Bundle savedInstanceState) { } }
UTF-8
Java
376
java
CardViewActivity.java
Java
[]
null
[]
package com.zxy.androidsample.ui.md.cardview; import android.os.Bundle; import com.zxy.androidsample.R; import com.zxy.common_library.BaseActivity; public class CardViewActivity extends BaseActivity { @Override public int getLayout() { return R.layout.activity_card_view; } @Override public void initView(Bundle savedInstanceState) { } }
376
0.726064
0.726064
19
18.789474
19.58404
53
false
false
0
0
0
0
0
0
0.263158
false
false
5
79ed0072e57a596c626824d01dbecd138406f044
23,965,917,532,740
1aa61c583b5a2cb266f07e4cf3ca59dcf7c647b5
/src/test/java/com/cybertek/Day02/SpartanTest2.java
1ed97256e464859665faf9a02aef1bd8f0b9b598
[]
no_license
raduga9199/RestAssured
https://github.com/raduga9199/RestAssured
c4383aca9df7bc51e115c90739c80ff9d0bfdd4d
f223e0d8f758d2ab20009892f234dfced5726610
refs/heads/master
2023-03-18T17:44:04.916000
2021-03-10T05:43:24
2021-03-10T05:43:24
345,019,960
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cybertek.Day02; import com.cybertek.Day01.importsAndURL; import io.restassured.http.ContentType; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; public class SpartanTest2 extends importsAndURL{ @BeforeAll public static void setUp(){ baseURI = baseSpartans_URI(); basePath = baseSpartans_Path(); } @DisplayName("Hello Test") @Test public void helloTest(){ given() .accept(ContentType.TEXT). when() .get("/hello") .prettyPeek(). then() .statusCode(is(200)) .contentType(ContentType.TEXT) .body(equalTo("Hello from Sparta")); } @DisplayName("Get 1 Spartan") @Test public void getSingleSpartan(){ // I want to log the request I sent so I see what is the URL, methods and so on given() .log().all(). //.log().uri(). when() .get("spartans/71"). //.prettyPeek(). then() .log().all() //.log().body() //.log().ifValidationFails() .statusCode(is(200)); } @DisplayName("Get All Spartans") @Test public void testAllSpartans() { baseURI = baseSpartans_URI(); basePath = baseSpartans_Path(); given().header("Accept","application/json"). when().get("/spartans") .then().statusCode(is(200)); } @DisplayName("Get All Spartans Test 2") @Test public void testAllSpartans2(){ given().baseUri(baseSpartans_URI()) .basePath(baseSpartans_Path()) // .accept("application/json"). .accept(ContentType.JSON). when() .get("/spartans"). then() .statusCode(is(200)) .contentType(ContentType.JSON); } }
UTF-8
Java
2,193
java
SpartanTest2.java
Java
[]
null
[]
package com.cybertek.Day02; import com.cybertek.Day01.importsAndURL; import io.restassured.http.ContentType; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; public class SpartanTest2 extends importsAndURL{ @BeforeAll public static void setUp(){ baseURI = baseSpartans_URI(); basePath = baseSpartans_Path(); } @DisplayName("Hello Test") @Test public void helloTest(){ given() .accept(ContentType.TEXT). when() .get("/hello") .prettyPeek(). then() .statusCode(is(200)) .contentType(ContentType.TEXT) .body(equalTo("Hello from Sparta")); } @DisplayName("Get 1 Spartan") @Test public void getSingleSpartan(){ // I want to log the request I sent so I see what is the URL, methods and so on given() .log().all(). //.log().uri(). when() .get("spartans/71"). //.prettyPeek(). then() .log().all() //.log().body() //.log().ifValidationFails() .statusCode(is(200)); } @DisplayName("Get All Spartans") @Test public void testAllSpartans() { baseURI = baseSpartans_URI(); basePath = baseSpartans_Path(); given().header("Accept","application/json"). when().get("/spartans") .then().statusCode(is(200)); } @DisplayName("Get All Spartans Test 2") @Test public void testAllSpartans2(){ given().baseUri(baseSpartans_URI()) .basePath(baseSpartans_Path()) // .accept("application/json"). .accept(ContentType.JSON). when() .get("/spartans"). then() .statusCode(is(200)) .contentType(ContentType.JSON); } }
2,193
0.528956
0.518924
92
22.836956
19.322929
92
false
false
0
0
0
0
0
0
0.206522
false
false
5
ae4dadf323962741e5f0f1132c4eaea4a9ad0864
652,835,062,263
d80d2875c4ff490fb7fce0eaa28dab897e9f63fe
/src/model/dao/impl/SellerDaoJDBC.java
612f44371e751812487b60821ce9b163fed23132
[]
no_license
tupiribas/project-workshop-javafx-jdbc
https://github.com/tupiribas/project-workshop-javafx-jdbc
4b8542eded13c33f5cff02d2d986b362caf7914e
b1a9ffbeddb877533593e0eb951f0f585c1b88c1
refs/heads/master
2023-07-27T00:49:29.305000
2021-09-15T01:56:58
2021-09-15T01:56:58
400,385,315
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model.dao.impl; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import db.DB; import db.DbException; import model.dao.SellerDAO; import model.entities.Department; import model.entities.Seller; public class SellerDaoJDBC implements SellerDAO { private Connection conn = null; public SellerDaoJDBC(Connection conn) {this.conn = conn;} @Override public void insert(Seller obj) { PreparedStatement stmt = null; try { String sql = "INSERT INTO " + "seller (Name, Email, BirthDate, BaseSalary, DepartmentId) " + "VALUES (?, ?, ?, ?, ?)"; stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); stmt.setString(1, obj.getName()); stmt.setString(2, obj.getEmail()); stmt.setDate(3, new Date(obj.getBirthDate().getTime())); stmt.setDouble(4, obj.getBaseSalary()); stmt.setInt(5, obj.getDepartment().getId()); int rowsAffected = stmt.executeUpdate(); if (rowsAffected > 0) { ResultSet rs = stmt.getGeneratedKeys(); if (rs.next()) { obj.setId(rs.getInt(1)); } DB.closeConnection(rs); } else { throw new DbException("UNEXPECTED ERROR! NO ROWS AFFECTED! cod.:08>>> "); } } catch (SQLException e) { throw new DbException("FAILED TO CATCH THE SELLER cod.:07>>> " + e.getMessage()); } finally { DB.closeConnection(stmt); } } @Override public void update(Seller obj) { PreparedStatement stmt = null; try { String sql = "UPDATE seller " + "SET Name = ?, Email = ?, BirthDate = ?, BaseSalary = ?, DepartmentId = ? " + "WHERE Id = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, obj.getName()); stmt.setString(2, obj.getEmail()); stmt.setDate(3, new Date(obj.getBirthDate().getTime())); stmt.setDouble(4, obj.getBaseSalary()); stmt.setInt(5, obj.getDepartment().getId()); stmt.setInt(6, obj.getId()); stmt.executeUpdate(); } catch (SQLException e) { throw new DbException("DATA UPDATE FAILED cod.:09>>> " + e.getMessage()); } finally { DB.closeConnection(stmt); } } @Override public void deleteById(Integer id) { PreparedStatement stmt = null; try { String sql = "DELETE FROM seller WHERE Id = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, id); int rows = stmt.executeUpdate(); if (rows == 0) { throw new DbException("ERROR: ID NON-EXISTENT cod.:011"); } } catch (Exception e) { throw new DbException("FAILED TO DELETE THE DATA cod.:010>>> " + e.getMessage()); } finally { DB.closeConnection(stmt); } } @Override public Seller findById(Integer id) { PreparedStatement stmt = null; ResultSet rs = null; try { String sql = "SELECT seller.*, department.Name AS DepName " + "FROM seller INNER JOIN department " + "ON seller.DepartmentId = department.Id " + "WHERE seller.Id = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, id); rs = stmt.executeQuery(); if (rs.next()) { Department dep = instantiateDepartment(rs); return instantiateSeller(rs, dep); } return null; } catch (SQLException e) { throw new DbException("FAILED TO SHOW SELLER DATA cod.:04>>> " + e.getMessage()); } finally { DB.closeConnection(stmt, rs); } } private Seller instantiateSeller(ResultSet rs, Department dep) throws SQLException { Seller obj = new Seller(); obj.setId(rs.getInt("Id")); obj.setName(rs.getString("Name")); obj.setEmail(rs.getString("Email")); obj.setBirthDate(new java.util.Date(rs.getTimestamp("BirthDate").getTime())); obj.setBaseSalary(rs.getDouble("BaseSalary")); obj.setDepartment(dep); return obj; } private Department instantiateDepartment(ResultSet rs) throws SQLException { Department dep = new Department(); dep.setId(rs.getInt("DepartmentId")); dep.setName(rs.getString("DepName")); return dep; } @Override public List<Seller> findAll() { PreparedStatement stmt = null; ResultSet rs = null; try { String sql = "SELECT seller.*, department.Name as DepName " + "FROM seller INNER JOIN department " + "ON seller.DepartmentId = department.Id ORDER BY Name"; stmt = conn.prepareStatement(sql); rs = stmt.executeQuery(); List<Seller> listSeller = new ArrayList<>(); while (rs.next()) { Department dep = verificationDepartment(rs); Seller obj = instantiateSeller(rs, dep); listSeller.add(obj); } return listSeller; } catch (SQLException e) { throw new DbException("FAILED TO SHOW SELLER DATA cod.:06>>> " + e.getMessage()); } finally { DB.closeConnection(stmt, rs); } } private Department verificationDepartment(ResultSet rs) throws SQLException { // Usa-se a coleção de pares map, pois ele não armazena valores repetidos Map<Integer, Department> map = new HashMap<>(); // Se o map.get() já tiver a chave estrangeira DepartmentId como chave do map Department dep = map.get(rs.getInt("DepartmentId")); // Ele reutiliza a variável dep para verificar se é nulo if (dep == null) { // Instancia e guarda os valores no Map para fazer a próxima verificação dep = instantiateDepartment(rs); map.put(rs.getInt("DepartmentId"), dep); } return dep; } @Override public List<Seller> findByDepartment(Department department) { PreparedStatement stmt = null; ResultSet rs = null; try { String sql = "SELECT seller.*, department.Name as DepName " + "FROM seller INNER JOIN department " + "ON seller.DepartmentId = department.Id " + "WHERE department.Id = ? ORDER BY Name"; stmt = conn.prepareStatement(sql); stmt.setInt(1, department.getId()); rs = stmt.executeQuery(); List<Seller> listSeller = new ArrayList<>(); while (rs.next()) { Department dep = verificationDepartment(rs); Seller obj = instantiateSeller(rs, dep); listSeller.add(obj); } return listSeller; } catch (SQLException e) { throw new DbException("FAILED TO SHOW SELLER DATA cod.:05>>> " + e.getMessage()); } finally { DB.closeConnection(stmt, rs); } } }
ISO-8859-1
Java
6,306
java
SellerDaoJDBC.java
Java
[]
null
[]
package model.dao.impl; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import db.DB; import db.DbException; import model.dao.SellerDAO; import model.entities.Department; import model.entities.Seller; public class SellerDaoJDBC implements SellerDAO { private Connection conn = null; public SellerDaoJDBC(Connection conn) {this.conn = conn;} @Override public void insert(Seller obj) { PreparedStatement stmt = null; try { String sql = "INSERT INTO " + "seller (Name, Email, BirthDate, BaseSalary, DepartmentId) " + "VALUES (?, ?, ?, ?, ?)"; stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); stmt.setString(1, obj.getName()); stmt.setString(2, obj.getEmail()); stmt.setDate(3, new Date(obj.getBirthDate().getTime())); stmt.setDouble(4, obj.getBaseSalary()); stmt.setInt(5, obj.getDepartment().getId()); int rowsAffected = stmt.executeUpdate(); if (rowsAffected > 0) { ResultSet rs = stmt.getGeneratedKeys(); if (rs.next()) { obj.setId(rs.getInt(1)); } DB.closeConnection(rs); } else { throw new DbException("UNEXPECTED ERROR! NO ROWS AFFECTED! cod.:08>>> "); } } catch (SQLException e) { throw new DbException("FAILED TO CATCH THE SELLER cod.:07>>> " + e.getMessage()); } finally { DB.closeConnection(stmt); } } @Override public void update(Seller obj) { PreparedStatement stmt = null; try { String sql = "UPDATE seller " + "SET Name = ?, Email = ?, BirthDate = ?, BaseSalary = ?, DepartmentId = ? " + "WHERE Id = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, obj.getName()); stmt.setString(2, obj.getEmail()); stmt.setDate(3, new Date(obj.getBirthDate().getTime())); stmt.setDouble(4, obj.getBaseSalary()); stmt.setInt(5, obj.getDepartment().getId()); stmt.setInt(6, obj.getId()); stmt.executeUpdate(); } catch (SQLException e) { throw new DbException("DATA UPDATE FAILED cod.:09>>> " + e.getMessage()); } finally { DB.closeConnection(stmt); } } @Override public void deleteById(Integer id) { PreparedStatement stmt = null; try { String sql = "DELETE FROM seller WHERE Id = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, id); int rows = stmt.executeUpdate(); if (rows == 0) { throw new DbException("ERROR: ID NON-EXISTENT cod.:011"); } } catch (Exception e) { throw new DbException("FAILED TO DELETE THE DATA cod.:010>>> " + e.getMessage()); } finally { DB.closeConnection(stmt); } } @Override public Seller findById(Integer id) { PreparedStatement stmt = null; ResultSet rs = null; try { String sql = "SELECT seller.*, department.Name AS DepName " + "FROM seller INNER JOIN department " + "ON seller.DepartmentId = department.Id " + "WHERE seller.Id = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, id); rs = stmt.executeQuery(); if (rs.next()) { Department dep = instantiateDepartment(rs); return instantiateSeller(rs, dep); } return null; } catch (SQLException e) { throw new DbException("FAILED TO SHOW SELLER DATA cod.:04>>> " + e.getMessage()); } finally { DB.closeConnection(stmt, rs); } } private Seller instantiateSeller(ResultSet rs, Department dep) throws SQLException { Seller obj = new Seller(); obj.setId(rs.getInt("Id")); obj.setName(rs.getString("Name")); obj.setEmail(rs.getString("Email")); obj.setBirthDate(new java.util.Date(rs.getTimestamp("BirthDate").getTime())); obj.setBaseSalary(rs.getDouble("BaseSalary")); obj.setDepartment(dep); return obj; } private Department instantiateDepartment(ResultSet rs) throws SQLException { Department dep = new Department(); dep.setId(rs.getInt("DepartmentId")); dep.setName(rs.getString("DepName")); return dep; } @Override public List<Seller> findAll() { PreparedStatement stmt = null; ResultSet rs = null; try { String sql = "SELECT seller.*, department.Name as DepName " + "FROM seller INNER JOIN department " + "ON seller.DepartmentId = department.Id ORDER BY Name"; stmt = conn.prepareStatement(sql); rs = stmt.executeQuery(); List<Seller> listSeller = new ArrayList<>(); while (rs.next()) { Department dep = verificationDepartment(rs); Seller obj = instantiateSeller(rs, dep); listSeller.add(obj); } return listSeller; } catch (SQLException e) { throw new DbException("FAILED TO SHOW SELLER DATA cod.:06>>> " + e.getMessage()); } finally { DB.closeConnection(stmt, rs); } } private Department verificationDepartment(ResultSet rs) throws SQLException { // Usa-se a coleção de pares map, pois ele não armazena valores repetidos Map<Integer, Department> map = new HashMap<>(); // Se o map.get() já tiver a chave estrangeira DepartmentId como chave do map Department dep = map.get(rs.getInt("DepartmentId")); // Ele reutiliza a variável dep para verificar se é nulo if (dep == null) { // Instancia e guarda os valores no Map para fazer a próxima verificação dep = instantiateDepartment(rs); map.put(rs.getInt("DepartmentId"), dep); } return dep; } @Override public List<Seller> findByDepartment(Department department) { PreparedStatement stmt = null; ResultSet rs = null; try { String sql = "SELECT seller.*, department.Name as DepName " + "FROM seller INNER JOIN department " + "ON seller.DepartmentId = department.Id " + "WHERE department.Id = ? ORDER BY Name"; stmt = conn.prepareStatement(sql); stmt.setInt(1, department.getId()); rs = stmt.executeQuery(); List<Seller> listSeller = new ArrayList<>(); while (rs.next()) { Department dep = verificationDepartment(rs); Seller obj = instantiateSeller(rs, dep); listSeller.add(obj); } return listSeller; } catch (SQLException e) { throw new DbException("FAILED TO SHOW SELLER DATA cod.:05>>> " + e.getMessage()); } finally { DB.closeConnection(stmt, rs); } } }
6,306
0.66492
0.659362
234
25.91453
22.642361
85
false
false
0
0
0
0
0
0
2.846154
false
false
5
8c14cfcea6255da84551e68225ec0e4fd8830aca
25,520,695,737,537
b47e617aa5d2497136bf7094fa78902c519008ab
/src/main/java/com/springboot/springboot/bootstrap/RepositoryBootstrap.java
1e67e96a4e5ce4070e1e74853e57db984fc18fb5
[]
no_license
heartccace/springboot
https://github.com/heartccace/springboot
6d5bc81bd8966644463f3fc93b65fadd7f69453c
507b079391119bd7d0831f346e6b7dbcd973b342
refs/heads/master
2022-07-05T18:55:09.814000
2020-10-21T13:52:59
2020-10-21T13:52:59
199,886,657
0
0
null
false
2022-06-21T01:34:46
2019-07-31T15:52:14
2020-10-21T13:53:28
2022-06-21T01:34:43
220
0
0
1
Java
false
false
package com.springboot.springboot.bootstrap; import com.springboot.springboot.repository.MyRepository; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ConfigurableApplicationContext; /** * @author liushuang * @create 2019-08-10 11:08 */ @SpringBootApplication(scanBasePackages = {"com.springboot.springboot.repository"}) public class RepositoryBootstrap { public static void main(String[] args) { ConfigurableApplicationContext context = new SpringApplicationBuilder(RepositoryBootstrap.class) .web(WebApplicationType.NONE) .run(args); MyRepository bean = context.getBean(MyRepository.class); System.out.println(bean); context.close(); } }
UTF-8
Java
942
java
RepositoryBootstrap.java
Java
[ { "context": "xt.ConfigurableApplicationContext;\n\n/**\n * @author liushuang\n * @create 2019-08-10 11:08\n */\n@SpringBootApplic", "end": 434, "score": 0.971176028251648, "start": 425, "tag": "USERNAME", "value": "liushuang" } ]
null
[]
package com.springboot.springboot.bootstrap; import com.springboot.springboot.repository.MyRepository; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ConfigurableApplicationContext; /** * @author liushuang * @create 2019-08-10 11:08 */ @SpringBootApplication(scanBasePackages = {"com.springboot.springboot.repository"}) public class RepositoryBootstrap { public static void main(String[] args) { ConfigurableApplicationContext context = new SpringApplicationBuilder(RepositoryBootstrap.class) .web(WebApplicationType.NONE) .run(args); MyRepository bean = context.getBean(MyRepository.class); System.out.println(bean); context.close(); } }
942
0.769639
0.7569
24
38.25
28.034576
104
false
false
0
0
0
0
0
0
0.458333
false
false
5
5af81312c9d72d7cd9acf534737e70e50175959a
26,121,991,157,368
ca9efbc1686051c6fd2c383bb32ec6fdae4ac7c1
/pctApp/src/com/pct/app/service/Authority.java
af0025fe21649f02a2ae024cc597afe83d4f9c2f
[]
no_license
peichunting/web-by-google-app-engine
https://github.com/peichunting/web-by-google-app-engine
3b55fd615cf36ed1b25c4c256cabfb3a992388ec
7f06ffc34ed4f0836b779f9d1ca9379059715709
refs/heads/master
2015-08-05T02:12:37.715000
2013-01-28T08:46:14
2013-01-28T08:46:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pct.app.service; import com.pct.app.AppConfig; import com.pct.app.model.Puser; import com.pct.app.utils.Operation; import com.pct.app.utils.Level; public class Authority{ public static boolean authority(Puser user,Operation operator) { Level level=user.getLevel(); Level authorityLevel=AppConfig.authorityMap.get(operator); if(level.compareFrom(authorityLevel)>=0) return true; else return false; } }
UTF-8
Java
465
java
Authority.java
Java
[]
null
[]
package com.pct.app.service; import com.pct.app.AppConfig; import com.pct.app.model.Puser; import com.pct.app.utils.Operation; import com.pct.app.utils.Level; public class Authority{ public static boolean authority(Puser user,Operation operator) { Level level=user.getLevel(); Level authorityLevel=AppConfig.authorityMap.get(operator); if(level.compareFrom(authorityLevel)>=0) return true; else return false; } }
465
0.711828
0.709677
23
18.217392
19.15147
63
false
false
0
0
0
0
0
0
1.391304
false
false
5
c1b1fa50a0d90c0b80bfcc7577a652fa4b24f91c
24,266,565,277,163
4e30232d3ef0137621f9be0530bf12f858a854c9
/src/test/java/org/sample2/ProjectCrse.java
8f0d9bbe0ceb3971d3f582aa231b0149718db24c
[]
no_license
Jai2623/ProjectMay2020
https://github.com/Jai2623/ProjectMay2020
13c16906933dde4d2097ff02a606465025b1d170
6110b4493141c6259260a50636925d3b70b05f0b
refs/heads/master
2022-07-31T14:49:49.349000
2020-05-25T15:24:44
2020-05-25T15:24:44
266,369,422
0
0
null
false
2020-05-25T15:24:46
2020-05-23T15:53:12
2020-05-25T15:07:01
2020-05-25T15:24:45
3
0
0
0
Java
false
false
package org.sample2; public class ProjectCrse { public static void main(String[] args) { System.out.println("Welcome"); System.out.println("How are you"); System.out.println("Hello world"); } }
UTF-8
Java
221
java
ProjectCrse.java
Java
[]
null
[]
package org.sample2; public class ProjectCrse { public static void main(String[] args) { System.out.println("Welcome"); System.out.println("How are you"); System.out.println("Hello world"); } }
221
0.647059
0.642534
13
16
17.51922
42
false
false
0
0
0
0
0
0
0.769231
false
false
5
5a8eda440baac7b1e23dc9251432329d5abeb43f
27,367,531,653,780
dd0dbe9365b6376a277620e17f31e2768fdcbfc4
/myi-lang/src/main/java/com/myitech/demos/spi/services/impl/TomHelloServiceImpl.java
9e1b553670c80d2555d7f120796093cd9eb315f6
[]
no_license
myifoo/myi-project
https://github.com/myifoo/myi-project
c1407ec162ca6d33e4fddcf2d2660b6fe6f23cd7
904bd605c9757e1a6b51e444b77157ce54abef6d
refs/heads/master
2021-05-03T06:19:00.034000
2018-02-07T09:27:16
2018-02-07T09:27:16
120,591,808
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.myitech.demos.spi.services.impl; import com.myitech.demos.spi.services.HelloService; /** * Created by A.T on 2018/1/26. */ public class TomHelloServiceImpl implements HelloService{ public String sayHello() { return "Tom : Hello Java SPI!"; } }
UTF-8
Java
277
java
TomHelloServiceImpl.java
Java
[ { "context": "emos.spi.services.HelloService;\n\n/**\n * Created by A.T on 2018/1/26.\n */\npublic class TomHelloServiceImp", "end": 120, "score": 0.999458372592926, "start": 117, "tag": "NAME", "value": "A.T" } ]
null
[]
package com.myitech.demos.spi.services.impl; import com.myitech.demos.spi.services.HelloService; /** * Created by A.T on 2018/1/26. */ public class TomHelloServiceImpl implements HelloService{ public String sayHello() { return "Tom : Hello Java SPI!"; } }
277
0.700361
0.67509
12
22.083334
21.289505
57
false
false
0
0
0
0
0
0
0.25
false
false
5
5badc6ad95af958d95e180bb8ef3c92e9fc72f1c
9,509,057,662,682
e4796f4a5ee7cfa2f951309928a46d7101ae56b7
/src/main/java/util/EnvFactory.java
6ad876c99c8241ddc89315ced52f41ffa1000dc4
[]
no_license
laba1203/TalkableProductAutomationProject
https://github.com/laba1203/TalkableProductAutomationProject
0a68c9790a48065dcf3fadd2752013adc5919202
5f2eaf780607038d54ccd04cec616e3747842caf
refs/heads/master
2021-05-11T19:08:50.355000
2019-03-01T16:02:16
2019-03-01T16:02:16
117,852,959
0
5
null
false
2018-07-04T10:09:07
2018-01-17T15:14:28
2018-07-04T09:53:24
2018-07-04T10:09:06
21,163
0
3
0
Java
false
null
package util; import org.testng.Assert; import util.logging.Log; import static util.EnvFactory.EnvType.*; public class EnvFactory { private static final String VOID_LINK = "void.talkable.com"; private static final String PROD_LINK = "talkable.com"; private static final String BASTION_LINK = "bastion.talkable.com"; private static final String COMMON_USER = PropertyLoader.loadProperty("talkable.user.common"); private static final String REPORTS_USER = PropertyLoader.loadProperty("talkable.user.reports"); private static final String password = PropertyLoader.loadProperty("talkable.password"); private static final String registrationPath = "/register?object_or_array"; private static final String baseApiPath = "/api/v2"; private static final String gitHubProjectLink = "https://github.com/tkbl-automation-account/tkbl-automation-account.github.io/edit/master/"; private static final String siteFromGitHub = "http://tkbl-automation-account.github.io/"; //prod/scenario/index.html private static EnvType envType; public enum EnvType{PROD, VOID, BASTION, BART} private static String getUrl() { switch (getEnvType()){ case PROD: return PROD_LINK; case VOID: return VOID_LINK; case BASTION: return BASTION_LINK; default: return null; } } public static EnvType getEnvType(){ if(envType==null){ setEnvType(); } return envType; } private static void setEnvType(){ //property described in pom.xml <test.environment>${env.NAME}</test.environment> if(envType == null) { String envName = ExecutionVariables.getMavenEnvName(); if (envName == null) { Assert.fail("ERROR: envType is null from maven variable env.NAME"); } switch (envName) { case "PROD": envType = PROD; break; case "VOID": envType = VOID; break; case "BASTION": envType = BASTION; break; case "BART": envType = BART; Assert.fail("ERROR: Test framework is not yet configured to <" + envType + "> environment."); break; default: Assert.fail("ERROR: Unknown env type: <" + envName + ">."); } } Log.logRecord("Test is running on <" + envType.toString() + "> environment"); } public static String getEnvUrl(){ return "https://" + getUrl(); } public static String getAdminUrl(){ return "https://admin." + getUrl(); } public static String getCommonUser(){ return COMMON_USER; } public static String getReportsUser() { return REPORTS_USER; } public static String getPassword(){ return password; } public static String getRegistrationURL(){ return getAdminUrl() + registrationPath; } public static String getApiUrl(){ getUrl(); if(envType == PROD) { return "https://www." + getUrl() + baseApiPath; }else { return getEnvUrl() + baseApiPath; } } public static String getGitHubEditLink(){ switch (getEnvType()){ default: return ""; case PROD: return gitHubProjectLink + "prod/"; case BART: return gitHubProjectLink + "bart/"; case BASTION: return gitHubProjectLink + "bastion/"; case VOID: return gitHubProjectLink + "void/"; } } public static String getGitHubSiteLink(){ switch (getEnvType()){ default: return ""; case PROD: return siteFromGitHub + "prod/"; case BART: return siteFromGitHub + "bart/"; case BASTION: return siteFromGitHub + "bastion/"; case VOID: return siteFromGitHub + "void/"; } } // private static String getMavenEnvName(){ // //property described in pom.xml <test.environment>${env.NAME}</test.environment> // //correct working: //// String env = System.getProperty("test.environment"); // //for local running of the project: // String env = "VOID"; //// String env = "PROD"; //// String env = "BASTION"; // // System.out.println("LOG - EnvFactory: Test is running on <" + env + "> environment"); // if(env == null){ // Assert.fail("ERROR: 'env' variable is null in EnvFactory.getMavenEnvName(). Make sure that env.NAME is provided."); // } // return env; // } }
UTF-8
Java
4,980
java
EnvFactory.java
Java
[ { "context": "al String gitHubProjectLink = \"https://github.com/tkbl-automation-account/tkbl-automation-account.github.io/edit/master/\";\n", "end": 859, "score": 0.6131622195243835, "start": 836, "tag": "USERNAME", "value": "tkbl-automation-account" }, { "context": "public static String getPassword(){\n return password;\n }\n\n public static String getRegistrationU", "end": 3079, "score": 0.990720272064209, "start": 3071, "tag": "PASSWORD", "value": "password" } ]
null
[]
package util; import org.testng.Assert; import util.logging.Log; import static util.EnvFactory.EnvType.*; public class EnvFactory { private static final String VOID_LINK = "void.talkable.com"; private static final String PROD_LINK = "talkable.com"; private static final String BASTION_LINK = "bastion.talkable.com"; private static final String COMMON_USER = PropertyLoader.loadProperty("talkable.user.common"); private static final String REPORTS_USER = PropertyLoader.loadProperty("talkable.user.reports"); private static final String password = PropertyLoader.loadProperty("talkable.password"); private static final String registrationPath = "/register?object_or_array"; private static final String baseApiPath = "/api/v2"; private static final String gitHubProjectLink = "https://github.com/tkbl-automation-account/tkbl-automation-account.github.io/edit/master/"; private static final String siteFromGitHub = "http://tkbl-automation-account.github.io/"; //prod/scenario/index.html private static EnvType envType; public enum EnvType{PROD, VOID, BASTION, BART} private static String getUrl() { switch (getEnvType()){ case PROD: return PROD_LINK; case VOID: return VOID_LINK; case BASTION: return BASTION_LINK; default: return null; } } public static EnvType getEnvType(){ if(envType==null){ setEnvType(); } return envType; } private static void setEnvType(){ //property described in pom.xml <test.environment>${env.NAME}</test.environment> if(envType == null) { String envName = ExecutionVariables.getMavenEnvName(); if (envName == null) { Assert.fail("ERROR: envType is null from maven variable env.NAME"); } switch (envName) { case "PROD": envType = PROD; break; case "VOID": envType = VOID; break; case "BASTION": envType = BASTION; break; case "BART": envType = BART; Assert.fail("ERROR: Test framework is not yet configured to <" + envType + "> environment."); break; default: Assert.fail("ERROR: Unknown env type: <" + envName + ">."); } } Log.logRecord("Test is running on <" + envType.toString() + "> environment"); } public static String getEnvUrl(){ return "https://" + getUrl(); } public static String getAdminUrl(){ return "https://admin." + getUrl(); } public static String getCommonUser(){ return COMMON_USER; } public static String getReportsUser() { return REPORTS_USER; } public static String getPassword(){ return <PASSWORD>; } public static String getRegistrationURL(){ return getAdminUrl() + registrationPath; } public static String getApiUrl(){ getUrl(); if(envType == PROD) { return "https://www." + getUrl() + baseApiPath; }else { return getEnvUrl() + baseApiPath; } } public static String getGitHubEditLink(){ switch (getEnvType()){ default: return ""; case PROD: return gitHubProjectLink + "prod/"; case BART: return gitHubProjectLink + "bart/"; case BASTION: return gitHubProjectLink + "bastion/"; case VOID: return gitHubProjectLink + "void/"; } } public static String getGitHubSiteLink(){ switch (getEnvType()){ default: return ""; case PROD: return siteFromGitHub + "prod/"; case BART: return siteFromGitHub + "bart/"; case BASTION: return siteFromGitHub + "bastion/"; case VOID: return siteFromGitHub + "void/"; } } // private static String getMavenEnvName(){ // //property described in pom.xml <test.environment>${env.NAME}</test.environment> // //correct working: //// String env = System.getProperty("test.environment"); // //for local running of the project: // String env = "VOID"; //// String env = "PROD"; //// String env = "BASTION"; // // System.out.println("LOG - EnvFactory: Test is running on <" + env + "> environment"); // if(env == null){ // Assert.fail("ERROR: 'env' variable is null in EnvFactory.getMavenEnvName(). Make sure that env.NAME is provided."); // } // return env; // } }
4,982
0.55
0.549799
164
29.365854
27.742506
144
false
false
0
0
0
0
0
0
0.384146
false
false
5
51fa2dd7d28d1cc9e467ac9e80a1665ff356548b
9,835,475,109,029
53d677a55e4ece8883526738f1c9d00fa6560ff7
/com/tencent/mm/plugin/luckymoney/particles/a.java
aed469b35c30e807f5b4fa48312c763664395bd3
[]
no_license
0jinxing/wechat-apk-source
https://github.com/0jinxing/wechat-apk-source
544c2d79bfc10261eb36389c1edfdf553d8f312a
f75eefd87e9b9ecf2f76fc6d48dbba8e24afcf3d
refs/heads/master
2020-06-07T20:06:03.580000
2019-06-21T09:17:26
2019-06-21T09:17:26
193,069,132
9
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tencent.mm.plugin.luckymoney.particles; import android.content.res.Resources; import android.view.ViewGroup; import com.tencent.matrix.trace.core.AppMethodBeat; public final class a { private static int nZA; private static int nZB; private static int nZC; private static int nZx; private static int nZy; private static int nZz; public c nZD; public a(ViewGroup paramViewGroup) { AppMethodBeat.i(42432); if (nZx == 0) { paramViewGroup = paramViewGroup.getResources(); nZx = paramViewGroup.getDimensionPixelSize(2131428262); nZy = paramViewGroup.getDimensionPixelOffset(2131428267); nZz = paramViewGroup.getDimensionPixelOffset(2131428266); nZA = paramViewGroup.getDimensionPixelOffset(2131428265); nZB = paramViewGroup.getDimensionPixelOffset(2131428268); nZC = paramViewGroup.getDimensionPixelOffset(2131428263); } AppMethodBeat.o(42432); } public static a a(ViewGroup paramViewGroup, b paramb) { AppMethodBeat.i(42433); a locala = new a(paramViewGroup); locala.b(paramViewGroup, paramb); AppMethodBeat.o(42433); return locala; } private void b(ViewGroup paramViewGroup, b paramb) { AppMethodBeat.i(42435); paramViewGroup = new c(paramViewGroup.getContext(), paramb, new d(paramViewGroup.getWidth() / 2, paramViewGroup.getHeight() + 400), paramViewGroup).R(0.0F, 800.0F).S(-2000.0F, 1250.0F).aH(2000.0F); paramViewGroup.oal = 3000.0F; paramViewGroup.oam = 500.0F; paramViewGroup = paramViewGroup.bLH(); paramViewGroup.nZO = e.bLQ(); this.nZD = paramViewGroup.bLI().bLJ(); AppMethodBeat.o(42435); } public final c P(int paramInt, long paramLong) { AppMethodBeat.i(42434); c localc = this.nZD; localc.nZL = 0; localc.nZM = paramLong; localc = localc.aF(paramInt).bLL(); AppMethodBeat.o(42434); return localc; } } /* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes5-dex2jar.jar * Qualified Name: com.tencent.mm.plugin.luckymoney.particles.a * JD-Core Version: 0.6.2 */
UTF-8
Java
2,191
java
a.java
Java
[]
null
[]
package com.tencent.mm.plugin.luckymoney.particles; import android.content.res.Resources; import android.view.ViewGroup; import com.tencent.matrix.trace.core.AppMethodBeat; public final class a { private static int nZA; private static int nZB; private static int nZC; private static int nZx; private static int nZy; private static int nZz; public c nZD; public a(ViewGroup paramViewGroup) { AppMethodBeat.i(42432); if (nZx == 0) { paramViewGroup = paramViewGroup.getResources(); nZx = paramViewGroup.getDimensionPixelSize(2131428262); nZy = paramViewGroup.getDimensionPixelOffset(2131428267); nZz = paramViewGroup.getDimensionPixelOffset(2131428266); nZA = paramViewGroup.getDimensionPixelOffset(2131428265); nZB = paramViewGroup.getDimensionPixelOffset(2131428268); nZC = paramViewGroup.getDimensionPixelOffset(2131428263); } AppMethodBeat.o(42432); } public static a a(ViewGroup paramViewGroup, b paramb) { AppMethodBeat.i(42433); a locala = new a(paramViewGroup); locala.b(paramViewGroup, paramb); AppMethodBeat.o(42433); return locala; } private void b(ViewGroup paramViewGroup, b paramb) { AppMethodBeat.i(42435); paramViewGroup = new c(paramViewGroup.getContext(), paramb, new d(paramViewGroup.getWidth() / 2, paramViewGroup.getHeight() + 400), paramViewGroup).R(0.0F, 800.0F).S(-2000.0F, 1250.0F).aH(2000.0F); paramViewGroup.oal = 3000.0F; paramViewGroup.oam = 500.0F; paramViewGroup = paramViewGroup.bLH(); paramViewGroup.nZO = e.bLQ(); this.nZD = paramViewGroup.bLI().bLJ(); AppMethodBeat.o(42435); } public final c P(int paramInt, long paramLong) { AppMethodBeat.i(42434); c localc = this.nZD; localc.nZL = 0; localc.nZM = paramLong; localc = localc.aF(paramInt).bLL(); AppMethodBeat.o(42434); return localc; } } /* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes5-dex2jar.jar * Qualified Name: com.tencent.mm.plugin.luckymoney.particles.a * JD-Core Version: 0.6.2 */
2,191
0.682337
0.616157
69
29.782608
30.484432
201
false
false
0
0
0
0
0
0
0.724638
false
false
5
b3323157dc91f42299c4297e86cc3b96b96a3b01
3,023,656,985,409
a98f9eeb7889a7094518f4d5b4b3c88f905a9196
/First/erhia/src/com/erhia/cxd/view/OrdinaryUserView.java
02bdf7f19dd956894b1006186d653adef53f7f63
[]
no_license
David7Cooper/learngit
https://github.com/David7Cooper/learngit
c788f1410b50c3b6cd9f3afb56da3e2f2253f011
6961320a4f3cb5bb606d7c97f1e54ded665249cf
refs/heads/master
2021-01-25T09:26:56.539000
2017-11-17T09:38:31
2017-11-17T09:38:31
93,839,283
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.erhia.cxd.view; import com.erhia.cxd.bean.Car; import com.erhia.cxd.bean.Record; import com.erhia.cxd.service.ICarService; import com.erhia.cxd.service.IRecordService; import com.erhia.cxd.service.imple.CarServiceImpl; import com.erhia.cxd.service.imple.RecordServiceImpl; import com.erhia.cxd.util.SCUtil; /** * 普通用户 * @author cxd * @para */ public class OrdinaryUserView { ICarService ics = new CarServiceImpl(); IRecordService irs = new RecordServiceImpl(); /** * 使用对象初始化语句块,让程序第一次执行时打印汽车的全部信息 */ { System.out.println("==============================================================="); System.out.println("编号\t汽车名称\t备注\t品牌\t类型\t价格\t是否可租\t是否上架"); for(Car car : ics.queryAll()){ System.out.println(car.toString()); } } /** * 用户主界面 */ public void main(){ boolean b = true; while(b){ System.out.println("输入0退出"); System.out.println("输入1按价格降序排序"); System.out.println("输入2按价格升序排序"); System.out.println("输入3按类型搜索"); System.out.println("输入4按品牌搜索"); System.out.println("输入5查看所有汽车"); System.out.println("输入6看看我的租车记录"); System.out.println("输入7租车"); System.out.println("输入8还车"); switch(SCUtil.getScanner().next()){ case "0" : /** * 可以直接退出总程序 * System.exit(0); */ b = false; break; case "1" : des(); break; case "2" : asc(); break; case "3" : this.queryKind(); break; case "4" : this.queryBrand(); break; case "5" : queryAll(); break; case "6" : queryRecordByMe(); break; case "7" : rentCar(); break; case "8" : backCar(); break; default : System.out.println("命令无效,请输入正确命令!!!"); } } } /** * 查询全部 */ public void queryAll(){ System.out.println("==============================================================="); System.out.println("编号\t汽车名称\t备注\t品牌\t类型\t价格\t是否可租\t是否上架"); for(Car car : ics.queryAll()){ System.out.println(car.toString()); } } /** * 降序 */ public void des(){ System.out.println("==============================================================="); System.out.println("编号\t汽车名称\t备注\t品牌\t类型\t价格\t是否可租\t是否上架"); for(Car car : ics.queryAllByDes()){ System.out.println(car.toString()); } } /** * 升序 */ public void asc(){ System.out.println("==============================================================="); System.out.println("编号\t汽车名称\t备注\t品牌\t类型\t价格\t是否可租\t是否上架"); for(Car car : ics.queryAllByAsc()){ System.out.println(car.toString()); } } /** * 按照类别(如舒适型 )查看汽车 */ public void queryKind(){ System.out.println("请输入汽车的类型>>>"); String kind = SCUtil.getScanner().next(); System.out.println("编号\t汽车名称\t备注\t品牌\t类型\t价格\t是否可租\t是否上架"); for(Car car : ics.queryByCategory(kind)){ System.out.println(car.toString()); } } /** *按照品牌(如大众)查看汽车 */ public void queryBrand(){ System.out.println("请输入汽车的品牌>>>"); String brand = SCUtil.getScanner().next(); System.out.println("编号\t汽车名称\t备注\t品牌\t类型\t价格\t是否可租\t是否上架"); for(Car car : ics.queryByBrand(brand)){ System.out.println(car.toString()); } } /** * 查看自己的租车记录 */ public void queryRecordByMe(){ System.out.println("编号\t汽车编号\t汽车名称\t备注\t品牌\t类型\t金额\t车牌号\t\t租用者\t\t开始租\t\t结束租\t\t每日租金\t总租金"); for(Record record : irs.queryAll()){ System.out.println(record.toString()); } } /** * 租车 */ public void rentCar(){ System.out.println("请输入你要租赁汽车的编号>>>"); String n = SCUtil.getScanner().next(); int carId = Integer.valueOf(n); System.out.println(irs.addCarRecord(carId)); } /** * 还车 */ public void backCar(){ for(Record record : irs.queryAllByBack()){ System.out.println(record.toString()); } System.out.println("请输入你要归还的汽车的编号>>>"); String n = SCUtil.getScanner().next(); int carId = Integer.valueOf(n); /** * irs.queryAllByBack()方法返回的是(当前登录用户还没归还的租车记录) * 用途: * 1.你只能归还你自己租的车 * 2.你不可以归还你没有租的车 */ String str = "错误:你只能归还自己租过的车!!!"; for(Record record : irs.queryAllByBack()){ if(record.getCarId()==carId){ str = irs.addCarRecordBack(record); } } System.out.println(str); } /** * End */ }
UTF-8
Java
5,038
java
OrdinaryUserView.java
Java
[ { "context": " com.erhia.cxd.util.SCUtil;\n/**\n * 普通用户\n * @author cxd\n * @para\n */\npublic class OrdinaryUserView {\n\tICa", "end": 345, "score": 0.9996688365936279, "start": 342, "tag": "USERNAME", "value": "cxd" } ]
null
[]
package com.erhia.cxd.view; import com.erhia.cxd.bean.Car; import com.erhia.cxd.bean.Record; import com.erhia.cxd.service.ICarService; import com.erhia.cxd.service.IRecordService; import com.erhia.cxd.service.imple.CarServiceImpl; import com.erhia.cxd.service.imple.RecordServiceImpl; import com.erhia.cxd.util.SCUtil; /** * 普通用户 * @author cxd * @para */ public class OrdinaryUserView { ICarService ics = new CarServiceImpl(); IRecordService irs = new RecordServiceImpl(); /** * 使用对象初始化语句块,让程序第一次执行时打印汽车的全部信息 */ { System.out.println("==============================================================="); System.out.println("编号\t汽车名称\t备注\t品牌\t类型\t价格\t是否可租\t是否上架"); for(Car car : ics.queryAll()){ System.out.println(car.toString()); } } /** * 用户主界面 */ public void main(){ boolean b = true; while(b){ System.out.println("输入0退出"); System.out.println("输入1按价格降序排序"); System.out.println("输入2按价格升序排序"); System.out.println("输入3按类型搜索"); System.out.println("输入4按品牌搜索"); System.out.println("输入5查看所有汽车"); System.out.println("输入6看看我的租车记录"); System.out.println("输入7租车"); System.out.println("输入8还车"); switch(SCUtil.getScanner().next()){ case "0" : /** * 可以直接退出总程序 * System.exit(0); */ b = false; break; case "1" : des(); break; case "2" : asc(); break; case "3" : this.queryKind(); break; case "4" : this.queryBrand(); break; case "5" : queryAll(); break; case "6" : queryRecordByMe(); break; case "7" : rentCar(); break; case "8" : backCar(); break; default : System.out.println("命令无效,请输入正确命令!!!"); } } } /** * 查询全部 */ public void queryAll(){ System.out.println("==============================================================="); System.out.println("编号\t汽车名称\t备注\t品牌\t类型\t价格\t是否可租\t是否上架"); for(Car car : ics.queryAll()){ System.out.println(car.toString()); } } /** * 降序 */ public void des(){ System.out.println("==============================================================="); System.out.println("编号\t汽车名称\t备注\t品牌\t类型\t价格\t是否可租\t是否上架"); for(Car car : ics.queryAllByDes()){ System.out.println(car.toString()); } } /** * 升序 */ public void asc(){ System.out.println("==============================================================="); System.out.println("编号\t汽车名称\t备注\t品牌\t类型\t价格\t是否可租\t是否上架"); for(Car car : ics.queryAllByAsc()){ System.out.println(car.toString()); } } /** * 按照类别(如舒适型 )查看汽车 */ public void queryKind(){ System.out.println("请输入汽车的类型>>>"); String kind = SCUtil.getScanner().next(); System.out.println("编号\t汽车名称\t备注\t品牌\t类型\t价格\t是否可租\t是否上架"); for(Car car : ics.queryByCategory(kind)){ System.out.println(car.toString()); } } /** *按照品牌(如大众)查看汽车 */ public void queryBrand(){ System.out.println("请输入汽车的品牌>>>"); String brand = SCUtil.getScanner().next(); System.out.println("编号\t汽车名称\t备注\t品牌\t类型\t价格\t是否可租\t是否上架"); for(Car car : ics.queryByBrand(brand)){ System.out.println(car.toString()); } } /** * 查看自己的租车记录 */ public void queryRecordByMe(){ System.out.println("编号\t汽车编号\t汽车名称\t备注\t品牌\t类型\t金额\t车牌号\t\t租用者\t\t开始租\t\t结束租\t\t每日租金\t总租金"); for(Record record : irs.queryAll()){ System.out.println(record.toString()); } } /** * 租车 */ public void rentCar(){ System.out.println("请输入你要租赁汽车的编号>>>"); String n = SCUtil.getScanner().next(); int carId = Integer.valueOf(n); System.out.println(irs.addCarRecord(carId)); } /** * 还车 */ public void backCar(){ for(Record record : irs.queryAllByBack()){ System.out.println(record.toString()); } System.out.println("请输入你要归还的汽车的编号>>>"); String n = SCUtil.getScanner().next(); int carId = Integer.valueOf(n); /** * irs.queryAllByBack()方法返回的是(当前登录用户还没归还的租车记录) * 用途: * 1.你只能归还你自己租的车 * 2.你不可以归还你没有租的车 */ String str = "错误:你只能归还自己租过的车!!!"; for(Record record : irs.queryAllByBack()){ if(record.getCarId()==carId){ str = irs.addCarRecordBack(record); } } System.out.println(str); } /** * End */ }
5,038
0.582086
0.577016
176
22.53409
19.974386
94
false
false
0
0
0
0
0
0
2.664773
false
false
5
facdb669fcdb99bfefa9803370bf8896ca596263
4,054,449,189,152
ba9eb838756013c44efe2f605b087166836df6f5
/Examen/src/examen/Circulo.java
da9ffcc24feb40e16bfef5e89323c108a1478b1a
[]
no_license
tiloanne96/homework
https://github.com/tiloanne96/homework
a61459b034c53b54c83c46225e8ddfb8b075f6a4
49a473d51b17c11d7f4055132c89fdbe03acef7f
refs/heads/master
2018-12-09T18:26:47.865000
2018-10-05T03:12:44
2018-10-05T03:12:44
147,244,855
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package examen; public class Circulo extends FiguraGeometrica { public Circulo(double valor1) { super(valor1); } @Override double getArea() { return (super.getValor1() * super.getValor1())*Math.PI; } @Override double getPerimetro() { return (2 * Math.PI * super.getValor1()); } }
UTF-8
Java
348
java
Circulo.java
Java
[]
null
[]
package examen; public class Circulo extends FiguraGeometrica { public Circulo(double valor1) { super(valor1); } @Override double getArea() { return (super.getValor1() * super.getValor1())*Math.PI; } @Override double getPerimetro() { return (2 * Math.PI * super.getValor1()); } }
348
0.586207
0.568965
18
18.333334
18.502253
63
false
false
0
0
0
0
0
0
0.222222
false
false
5
f5915dff4fc491b0809c19c4ae8b65b4d171d31c
32,246,614,528,491
25674874607baac5b889b7964001ad10ace25372
/src/mainTest.java
a532b4b781b4b36cd8c0fbdcc26f34a4d88f0ede
[]
no_license
nush2003/BritannicaTest
https://github.com/nush2003/BritannicaTest
df48f06fff6602a79ec731cd8c8e2abffcf29425
abc849d8de25154afce7eef7923282aebe39d858
refs/heads/main
2023-05-13T15:00:04.760000
2021-06-02T10:44:24
2021-06-02T10:44:24
373,129,868
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.IOException; import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; public class mainTest { static WebDriver driver; LoginPage login = new LoginPage(driver); SearchPage search = new SearchPage(driver); BasketPage basket = new BasketPage(driver); @BeforeClass public static void initDriver() { String path = System.getProperty("user.dir"); System.setProperty("webdriver.chrome.driver", path + "\\Drivers\\chromedriver.exe"); ChromeOptions options = new ChromeOptions(); driver = new ChromeDriver(options); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); } @Test public void test() throws IOException, InterruptedException { driver.get("https://www.shufersal.co.il"); login.login("innar@britannica-ks.com", "0547630768"); login.checkLoginAccountName("אינה"); basket.startBuying(); search.searchForAnItem("חלב"); search.sortItems("pricePerUnit-asc"); double cheapestPrice = search.addItemToTheBasket(); basket.checkTotalBasketSum(cheapestPrice); } @AfterClass public static void tearDown() { driver.quit(); } }
WINDOWS-1255
Java
1,479
java
mainTest.java
Java
[ { "context": "ttps://www.shufersal.co.il\");\t\r\n\t login.login(\"innar@britannica-ks.com\", \"0547630768\");\r\n\t login.checkLoginAccountNam", "end": 1075, "score": 0.9999207854270935, "start": 1052, "tag": "EMAIL", "value": "innar@britannica-ks.com" }, { "context": "\"0547630768\");\r\n\t login.checkLoginAccountName(\"אינה\");\r\n\t \r\n\t basket.startBuying();\r\n\t searc", "end": 1132, "score": 0.9970093369483948, "start": 1128, "tag": "NAME", "value": "אינה" } ]
null
[]
import java.io.IOException; import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; public class mainTest { static WebDriver driver; LoginPage login = new LoginPage(driver); SearchPage search = new SearchPage(driver); BasketPage basket = new BasketPage(driver); @BeforeClass public static void initDriver() { String path = System.getProperty("user.dir"); System.setProperty("webdriver.chrome.driver", path + "\\Drivers\\chromedriver.exe"); ChromeOptions options = new ChromeOptions(); driver = new ChromeDriver(options); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); } @Test public void test() throws IOException, InterruptedException { driver.get("https://www.shufersal.co.il"); login.login("<EMAIL>", "0547630768"); login.checkLoginAccountName("אינה"); basket.startBuying(); search.searchForAnItem("חלב"); search.sortItems("pricePerUnit-asc"); double cheapestPrice = search.addItemToTheBasket(); basket.checkTotalBasketSum(cheapestPrice); } @AfterClass public static void tearDown() { driver.quit(); } }
1,463
0.683424
0.675272
59
22.915255
22.131569
88
false
false
0
0
0
0
0
0
1.661017
false
false
5
70b53f260d29778f950106bd0e373831d5e5089d
18,210,661,379,745
6a0dbd66834cc4f099777db0df61476b4c58bade
/Points.java
fc89d79f61decf2e2ccd08c4a4689aa363c90d83
[]
no_license
gmndaniel/Pong
https://github.com/gmndaniel/Pong
3c4377d05e7fcc5c047a1cc43b76568c72fb35f3
5fb3d804e5d71f698cb2ac90610f5d7c26818be7
refs/heads/master
2020-06-13T01:54:19.667000
2019-06-30T09:51:19
2019-06-30T09:51:19
194,490,893
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package PongGame; import java.awt.*; public class Points { private int points; private int x; private int y; Points(int points, int x, int y) { this.points = points; this.x = x; this.y = y; } public void draw(Graphics g) { g.setColor(Color.WHITE); g.setFont(new Font("TimesRoman", Font.PLAIN, 40)); g.drawString("" + points, x, y); } void addPoint() { ++points; } }
UTF-8
Java
463
java
Points.java
Java
[]
null
[]
package PongGame; import java.awt.*; public class Points { private int points; private int x; private int y; Points(int points, int x, int y) { this.points = points; this.x = x; this.y = y; } public void draw(Graphics g) { g.setColor(Color.WHITE); g.setFont(new Font("TimesRoman", Font.PLAIN, 40)); g.drawString("" + points, x, y); } void addPoint() { ++points; } }
463
0.537797
0.533477
25
17.52
14.851585
58
false
false
0
0
0
0
0
0
0.72
false
false
5
f7521d62f1fa16a740e371e12b683f30ade0b92a
5,403,068,892,359
df22fdddc4d4d61cfb32c73d913a1dc82bc49bc5
/src/ItfGenerator.java
abb8820b115920be46062089779ead9d0d1dc3d2
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
palkeo/objets-dupliques
https://github.com/palkeo/objets-dupliques
4814eb569ed4da4c0bc7778f6778cd1fbfe408d6
1a8f138e3b5880f047facf99197d5194969dde93
refs/heads/master
2020-03-30T14:21:56.932000
2014-01-22T00:57:35
2014-01-22T00:57:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class ItfGenerator { public static void main(String argv[]) { if(argv.length != 1 || argv[0].equals("-h") || argv[0].equals("--help")) { System.out.println("java ItfGenerator <class>"); System.out.println(""); System.out.println("Generate the <class>_itf interface."); return; } try { String class_name = argv[0]; String itf = Generator.generateItf(Class.forName(class_name)); System.out.println(itf); } catch(ClassNotFoundException e) { System.out.println(e); } } }
UTF-8
Java
647
java
ItfGenerator.java
Java
[]
null
[]
public class ItfGenerator { public static void main(String argv[]) { if(argv.length != 1 || argv[0].equals("-h") || argv[0].equals("--help")) { System.out.println("java ItfGenerator <class>"); System.out.println(""); System.out.println("Generate the <class>_itf interface."); return; } try { String class_name = argv[0]; String itf = Generator.generateItf(Class.forName(class_name)); System.out.println(itf); } catch(ClassNotFoundException e) { System.out.println(e); } } }
647
0.514683
0.508501
23
27.130434
24.435015
80
false
false
0
0
0
0
0
0
0.521739
false
false
5
497dae7263b536a5918865ee9d580a5fbe590ce2
14,851,996,942,915
ed1fd608f8d80bd8fe242eaf8da4247cafbe5f50
/app/src/main/java/coms/example/modaservice/adapter/FeaturedPagerAdapter.java
1667cba97653ee846efdb9f49b353f0f31e5de0f
[]
no_license
JMcunst/ModaScheduler
https://github.com/JMcunst/ModaScheduler
7d4f5d6c6314bfcb13070f64d26328637e6094cb
88421c0ac07ca6c1cfd29eb65c24dff6e461ddfb
refs/heads/master
2023-04-19T20:46:45.756000
2021-05-06T11:52:35
2021-05-06T11:52:35
364,890,833
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package coms.example.modaservice.adapter; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import coms.example.modaservice.fragment.FeaturedCalendarFragment; import coms.example.modaservice.fragment.FeaturedNoteFragment; import coms.example.modaservice.fragment.FeaturedScheduleFragment; /** * Scheduler Android App * Created by Angga on 10/7/2015. */ public class FeaturedPagerAdapter extends FragmentPagerAdapter { public FeaturedPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int index) { switch (index) { case 0: return new FeaturedCalendarFragment(); case 1: return new FeaturedNoteFragment(); case 2: return new FeaturedScheduleFragment(); default: return new FeaturedCalendarFragment(); } } @Override public int getCount() { return 3; } }
UTF-8
Java
1,054
java
FeaturedPagerAdapter.java
Java
[ { "context": "gment;\n\n/**\n * Scheduler Android App\n * Created by Angga on 10/7/2015.\n */\npublic class FeaturedPagerAdapt", "end": 427, "score": 0.9993293285369873, "start": 422, "tag": "USERNAME", "value": "Angga" } ]
null
[]
package coms.example.modaservice.adapter; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import coms.example.modaservice.fragment.FeaturedCalendarFragment; import coms.example.modaservice.fragment.FeaturedNoteFragment; import coms.example.modaservice.fragment.FeaturedScheduleFragment; /** * Scheduler Android App * Created by Angga on 10/7/2015. */ public class FeaturedPagerAdapter extends FragmentPagerAdapter { public FeaturedPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int index) { switch (index) { case 0: return new FeaturedCalendarFragment(); case 1: return new FeaturedNoteFragment(); case 2: return new FeaturedScheduleFragment(); default: return new FeaturedCalendarFragment(); } } @Override public int getCount() { return 3; } }
1,054
0.673624
0.663188
40
25.35
22.267185
66
false
false
0
0
0
0
0
0
0.325
false
false
5
ed3e400c595597b8e638696c39e6e1703d1e899f
21,861,383,596,974
34e97457964fa03381f2cdd16f86511185f89cab
/src/com/github/devmanu/automaticbooks/AutomaticBooks.java
86822430ba0468b90ea592967efe0501a2bbd614
[]
no_license
DevManu/AutomaticBooks
https://github.com/DevManu/AutomaticBooks
98417343db652390cefe1a8bf72bb1140652858a
5426517db16b8ac1df6ac140722f8d16d6f932f2
refs/heads/master
2023-01-04T18:52:02.197000
2022-12-26T21:44:16
2022-12-26T21:44:16
208,552,967
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.devmanu.automaticbooks; import com.github.devmanu.automaticbooks.book_openers.*; import com.github.devmanu.automaticbooks.commands.BookCommand; import com.github.devmanu.automaticbooks.events.JoinEvent; import com.github.devmanu.automaticbooks.events.ResourcePackEvent; import stats.Metrics; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitRunnable; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; public class AutomaticBooks extends JavaPlugin { private BookOpener bookOpener; private boolean usingPlaceholderAPI; boolean requiresProtocolLib = true; private File joinBook; private JSONObject joinData; private YamlConfiguration config; private File configFile = new File(getDataFolder() + File.separator + "config.yml"); private static final String VERSION = "3.0"; private Updater updater; @Override public void onEnable() { consoleMessage("§aPlugin enabled."); AutomaticBooksAPI.instance = this; String ver = Bukkit.getVersion(); String[] version = ver.replace(")", "").split("\\."); int v1 = Integer.valueOf(version[1]); int v2 = 0; if (version.length >=3) v2 = Integer.valueOf(version[2]); consoleMessage("" + v2); if (v1 >= 8 && v1 <= 12) bookOpener = new BookOpener_1_8(this); else if (v1 == 13) bookOpener = new BookOpener_1_13(this); else if (v1 == 14 && (v2 == 0 || v2 == 1)) bookOpener = new BookOpener_1_14(this); else { bookOpener = new BookOpener_1_14_2(this); requiresProtocolLib = false; } Bukkit.getPluginManager().registerEvents(new JoinEvent(this), this); Bukkit.getPluginManager().registerEvents(new ResourcePackEvent(this), this); getCommand("book").setExecutor(new BookCommand(this)); Metrics metrics = new Metrics(this, 5715); updater = new Updater(this); reloadPlugin(); if (config.getBoolean("searchForUpdates")) updater.searchForUpdates(); new BukkitRunnable() { @Override public void run() { if (protocolLibError()) { consoleMessage("-------------------------------------"); consoleMessage("§c§lPlease install ProtocolLib!"); consoleMessage("-------------------------------------"); } } }.runTaskLaterAsynchronously(this, 20 * 10); //Config fix if (getConfig().get("resetViewsOnBookChange") == null) { getConfig().set("resetViewsOnBookChange", true); saveConfig(); } if (getConfig().get("messages.openUsage") == null) { getConfig().set("messages.openUsage", "&aOpen the book with /book open"); saveConfig(); } } @Override public void onDisable() { consoleMessage("§cPlugin disabled."); } public void consoleMessage(String msg) { Bukkit.getConsoleSender().sendMessage("§b[AutomaticBooks] §r" + msg); } public ItemStack getEmptyBook() { return bookOpener.getEmptyBook(); } public ItemStack getBook(Player player, List<String> pages, boolean placeholderAPI) { ItemStack book = new ItemStack(Material.WRITTEN_BOOK); BookMeta meta = (BookMeta) book.getItemMeta(); if (meta == null || pages == null) return null; List<String> colored = new ArrayList<String>(); for (String s : pages) { //Official Placeholders s = s.replace("{Player}", player.getName()); s = s.replace("{OnlinePlayers}", Bukkit.getOnlinePlayers().size() + ""); //Placeholder compatibility if (placeholderAPI) s = PlaceholderAPI.setPlaceholders(player, s); colored.add(ChatColor.translateAlternateColorCodes('&', s)); } meta.setPages(colored); meta.setTitle("§eAutomaticBooks"); meta.setDisplayName("§eAutomaticBooks"); meta.setAuthor(player.getName()); book.setItemMeta(meta); return book; } public boolean protocolLibError() { return requiresProtocolLib && !Bukkit.getPluginManager().isPluginEnabled("ProtocolLib"); } public boolean isUsingPlaceholderAPI() { return usingPlaceholderAPI; } public File getJoinBook() { return joinBook; } public BookOpener getBookOpener() { return bookOpener; } @Override public YamlConfiguration getConfig() { return config; } public void reloadPlugin() { if (!configFile.exists()) { saveDefaultConfig(); } //data check File data = new File(getDataFolder() + File.separator + "data"); if (!data.exists() || !data.isDirectory()) data.mkdir(); //data/join.json check joinBook = new File(getDataFolder() + File.separator + "data" + File.separator + "join.json"); new BukkitRunnable() { @Override public void run() { if (!joinBook.exists()) { try { joinBook.createNewFile(); Writer writer = new OutputStreamWriter(new FileOutputStream(joinBook), StandardCharsets.UTF_8); JSONObject obj = new JSONObject(); JSONArray array = new JSONArray(); array.add("&3Welcome to &6&lAutomaticBooks&3.\n\n&2&nCreate your awesome books!\n\n&9Use &9&l/book&9 to start configuring this plugin.\n\n&8Please leave a review!\n\n\n&8&oMade with &c\u2764 &8&oby _Ma_nu_"); obj.put("pages", array); writer.write(obj.toJSONString()); writer.flush(); } catch (IOException e) { e.printStackTrace(); } } try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(joinBook), StandardCharsets.UTF_8)); JSONParser parser = new JSONParser(); joinData = (JSONObject) parser.parse(reader); } catch (IOException | ParseException e) { e.printStackTrace(); } } }.runTaskAsynchronously(this); try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(configFile), StandardCharsets.UTF_8)); config = YamlConfiguration.loadConfiguration(reader); reader.close(); } catch (IOException e) { e.printStackTrace(); } usingPlaceholderAPI = config.getBoolean("usePlaceholderAPI"); if (usingPlaceholderAPI) { if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) consoleMessage("§3PlaceholderAPI detected and successfully activated"); else { consoleMessage("§cPlaceholderAPI not detected. If you want to hide this messages, set usePlaceholderAPI to false in config.yml"); usingPlaceholderAPI = false; } } if (config.getBoolean("searchForUpdates")) updater.searchForUpdates(); else updater.stopSearching(); } public JSONObject getJoinData() { return joinData; } public List<String> getJoinBookPages() { JSONArray array = (JSONArray) joinData.get("pages"); if (array == null) return null; List<String> pages = new ArrayList<String>(); for (Object o : array) pages.add(o.toString()); return pages; } public void sendMessage(Player player, String message) { String msg = config.getString("messages." + message); if (msg == null) { return; } player.sendMessage(ChatColor.translateAlternateColorCodes('&', msg)); } public String getVersion() { return VERSION; } public Updater getUpdater() { return updater; } public void saveConfig() { try { Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(configFile), StandardCharsets.UTF_8)); try { out.write(config.saveToString()); } finally { out.close(); } } catch (IOException e) { e.printStackTrace(); } } public void openJoinBook(Player player) { if (config.getBoolean("usePermission") && !player.hasPermission("AutomaticBooks.join.read")) return; int times = getConfig().getInt("times"); if (times == 0) return; new BukkitRunnable() { @Override public void run() { try { JSONObject obj = getJoinData(); JSONArray array = (JSONArray) obj.get("players"); if (array == null) { array = new JSONArray(); obj.put("players", array); } JSONObject pl = null; for (int i = 0; i < array.size(); i++) { if (((JSONObject) array.get(i)).get("name").equals(player.getName())) { pl = (JSONObject) array.get(i); break; } } if (pl == null) { pl = new JSONObject(); pl.put("name", player.getName()); pl.put("views", 1); array.add(pl); } else { int views = (Integer.parseInt(pl.get("views").toString())); if (times >= 0 && views >= times) { return; } pl.put("views", views + 1); } Writer writer = new OutputStreamWriter(new FileOutputStream(getJoinBook()), StandardCharsets.UTF_8); writer.write(obj.toString()); writer.flush(); writer.close(); getBookOpener().openBook(player, getJoinBookPages()); } catch (IOException e) { e.printStackTrace(); } } }.runTaskLaterAsynchronously(this, getConfig().getInt("delay") * 20); if (player.hasPermission("AutomaticBooks.admin")) { Updater updater = getUpdater(); updater.sendWarning(player); } } }
UTF-8
Java
11,461
java
AutomaticBooks.java
Java
[ { "context": "package com.github.devmanu.automaticbooks;\n\nimport com.github.devmanu.automa", "end": 26, "score": 0.9803116917610168, "start": 19, "tag": "USERNAME", "value": "devmanu" }, { "context": "github.devmanu.automaticbooks;\n\nimport com.github.devmanu.automaticbooks.book_openers.*;\nimport com.github.", "end": 69, "score": 0.9837152361869812, "start": 62, "tag": "USERNAME", "value": "devmanu" }, { "context": ".automaticbooks.book_openers.*;\nimport com.github.devmanu.automaticbooks.commands.BookCommand;\nimport com.g", "end": 126, "score": 0.9873645901679993, "start": 119, "tag": "USERNAME", "value": "devmanu" }, { "context": "aticbooks.commands.BookCommand;\nimport com.github.devmanu.automaticbooks.events.JoinEvent;\nimport com.githu", "end": 189, "score": 0.9834797978401184, "start": 182, "tag": "USERNAME", "value": "devmanu" }, { "context": "utomaticbooks.events.JoinEvent;\nimport com.github.devmanu.automaticbooks.events.ResourcePackEvent;\nimport s", "end": 248, "score": 0.9735445976257324, "start": 241, "tag": "USERNAME", "value": "devmanu" } ]
null
[]
package com.github.devmanu.automaticbooks; import com.github.devmanu.automaticbooks.book_openers.*; import com.github.devmanu.automaticbooks.commands.BookCommand; import com.github.devmanu.automaticbooks.events.JoinEvent; import com.github.devmanu.automaticbooks.events.ResourcePackEvent; import stats.Metrics; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitRunnable; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; public class AutomaticBooks extends JavaPlugin { private BookOpener bookOpener; private boolean usingPlaceholderAPI; boolean requiresProtocolLib = true; private File joinBook; private JSONObject joinData; private YamlConfiguration config; private File configFile = new File(getDataFolder() + File.separator + "config.yml"); private static final String VERSION = "3.0"; private Updater updater; @Override public void onEnable() { consoleMessage("§aPlugin enabled."); AutomaticBooksAPI.instance = this; String ver = Bukkit.getVersion(); String[] version = ver.replace(")", "").split("\\."); int v1 = Integer.valueOf(version[1]); int v2 = 0; if (version.length >=3) v2 = Integer.valueOf(version[2]); consoleMessage("" + v2); if (v1 >= 8 && v1 <= 12) bookOpener = new BookOpener_1_8(this); else if (v1 == 13) bookOpener = new BookOpener_1_13(this); else if (v1 == 14 && (v2 == 0 || v2 == 1)) bookOpener = new BookOpener_1_14(this); else { bookOpener = new BookOpener_1_14_2(this); requiresProtocolLib = false; } Bukkit.getPluginManager().registerEvents(new JoinEvent(this), this); Bukkit.getPluginManager().registerEvents(new ResourcePackEvent(this), this); getCommand("book").setExecutor(new BookCommand(this)); Metrics metrics = new Metrics(this, 5715); updater = new Updater(this); reloadPlugin(); if (config.getBoolean("searchForUpdates")) updater.searchForUpdates(); new BukkitRunnable() { @Override public void run() { if (protocolLibError()) { consoleMessage("-------------------------------------"); consoleMessage("§c§lPlease install ProtocolLib!"); consoleMessage("-------------------------------------"); } } }.runTaskLaterAsynchronously(this, 20 * 10); //Config fix if (getConfig().get("resetViewsOnBookChange") == null) { getConfig().set("resetViewsOnBookChange", true); saveConfig(); } if (getConfig().get("messages.openUsage") == null) { getConfig().set("messages.openUsage", "&aOpen the book with /book open"); saveConfig(); } } @Override public void onDisable() { consoleMessage("§cPlugin disabled."); } public void consoleMessage(String msg) { Bukkit.getConsoleSender().sendMessage("§b[AutomaticBooks] §r" + msg); } public ItemStack getEmptyBook() { return bookOpener.getEmptyBook(); } public ItemStack getBook(Player player, List<String> pages, boolean placeholderAPI) { ItemStack book = new ItemStack(Material.WRITTEN_BOOK); BookMeta meta = (BookMeta) book.getItemMeta(); if (meta == null || pages == null) return null; List<String> colored = new ArrayList<String>(); for (String s : pages) { //Official Placeholders s = s.replace("{Player}", player.getName()); s = s.replace("{OnlinePlayers}", Bukkit.getOnlinePlayers().size() + ""); //Placeholder compatibility if (placeholderAPI) s = PlaceholderAPI.setPlaceholders(player, s); colored.add(ChatColor.translateAlternateColorCodes('&', s)); } meta.setPages(colored); meta.setTitle("§eAutomaticBooks"); meta.setDisplayName("§eAutomaticBooks"); meta.setAuthor(player.getName()); book.setItemMeta(meta); return book; } public boolean protocolLibError() { return requiresProtocolLib && !Bukkit.getPluginManager().isPluginEnabled("ProtocolLib"); } public boolean isUsingPlaceholderAPI() { return usingPlaceholderAPI; } public File getJoinBook() { return joinBook; } public BookOpener getBookOpener() { return bookOpener; } @Override public YamlConfiguration getConfig() { return config; } public void reloadPlugin() { if (!configFile.exists()) { saveDefaultConfig(); } //data check File data = new File(getDataFolder() + File.separator + "data"); if (!data.exists() || !data.isDirectory()) data.mkdir(); //data/join.json check joinBook = new File(getDataFolder() + File.separator + "data" + File.separator + "join.json"); new BukkitRunnable() { @Override public void run() { if (!joinBook.exists()) { try { joinBook.createNewFile(); Writer writer = new OutputStreamWriter(new FileOutputStream(joinBook), StandardCharsets.UTF_8); JSONObject obj = new JSONObject(); JSONArray array = new JSONArray(); array.add("&3Welcome to &6&lAutomaticBooks&3.\n\n&2&nCreate your awesome books!\n\n&9Use &9&l/book&9 to start configuring this plugin.\n\n&8Please leave a review!\n\n\n&8&oMade with &c\u2764 &8&oby _Ma_nu_"); obj.put("pages", array); writer.write(obj.toJSONString()); writer.flush(); } catch (IOException e) { e.printStackTrace(); } } try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(joinBook), StandardCharsets.UTF_8)); JSONParser parser = new JSONParser(); joinData = (JSONObject) parser.parse(reader); } catch (IOException | ParseException e) { e.printStackTrace(); } } }.runTaskAsynchronously(this); try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(configFile), StandardCharsets.UTF_8)); config = YamlConfiguration.loadConfiguration(reader); reader.close(); } catch (IOException e) { e.printStackTrace(); } usingPlaceholderAPI = config.getBoolean("usePlaceholderAPI"); if (usingPlaceholderAPI) { if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) consoleMessage("§3PlaceholderAPI detected and successfully activated"); else { consoleMessage("§cPlaceholderAPI not detected. If you want to hide this messages, set usePlaceholderAPI to false in config.yml"); usingPlaceholderAPI = false; } } if (config.getBoolean("searchForUpdates")) updater.searchForUpdates(); else updater.stopSearching(); } public JSONObject getJoinData() { return joinData; } public List<String> getJoinBookPages() { JSONArray array = (JSONArray) joinData.get("pages"); if (array == null) return null; List<String> pages = new ArrayList<String>(); for (Object o : array) pages.add(o.toString()); return pages; } public void sendMessage(Player player, String message) { String msg = config.getString("messages." + message); if (msg == null) { return; } player.sendMessage(ChatColor.translateAlternateColorCodes('&', msg)); } public String getVersion() { return VERSION; } public Updater getUpdater() { return updater; } public void saveConfig() { try { Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(configFile), StandardCharsets.UTF_8)); try { out.write(config.saveToString()); } finally { out.close(); } } catch (IOException e) { e.printStackTrace(); } } public void openJoinBook(Player player) { if (config.getBoolean("usePermission") && !player.hasPermission("AutomaticBooks.join.read")) return; int times = getConfig().getInt("times"); if (times == 0) return; new BukkitRunnable() { @Override public void run() { try { JSONObject obj = getJoinData(); JSONArray array = (JSONArray) obj.get("players"); if (array == null) { array = new JSONArray(); obj.put("players", array); } JSONObject pl = null; for (int i = 0; i < array.size(); i++) { if (((JSONObject) array.get(i)).get("name").equals(player.getName())) { pl = (JSONObject) array.get(i); break; } } if (pl == null) { pl = new JSONObject(); pl.put("name", player.getName()); pl.put("views", 1); array.add(pl); } else { int views = (Integer.parseInt(pl.get("views").toString())); if (times >= 0 && views >= times) { return; } pl.put("views", views + 1); } Writer writer = new OutputStreamWriter(new FileOutputStream(getJoinBook()), StandardCharsets.UTF_8); writer.write(obj.toString()); writer.flush(); writer.close(); getBookOpener().openBook(player, getJoinBookPages()); } catch (IOException e) { e.printStackTrace(); } } }.runTaskLaterAsynchronously(this, getConfig().getInt("delay") * 20); if (player.hasPermission("AutomaticBooks.admin")) { Updater updater = getUpdater(); updater.sendWarning(player); } } }
11,461
0.550782
0.544494
379
29.21372
29.170851
232
false
false
0
0
0
0
0
0
0.498681
false
false
5
dcdeae7a4eacd4324a0dfe98cf5a39e3e42ad02b
23,381,802,028,964
3195baea39a2dfdbcef1537ef12c9c1f3eb9e7cb
/unison/unison-sdk/src/main/java/com/tremolosecurity/proxy/util/ProxyTools.java
0ca79f1f09eeb17d27b7d06501f2a08d1fb359e0
[ "Apache-2.0" ]
permissive
TremoloSecurity/OpenUnison
https://github.com/TremoloSecurity/OpenUnison
631e89753a9c53f9d4004053ef7b82ae6a210980
bfd5be940b1e611cdb8c5cef7b57a738e91e5a0e
refs/heads/master
2023-08-30T21:56:00.708000
2023-07-25T15:13:35
2023-07-25T15:13:35
37,793,120
79
9
Apache-2.0
false
2023-09-14T15:05:10
2015-06-21T02:03:33
2023-08-08T16:20:46
2023-09-14T15:05:10
8,577
68
9
179
Java
false
false
/* Copyright 2015, 2017 Tremolo Security, 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 com.tremolosecurity.proxy.util; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Iterator; import jakarta.servlet.http.HttpServletRequest; import org.apache.logging.log4j.Logger; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.tremolosecurity.config.util.UrlHolder; import com.tremolosecurity.config.xml.CookieConfigType; import com.tremolosecurity.proxy.filter.HttpFilterRequest; import com.tremolosecurity.proxy.myvd.MyVDConnection; import com.tremolosecurity.saml.Attribute; public class ProxyTools { public static final String OVERRIDE_HOST = "openunison.overridehost"; static Logger logger = org.apache.logging.log4j.LogManager.getLogger(ProxyTools.class); static ProxyTools instance; BigInteger negone; public ProxyTools() { this.negone = BigInteger.valueOf(-1); } public static ProxyTools getInstance() { if (instance == null) { instance = new ProxyTools(); } return instance; } public String getCookieDomain(CookieConfigType cfg,HttpServletRequest request) { //no cookie config, assume host cookie if (cfg == null) { return null;//request.getServerName(); } //if (cfg.getScope().equals(negone)) { if (cfg.getDomain().equalsIgnoreCase("*") || cfg.getDomain().equalsIgnoreCase(request.getServerName())) { return null;//request.getServerName(); } else { return cfg.getDomain(); } //} //TODO add cookie scope work //return ""; } public String getFqdnUrl(String url,HttpServletRequest req) { if (url.startsWith("http")) { return url; //return this.getHttpsUrl(url, req); } else { StringBuffer sb = new StringBuffer(); String fwdProto = req.getHeader("X-Forwarded-Proto"); if (fwdProto == null) { fwdProto = req.getHeader("x-forwarded-proto"); } if (req.isSecure() || (fwdProto != null && fwdProto.startsWith("https"))) { sb.append("https://"); } else { sb.append("http://"); } String overrideHost = (String) req.getAttribute(ProxyTools.OVERRIDE_HOST); if (overrideHost != null) { sb.append(overrideHost); } else { sb.append(req.getServerName()); } String fwdPort = req.getHeader("X-Forwarded-Port"); if (fwdPort == null) { fwdPort = req.getHeader("x-forwarded-port"); } int serverPort = req.getServerPort(); if (fwdPort != null) { try { serverPort = Integer.parseInt(fwdPort); } catch (NumberFormatException e) { logger.warn(new StringBuilder().append("Invalid port '").append(fwdPort).append("'")); } } if (serverPort != 80 && serverPort != 443 && serverPort != -1) { sb.append(':').append(serverPort); } sb.append(url); url = sb.toString(); } return url; } public String getHttpsUrl(String url,HttpServletRequest req) { URL parsedURL = null; try { parsedURL = new URL(url); } catch (MalformedURLException e) { logger.warn("Could not parse " + url,e); } StringBuffer sb = new StringBuffer(); String fwdProto = req.getHeader("X-Forwarded-Proto"); if (fwdProto == null) { fwdProto = req.getHeader("x-forwarded-proto"); } if (req.isSecure() || (fwdProto != null && fwdProto.startsWith("https"))) { sb.append("https://"); } else { sb.append("http://"); } sb.append(parsedURL.getHost()); if (parsedURL.getPort() != 80 && parsedURL.getPort() != 443 && parsedURL.getPort() != -1) { sb.append(':').append(parsedURL.getPort()); } sb.append(parsedURL.getPath()); if (parsedURL.getQuery() != null) { sb.append('?').append(parsedURL.getQuery()); } url = sb.toString(); return url; } public StringBuffer getGETUrl(HttpFilterRequest req, UrlHolder holder, HashMap<String, String> uriParams) { StringBuffer proxyToURL = new StringBuffer(); proxyToURL.append(holder.getProxyURL(uriParams)); return proxyToURL; } /*public String elementToString(Node n) { String name = n.getNodeName(); short type = n.getNodeType(); if (Node.CDATA_SECTION_NODE == type) { return "<![CDATA[" + n.getNodeValue() + "]]&gt;"; } if (name.startsWith("#")) { return ""; } StringBuffer sb = new StringBuffer(); sb.append('<').append(name); NamedNodeMap attrs = n.getAttributes(); if (attrs != null) { for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); sb.append(' ').append(attr.getNodeName()).append("=\"").append(attr.getNodeValue()).append( "\""); } } String textContent = null; NodeList children = n.getChildNodes(); if (children.getLength() == 0) { if ((textContent = XMLUtil.getTextContent(n)) != null && !"".equals(textContent)) { sb.append(textContent).append("</").append(name).append('>'); ; } else { sb.append("/>").append('\n'); } } else { sb.append('>').append('\n'); boolean hasValidChildren = false; for (int i = 0; i < children.getLength(); i++) { String childToString = elementToString(children.item(i)); if (!"".equals(childToString)) { sb.append(childToString); hasValidChildren = true; } } if (!hasValidChildren && ((textContent = XMLUtil.getTextContent(n)) != null)) { sb.append(textContent); } sb.append("</").append(name).append('>'); } return sb.toString(); }*/ }
UTF-8
Java
6,287
java
ProxyTools.java
Java
[]
null
[]
/* Copyright 2015, 2017 Tremolo Security, 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 com.tremolosecurity.proxy.util; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Iterator; import jakarta.servlet.http.HttpServletRequest; import org.apache.logging.log4j.Logger; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.tremolosecurity.config.util.UrlHolder; import com.tremolosecurity.config.xml.CookieConfigType; import com.tremolosecurity.proxy.filter.HttpFilterRequest; import com.tremolosecurity.proxy.myvd.MyVDConnection; import com.tremolosecurity.saml.Attribute; public class ProxyTools { public static final String OVERRIDE_HOST = "openunison.overridehost"; static Logger logger = org.apache.logging.log4j.LogManager.getLogger(ProxyTools.class); static ProxyTools instance; BigInteger negone; public ProxyTools() { this.negone = BigInteger.valueOf(-1); } public static ProxyTools getInstance() { if (instance == null) { instance = new ProxyTools(); } return instance; } public String getCookieDomain(CookieConfigType cfg,HttpServletRequest request) { //no cookie config, assume host cookie if (cfg == null) { return null;//request.getServerName(); } //if (cfg.getScope().equals(negone)) { if (cfg.getDomain().equalsIgnoreCase("*") || cfg.getDomain().equalsIgnoreCase(request.getServerName())) { return null;//request.getServerName(); } else { return cfg.getDomain(); } //} //TODO add cookie scope work //return ""; } public String getFqdnUrl(String url,HttpServletRequest req) { if (url.startsWith("http")) { return url; //return this.getHttpsUrl(url, req); } else { StringBuffer sb = new StringBuffer(); String fwdProto = req.getHeader("X-Forwarded-Proto"); if (fwdProto == null) { fwdProto = req.getHeader("x-forwarded-proto"); } if (req.isSecure() || (fwdProto != null && fwdProto.startsWith("https"))) { sb.append("https://"); } else { sb.append("http://"); } String overrideHost = (String) req.getAttribute(ProxyTools.OVERRIDE_HOST); if (overrideHost != null) { sb.append(overrideHost); } else { sb.append(req.getServerName()); } String fwdPort = req.getHeader("X-Forwarded-Port"); if (fwdPort == null) { fwdPort = req.getHeader("x-forwarded-port"); } int serverPort = req.getServerPort(); if (fwdPort != null) { try { serverPort = Integer.parseInt(fwdPort); } catch (NumberFormatException e) { logger.warn(new StringBuilder().append("Invalid port '").append(fwdPort).append("'")); } } if (serverPort != 80 && serverPort != 443 && serverPort != -1) { sb.append(':').append(serverPort); } sb.append(url); url = sb.toString(); } return url; } public String getHttpsUrl(String url,HttpServletRequest req) { URL parsedURL = null; try { parsedURL = new URL(url); } catch (MalformedURLException e) { logger.warn("Could not parse " + url,e); } StringBuffer sb = new StringBuffer(); String fwdProto = req.getHeader("X-Forwarded-Proto"); if (fwdProto == null) { fwdProto = req.getHeader("x-forwarded-proto"); } if (req.isSecure() || (fwdProto != null && fwdProto.startsWith("https"))) { sb.append("https://"); } else { sb.append("http://"); } sb.append(parsedURL.getHost()); if (parsedURL.getPort() != 80 && parsedURL.getPort() != 443 && parsedURL.getPort() != -1) { sb.append(':').append(parsedURL.getPort()); } sb.append(parsedURL.getPath()); if (parsedURL.getQuery() != null) { sb.append('?').append(parsedURL.getQuery()); } url = sb.toString(); return url; } public StringBuffer getGETUrl(HttpFilterRequest req, UrlHolder holder, HashMap<String, String> uriParams) { StringBuffer proxyToURL = new StringBuffer(); proxyToURL.append(holder.getProxyURL(uriParams)); return proxyToURL; } /*public String elementToString(Node n) { String name = n.getNodeName(); short type = n.getNodeType(); if (Node.CDATA_SECTION_NODE == type) { return "<![CDATA[" + n.getNodeValue() + "]]&gt;"; } if (name.startsWith("#")) { return ""; } StringBuffer sb = new StringBuffer(); sb.append('<').append(name); NamedNodeMap attrs = n.getAttributes(); if (attrs != null) { for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); sb.append(' ').append(attr.getNodeName()).append("=\"").append(attr.getNodeValue()).append( "\""); } } String textContent = null; NodeList children = n.getChildNodes(); if (children.getLength() == 0) { if ((textContent = XMLUtil.getTextContent(n)) != null && !"".equals(textContent)) { sb.append(textContent).append("</").append(name).append('>'); ; } else { sb.append("/>").append('\n'); } } else { sb.append('>').append('\n'); boolean hasValidChildren = false; for (int i = 0; i < children.getLength(); i++) { String childToString = elementToString(children.item(i)); if (!"".equals(childToString)) { sb.append(childToString); hasValidChildren = true; } } if (!hasValidChildren && ((textContent = XMLUtil.getTextContent(n)) != null)) { sb.append(textContent); } sb.append("</").append(name).append('>'); } return sb.toString(); }*/ }
6,287
0.632893
0.627644
261
23.088123
24.21242
108
false
false
0
0
0
0
0
0
2.099617
false
false
5
150ce90e2d8a443a4fd4abf3f00df2a7e196fac0
10,488,310,170,018
fcefa5ea58512f20d07d50d585525982d18b5da5
/cs101/squareRoot/src/SquareRoot/SquareRoot.java
8fc69697dd54487a9a03e882d44f7688e3694570
[]
no_license
spkrpro24/cs101
https://github.com/spkrpro24/cs101
ae8588861b6def815815fcd5841f3075239537ed
4355f2edbac06689c9e3e9cd24eed49bca6eb471
refs/heads/master
2021-01-10T19:01:55.560000
2015-05-07T03:44:33
2015-05-07T03:44:33
29,163,774
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package SquareRoot; public class SquareRoot { //Exercise 7.2 method called squareRoot that takes a double as a parameter //and returns an approximation of the square root of the parameter public static double squareRt(int a) { double i = .000000000000001; double x0 = a / 2; while ((x0 * x0) - a > i) { // # is not equal to //absolute value gives you the magnitude x0 = (x0 + a / x0) / 2; //variable + variable / 2 System.out.println(x0); } return x0; } public static void main(String[] args) { System.out.println(squareRt(9)); } }
UTF-8
Java
575
java
SquareRoot.java
Java
[]
null
[]
package SquareRoot; public class SquareRoot { //Exercise 7.2 method called squareRoot that takes a double as a parameter //and returns an approximation of the square root of the parameter public static double squareRt(int a) { double i = .000000000000001; double x0 = a / 2; while ((x0 * x0) - a > i) { // # is not equal to //absolute value gives you the magnitude x0 = (x0 + a / x0) / 2; //variable + variable / 2 System.out.println(x0); } return x0; } public static void main(String[] args) { System.out.println(squareRt(9)); } }
575
0.653913
0.603478
17
32.823528
31.041216
103
false
false
0
0
0
0
0
0
3.058824
false
false
5
38add0e394377dde2b678a17bedcfd829bd9c19d
21,973,052,749,276
272b696e0cadfbc224730a5beaf0fe82c1c172e7
/annotation/com/lounger/annotation/WebPath.java
0bbca21d7e43f46d70f92a45967414a371fd25fc
[]
no_license
zhangzeyin/Lounger
https://github.com/zhangzeyin/Lounger
620b31dc66bed43a3a012c9089b71597104abec7
f37062d1475c8c02866c5ce6dd02696163dce233
refs/heads/master
2021-01-17T11:23:22.859000
2019-06-09T07:51:49
2019-06-09T07:51:49
84,033,200
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lounger.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * <pre>项目名称:Lounger * 类名称:WebPath * 类描述:说明该类或该方法的访问路径 * @version </pre> */ @Target(value={ElementType.METHOD,ElementType.TYPE}) @Documented @Retention(RetentionPolicy.RUNTIME) public @interface WebPath { String value(); }
UTF-8
Java
550
java
WebPath.java
Java
[]
null
[]
package com.lounger.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * <pre>项目名称:Lounger * 类名称:WebPath * 类描述:说明该类或该方法的访问路径 * @version </pre> */ @Target(value={ElementType.METHOD,ElementType.TYPE}) @Documented @Retention(RetentionPolicy.RUNTIME) public @interface WebPath { String value(); }
550
0.732932
0.732932
21
21.714285
16.189775
52
false
false
0
0
0
0
0
0
0.428571
false
false
5
c8ca139ffa9cee9af806cbd4f21de4eb1bc5e9c6
21,973,052,751,862
74415ff91d88478e23c39268c85a8e5379938e0d
/dbhelper/src/main/java/com/meila/meigou/dbhelper/DataSourceSelector.java
b7ba78a35af0c737de3bfda30022b8893598faa2
[]
no_license
pk07an/db-helper
https://github.com/pk07an/db-helper
90f25ad05fbbc28357c58fbd59643b69abc91883
14eae65d8b40ef2ae30cb5e861d24bbd8c962419
refs/heads/master
2021-01-17T09:59:19.482000
2015-12-14T11:02:58
2015-12-14T11:02:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.meila.meigou.dbhelper; import java.util.List; import javax.sql.DataSource; /** ************************************************************ * @类名 : DataSourceSelector.java * * @DESCRIPTION : * @AUTHOR : flong * @DATE : 2015年11月9日 ************************************************************ */ public interface DataSourceSelector { DataSource select(List<DataSource> slaveDataSources); }
UTF-8
Java
437
java
DataSourceSelector.java
Java
[ { "context": "rceSelector.java\n *\n * @DESCRIPTION :\n * @AUTHOR : flong\n * @DATE : 2015年11月9日\n **************************", "end": 240, "score": 0.9995209574699402, "start": 235, "tag": "USERNAME", "value": "flong" } ]
null
[]
/** * */ package com.meila.meigou.dbhelper; import java.util.List; import javax.sql.DataSource; /** ************************************************************ * @类名 : DataSourceSelector.java * * @DESCRIPTION : * @AUTHOR : flong * @DATE : 2015年11月9日 ************************************************************ */ public interface DataSourceSelector { DataSource select(List<DataSource> slaveDataSources); }
437
0.491803
0.47541
21
19.333334
20.427183
61
false
false
0
0
0
0
0
0
0.190476
false
false
5
648cc83bd601faa50724ba7eeb54311172c33c5f
27,298,812,150,548
fd1b1e6160cf8ec649ad294c4e5ac42c82b331f1
/okul/okul/src/main/java/com/example/okul/service/KantinUrunService.java
3a13c68a23dfa5224fee9d1ecbbe05d8c3df97e6
[]
no_license
bahadir-g/educationalERP
https://github.com/bahadir-g/educationalERP
0e973c48d94ba412751cbf3ae928cf1fef902fa1
fbf8c7e80c701a853f2af341c6fddad480c795c6
refs/heads/master
2023-07-26T04:43:37.317000
2021-09-02T13:30:33
2021-09-02T13:30:33
294,511,425
0
0
null
false
2021-07-12T09:05:08
2020-09-10T20:07:35
2021-07-12T09:00:07
2021-07-12T09:05:07
72
0
0
0
Java
false
false
package com.example.okul.service; import com.example.okul.annotation.TcKimlik; import com.example.okul.base.service.BaseService; import com.example.okul.entity.KantinUrun; import com.example.okul.model.KantinUrunModel; import javax.transaction.Transactional; @Transactional public interface KantinUrunService extends BaseService<KantinUrun, Long> { KantinUrun create(KantinUrunModel kantinUrunModel); KantinUrun update(KantinUrunModel kantinUrunModel); }
UTF-8
Java
468
java
KantinUrunService.java
Java
[]
null
[]
package com.example.okul.service; import com.example.okul.annotation.TcKimlik; import com.example.okul.base.service.BaseService; import com.example.okul.entity.KantinUrun; import com.example.okul.model.KantinUrunModel; import javax.transaction.Transactional; @Transactional public interface KantinUrunService extends BaseService<KantinUrun, Long> { KantinUrun create(KantinUrunModel kantinUrunModel); KantinUrun update(KantinUrunModel kantinUrunModel); }
468
0.82906
0.82906
16
28.25
24.724735
74
false
false
0
0
0
0
0
0
0.5625
false
false
5
9461b2045524677e0d4b22c85b316ae0621992ba
27,298,812,151,415
e05b821b7444185af42400a8b658d46197f55a64
/almoco-ejb/src/main/java/org/marco/almoco/model/RestaurantVisit.java
29adca9bd223dd51542df762e62fc70dfc7376ac
[]
no_license
marcops/JavaEE_Lunch
https://github.com/marcops/JavaEE_Lunch
c46faad7cd09d089fffe2425a77f6836778cce00
e0c9892a59de55d7e73296a8d6d7c5d02dd592ec
refs/heads/master
2016-09-06T08:33:28.581000
2015-08-31T20:35:56
2015-08-31T20:35:56
41,697,301
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.marco.almoco.model; import java.util.Calendar; public class RestaurantVisit { private RestaurantVote restaurant; private Calendar calendar; public RestaurantVisit(RestaurantVote rest) { calendar = Calendar.getInstance(); restaurant = rest; } public RestaurantVote getRestaurantVote() { return restaurant; } public void setRestaurantVote(RestaurantVote restaurant) { this.restaurant = restaurant; } public Calendar getCalendar() { return calendar; } public void setCalendar(Calendar calendar) { this.calendar = calendar; } }
UTF-8
Java
565
java
RestaurantVisit.java
Java
[]
null
[]
package org.marco.almoco.model; import java.util.Calendar; public class RestaurantVisit { private RestaurantVote restaurant; private Calendar calendar; public RestaurantVisit(RestaurantVote rest) { calendar = Calendar.getInstance(); restaurant = rest; } public RestaurantVote getRestaurantVote() { return restaurant; } public void setRestaurantVote(RestaurantVote restaurant) { this.restaurant = restaurant; } public Calendar getCalendar() { return calendar; } public void setCalendar(Calendar calendar) { this.calendar = calendar; } }
565
0.764602
0.764602
26
20.73077
17.575239
59
false
false
0
0
0
0
0
0
1.346154
false
false
5
b88133352c8da1d3a673c7ec76a2e061644a01cf
15,178,414,488,431
300da9bd4740615fafdbd73f62a50eaae5895aa0
/androidApp/app/src/main/java/com/example/seg2105_project/activities/RegisterActivity.java
a12dc9b25f31bbd8bf04b294a51cd98e90ca58ed
[ "MIT" ]
permissive
WeiqiMaster/Project-SEG2105-WalkinClinic
https://github.com/WeiqiMaster/Project-SEG2105-WalkinClinic
5bdf67a1a2fa90c5fc868992edddde74ff11eb3a
af4280f0f856a79863fe8196ca16168eefe00771
refs/heads/master
2022-04-03T06:57:12.057000
2021-05-22T21:30:16
2021-05-22T21:30:16
225,979,987
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.seg2105_project.activities; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Switch; import android.widget.Toast; import com.example.seg2105_project.objects.Employee; import com.example.seg2105_project.objects.Patient; import com.example.seg2105_project.R; import com.example.seg2105_project.objects.User; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.security.NoSuchAlgorithmException; import static com.example.seg2105_project.Hash_256.getSHA; import static com.example.seg2105_project.Hash_256.toHexString; public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{ Switch swIsEmployee; EditText etName, etEmail, etPassword, etConfirmPassword; Button bRegister; User user; DatabaseReference reff; FirebaseAuth mAuth; FirebaseDatabase mDatabase; static long maxId; Employee e; Patient p; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); mAuth = FirebaseAuth.getInstance(); mDatabase = FirebaseDatabase.getInstance(); etName = (EditText) findViewById(R.id.etName); swIsEmployee = (Switch) findViewById(R.id.swIsEmployee); etEmail = (EditText) findViewById(R.id.etEmail); etPassword = (EditText) findViewById(R.id.etPassword); etConfirmPassword = (EditText) findViewById(R.id.etConfirmPassword); bRegister = (Button) findViewById(R.id.bRegister); bRegister.setOnClickListener(this); reff = FirebaseDatabase.getInstance().getReference().child("User"); reff.addValueEventListener((new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { maxId = dataSnapshot.getChildrenCount(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } })); } @Override public void onClick(View v) { String name = etName.getText().toString().trim(); final boolean isEmployee = swIsEmployee.isChecked(); final String email = etEmail.getText().toString().trim(); String password1 = etPassword.getText().toString().trim(); String password2 = etConfirmPassword.getText().toString().trim(); if (name.isEmpty()) { Toast.makeText(getApplicationContext(), "You must enter a name", Toast.LENGTH_LONG).show(); } else if (email.isEmpty()) { Toast.makeText(getApplicationContext(), "You must enter an Email", Toast.LENGTH_LONG).show(); } else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) { etEmail.setError("Please enter a valid email"); etEmail.requestFocus(); } else if (password1.length() < 6 ) { Toast.makeText(getApplicationContext(), "Password has to be at least 6 characters", Toast.LENGTH_LONG).show(); } else if (password1.equals(password2)) { if (isEmployee) { e = new Employee(); e.setEmail(email); e.setName(name); } else { p = new Patient(); p.setEmail(email); p.setName(name); } String password = ""; try { password = toHexString(getSHA(password1)); } catch (NoSuchAlgorithmException e) { } mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { if (isEmployee) { reff = FirebaseDatabase.getInstance().getReference().child("Employee"); reff.child(email.replace(".", "")).setValue(e); } else { reff = FirebaseDatabase.getInstance().getReference().child("Patient"); reff.child(email.replace(".", "")).setValue(p); } //reff; //reff.child(String.valueOf(maxId + 1)).setValue(user); //FirebaseUser fUser = FirebaseAuth.getInstance().getCurrentUser(); Toast.makeText(getApplicationContext(), "You have successfully registered as " + (isEmployee ? "Employee" : "Patient"), Toast.LENGTH_LONG).show(); finish(); } else { Toast.makeText(getApplicationContext(), "Firebase Authentication Error", Toast.LENGTH_LONG).show(); } } }); } else { Toast.makeText(getApplicationContext(), "Two passwords don't match", Toast.LENGTH_LONG).show(); } } }
UTF-8
Java
5,972
java
RegisterActivity.java
Java
[]
null
[]
package com.example.seg2105_project.activities; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Switch; import android.widget.Toast; import com.example.seg2105_project.objects.Employee; import com.example.seg2105_project.objects.Patient; import com.example.seg2105_project.R; import com.example.seg2105_project.objects.User; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.security.NoSuchAlgorithmException; import static com.example.seg2105_project.Hash_256.getSHA; import static com.example.seg2105_project.Hash_256.toHexString; public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{ Switch swIsEmployee; EditText etName, etEmail, etPassword, etConfirmPassword; Button bRegister; User user; DatabaseReference reff; FirebaseAuth mAuth; FirebaseDatabase mDatabase; static long maxId; Employee e; Patient p; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); mAuth = FirebaseAuth.getInstance(); mDatabase = FirebaseDatabase.getInstance(); etName = (EditText) findViewById(R.id.etName); swIsEmployee = (Switch) findViewById(R.id.swIsEmployee); etEmail = (EditText) findViewById(R.id.etEmail); etPassword = (EditText) findViewById(R.id.etPassword); etConfirmPassword = (EditText) findViewById(R.id.etConfirmPassword); bRegister = (Button) findViewById(R.id.bRegister); bRegister.setOnClickListener(this); reff = FirebaseDatabase.getInstance().getReference().child("User"); reff.addValueEventListener((new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { maxId = dataSnapshot.getChildrenCount(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } })); } @Override public void onClick(View v) { String name = etName.getText().toString().trim(); final boolean isEmployee = swIsEmployee.isChecked(); final String email = etEmail.getText().toString().trim(); String password1 = etPassword.getText().toString().trim(); String password2 = etConfirmPassword.getText().toString().trim(); if (name.isEmpty()) { Toast.makeText(getApplicationContext(), "You must enter a name", Toast.LENGTH_LONG).show(); } else if (email.isEmpty()) { Toast.makeText(getApplicationContext(), "You must enter an Email", Toast.LENGTH_LONG).show(); } else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) { etEmail.setError("Please enter a valid email"); etEmail.requestFocus(); } else if (password1.length() < 6 ) { Toast.makeText(getApplicationContext(), "Password has to be at least 6 characters", Toast.LENGTH_LONG).show(); } else if (password1.equals(password2)) { if (isEmployee) { e = new Employee(); e.setEmail(email); e.setName(name); } else { p = new Patient(); p.setEmail(email); p.setName(name); } String password = ""; try { password = toHexString(getSHA(password1)); } catch (NoSuchAlgorithmException e) { } mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { if (isEmployee) { reff = FirebaseDatabase.getInstance().getReference().child("Employee"); reff.child(email.replace(".", "")).setValue(e); } else { reff = FirebaseDatabase.getInstance().getReference().child("Patient"); reff.child(email.replace(".", "")).setValue(p); } //reff; //reff.child(String.valueOf(maxId + 1)).setValue(user); //FirebaseUser fUser = FirebaseAuth.getInstance().getCurrentUser(); Toast.makeText(getApplicationContext(), "You have successfully registered as " + (isEmployee ? "Employee" : "Patient"), Toast.LENGTH_LONG).show(); finish(); } else { Toast.makeText(getApplicationContext(), "Firebase Authentication Error", Toast.LENGTH_LONG).show(); } } }); } else { Toast.makeText(getApplicationContext(), "Two passwords don't match", Toast.LENGTH_LONG).show(); } } }
5,972
0.594441
0.58724
154
37.779221
25.902225
126
false
false
0
0
0
0
0
0
0.636364
false
false
5
e37ba532328133414cf64e34b517e51a9e9f9af7
7,215,545,059,698
5e87e57de855afa2cb774d01301e643e7c26e491
/src/main/java/br/com/caelum/genus/dtos/InfoStatus.java
f4e7c8e805da360c5e6f9df08059097bb8caf2e7
[]
no_license
joviane/genus
https://github.com/joviane/genus
b87673fe47ed80f2c74f010fd3631c0f80c75dd7
5f9610b6008eb622ddb4b025faf2bc67242b7049
refs/heads/master
2021-05-03T17:14:36.438000
2017-05-23T16:05:30
2017-05-23T16:05:30
66,591,907
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.caelum.genus.dtos; import br.com.caelum.genus.models.Status; public class InfoStatus { private Status status; private Integer traineeId; public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public Integer getTraineeId() { return traineeId; } public void setTraineeId(Integer id) { this.traineeId = id; } }
UTF-8
Java
429
java
InfoStatus.java
Java
[]
null
[]
package br.com.caelum.genus.dtos; import br.com.caelum.genus.models.Status; public class InfoStatus { private Status status; private Integer traineeId; public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public Integer getTraineeId() { return traineeId; } public void setTraineeId(Integer id) { this.traineeId = id; } }
429
0.675991
0.675991
27
14.888889
15.24451
42
false
false
0
0
0
0
0
0
0.444444
false
false
5
340ade9847e213f08cbdc64e88b87531da96427d
30,674,656,434,126
6623c6e018b02b09ae75a807850dfe5c6f2fc566
/jeefuse-core/src/main/java/com/jeefuse/base/web/jcaptcha/NumberImageEngine.java
33b48fd84c7dd8ef3aa525fd91c5f2a75d362578
[]
no_license
zhanght86/jeefuseMDA
https://github.com/zhanght86/jeefuseMDA
922e5db028932033a82ba2488f15a36d3eb73e3a
117efc43190c0023d29931f7f80419e2062f84ee
refs/heads/master
2021-05-07T16:13:30.874000
2013-08-20T01:54:37
2013-08-20T01:54:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jeefuse.base.web.jcaptcha; import java.awt.Font; import com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator; import com.octo.captcha.component.image.backgroundgenerator.FunkyBackgroundGenerator; import com.octo.captcha.component.image.color.RandomRangeColorGenerator; import com.octo.captcha.component.image.fontgenerator.FontGenerator; import com.octo.captcha.component.image.fontgenerator.RandomFontGenerator; import com.octo.captcha.component.image.textpaster.RandomTextPaster; import com.octo.captcha.component.image.textpaster.TextPaster; import com.octo.captcha.component.image.wordtoimage.ComposedWordToImage; import com.octo.captcha.component.image.wordtoimage.WordToImage; import com.octo.captcha.component.word.wordgenerator.RandomWordGenerator; import com.octo.captcha.component.word.wordgenerator.WordGenerator; import com.octo.captcha.engine.image.ListImageCaptchaEngine; import com.octo.captcha.image.gimpy.GimpyFactory; /** * 生成数字验证码. * * @author yonclv * @email yonclv@gmail.com */ public class NumberImageEngine extends ListImageCaptchaEngine { final private int minWordLength = 4; final private int maxWordLength = 5; final private int fontSize = 18; final private int imageWidth = 100; final private int imageHeight = 30; @Override protected void buildInitialFactories() { // 随机生成的字符 WordGenerator wgen = new RandomWordGenerator("123456789"); RandomRangeColorGenerator cgen = new RandomRangeColorGenerator(new int[] { 0, 100 }, new int[] { 0, 100 }, new int[] { 0, 100 }); // 文字显示的个数 TextPaster textPaster = new RandomTextPaster(minWordLength, maxWordLength, cgen, true); // 图片的大小 BackgroundGenerator backgroundGenerator = new FunkyBackgroundGenerator(imageWidth, imageHeight); // 字体格式 Font[] fontsList = new Font[] { new Font("Arial", 0, fontSize), new Font("Tahoma", 0, fontSize), new Font("Verdana", 0, fontSize), }; // 文字的大小 FontGenerator fontGenerator = new RandomFontGenerator(fontSize, fontSize, fontsList); WordToImage wordToImage = new ComposedWordToImage(fontGenerator, backgroundGenerator, textPaster); this.addFactory(new GimpyFactory(wgen, wordToImage)); } }
UTF-8
Java
2,300
java
NumberImageEngine.java
Java
[ { "context": "GimpyFactory;\r\n\r\n/**\r\n * 生成数字验证码.\r\n * \r\n * @author yonclv\r\n * @email yonclv@gmail.com\r\n */\r\npublic class Nu", "end": 1029, "score": 0.9997214078903198, "start": 1023, "tag": "USERNAME", "value": "yonclv" }, { "context": "**\r\n * 生成数字验证码.\r\n * \r\n * @author yonclv\r\n * @email yonclv@gmail.com\r\n */\r\npublic class NumberImageEngine extends List", "end": 1057, "score": 0.9999305009841919, "start": 1041, "tag": "EMAIL", "value": "yonclv@gmail.com" } ]
null
[]
package com.jeefuse.base.web.jcaptcha; import java.awt.Font; import com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator; import com.octo.captcha.component.image.backgroundgenerator.FunkyBackgroundGenerator; import com.octo.captcha.component.image.color.RandomRangeColorGenerator; import com.octo.captcha.component.image.fontgenerator.FontGenerator; import com.octo.captcha.component.image.fontgenerator.RandomFontGenerator; import com.octo.captcha.component.image.textpaster.RandomTextPaster; import com.octo.captcha.component.image.textpaster.TextPaster; import com.octo.captcha.component.image.wordtoimage.ComposedWordToImage; import com.octo.captcha.component.image.wordtoimage.WordToImage; import com.octo.captcha.component.word.wordgenerator.RandomWordGenerator; import com.octo.captcha.component.word.wordgenerator.WordGenerator; import com.octo.captcha.engine.image.ListImageCaptchaEngine; import com.octo.captcha.image.gimpy.GimpyFactory; /** * 生成数字验证码. * * @author yonclv * @email <EMAIL> */ public class NumberImageEngine extends ListImageCaptchaEngine { final private int minWordLength = 4; final private int maxWordLength = 5; final private int fontSize = 18; final private int imageWidth = 100; final private int imageHeight = 30; @Override protected void buildInitialFactories() { // 随机生成的字符 WordGenerator wgen = new RandomWordGenerator("123456789"); RandomRangeColorGenerator cgen = new RandomRangeColorGenerator(new int[] { 0, 100 }, new int[] { 0, 100 }, new int[] { 0, 100 }); // 文字显示的个数 TextPaster textPaster = new RandomTextPaster(minWordLength, maxWordLength, cgen, true); // 图片的大小 BackgroundGenerator backgroundGenerator = new FunkyBackgroundGenerator(imageWidth, imageHeight); // 字体格式 Font[] fontsList = new Font[] { new Font("Arial", 0, fontSize), new Font("Tahoma", 0, fontSize), new Font("Verdana", 0, fontSize), }; // 文字的大小 FontGenerator fontGenerator = new RandomFontGenerator(fontSize, fontSize, fontsList); WordToImage wordToImage = new ComposedWordToImage(fontGenerator, backgroundGenerator, textPaster); this.addFactory(new GimpyFactory(wgen, wordToImage)); } }
2,291
0.774888
0.76009
52
40.884617
32.97998
108
false
false
0
0
0
0
0
0
1.788462
false
false
5
f14e2ccff89074741a7ec3727eab6232f35afdf6
30,674,656,437,613
b0264dd107d55b2d1475a04a1475085e243f9210
/RodriguezAlvarezAlejandro/src/uo/sdi/acciones/CancelarSolicitudAction.java
d4d2b7c3e8d1a406f33b6a713510af51324bb64e
[]
no_license
AlejandroRguez/JavaServerPages
https://github.com/AlejandroRguez/JavaServerPages
42e99e64fd6e5ab93aa90b6dc64b16d1fcb4a5f7
e152c171b025b219a42bd1b1dedf2d4aa136ac48
refs/heads/master
2021-01-25T09:08:36.579000
2017-06-08T18:41:18
2017-06-08T18:41:18
93,780,782
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package uo.sdi.acciones; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import uo.sdi.common.StatusInfo; import uo.sdi.model.Trip; import uo.sdi.model.User; import uo.sdi.persistence.ApplicationDao; import uo.sdi.persistence.PersistenceFactory; import uo.sdi.persistence.SeatDao; import uo.sdi.persistence.TripDao; import alb.util.log.Log; public class CancelarSolicitudAction implements Accion { @Override public String execute(HttpServletRequest request, HttpServletResponse response) { String resultado = "EXITO"; Long id =Long.parseLong(request.getParameter("id")); User user = (User) request.getSession().getAttribute("user"); Long [] ids = {user.getId(), id}; ApplicationDao app = PersistenceFactory.newApplicationDao(); SeatDao seat = PersistenceFactory.newSeatDao(); TripDao tdao = PersistenceFactory.newTripDao(); Trip t = tdao.findById(id); if (app.findById(ids) != null){ app.delete(ids); Log.info("Borrada la solicitud del usuario [%s]", user.getLogin()); request.setAttribute("status", new StatusInfo() {{ value = "Su solicitud ha sido eliminada"; }}); } if (seat.findByUserAndTrip(user.getId(), id) != null){ seat.delete(ids); t.setAvailablePax(t.getAvailablePax() + 1); tdao.update(t); Log.info("Borrada la solicitud del usuario [%s]", user.getLogin()); request.setAttribute("status", new StatusInfo() {{ value = "Su solicitud ha sido eliminada"; }}); } return resultado; } }
UTF-8
Java
1,517
java
CancelarSolicitudAction.java
Java
[]
null
[]
package uo.sdi.acciones; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import uo.sdi.common.StatusInfo; import uo.sdi.model.Trip; import uo.sdi.model.User; import uo.sdi.persistence.ApplicationDao; import uo.sdi.persistence.PersistenceFactory; import uo.sdi.persistence.SeatDao; import uo.sdi.persistence.TripDao; import alb.util.log.Log; public class CancelarSolicitudAction implements Accion { @Override public String execute(HttpServletRequest request, HttpServletResponse response) { String resultado = "EXITO"; Long id =Long.parseLong(request.getParameter("id")); User user = (User) request.getSession().getAttribute("user"); Long [] ids = {user.getId(), id}; ApplicationDao app = PersistenceFactory.newApplicationDao(); SeatDao seat = PersistenceFactory.newSeatDao(); TripDao tdao = PersistenceFactory.newTripDao(); Trip t = tdao.findById(id); if (app.findById(ids) != null){ app.delete(ids); Log.info("Borrada la solicitud del usuario [%s]", user.getLogin()); request.setAttribute("status", new StatusInfo() {{ value = "Su solicitud ha sido eliminada"; }}); } if (seat.findByUserAndTrip(user.getId(), id) != null){ seat.delete(ids); t.setAvailablePax(t.getAvailablePax() + 1); tdao.update(t); Log.info("Borrada la solicitud del usuario [%s]", user.getLogin()); request.setAttribute("status", new StatusInfo() {{ value = "Su solicitud ha sido eliminada"; }}); } return resultado; } }
1,517
0.723797
0.723138
49
29.959183
21.394218
70
false
false
0
0
0
0
0
0
2.22449
false
false
5
f5f0efbff2c7c486b521a75609adbc6283d5ec29
10,187,662,473,101
fcc2fd69eea816b621890d9a9ce17e3969ea2ed3
/src/main/java/pl/sda/last/Names.java
699c3e03c1c1aa208a2b0faad350d1c85704183d
[]
no_license
Sebue/-SDA-Servlets-01
https://github.com/Sebue/-SDA-Servlets-01
ac863847a089f0e58b9d94258a518da69123b887
1ced19864eb6c11bfb5b1d7a1e5394d592311cfd
refs/heads/master
2021-06-22T15:17:35.314000
2020-03-01T14:22:25
2020-03-01T14:22:25
199,337,334
0
0
null
false
2021-03-31T21:27:12
2019-07-28T21:08:07
2020-03-01T14:22:49
2021-03-31T21:27:12
19
0
0
2
Java
false
false
package pl.sda.last; import com.google.common.collect.Lists; import java.util.List; public class Names { public static final List<String> FEMALE_NAMES = Lists.newArrayList(); public static final List<String> MALE_NAMES = Lists.newArrayList(); }
UTF-8
Java
256
java
Names.java
Java
[]
null
[]
package pl.sda.last; import com.google.common.collect.Lists; import java.util.List; public class Names { public static final List<String> FEMALE_NAMES = Lists.newArrayList(); public static final List<String> MALE_NAMES = Lists.newArrayList(); }
256
0.746094
0.746094
10
24.6
26.691572
73
false
false
0
0
0
0
0
0
0.5
false
false
5
e0bcf7af17bad87e5b8a0001d0ab180f50f68408
29,145,648,114,782
d585060ae163419adad40a5af224cb9fb63f2dd9
/OnJava8/src/初始化和清理/Mus.java
872922e61e9281a44611cd8b0686de09a25535ac
[]
no_license
NieMinxin/OnJava8
https://github.com/NieMinxin/OnJava8
50e4f8e49b52d8e23792e01b272b6ff09516598a
dabec8ed5c2e8fcc598f99fff5d7953edd8d7000
refs/heads/master
2021-01-13T20:53:55.748000
2020-04-02T15:16:47
2020-04-02T15:16:47
242,491,463
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package 初始化和清理; public class Mus { Mug mug1; Mug mug2; { // [1] mug1 = new Mug(1); mug2 = new Mug(2); System.out.println("mug1 & mug2 initialized"); } Mus() { System.out.println("Mus()"); } Mus(int i) { System.out.println("Mus(int)"); } public static void main(String[] args) { System.out.println("Inside main()"); new Mus(); System.out.println("new Mugs() completed"); new Mus(1); System.out.println("new Mugs(1) completed"); } } class Mug { Mug(int marker) { System.out.println("Mug(" + marker + ")"); } }
UTF-8
Java
658
java
Mus.java
Java
[]
null
[]
package 初始化和清理; public class Mus { Mug mug1; Mug mug2; { // [1] mug1 = new Mug(1); mug2 = new Mug(2); System.out.println("mug1 & mug2 initialized"); } Mus() { System.out.println("Mus()"); } Mus(int i) { System.out.println("Mus(int)"); } public static void main(String[] args) { System.out.println("Inside main()"); new Mus(); System.out.println("new Mugs() completed"); new Mus(1); System.out.println("new Mugs(1) completed"); } } class Mug { Mug(int marker) { System.out.println("Mug(" + marker + ")"); } }
658
0.509288
0.49226
32
19.21875
17.14959
54
false
false
0
0
0
0
0
0
0.53125
false
false
5
180b3b765bd768bf6c18f81a7206b38ae9156fea
30,949,534,344,951
82a1dda1710dfb9180f71342fe4db96bb872a0c9
/toop-commons/src/main/java/eu/toop/commons/usecase/EToopConcept_0_10_7.java
410d6c7d20462ba92fa3a2a9f882219902f95a27
[ "Apache-2.0" ]
permissive
TOOP4EU/toop-commons
https://github.com/TOOP4EU/toop-commons
fbd9028c2cc5b618103ec5ff20d5e3ffde3e2e1d
3fa0e9d0852806483fda772e4fb7cde68b814cf8
refs/heads/master
2021-06-02T02:36:13.253000
2020-03-22T15:40:14
2020-03-22T15:40:14
118,627,918
0
1
Apache-2.0
false
2019-09-23T08:33:55
2018-01-23T15:18:18
2019-09-09T19:20:09
2019-09-23T08:33:54
869
0
1
0
Java
false
false
/** * Copyright (C) 2018-2020 toop.eu * * 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 eu.toop.commons.usecase; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.helger.commons.annotation.Nonempty; import com.helger.commons.lang.EnumHelper; /** * Predefined TOOP concepts for "registered organization". Source * http://wiki.ds.unipi.gr/display/TOOP/National+data+models - all properties * (P) * * @author Philip Helger * @since 0.10.0 * @see EToopConcept for the most update to date concept names */ public enum EToopConcept_0_10_7 implements IToopConcept { ACTIVITY_DESCRIPTION ("activityDescription", EToopConcept.ACTIVITY_DESCRIPTION), BIRTH_DATE ("birthDate", EToopConcept.BIRTH_DATE), CAPTIAL_TYPE ("capitalType", EToopConcept.CAPTIAL_TYPE), COMPANY_CODE ("CompanyCode", EToopConcept.COMPANY_CODE), COMPANY_NAME ("companyName", EToopConcept.COMPANY_NAME), COMPANY_TYPE ("companyType", EToopConcept.COMPANY_TYPE), COUNTRY_NAME ("countryName", EToopConcept.COUNTRY_NAME), EMAIL_ADDRESS ("EmailAddress", EToopConcept.EMAIL_ADDRESS), FAMILY_NAME ("familyName", EToopConcept.FAMILY_NAME), FAX_NUMBER ("FaxNumber", EToopConcept.FAX_NUMBER), FOUNDATION_DATE ("foundationDate", EToopConcept.FOUNDATION_DATE), GIVEN_NAME ("givenName", EToopConcept.GIVEN_NAME), HAS_LEGAL_REPRESENTATIVE ("hasLegalRepresentative", EToopConcept.HAS_LEGAL_REPRESENTATIVE), LEGAL_STATUS ("legalStatus", EToopConcept.LEGAL_STATUS), LEGAL_STATUS_EFFECTIVE_DATE ("legalStatusEffectiveDate", EToopConcept.LEGAL_STATUS_EFFECTIVE_DATE), LOCALITY ("locality", EToopConcept.LOCALITY), NACE_CODE ("naceCode", EToopConcept.NACE_CODE), PERSON ("Person", EToopConcept.PERSON), POSTAL_CODE ("postalCode", EToopConcept.POSTAL_CODE), REGION ("region", EToopConcept.REGION), REGISTERED_ORGANIZATION ("RegisteredOrganization", EToopConcept.REGISTERED_ORGANIZATION), REGISTRATION_AUTH ("RegistrationAuthority", EToopConcept.REGISTRATION_AUTH), REGISTRATION_DATE ("registrationDate", EToopConcept.REGISTRATION_DATE), REGISTRATION_NUMBER ("RegistrationNumber", EToopConcept.REGISTRATION_NUMBER), SOCIAL_SEC_NUMBER ("SSNumber", EToopConcept.SOCIAL_SEC_NUMBER), STREET_ADDRESS ("streetAddress", EToopConcept.STREET_ADDRESS), TELEPHONE_NUMBER ("TelephoneNumber", EToopConcept.TELEPHONE_NUMBER), VAT_NUMBER ("VATNumber", EToopConcept.VAT_NUMBER); private final String m_sID; private final EToopConcept m_eNewConcept; private EToopConcept_0_10_7 (@Nonnull @Nonempty final String sID, @Nonnull final EToopConcept eNewConcept) { m_sID = sID; m_eNewConcept = eNewConcept; } @Nonnull @Nonempty public String getID () { return m_sID; } @Nonnull @Nonempty public String getConceptNamespaceURI () { return SMMDocumentTypeMapping.SMM_DOMAIN_REGISTERED_ORGANIZATION; } @Nonnull public EToopConcept getNewConcept () { return m_eNewConcept; } @Nullable public static EToopConcept_0_10_7 getFromIDOrNull (@Nullable final String sID) { return EnumHelper.getFromIDOrNull (EToopConcept_0_10_7.class, sID); } }
UTF-8
Java
3,642
java
EToopConcept_0_10_7.java
Java
[ { "context": "+data+models - all properties\n * (P)\n *\n * @author Philip Helger\n * @since 0.10.0\n * @see EToopConcept for the mos", "end": 980, "score": 0.9996278882026672, "start": 967, "tag": "NAME", "value": "Philip Helger" } ]
null
[]
/** * Copyright (C) 2018-2020 toop.eu * * 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 eu.toop.commons.usecase; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.helger.commons.annotation.Nonempty; import com.helger.commons.lang.EnumHelper; /** * Predefined TOOP concepts for "registered organization". Source * http://wiki.ds.unipi.gr/display/TOOP/National+data+models - all properties * (P) * * @author <NAME> * @since 0.10.0 * @see EToopConcept for the most update to date concept names */ public enum EToopConcept_0_10_7 implements IToopConcept { ACTIVITY_DESCRIPTION ("activityDescription", EToopConcept.ACTIVITY_DESCRIPTION), BIRTH_DATE ("birthDate", EToopConcept.BIRTH_DATE), CAPTIAL_TYPE ("capitalType", EToopConcept.CAPTIAL_TYPE), COMPANY_CODE ("CompanyCode", EToopConcept.COMPANY_CODE), COMPANY_NAME ("companyName", EToopConcept.COMPANY_NAME), COMPANY_TYPE ("companyType", EToopConcept.COMPANY_TYPE), COUNTRY_NAME ("countryName", EToopConcept.COUNTRY_NAME), EMAIL_ADDRESS ("EmailAddress", EToopConcept.EMAIL_ADDRESS), FAMILY_NAME ("familyName", EToopConcept.FAMILY_NAME), FAX_NUMBER ("FaxNumber", EToopConcept.FAX_NUMBER), FOUNDATION_DATE ("foundationDate", EToopConcept.FOUNDATION_DATE), GIVEN_NAME ("givenName", EToopConcept.GIVEN_NAME), HAS_LEGAL_REPRESENTATIVE ("hasLegalRepresentative", EToopConcept.HAS_LEGAL_REPRESENTATIVE), LEGAL_STATUS ("legalStatus", EToopConcept.LEGAL_STATUS), LEGAL_STATUS_EFFECTIVE_DATE ("legalStatusEffectiveDate", EToopConcept.LEGAL_STATUS_EFFECTIVE_DATE), LOCALITY ("locality", EToopConcept.LOCALITY), NACE_CODE ("naceCode", EToopConcept.NACE_CODE), PERSON ("Person", EToopConcept.PERSON), POSTAL_CODE ("postalCode", EToopConcept.POSTAL_CODE), REGION ("region", EToopConcept.REGION), REGISTERED_ORGANIZATION ("RegisteredOrganization", EToopConcept.REGISTERED_ORGANIZATION), REGISTRATION_AUTH ("RegistrationAuthority", EToopConcept.REGISTRATION_AUTH), REGISTRATION_DATE ("registrationDate", EToopConcept.REGISTRATION_DATE), REGISTRATION_NUMBER ("RegistrationNumber", EToopConcept.REGISTRATION_NUMBER), SOCIAL_SEC_NUMBER ("SSNumber", EToopConcept.SOCIAL_SEC_NUMBER), STREET_ADDRESS ("streetAddress", EToopConcept.STREET_ADDRESS), TELEPHONE_NUMBER ("TelephoneNumber", EToopConcept.TELEPHONE_NUMBER), VAT_NUMBER ("VATNumber", EToopConcept.VAT_NUMBER); private final String m_sID; private final EToopConcept m_eNewConcept; private EToopConcept_0_10_7 (@Nonnull @Nonempty final String sID, @Nonnull final EToopConcept eNewConcept) { m_sID = sID; m_eNewConcept = eNewConcept; } @Nonnull @Nonempty public String getID () { return m_sID; } @Nonnull @Nonempty public String getConceptNamespaceURI () { return SMMDocumentTypeMapping.SMM_DOMAIN_REGISTERED_ORGANIZATION; } @Nonnull public EToopConcept getNewConcept () { return m_eNewConcept; } @Nullable public static EToopConcept_0_10_7 getFromIDOrNull (@Nullable final String sID) { return EnumHelper.getFromIDOrNull (EToopConcept_0_10_7.class, sID); } }
3,635
0.75453
0.745744
98
36.163265
29.910988
108
false
false
0
0
0
0
0
0
0.77551
false
false
5
01cd5149e2678a1e1158c534be7018a28e10d3b2
12,481,175,013,169
75e90bd38aed729c201a0a2466a5c306c4bd0cec
/02_grammar/Ex16.java
a1793774e825ff8a24d069bcb22bf3346dd67390
[]
no_license
wjdghkscks/java_basics_2020
https://github.com/wjdghkscks/java_basics_2020
85ac279188b1ea10a98b5aa768c6661484074a67
ab56f9c9e65c9e45ba3a14dfc66504a76da9b526
refs/heads/master
2022-10-17T04:36:30.841000
2020-06-12T09:07:03
2020-06-12T09:07:03
261,988,075
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Ex16{ public static void main(String[] args){ // 논리 연산자: &&(AND, 논리곱), ||(OR, 논리합), !(NOT, 논리부정)) // 논리 연산자의 대상(들어오는 정보): boolean형, 비교연산, 논리연산 // 논리 연산의 결과는 boolean형으로 도출. 즉, 조건식에서 사용. // || (OR, 논리합): 주어진 조건 중 하나라도 true면 결과는 true // 주어진 조건들 중 true를 만나면 결과는 true // true를 만나면 이후 조건들의 연산은 하지 않음 int su1 = 10; int su2 = 7; boolean result = false; // result를 초기화 result = (su1 >= 7) || (su2 >= 5); // true = true || true System.out.println("결과 : " + result); result = (su1 >= 7) || (su2 <= 5); // true = true || false System.out.println("결과 : " + result); result = (su1 <= 7) || (su2 >= 5); // true = false || true System.out.println("결과 : " + result); result = (su1 <= 7) || (su2 <= 5); // false = false || false System.out.println("결과 : " + result); System.out.println("========================================"); // OR은 true인 조건을 만나면 이후 조건은 연산하지 않음 result = ((su1 = su1 + 2) > su2) || (su1 == (su2 = su2 + 5)); System.out.println("결과 : " + result); System.out.println("su1 : " + su1); System.out.println("su2 : " + su2); System.out.println("========================================"); // ! (NOT, 논리부정): 주어진 논리값을 반대로 출력함 result = true; System.out.println(result); System.out.println(! result); System.out.println(!! result); System.out.println(!!! result); } }
UTF-8
Java
1,665
java
Ex16.java
Java
[]
null
[]
class Ex16{ public static void main(String[] args){ // 논리 연산자: &&(AND, 논리곱), ||(OR, 논리합), !(NOT, 논리부정)) // 논리 연산자의 대상(들어오는 정보): boolean형, 비교연산, 논리연산 // 논리 연산의 결과는 boolean형으로 도출. 즉, 조건식에서 사용. // || (OR, 논리합): 주어진 조건 중 하나라도 true면 결과는 true // 주어진 조건들 중 true를 만나면 결과는 true // true를 만나면 이후 조건들의 연산은 하지 않음 int su1 = 10; int su2 = 7; boolean result = false; // result를 초기화 result = (su1 >= 7) || (su2 >= 5); // true = true || true System.out.println("결과 : " + result); result = (su1 >= 7) || (su2 <= 5); // true = true || false System.out.println("결과 : " + result); result = (su1 <= 7) || (su2 >= 5); // true = false || true System.out.println("결과 : " + result); result = (su1 <= 7) || (su2 <= 5); // false = false || false System.out.println("결과 : " + result); System.out.println("========================================"); // OR은 true인 조건을 만나면 이후 조건은 연산하지 않음 result = ((su1 = su1 + 2) > su2) || (su1 == (su2 = su2 + 5)); System.out.println("결과 : " + result); System.out.println("su1 : " + su1); System.out.println("su2 : " + su2); System.out.println("========================================"); // ! (NOT, 논리부정): 주어진 논리값을 반대로 출력함 result = true; System.out.println(result); System.out.println(! result); System.out.println(!! result); System.out.println(!!! result); } }
1,665
0.523316
0.497409
49
26.571428
22.591311
66
false
false
0
0
0
0
0
0
2.408163
false
false
5
e0f885785997216d0a30ab5d69b2a7951767b0d5
8,065,948,651,634
bf0e182be17069818203c342b9ba917b34617449
/app/src/main/java/com/example/smartenergymonitoring/expense/AddExpenseScreen.java
2e8efb01c759566c07109e3511c45cd0b5329904
[ "MIT" ]
permissive
sumeet22/Smart-Energy-Monitoring
https://github.com/sumeet22/Smart-Energy-Monitoring
8a590aa882dae6ed9ee9631995c9f755f8ee03e7
974ba90fbc2c57b4fe5955f3c168b667ad4684e0
refs/heads/master
2022-12-03T08:44:34.855000
2020-08-21T05:55:25
2020-08-21T05:55:25
289,179,763
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.smartenergymonitoring.expense; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.smartenergymonitoring.R; import com.example.smartenergymonitoring.database.SQLHelper; import com.example.smartenergymonitoring.models.ExpenseModel; import com.example.smartenergymonitoring.util.DateUtil; public class AddExpenseScreen extends AppCompatActivity implements View.OnClickListener { EditText edtTitle,edtDesc,edtAmount; Button btnAdd; String mode,currentTimeStamp; SQLHelper myDb; ExpenseModel _expenseModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_expense_screen); myDb = new SQLHelper(this); currentTimeStamp = DateUtil.getCurrentTimeStamp(); edtTitle = findViewById(R.id.edtTitle); edtDesc = findViewById(R.id.edtDesc); edtAmount = findViewById(R.id.edtAmount); btnAdd = findViewById(R.id.btnAdd); //get data from intent............................... if(getIntent().getExtras() != null){ mode = getIntent().getStringExtra("mode"); } if(getSupportActionBar() != null){ getSupportActionBar().setDisplayHomeAsUpEnabled(true); } //for add mode....................................... if(mode.equals("add")){ getSupportActionBar().setTitle("Create Monthly Bill"); btnAdd.setText("Add"); }else { //for edit mode.................................... getSupportActionBar().setTitle("Edit Monthly Bill"); btnAdd.setText("Update"); _expenseModel = (ExpenseModel) getIntent().getSerializableExtra("model"); if(_expenseModel != null){ edtTitle.setText(_expenseModel.getTitle()); edtDesc.setText(_expenseModel.getDesc()); edtAmount.setText(_expenseModel.getAmount()); } } btnAdd.setOnClickListener(this); } @Override public void onClick(View v) { if(v.getId() == R.id.btnAdd){ if(validate(edtTitle.getText().toString().trim(),edtDesc.getText().toString().trim(),edtAmount.getText().toString().trim())){ ExpenseModel expenseModel = new ExpenseModel(); expenseModel.setTitle(edtTitle.getText().toString().trim()); expenseModel.setDesc(edtDesc.getText().toString().trim()); expenseModel.setAmount(edtAmount.getText().toString().trim()); expenseModel.setTimeStamp(currentTimeStamp); boolean result = false; //for add mode........................................ if(mode.equals("add")){ hideKeyboard(); result = myDb.insertExpenseData(expenseModel); if (result){ ExpenseScreen.isRefresh = true; showToastMessage("Expense Added Successfully."); finish(); } }else { hideKeyboard(); //for edit mode.................................... result = myDb.updateExpenseData(_expenseModel.getId(),expenseModel); if (result){ ExpenseScreen.isRefresh = true; showToastMessage("Expense Updated Successfully."); finish(); } } } } } public boolean validate(String title,String desc,String amount){ boolean result = true; if(title.equals("null") || title.equals("")){ showToastMessage("Please enter title."); result = false; }else if(desc.equals("null") || desc.equals("")){ showToastMessage("Please enter Description."); result = false; }else if(amount.equals("null") || amount.equals("")){ showToastMessage("Please enter Amount."); result = false; } return result; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } //show toaster message................................................................ public void showToastMessage(final String message){ AddExpenseScreen.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(AddExpenseScreen.this,message,Toast.LENGTH_SHORT).show(); } }); } public void hideKeyboard() { try { InputMethodManager inputmanager = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE); if (inputmanager != null) { inputmanager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0); } } catch (Exception var2) { } } }
UTF-8
Java
5,506
java
AddExpenseScreen.java
Java
[]
null
[]
package com.example.smartenergymonitoring.expense; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.smartenergymonitoring.R; import com.example.smartenergymonitoring.database.SQLHelper; import com.example.smartenergymonitoring.models.ExpenseModel; import com.example.smartenergymonitoring.util.DateUtil; public class AddExpenseScreen extends AppCompatActivity implements View.OnClickListener { EditText edtTitle,edtDesc,edtAmount; Button btnAdd; String mode,currentTimeStamp; SQLHelper myDb; ExpenseModel _expenseModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_expense_screen); myDb = new SQLHelper(this); currentTimeStamp = DateUtil.getCurrentTimeStamp(); edtTitle = findViewById(R.id.edtTitle); edtDesc = findViewById(R.id.edtDesc); edtAmount = findViewById(R.id.edtAmount); btnAdd = findViewById(R.id.btnAdd); //get data from intent............................... if(getIntent().getExtras() != null){ mode = getIntent().getStringExtra("mode"); } if(getSupportActionBar() != null){ getSupportActionBar().setDisplayHomeAsUpEnabled(true); } //for add mode....................................... if(mode.equals("add")){ getSupportActionBar().setTitle("Create Monthly Bill"); btnAdd.setText("Add"); }else { //for edit mode.................................... getSupportActionBar().setTitle("Edit Monthly Bill"); btnAdd.setText("Update"); _expenseModel = (ExpenseModel) getIntent().getSerializableExtra("model"); if(_expenseModel != null){ edtTitle.setText(_expenseModel.getTitle()); edtDesc.setText(_expenseModel.getDesc()); edtAmount.setText(_expenseModel.getAmount()); } } btnAdd.setOnClickListener(this); } @Override public void onClick(View v) { if(v.getId() == R.id.btnAdd){ if(validate(edtTitle.getText().toString().trim(),edtDesc.getText().toString().trim(),edtAmount.getText().toString().trim())){ ExpenseModel expenseModel = new ExpenseModel(); expenseModel.setTitle(edtTitle.getText().toString().trim()); expenseModel.setDesc(edtDesc.getText().toString().trim()); expenseModel.setAmount(edtAmount.getText().toString().trim()); expenseModel.setTimeStamp(currentTimeStamp); boolean result = false; //for add mode........................................ if(mode.equals("add")){ hideKeyboard(); result = myDb.insertExpenseData(expenseModel); if (result){ ExpenseScreen.isRefresh = true; showToastMessage("Expense Added Successfully."); finish(); } }else { hideKeyboard(); //for edit mode.................................... result = myDb.updateExpenseData(_expenseModel.getId(),expenseModel); if (result){ ExpenseScreen.isRefresh = true; showToastMessage("Expense Updated Successfully."); finish(); } } } } } public boolean validate(String title,String desc,String amount){ boolean result = true; if(title.equals("null") || title.equals("")){ showToastMessage("Please enter title."); result = false; }else if(desc.equals("null") || desc.equals("")){ showToastMessage("Please enter Description."); result = false; }else if(amount.equals("null") || amount.equals("")){ showToastMessage("Please enter Amount."); result = false; } return result; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } //show toaster message................................................................ public void showToastMessage(final String message){ AddExpenseScreen.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(AddExpenseScreen.this,message,Toast.LENGTH_SHORT).show(); } }); } public void hideKeyboard() { try { InputMethodManager inputmanager = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE); if (inputmanager != null) { inputmanager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0); } } catch (Exception var2) { } } }
5,506
0.564657
0.564294
141
38.056736
26.41748
137
false
false
0
0
0
0
0
0
0.609929
false
false
5
f67113df5823cb9b10a9a9d844cb4ca30425bceb
15,753,940,098,344
27a3ca32bb68b7478981b252470fad5634b8cb15
/spark-executor-protolib/src/test/java/com/streamsets/datacollector/pipeline/executor/spark/yarn/TestSparkExecutorHomeDirectories.java
155e218e4c84465d981f3d19c0f7d566c36b3a82
[ "Apache-2.0" ]
permissive
streamsets/datacollector
https://github.com/streamsets/datacollector
557bedd829a95b34bdb6cb39b220961b88e1ae2d
9f18fa8884fa4254b77349729428e9b0f8a95e4d
refs/heads/master
2020-04-11T02:08:05.997000
2020-04-09T20:27:52
2020-04-10T20:04:55
42,208,696
1,230
731
Apache-2.0
false
2021-03-14T22:08:34
2015-09-09T22:43:02
2021-03-13T21:35:05
2021-03-13T21:35:01
463,198
1,130
607
35
Java
false
false
/* * Copyright 2017 StreamSets 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 com.streamsets.datacollector.pipeline.executor.spark.yarn; import com.streamsets.datacollector.pipeline.executor.spark.SparkDExecutor; import com.streamsets.datacollector.pipeline.executor.spark.SparkExecutor; import com.streamsets.pipeline.api.OnRecordError; import com.streamsets.pipeline.api.StageException; import com.streamsets.pipeline.sdk.ExecutorRunner; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; // Due to a bug in PowerMock, we can't use it to run the test that run the actual executor, // so we use PowerMockRunner only for the methods we need. All others simply use Mockito. // Bug: https://github.com/powermock/powermock/issues/736 // This causes an exception when lambdas are called in YarnLauncher @RunWith(PowerMockRunner.class) @PrepareForTest({YarnAppLauncher.class}) public class TestSparkExecutorHomeDirectories extends BaseSparkExecutorTest { @Test(expected = StageException.class) public void testNoJavaHome() throws Exception { conf.javaHome = ""; PowerMockito.mockStatic(System.class); Mockito.when(System.getenv("JAVA_HOME")).thenReturn(""); SparkExecutor executor = new TestSparkExecutor.ExtendedSparkExecutor(conf); ExecutorRunner runner = new ExecutorRunner.Builder(SparkDExecutor.class, executor) .setOnRecordError(OnRecordError.TO_ERROR) .build(); runner.runInit(); Assert.fail(); } @Test(expected = StageException.class) public void testNoSparkHome() throws Exception { conf.sparkHome = ""; SparkExecutor executor = new TestSparkExecutor.ExtendedSparkExecutor(conf); ExecutorRunner runner = new ExecutorRunner.Builder(SparkDExecutor.class, executor) .setOnRecordError(OnRecordError.TO_ERROR) .build(); runner.runInit(); Assert.fail(); } @Test public void testEnvJavaHome() throws Exception { String javaHome = testFolder.newFolder("java_home").toString(); conf.javaHome = ""; PowerMockito.mockStatic(System.class); Mockito.when(System.getenv("JAVA_HOME")).thenReturn(javaHome); SparkExecutor executor = new TestSparkExecutor.ExtendedSparkExecutor(conf); ExecutorRunner runner = new ExecutorRunner.Builder(SparkDExecutor.class, executor) .setOnRecordError(OnRecordError.TO_ERROR) .build(); runner.runInit(); runner.runDestroy(); } @Test public void testEnvSparkHome() throws Exception { String sparkHome = testFolder.newFolder("spark_home").toString(); conf.sparkHome = ""; PowerMockito.mockStatic(System.class); Mockito.when(System.getenv("SPARK_HOME")).thenReturn(sparkHome); SparkExecutor executor = new TestSparkExecutor.ExtendedSparkExecutor(conf); ExecutorRunner runner = new ExecutorRunner.Builder(SparkDExecutor.class, executor) .setOnRecordError(OnRecordError.TO_ERROR) .build(); runner.runInit(); runner.runDestroy(); } @Test(expected = StageException.class) public void testEnvJavaHomeInaccessible() throws Exception { conf.javaHome = ""; PowerMockito.mockStatic(System.class); Mockito.when(System.getenv("JAVA_HOME")).thenReturn("/not/real"); SparkExecutor executor = new TestSparkExecutor.ExtendedSparkExecutor(conf); ExecutorRunner runner = new ExecutorRunner.Builder(SparkDExecutor.class, executor) .setOnRecordError(OnRecordError.TO_ERROR) .build(); runner.runInit(); Assert.fail(); } @Test(expected = StageException.class) public void testEnvSparkHomeInaccessible() throws Exception { conf.javaHome = ""; PowerMockito.mockStatic(System.class); Mockito.when(System.getenv("SPARK_HOME")).thenReturn("/not/real"); SparkExecutor executor = new TestSparkExecutor.ExtendedSparkExecutor(conf); ExecutorRunner runner = new ExecutorRunner.Builder(SparkDExecutor.class, executor) .setOnRecordError(OnRecordError.TO_ERROR) .build(); runner.runInit(); Assert.fail(); } }
UTF-8
Java
4,764
java
TestSparkExecutorHomeDirectories.java
Java
[ { "context": "rs simply use Mockito.\n// Bug: https://github.com/powermock/powermock/issues/736\n// This causes an exception ", "end": 1464, "score": 0.999521791934967, "start": 1455, "tag": "USERNAME", "value": "powermock" } ]
null
[]
/* * Copyright 2017 StreamSets 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 com.streamsets.datacollector.pipeline.executor.spark.yarn; import com.streamsets.datacollector.pipeline.executor.spark.SparkDExecutor; import com.streamsets.datacollector.pipeline.executor.spark.SparkExecutor; import com.streamsets.pipeline.api.OnRecordError; import com.streamsets.pipeline.api.StageException; import com.streamsets.pipeline.sdk.ExecutorRunner; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; // Due to a bug in PowerMock, we can't use it to run the test that run the actual executor, // so we use PowerMockRunner only for the methods we need. All others simply use Mockito. // Bug: https://github.com/powermock/powermock/issues/736 // This causes an exception when lambdas are called in YarnLauncher @RunWith(PowerMockRunner.class) @PrepareForTest({YarnAppLauncher.class}) public class TestSparkExecutorHomeDirectories extends BaseSparkExecutorTest { @Test(expected = StageException.class) public void testNoJavaHome() throws Exception { conf.javaHome = ""; PowerMockito.mockStatic(System.class); Mockito.when(System.getenv("JAVA_HOME")).thenReturn(""); SparkExecutor executor = new TestSparkExecutor.ExtendedSparkExecutor(conf); ExecutorRunner runner = new ExecutorRunner.Builder(SparkDExecutor.class, executor) .setOnRecordError(OnRecordError.TO_ERROR) .build(); runner.runInit(); Assert.fail(); } @Test(expected = StageException.class) public void testNoSparkHome() throws Exception { conf.sparkHome = ""; SparkExecutor executor = new TestSparkExecutor.ExtendedSparkExecutor(conf); ExecutorRunner runner = new ExecutorRunner.Builder(SparkDExecutor.class, executor) .setOnRecordError(OnRecordError.TO_ERROR) .build(); runner.runInit(); Assert.fail(); } @Test public void testEnvJavaHome() throws Exception { String javaHome = testFolder.newFolder("java_home").toString(); conf.javaHome = ""; PowerMockito.mockStatic(System.class); Mockito.when(System.getenv("JAVA_HOME")).thenReturn(javaHome); SparkExecutor executor = new TestSparkExecutor.ExtendedSparkExecutor(conf); ExecutorRunner runner = new ExecutorRunner.Builder(SparkDExecutor.class, executor) .setOnRecordError(OnRecordError.TO_ERROR) .build(); runner.runInit(); runner.runDestroy(); } @Test public void testEnvSparkHome() throws Exception { String sparkHome = testFolder.newFolder("spark_home").toString(); conf.sparkHome = ""; PowerMockito.mockStatic(System.class); Mockito.when(System.getenv("SPARK_HOME")).thenReturn(sparkHome); SparkExecutor executor = new TestSparkExecutor.ExtendedSparkExecutor(conf); ExecutorRunner runner = new ExecutorRunner.Builder(SparkDExecutor.class, executor) .setOnRecordError(OnRecordError.TO_ERROR) .build(); runner.runInit(); runner.runDestroy(); } @Test(expected = StageException.class) public void testEnvJavaHomeInaccessible() throws Exception { conf.javaHome = ""; PowerMockito.mockStatic(System.class); Mockito.when(System.getenv("JAVA_HOME")).thenReturn("/not/real"); SparkExecutor executor = new TestSparkExecutor.ExtendedSparkExecutor(conf); ExecutorRunner runner = new ExecutorRunner.Builder(SparkDExecutor.class, executor) .setOnRecordError(OnRecordError.TO_ERROR) .build(); runner.runInit(); Assert.fail(); } @Test(expected = StageException.class) public void testEnvSparkHomeInaccessible() throws Exception { conf.javaHome = ""; PowerMockito.mockStatic(System.class); Mockito.when(System.getenv("SPARK_HOME")).thenReturn("/not/real"); SparkExecutor executor = new TestSparkExecutor.ExtendedSparkExecutor(conf); ExecutorRunner runner = new ExecutorRunner.Builder(SparkDExecutor.class, executor) .setOnRecordError(OnRecordError.TO_ERROR) .build(); runner.runInit(); Assert.fail(); } }
4,764
0.746432
0.743913
127
36.51181
28.63093
91
false
false
0
0
0
0
0
0
0.535433
false
false
5
60fa6bb39f9658985e19d4574e193ecc59445e59
15,753,940,095,692
2f92dfff9b9929b64e645fdc254815d06bf2b8d2
/src/test/test/lee/codetest/code_863__All_Nodes_Distance_K_in_Binary_Tree/CodeTest.java
c5b3a7064631ae1747bda4700ec76875a355f163
[ "MIT" ]
permissive
code543/leetcodequestions
https://github.com/code543/leetcodequestions
fc5036d63e4c3e1b622fe73552fb33c039e63fb0
44cbfe6718ada04807b6600a5d62b9f0016d4ab2
refs/heads/master
2020-04-05T19:43:15.530000
2018-12-07T04:09:07
2018-12-07T04:09:07
157,147,529
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lee.codetest.code_863__All_Nodes_Distance_K_in_Binary_Tree; import org.junit.Test; /** testcase:[3,5,1,6,2,0,8,null,null,7,4] 5 2 */ public class CodeTest { @Test public void testSolution() throws Exception { //new Solution() lee.code.code_863__All_Nodes_Distance_K_in_Binary_Tree.C863_MainClass.main(null);; } } /** * * * 863.All Nodes Distance K in Binary Tree * * difficulty: Medium * @see https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/description/ * @see description_863.md * @Similiar Topics * -->Tree https://leetcode.com//tag/tree * -->Breadth-first Search https://leetcode.com//tag/breadth-first-search * -->Depth-first Search https://leetcode.com//tag/depth-first-search * @Similiar Problems * Run solution from Unit Test: * @see lee.codetest.code_863__All_Nodes_Distance_K_in_Binary_Tree.CodeTest * Run solution from Main Judge Class: * @see lee.code.code_863__All_Nodes_Distance_K_in_Binary_Tree.C863_MainClass * */
UTF-8
Java
1,005
java
CodeTest.java
Java
[]
null
[]
package lee.codetest.code_863__All_Nodes_Distance_K_in_Binary_Tree; import org.junit.Test; /** testcase:[3,5,1,6,2,0,8,null,null,7,4] 5 2 */ public class CodeTest { @Test public void testSolution() throws Exception { //new Solution() lee.code.code_863__All_Nodes_Distance_K_in_Binary_Tree.C863_MainClass.main(null);; } } /** * * * 863.All Nodes Distance K in Binary Tree * * difficulty: Medium * @see https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/description/ * @see description_863.md * @Similiar Topics * -->Tree https://leetcode.com//tag/tree * -->Breadth-first Search https://leetcode.com//tag/breadth-first-search * -->Depth-first Search https://leetcode.com//tag/depth-first-search * @Similiar Problems * Run solution from Unit Test: * @see lee.codetest.code_863__All_Nodes_Distance_K_in_Binary_Tree.CodeTest * Run solution from Main Judge Class: * @see lee.code.code_863__All_Nodes_Distance_K_in_Binary_Tree.C863_MainClass * */
1,005
0.696517
0.661692
36
26.861111
28.130798
85
false
false
0
0
0
0
0
0
0.444444
false
false
5
64af036fdc49872afa32b327d9713bb6b4a6a46e
15,753,940,095,768
4dbbaed60c520d07ccae9508c185ef1ae7fb1fbb
/seating/src/main/java/com/project/java/seating/tools/JsonTools.java
cd888068fb5e0dcb143881208ca0439cb6a5de36
[]
no_license
cestzen/seatingProject
https://github.com/cestzen/seatingProject
66627b52423c16c8fbbf90b554f28e0757e70b68
a061f9f8faea7ceeb86685a0a2065983466850ba
refs/heads/master
2021-05-08T05:51:26.292000
2017-12-07T13:23:42
2017-12-07T13:23:42
106,523,717
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.project.java.seating.tools; import java.io.ByteArrayOutputStream; import java.io.IOException; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonTools<T> { private Class<T> type; public JsonTools(Class<T> type) { super(); this.type = type; } public String createJson(T object) { ObjectMapper mapper = new ObjectMapper(); ByteArrayOutputStream str = new ByteArrayOutputStream(); ; // Object to JSON in file try { mapper.writeValue(str, object); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } final byte[] data = str.toByteArray(); // Object to JSON in String return new String(data); } public T createObject(String json){ ObjectMapper mapper = new ObjectMapper(); try { return mapper.readValue(json, type); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
UTF-8
Java
986
java
JsonTools.java
Java
[]
null
[]
package com.project.java.seating.tools; import java.io.ByteArrayOutputStream; import java.io.IOException; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonTools<T> { private Class<T> type; public JsonTools(Class<T> type) { super(); this.type = type; } public String createJson(T object) { ObjectMapper mapper = new ObjectMapper(); ByteArrayOutputStream str = new ByteArrayOutputStream(); ; // Object to JSON in file try { mapper.writeValue(str, object); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } final byte[] data = str.toByteArray(); // Object to JSON in String return new String(data); } public T createObject(String json){ ObjectMapper mapper = new ObjectMapper(); try { return mapper.readValue(json, type); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
986
0.669371
0.669371
44
20.40909
16.926739
58
false
false
0
0
0
0
0
0
1.818182
false
false
5
23c554702c6471f0ed1184ed044cf7bd1736fe48
15,436,112,529,496
fd38ecd08f2e64357ff90b94d8205a7ad8f2168d
/src/test/java/com/example/ChessNew/FenAPITest.java
de4a0a1f7b3f260f57eab33542ee2e2385c2268d
[]
no_license
CezaryKretkowski/NewChess
https://github.com/CezaryKretkowski/NewChess
eb8916b7d5d44e4a1bba61dbd25dd8d8fd97ecac
c967b7250afef184231e2cf7c8f3ee92e8a53858
refs/heads/master
2023-08-22T15:16:25.006000
2021-10-07T12:53:35
2021-10-07T12:53:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.ChessNew; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import com.example.ChessNew.Api.Fen; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import static org.junit.Assert.assertTrue; public class FenAPITest { public Boolean checkFen(List<String> posytion){ Iterator<String> i=posytion.listIterator(); int w=0; boolean check =true; CheackingLoop:while(i.hasNext()) { String startFen=i.next(); startFen+="/"; Fen test=new Fen(startFen); String fen = test.tabToFen(test.fenToTab()); w++; if (!startFen.equals(fen)) check =false; break CheackingLoop; } return check; } public Boolean checkFen1(List<String> posytion){ Iterator<String> i=posytion.listIterator(); Fen test=new Fen(); int w=0; boolean check =true; CheackingLoop:while(i.hasNext()) { String startFen=i.next(); startFen+="/"; String fen = test.tabToFen(test.fenToTab(startFen)); w++; if (!startFen.equals(fen)) check =false; break CheackingLoop; } return check; } @Test @Order(1) public void testFen(){ List<String> posytion = new LinkedList<String>(); posytion.add("8/1bRq4/P5R1/1NP5/3pPk2/3Pp3/7K/Qr2B3"); posytion.add("3b2n1/3P1pr1/pp5p/6P1/1k6/1N1RQ3/5P1K/3r4"); posytion.add("3N4/K2k1P2/2p5/2PPp2P/1rp5/2Pb1Q2/1B6/5N2"); posytion.add("2b5/1pk5/4Pn2/2pP1KP1/1P1p4/P1p1b2N/5P2/8"); posytion.add("6b1/7Q/3p2n1/1KpP1p2/1B2p2p/P7/2R1P3/5n1k"); assertTrue(checkFen(posytion)); assertTrue(checkFen1(posytion)); } @Test @Order(2) public void testFen1(){ List<String> posytion = new LinkedList<String>(); posytion.add("8/1bRq4/P5R1/1NP5/3pPk2/3Pp3/7K/Qr2B3"); posytion.add("3b2n1/3P1pr1/pp5p/6P1/1k6/1N1RQ3/5P1K/3r4"); posytion.add("3N4/K2k1P2/2p5/2PPp2P/1rp5/2Pb1Q2/1B6/5N2"); posytion.add("2b5/1pk5/4Pn2/2pP1KP1/1P1p4/P1p1b2N/5P2/8"); posytion.add("6b1/7Q/3p2n1/1KpP1p2/1B2p2p/P7/2R1P3/5n1k"); assertTrue(checkFen1(posytion)); } }
UTF-8
Java
2,327
java
FenAPITest.java
Java
[]
null
[]
package com.example.ChessNew; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import com.example.ChessNew.Api.Fen; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import static org.junit.Assert.assertTrue; public class FenAPITest { public Boolean checkFen(List<String> posytion){ Iterator<String> i=posytion.listIterator(); int w=0; boolean check =true; CheackingLoop:while(i.hasNext()) { String startFen=i.next(); startFen+="/"; Fen test=new Fen(startFen); String fen = test.tabToFen(test.fenToTab()); w++; if (!startFen.equals(fen)) check =false; break CheackingLoop; } return check; } public Boolean checkFen1(List<String> posytion){ Iterator<String> i=posytion.listIterator(); Fen test=new Fen(); int w=0; boolean check =true; CheackingLoop:while(i.hasNext()) { String startFen=i.next(); startFen+="/"; String fen = test.tabToFen(test.fenToTab(startFen)); w++; if (!startFen.equals(fen)) check =false; break CheackingLoop; } return check; } @Test @Order(1) public void testFen(){ List<String> posytion = new LinkedList<String>(); posytion.add("8/1bRq4/P5R1/1NP5/3pPk2/3Pp3/7K/Qr2B3"); posytion.add("3b2n1/3P1pr1/pp5p/6P1/1k6/1N1RQ3/5P1K/3r4"); posytion.add("3N4/K2k1P2/2p5/2PPp2P/1rp5/2Pb1Q2/1B6/5N2"); posytion.add("2b5/1pk5/4Pn2/2pP1KP1/1P1p4/P1p1b2N/5P2/8"); posytion.add("6b1/7Q/3p2n1/1KpP1p2/1B2p2p/P7/2R1P3/5n1k"); assertTrue(checkFen(posytion)); assertTrue(checkFen1(posytion)); } @Test @Order(2) public void testFen1(){ List<String> posytion = new LinkedList<String>(); posytion.add("8/1bRq4/P5R1/1NP5/3pPk2/3Pp3/7K/Qr2B3"); posytion.add("3b2n1/3P1pr1/pp5p/6P1/1k6/1N1RQ3/5P1K/3r4"); posytion.add("3N4/K2k1P2/2p5/2PPp2P/1rp5/2Pb1Q2/1B6/5N2"); posytion.add("2b5/1pk5/4Pn2/2pP1KP1/1P1p4/P1p1b2N/5P2/8"); posytion.add("6b1/7Q/3p2n1/1KpP1p2/1B2p2p/P7/2R1P3/5n1k"); assertTrue(checkFen1(posytion)); } }
2,327
0.604641
0.527288
80
28.0875
22.322742
66
false
false
0
0
0
0
0
0
0.5625
false
false
5
5e583ee22c3f0d14f99bd07df8b0258bf2b91089
24,103,356,474,223
c43d71dc2ae3a19742b75035456b9619d28458df
/src/ideogram/r/exceptions/InvalidInputException.java
9742c20a469700c9fe440e3f2210958e183988ac
[ "CC-BY-2.5" ]
permissive
sysbio-bioinf/IdeogramBrowser
https://github.com/sysbio-bioinf/IdeogramBrowser
32bd8092c921f3cd5d477c4571cf66c77888e221
68b96b55212fcdc5b4a8ac8bed15ad8baa110a17
refs/heads/master
2021-01-10T20:20:38.874000
2013-04-24T10:31:13
2013-04-24T10:31:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * File: InvalidInputException.java * * Created: 10.12.2007 * * Author: Ferdinand Hofherr <ferdinand.hofherr@uni-ulm.de> */ package ideogram.r.exceptions; /** * TODO INSERT DOCUMENTATION HERE! * * @author Ferdinand Hofherr * */ public class InvalidInputException extends Exception { /** * INSERT DOCUMENTATION HERE! * */ public InvalidInputException() { // TODO Auto-generated constructor stub } /** * INSERT DOCUMENTATION HERE! * * @param message */ public InvalidInputException(String message) { super(message); // TODO Auto-generated constructor stub } /** * INSERT DOCUMENTATION HERE! * * @param cause */ public InvalidInputException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } /** * INSERT DOCUMENTATION HERE! * * @param message * @param cause */ public InvalidInputException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } }
UTF-8
Java
1,077
java
InvalidInputException.java
Java
[ { "context": "n.java\n * \n * Created: \t10.12.2007\n * \n * Author:\tFerdinand Hofherr <ferdinand.hofherr@uni-ulm.de>\n */\npackage ideogr", "end": 99, "score": 0.9998875856399536, "start": 82, "tag": "NAME", "value": "Ferdinand Hofherr" }, { "context": "ed: \t10.12.2007\n * \n * Author:\tFerdinand Hofherr <ferdinand.hofherr@uni-ulm.de>\n */\npackage ideogram.r.exceptions;\n\n/**\n * TODO ", "end": 129, "score": 0.9999315738677979, "start": 101, "tag": "EMAIL", "value": "ferdinand.hofherr@uni-ulm.de" }, { "context": "\n * TODO INSERT DOCUMENTATION HERE!\n * \n * @author Ferdinand Hofherr\n * \n */\npublic class InvalidInputException extend", "end": 238, "score": 0.9998875856399536, "start": 221, "tag": "NAME", "value": "Ferdinand Hofherr" } ]
null
[]
/* * File: InvalidInputException.java * * Created: 10.12.2007 * * Author: <NAME> <<EMAIL>> */ package ideogram.r.exceptions; /** * TODO INSERT DOCUMENTATION HERE! * * @author <NAME> * */ public class InvalidInputException extends Exception { /** * INSERT DOCUMENTATION HERE! * */ public InvalidInputException() { // TODO Auto-generated constructor stub } /** * INSERT DOCUMENTATION HERE! * * @param message */ public InvalidInputException(String message) { super(message); // TODO Auto-generated constructor stub } /** * INSERT DOCUMENTATION HERE! * * @param cause */ public InvalidInputException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } /** * INSERT DOCUMENTATION HERE! * * @param message * @param cause */ public InvalidInputException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } }
1,034
0.629526
0.622098
57
17.894737
17.632391
67
false
false
0
0
0
0
0
0
0.280702
false
false
5
a469af0116754805599cf18f20964975add36893
16,501,264,364,375
abf0d5b3837222273505a047cc2c0f3594c49269
/src/Node/ORFNode.java
327a84a4dd08f5ffa1fbc5a223ec757f266b3a64
[]
no_license
taoliu/HMMRATAC
https://github.com/taoliu/HMMRATAC
6d7dee5ec7f72902e7d4228c6de94caaabc06e50
12ab40038ca2082ea976901cd24f58d90fb1f94b
refs/heads/master
2020-04-17T18:40:14.819000
2019-01-22T08:15:11
2019-01-22T08:15:11
166,836,230
2
0
null
true
2019-01-21T15:25:34
2019-01-21T15:25:34
2019-01-20T19:01:15
2019-01-20T19:01:13
28,404
0
0
0
null
false
null
package Node; public class ORFNode { private String Chrom = ""; private int Start = 0; private int Stop = 0; private int Direction = 0; private String ID = ""; private double FPKM = 0.0; public ORFNode(){ } public ORFNode(String chr,int start,int stop,int dir,String name,double fpkm) { Chrom = chr; Start = start; Stop = stop; Direction = dir; ID = name; FPKM = fpkm; } public double getFPKM(){ return FPKM; } public void setFPKM(double fpkm){ FPKM = fpkm; } public String getChrom(){ return Chrom; } public void setChrom(String chr){ Chrom = chr; } public int getStart(){ return Start; } public void setStart(int start){ Start = start; } public int getStop(){ return Stop; } public void setStop(int stop){ Stop = stop; } public int getDir(){ return Direction; } public void setDir(int dir){ Direction = dir; } public String getID(){ return ID; } public void setID(String name){ ID = name; } }
UTF-8
Java
1,119
java
ORFNode.java
Java
[]
null
[]
package Node; public class ORFNode { private String Chrom = ""; private int Start = 0; private int Stop = 0; private int Direction = 0; private String ID = ""; private double FPKM = 0.0; public ORFNode(){ } public ORFNode(String chr,int start,int stop,int dir,String name,double fpkm) { Chrom = chr; Start = start; Stop = stop; Direction = dir; ID = name; FPKM = fpkm; } public double getFPKM(){ return FPKM; } public void setFPKM(double fpkm){ FPKM = fpkm; } public String getChrom(){ return Chrom; } public void setChrom(String chr){ Chrom = chr; } public int getStart(){ return Start; } public void setStart(int start){ Start = start; } public int getStop(){ return Stop; } public void setStop(int stop){ Stop = stop; } public int getDir(){ return Direction; } public void setDir(int dir){ Direction = dir; } public String getID(){ return ID; } public void setID(String name){ ID = name; } }
1,119
0.56479
0.560322
68
14.455882
13.291344
79
false
false
0
0
0
0
0
0
2.558824
false
false
5
21cb25b55a9feb45dc9e71e7651e44fa5d1aa2dd
6,657,199,329,267
968d32923e006a813486b6325cb406c06e6e2350
/spring-boot-01-helloworld-quick/src/main/java/com/tyron/springboot/controller/HelloController.java
9845a95f7003baf1542c918962408d0b7de45976
[]
no_license
ssesal/spring-boot-learning
https://github.com/ssesal/spring-boot-learning
d91cdce0ec74a1e4b6fadcd8dad3f003af38beb8
414f3c47a365e2b57eda558a9806bc7135a0901a
refs/heads/master
2023-03-17T10:34:06.276000
2021-01-26T14:16:23
2021-01-26T14:16:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tyron.springboot.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; /** * @Description: hello控制类 * @Author: tyron * @date: 2019/1/20 */ //@Controller //@ResponseBody @RestController public class HelloController { @RequestMapping("hello") public String hello() { return "hello world quick!"; } }
UTF-8
Java
538
java
HelloController.java
Java
[ { "context": "roller;\n\n/**\n * @Description: hello控制类\n * @Author: tyron\n * @date: 2019/1/20\n */\n//@Controller\n//@Response", "end": 327, "score": 0.9996763467788696, "start": 322, "tag": "USERNAME", "value": "tyron" } ]
null
[]
package com.tyron.springboot.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; /** * @Description: hello控制类 * @Author: tyron * @date: 2019/1/20 */ //@Controller //@ResponseBody @RestController public class HelloController { @RequestMapping("hello") public String hello() { return "hello world quick!"; } }
538
0.755639
0.742481
22
23.181818
20.352879
62
false
false
0
0
0
0
0
0
0.272727
false
false
5
c95c7d62486f87a82601f78303e66d51ac9445fa
22,428,319,285,561
38086a7d5d1cf7de70c62104b8ab507073580324
/app/src/main/java/com/sample/sample/volley/VolleyRequestHandler.java
d3b70444452897b910a7f2b75e7d9b0824d76437
[]
no_license
kcsteve66/weather_lookup
https://github.com/kcsteve66/weather_lookup
8c4d8329906b1fdf2f56a7a2b1c8d7f538f206f4
1cd2412176594e31b3b5e7a5da41610c86f00332
refs/heads/master
2021-01-20T07:23:08.486000
2017-05-02T05:51:05
2017-05-02T05:51:05
89,995,527
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sample.sample.volley; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.sample.sample.AppController; import com.sample.sample.interfaces.VolleyRequestListener; import org.json.JSONException; import org.json.JSONObject; public class VolleyRequestHandler { public static void getJsonObject(final VolleyRequestListener listener, final ProgressBar progressBar, String url, String tag) { showProgressBar(progressBar); // Pass third argument as "null" for GET requests. JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { Log.i("Response:%n %s", response.toString(4)); hideProgressBar(progressBar); listener.onVolleyJsonObjectResponse(response); } catch (JSONException e) { Log.e("Error: ", e.getMessage()); hideProgressBar(progressBar); listener.onVolleyErrorResponse(e.getMessage()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { String errorMsg = ""; if (error.getMessage() != null) { Log.e("Error: ", error.getMessage()); errorMsg = error.getMessage(); } else { errorMsg = "Error processing request."; } hideProgressBar(progressBar); listener.onVolleyErrorResponse(errorMsg); } }); // Add the request object to the queue to be executed. AppController.getInstance().addToRequestQueue(req, tag); } public static void postJsonObject() { } private static void showProgressBar(ProgressBar progressBar) { if (progressBar != null) progressBar.setVisibility(View.VISIBLE); } private static void hideProgressBar(ProgressBar progressBar) { if (progressBar != null) progressBar.setVisibility(View.GONE); } }
UTF-8
Java
2,566
java
VolleyRequestHandler.java
Java
[]
null
[]
package com.sample.sample.volley; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.sample.sample.AppController; import com.sample.sample.interfaces.VolleyRequestListener; import org.json.JSONException; import org.json.JSONObject; public class VolleyRequestHandler { public static void getJsonObject(final VolleyRequestListener listener, final ProgressBar progressBar, String url, String tag) { showProgressBar(progressBar); // Pass third argument as "null" for GET requests. JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { Log.i("Response:%n %s", response.toString(4)); hideProgressBar(progressBar); listener.onVolleyJsonObjectResponse(response); } catch (JSONException e) { Log.e("Error: ", e.getMessage()); hideProgressBar(progressBar); listener.onVolleyErrorResponse(e.getMessage()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { String errorMsg = ""; if (error.getMessage() != null) { Log.e("Error: ", error.getMessage()); errorMsg = error.getMessage(); } else { errorMsg = "Error processing request."; } hideProgressBar(progressBar); listener.onVolleyErrorResponse(errorMsg); } }); // Add the request object to the queue to be executed. AppController.getInstance().addToRequestQueue(req, tag); } public static void postJsonObject() { } private static void showProgressBar(ProgressBar progressBar) { if (progressBar != null) progressBar.setVisibility(View.VISIBLE); } private static void hideProgressBar(ProgressBar progressBar) { if (progressBar != null) progressBar.setVisibility(View.GONE); } }
2,566
0.583788
0.583398
72
34.638889
26.642857
131
false
false
0
0
0
0
0
0
0.555556
false
false
5
58d20f5b25620d1ee43f04a03ecdc0cf32b3e259
12,773,232,739,005
9e6d5c8e23a79eb4948dba2aa3e0a7146b2f7994
/day15AsyncLoader/src/main/java/com/example/day15asyncloader/ContactAdapter.java
015db6f3ebf01ed5eb218f54e59c1a7d46b2d371
[]
no_license
hezijie1234/QianFengMyApplication
https://github.com/hezijie1234/QianFengMyApplication
e6a5256c6c2daa8c5b1fff1dc676f88a4e65e622
6f88dcc48f8315962e79deafad014baccfce9382
refs/heads/master
2021-01-25T14:23:36.703000
2018-03-03T13:13:46
2018-03-03T13:13:46
123,692,983
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.day15asyncloader; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class ContactAdapter extends BaseAdapter{ private List<MyContacts> mDataList; private Context context; private LayoutInflater inflater; public ContactAdapter(Context context,List<MyContacts> list){ this.mDataList = list; inflater = LayoutInflater.from(context); } @Override public int getCount() { return mDataList==null? 0 : mDataList.size(); } @Override public Object getItem(int position) { return mDataList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if(convertView==null){ holder = new ViewHolder(); convertView = inflater.inflate(R.layout.contacts_, parent,false); holder.contactId = (TextView) convertView.findViewById(R.id.contact_id_tv); holder.contactName = (TextView)convertView.findViewById(R.id.contact_name_tv); holder.contactNum = (TextView)convertView.findViewById(R.id.contact_number_tv); convertView.setTag(holder); }else { holder = (ViewHolder) convertView.getTag(); } MyContacts contact = mDataList.get(position); holder.contactId.setText(contact.getId()); holder.contactName.setText(contact.getName()); holder.contactNum.setText(""+contact.getNumber()); return convertView; } static class ViewHolder{ TextView contactId; TextView contactName; TextView contactNum; } }
UTF-8
Java
1,685
java
ContactAdapter.java
Java
[]
null
[]
package com.example.day15asyncloader; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class ContactAdapter extends BaseAdapter{ private List<MyContacts> mDataList; private Context context; private LayoutInflater inflater; public ContactAdapter(Context context,List<MyContacts> list){ this.mDataList = list; inflater = LayoutInflater.from(context); } @Override public int getCount() { return mDataList==null? 0 : mDataList.size(); } @Override public Object getItem(int position) { return mDataList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if(convertView==null){ holder = new ViewHolder(); convertView = inflater.inflate(R.layout.contacts_, parent,false); holder.contactId = (TextView) convertView.findViewById(R.id.contact_id_tv); holder.contactName = (TextView)convertView.findViewById(R.id.contact_name_tv); holder.contactNum = (TextView)convertView.findViewById(R.id.contact_number_tv); convertView.setTag(holder); }else { holder = (ViewHolder) convertView.getTag(); } MyContacts contact = mDataList.get(position); holder.contactId.setText(contact.getId()); holder.contactName.setText(contact.getName()); holder.contactNum.setText(""+contact.getNumber()); return convertView; } static class ViewHolder{ TextView contactId; TextView contactName; TextView contactNum; } }
1,685
0.756677
0.754896
63
25.746031
22.196074
82
false
false
0
0
0
0
0
0
1.825397
false
false
5
ea6e557f3c7070d7e292d1171cc4e9b1ae493e2b
3,272,765,080,885
97f2758d73535ed2424f87917bb6ddc28e59b464
/src/main/java/top/kangyong/study01/test01/RaceCar.java
1ca1ed3c0981fcd1e43ea7da9a246dc68a3e9c4e
[]
no_license
kzdwts/q_project
https://github.com/kzdwts/q_project
364ee47de163f23e27252ac7414dbb98970bc967
972a2e5fc404305b57974ed980aaaa3435939fb2
refs/heads/master
2023-08-18T03:34:42.842000
2023-08-04T07:49:48
2023-08-04T07:49:48
160,373,590
0
2
null
false
2023-06-14T16:39:35
2018-12-04T14:52:52
2023-01-31T17:08:07
2023-06-14T16:39:31
3,026
0
2
5
Java
false
false
package top.kangyong.study01.test01; /** * 交通工具 */ abstract class Vehicle { public int speed() { return 0; } } class Car extends Vehicle{ @Override public int speed() { return 60; } } /** * 跑车 */ public class RaceCar extends Car{ @Override public int speed() { return 150; } public static void main(String[] args) { System.out.println(new RaceCar().speed()); } }
UTF-8
Java
459
java
RaceCar.java
Java
[]
null
[]
package top.kangyong.study01.test01; /** * 交通工具 */ abstract class Vehicle { public int speed() { return 0; } } class Car extends Vehicle{ @Override public int speed() { return 60; } } /** * 跑车 */ public class RaceCar extends Car{ @Override public int speed() { return 150; } public static void main(String[] args) { System.out.println(new RaceCar().speed()); } }
459
0.559284
0.536913
35
11.771428
13.602701
50
false
false
0
0
0
0
0
0
0.142857
false
false
5
49b3d24f46724f378cdfd89ea8c9757e99974313
28,458,453,361,576
a340f5bcc88a4aba9f7ee255fea4d5101b54ef8f
/app/src/main/java/com/udacity/popularmovies/FavoriteViewModel.java
7ced3eb1611768d3e2f4fc040e7e016ab081d041
[]
no_license
mkillewald/GwG2018_Popular-Movies-Stage-2
https://github.com/mkillewald/GwG2018_Popular-Movies-Stage-2
716eaefd4fb4c25e96b2d98f8908282ed9db8dc2
804285fdd647567298950f74599c8d19ba6f03f8
refs/heads/master
2020-03-19T09:06:18.697000
2018-07-27T17:36:36
2018-07-27T17:36:36
136,260,317
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.udacity.popularmovies; import android.app.Application; import android.arch.lifecycle.AndroidViewModel; import android.arch.lifecycle.LiveData; import android.support.annotation.NonNull; import com.udacity.popularmovies.database.AppDatabase; import com.udacity.popularmovies.model.Poster; import java.util.List; public class FavoriteViewModel extends AndroidViewModel { private LiveData<List<Poster>> mFavorites; public FavoriteViewModel(@NonNull Application application) { super(application); AppDatabase appDatabase = AppDatabase.getInstance(this.getApplication()); mFavorites = appDatabase.favoriteDao().loadAllFavorites(); } public LiveData<List<Poster>> getFavorites() { return mFavorites; } }
UTF-8
Java
770
java
FavoriteViewModel.java
Java
[]
null
[]
package com.udacity.popularmovies; import android.app.Application; import android.arch.lifecycle.AndroidViewModel; import android.arch.lifecycle.LiveData; import android.support.annotation.NonNull; import com.udacity.popularmovies.database.AppDatabase; import com.udacity.popularmovies.model.Poster; import java.util.List; public class FavoriteViewModel extends AndroidViewModel { private LiveData<List<Poster>> mFavorites; public FavoriteViewModel(@NonNull Application application) { super(application); AppDatabase appDatabase = AppDatabase.getInstance(this.getApplication()); mFavorites = appDatabase.favoriteDao().loadAllFavorites(); } public LiveData<List<Poster>> getFavorites() { return mFavorites; } }
770
0.768831
0.768831
27
27.518518
25.103298
81
false
false
0
0
0
0
0
0
0.481481
false
false
5
551c0a877e8f24d0014f879f2d4eb9e64f2f20df
30,356,828,911,124
f6415cf3c09e29bfc39503e5f90c5021e483b49a
/OOP from Sensors to Actuators Labs/Lab6/src/model/StudentManagementSystem.java
fe3cd3bb64d6cfc432d6f36f482c6e4b7abef020
[]
no_license
Jihal/University
https://github.com/Jihal/University
b718cb1e65156dd583e9528186620443b0b22604
ab7f263e0a92a1d8c53d6c5ecde9ccf69dd34c8a
refs/heads/master
2020-12-21T09:36:37.975000
2020-01-26T22:39:09
2020-01-26T22:39:09
236,385,065
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model; public class StudentManagementSystem { public Student [] students= new Student[100]; int nos=0; //# of students public StudentManagementSystem() { } // Getter (gets studennts) public Student [] getStudents() { // Creating method Student[] returnS = new Student[nos]; for(int i=0; i < nos; i++) { returnS[i]= students[i]; } return returnS; } public String getDescription() { String desc= ""; if(nos==0) { desc= "Student management system currently stores no students."; } else { desc+= "Student management system currently stores " + nos + " students:\n"; for(int i=0; i < this.nos; i++) { desc+= "\n"+students[i].getDescription()+ "\n"; } } return desc; } public void addStudent(Student s) { this.students[nos]=s; nos++; } public int getMarks(String name, String title) { for(int i=0; i < nos; i++) { if(this.students[i].name == name) { return this.students[i].getMarks(title); } } return -1; } public void addStudent(String name) { this.students[nos]= new Student(name); nos++; } public void addCourse(String name, CourseRecord cr) { for(int i=0; i < nos; i++) { if(this.students[i].name==name) { this.students[i].addCourse(cr); } } } public double getGPA(String name) { for(int i=0; i < nos; i++) { if(this.students[i].name==name) { return this.students[i].getGPA(); } } return 0; } public void setMarks(String name, String title, int marks) { for(int i=0; i < nos; i++) { if(this.students[i].name==name) { students[i].setMarks(title, marks); } } } }
UTF-8
Java
1,747
java
StudentManagementSystem.java
Java
[]
null
[]
package model; public class StudentManagementSystem { public Student [] students= new Student[100]; int nos=0; //# of students public StudentManagementSystem() { } // Getter (gets studennts) public Student [] getStudents() { // Creating method Student[] returnS = new Student[nos]; for(int i=0; i < nos; i++) { returnS[i]= students[i]; } return returnS; } public String getDescription() { String desc= ""; if(nos==0) { desc= "Student management system currently stores no students."; } else { desc+= "Student management system currently stores " + nos + " students:\n"; for(int i=0; i < this.nos; i++) { desc+= "\n"+students[i].getDescription()+ "\n"; } } return desc; } public void addStudent(Student s) { this.students[nos]=s; nos++; } public int getMarks(String name, String title) { for(int i=0; i < nos; i++) { if(this.students[i].name == name) { return this.students[i].getMarks(title); } } return -1; } public void addStudent(String name) { this.students[nos]= new Student(name); nos++; } public void addCourse(String name, CourseRecord cr) { for(int i=0; i < nos; i++) { if(this.students[i].name==name) { this.students[i].addCourse(cr); } } } public double getGPA(String name) { for(int i=0; i < nos; i++) { if(this.students[i].name==name) { return this.students[i].getGPA(); } } return 0; } public void setMarks(String name, String title, int marks) { for(int i=0; i < nos; i++) { if(this.students[i].name==name) { students[i].setMarks(title, marks); } } } }
1,747
0.567831
0.560389
115
13.191304
18.197895
78
false
false
0
0
0
0
0
0
1.2
false
false
5
0edc95e880c484d2b7ab1c660d25321e79fff025
30,356,828,909,826
6d88c837fb25532dfa5b718d90fca52bc5028b82
/src/example57_serialization1/Serialization1.java
d53555af4a61e34e4cfdd1f0daf4bc213d0d2fc7
[]
no_license
harry83528/JavaExample
https://github.com/harry83528/JavaExample
1dcaaa728665721b0a6a5bd4292f40cdef073e97
033767d35ca238a2765b4aedd3c62ac41614069d
refs/heads/master
2021-01-18T04:24:20.605000
2020-11-03T07:24:02
2020-11-03T07:24:02
84,273,069
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package example57_serialization1; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; //序列化過程簡單說就是為了保存在內存中的各種對象的狀態(也就是實例變量,不只是類別本身),並且可以把保存的對象狀態再讀出來 //什麽情況下需要序列化 :1.當你想把的內存中的對象狀態保存到一個文件中或者數據庫中時候2.當你想用套接字在網絡上傳送對象的時候3.當你想通過RMI傳輸對象的時候 //當一個父類實現序列化,子類自動實現序列化,不需要實作Serializable //在Java這樣支援物件導向的程式中撰寫程式,很多資料都是以物件的方式存在,在程式運行過後,您會希望將這些資料加以儲存,以供下次執行程式時使用,這時您可以使用ObjectInputStream、ObjectOutputStream 來進行這項工作... public class Serialization1 { public static void main(String[] args) { // 在沒有序列化前,每個保存在堆(Heap)中的對象都有相應的狀態(state),即實例變量(instance ariable) Employee e = new Employee(); e.name = "harry"; e.address = "Taiwan"; e.phone = 25372480; e.number = 51; // 序列化之後,Employee中的實例變量的值都被保存到Employee.ser文件 // 這樣以後又可以把它 從文件中讀出來,重新在堆中創建原來的對象(反序列化) try { FileOutputStream fileOut = new FileOutputStream("employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e); out.close(); fileOut.close(); System.out.println("序列化成功"); } catch (IOException i) { i.printStackTrace(); } System.out.println("========="); try { FileInputStream fileIn = new FileInputStream("employee.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); e = (Employee) in.readObject(); in.close(); fileIn.close(); } catch (Exception i) { System.out.print(i.toString()); } System.out.println("反序列化");// 並不會出現Employee的建構子,因為序列化只保存該物件的狀態並不保存方法/建構子 System.out.println("Name: " + e.name);// Name: harry System.out.println("Address: " + e.address);// Address: Taiwan System.out.println("phone: " + e.phone);// phone:0(因為phone加了transient不可序列化,這個值是不會被發送到輸出流。反序列化的Employee對象的phone為0) System.out.println("Number: " + e.number);// Number: 51 } } // 一類被序列化成功,兩個條件必須滿足: // 1.這個類必須實現java.io.Serializable // 2.所有在類中的字段必須是可序列化的。如果一個字段不是可序列化的,必須注明transient class boss { boss() { System.out.println("這是boss的建構子"); } } class Employee extends boss implements Serializable { public String name; public String address; public transient int phone; public int number; Employee() { System.out.println("這是Employee的建構子"); } }
UTF-8
Java
3,172
java
Serialization1.java
Java
[ { "context": "iable)\n\t\tEmployee e = new Employee();\n\t\te.name = \"harry\";\n\t\te.address = \"Taiwan\";\n\t\te.phone = 25372480;\n\t", "end": 731, "score": 0.9991889595985413, "start": 726, "tag": "NAME", "value": "harry" }, { "context": "子\n\t\tSystem.out.println(\"Name: \" + e.name);// Name: harry\n\t\tSystem.out.println(\"Address: \" + e.address);// ", "end": 1598, "score": 0.9986495971679688, "start": 1593, "tag": "NAME", "value": "harry" } ]
null
[]
package example57_serialization1; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; //序列化過程簡單說就是為了保存在內存中的各種對象的狀態(也就是實例變量,不只是類別本身),並且可以把保存的對象狀態再讀出來 //什麽情況下需要序列化 :1.當你想把的內存中的對象狀態保存到一個文件中或者數據庫中時候2.當你想用套接字在網絡上傳送對象的時候3.當你想通過RMI傳輸對象的時候 //當一個父類實現序列化,子類自動實現序列化,不需要實作Serializable //在Java這樣支援物件導向的程式中撰寫程式,很多資料都是以物件的方式存在,在程式運行過後,您會希望將這些資料加以儲存,以供下次執行程式時使用,這時您可以使用ObjectInputStream、ObjectOutputStream 來進行這項工作... public class Serialization1 { public static void main(String[] args) { // 在沒有序列化前,每個保存在堆(Heap)中的對象都有相應的狀態(state),即實例變量(instance ariable) Employee e = new Employee(); e.name = "harry"; e.address = "Taiwan"; e.phone = 25372480; e.number = 51; // 序列化之後,Employee中的實例變量的值都被保存到Employee.ser文件 // 這樣以後又可以把它 從文件中讀出來,重新在堆中創建原來的對象(反序列化) try { FileOutputStream fileOut = new FileOutputStream("employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e); out.close(); fileOut.close(); System.out.println("序列化成功"); } catch (IOException i) { i.printStackTrace(); } System.out.println("========="); try { FileInputStream fileIn = new FileInputStream("employee.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); e = (Employee) in.readObject(); in.close(); fileIn.close(); } catch (Exception i) { System.out.print(i.toString()); } System.out.println("反序列化");// 並不會出現Employee的建構子,因為序列化只保存該物件的狀態並不保存方法/建構子 System.out.println("Name: " + e.name);// Name: harry System.out.println("Address: " + e.address);// Address: Taiwan System.out.println("phone: " + e.phone);// phone:0(因為phone加了transient不可序列化,這個值是不會被發送到輸出流。反序列化的Employee對象的phone為0) System.out.println("Number: " + e.number);// Number: 51 } } // 一類被序列化成功,兩個條件必須滿足: // 1.這個類必須實現java.io.Serializable // 2.所有在類中的字段必須是可序列化的。如果一個字段不是可序列化的,必須注明transient class boss { boss() { System.out.println("這是boss的建構子"); } } class Employee extends boss implements Serializable { public String name; public String address; public transient int phone; public int number; Employee() { System.out.println("這是Employee的建構子"); } }
3,172
0.742806
0.732464
73
29.465754
25.973686
127
false
false
0
0
0
0
0
0
1.79452
false
false
5
65581c05ce114ade38b5a6b09eb10ade3f60c5bf
5,995,774,412,930
9c795cf7774d2a75bdc99f192d8ea50823d6a490
/src/main/java/case1/refactory8/Rental.java
1cd945969a161fbe2d569d6db64065173cefae44
[]
no_license
wangchao550586585/refactory
https://github.com/wangchao550586585/refactory
a69ae0ed7b058be3d921a14d432a6c87f38db6a6
87ed58b1aa86811a4cf7ea76030d5fba1257093d
refs/heads/master
2022-04-18T15:09:27.921000
2020-04-14T04:19:38
2020-04-14T04:19:38
255,508,626
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package case1.refactory8; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * 函数应该放在它所使用的数据的所属对象内 * * @author Administrator */ @Setter @Getter @AllArgsConstructor @NoArgsConstructor @Builder public class Rental { private Movie movie; private int daysRented; public double getCharge() { return movie.getCharge(daysRented); } int getFrequentRenterPoints() { return movie.getFrequentRenterPoints(daysRented); } }
UTF-8
Java
555
java
Rental.java
Java
[ { "context": "Setter;\n\n/**\n * 函数应该放在它所使用的数据的所属对象内\n * \n * @author Administrator\n */\n@Setter\n@Getter\n@AllArgsConstructor\n@NoArgsCo", "end": 217, "score": 0.9574550986289978, "start": 204, "tag": "NAME", "value": "Administrator" } ]
null
[]
package case1.refactory8; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * 函数应该放在它所使用的数据的所属对象内 * * @author Administrator */ @Setter @Getter @AllArgsConstructor @NoArgsConstructor @Builder public class Rental { private Movie movie; private int daysRented; public double getCharge() { return movie.getCharge(daysRented); } int getFrequentRenterPoints() { return movie.getFrequentRenterPoints(daysRented); } }
555
0.779497
0.775629
30
16.233334
13.388262
51
false
false
0
0
0
0
0
0
0.666667
false
false
5
1fec743eda07541a94f6e7138be7af83d516a991
5,995,774,411,658
8779db8206c46521da5436acd1f6ff9c28ba3f85
/app/src/main/java/com/example/myapplication/model/bean/DaoBean.java
8f57599639085dfd804b497212db296ee8b8effa
[]
no_license
landuhello/MyApplication3
https://github.com/landuhello/MyApplication3
b73a1e0c616bc6ba216d96a17d92d1b31a6d219c
154142e8f15dfc1dd3f860abe416c7f5b26b856c
refs/heads/master
2020-09-05T00:36:40.931000
2019-11-29T00:48:47
2019-11-29T00:48:47
219,935,039
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.myapplication.model.bean; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.Generated; /* *@Auther:刘炳良 *@Date: 时间 *@Description:功能 * */ @Entity public class DaoBean { @Id(autoincrement = true) private Long id; private String email; private String pwd; public String getPwd() { return this.pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @Generated(hash = 1142056450) public DaoBean(Long id, String email, String pwd) { this.id = id; this.email = email; this.pwd = pwd; } @Generated(hash = 405743142) public DaoBean() { } }
UTF-8
Java
1,015
java
DaoBean.java
Java
[ { "context": "obot.greendao.annotation.Generated;\n\n/*\n *@Auther:刘炳良\n *@Date: 时间\n *@Description:功能\n * */\n@Entity\npubli", "end": 213, "score": 0.9998683929443359, "start": 210, "tag": "NAME", "value": "刘炳良" }, { "context": "id;\n this.email = email;\n this.pwd = pwd;\n }\n @Generated(hash = 405743142)\n publi", "end": 927, "score": 0.9839624166488647, "start": 924, "tag": "PASSWORD", "value": "pwd" } ]
null
[]
package com.example.myapplication.model.bean; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.Generated; /* *@Auther:刘炳良 *@Date: 时间 *@Description:功能 * */ @Entity public class DaoBean { @Id(autoincrement = true) private Long id; private String email; private String pwd; public String getPwd() { return this.pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @Generated(hash = 1142056450) public DaoBean(Long id, String email, String pwd) { this.id = id; this.email = email; this.pwd = pwd; } @Generated(hash = 405743142) public DaoBean() { } }
1,015
0.613387
0.594406
47
20.297873
14.987818
55
false
false
0
0
0
0
0
0
0.382979
false
false
5
bc46388b277477bcce99df795360c3dc3c033536
24,464,133,782,832
b929c30df6c39a612f5bf1423f2701beab3df369
/src/main/java/practice3_adv/RectangleSquare.java
1f8eb92cfbcc3288fee5b6d8e33a267d40657c39
[]
no_license
freedomserg/GoIT_JavaTech
https://github.com/freedomserg/GoIT_JavaTech
0d48fe3533d61e8cf55f6a22453e5e4ccd03262e
15d1addace757541b7b995739b35ba159ddadf14
refs/heads/master
2021-01-10T11:43:32.747000
2016-03-22T11:00:53
2016-03-22T11:00:53
53,983,048
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package practice3_adv; /*Площа прямокутників Знайти площу яку займають N прямокутників на площині. У всіх прямокутників одна зі сторін лежить на осі абсцис (X). Дано три масива довжиною N. В першому масиві Х координата нижньої-лівої вершини і-го прямокутника , висота в другому, ширина в третьому. Всі значення невід'ємні. Приклад: X - [0, 0] H - [20, 10] W - [10, 20] Відповідь - 300. */ import java.util.HashSet; import java.util.Set; public class RectangleSquare { public int measure(int[] x, int[] h, int[] w) { Set<String> unitsSet = new HashSet<>(); for (int i = 0; i < x.length; i++) { int[][][] matrix = new int[h[i]][w[i]][2]; for (int j = 0; j < matrix.length; j++) { for (int k = 0; k < matrix[j].length; k++) { matrix[j][k][0] = k + x[i]; matrix[j][k][1] = matrix.length - 1 - j; String unit = "[" + matrix[j][k][0] + "; " + matrix[j][k][1] + "]"; if (!unitsSet.contains(unit)) { unitsSet.add(unit); } } } } return unitsSet.size(); } public static void main(String[] args) { System.out.println(new RectangleSquare().measure(new int[]{0, 0}, new int[]{20, 10}, new int[]{10, 20})); } }
UTF-8
Java
1,607
java
RectangleSquare.java
Java
[]
null
[]
package practice3_adv; /*Площа прямокутників Знайти площу яку займають N прямокутників на площині. У всіх прямокутників одна зі сторін лежить на осі абсцис (X). Дано три масива довжиною N. В першому масиві Х координата нижньої-лівої вершини і-го прямокутника , висота в другому, ширина в третьому. Всі значення невід'ємні. Приклад: X - [0, 0] H - [20, 10] W - [10, 20] Відповідь - 300. */ import java.util.HashSet; import java.util.Set; public class RectangleSquare { public int measure(int[] x, int[] h, int[] w) { Set<String> unitsSet = new HashSet<>(); for (int i = 0; i < x.length; i++) { int[][][] matrix = new int[h[i]][w[i]][2]; for (int j = 0; j < matrix.length; j++) { for (int k = 0; k < matrix[j].length; k++) { matrix[j][k][0] = k + x[i]; matrix[j][k][1] = matrix.length - 1 - j; String unit = "[" + matrix[j][k][0] + "; " + matrix[j][k][1] + "]"; if (!unitsSet.contains(unit)) { unitsSet.add(unit); } } } } return unitsSet.size(); } public static void main(String[] args) { System.out.println(new RectangleSquare().measure(new int[]{0, 0}, new int[]{20, 10}, new int[]{10, 20})); } }
1,607
0.52476
0.50037
44
29.75
26.736191
113
false
false
0
0
0
0
0
0
0.681818
false
false
5
cc631ff8e0df5b140427e1c3cc93c8179cff0058
7,722,351,263,436
0855bf9e3a09ee5678e8fe25e0e86adede4493fd
/app/src/main/java/com/winwin/android/UI/Adapter/MyRecommendAdapter.java
ffccb200b0bcfc12c5dcd7d4b280b1c6639c5ce2
[]
no_license
luosonglin/WW
https://github.com/luosonglin/WW
0b7d5d90de8c1d3b29f1b669caeea3eda7c9e8f0
8fd60e054a0aadec6193e2d71a8e6a468204468a
refs/heads/master
2020-03-14T09:41:54.649000
2017-09-08T03:15:46
2017-09-08T03:15:46
131,550,343
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.winwin.android.UI.Adapter; import android.util.Log; import android.view.View; import com.winwin.android.Data.HttpData.HttpData; import com.winwin.android.R; import com.winwin.android.UI.Entity.CommendCustomerVo; import com.winwin.android.UI.Entity.CustomerDto; import com.winwin.android.UI.Entity.HttpResult; import com.winwin.android.Util.DateUtils; import com.winwin.android.Util.ToastUtils; import com.xiaochao.lcrapiddeveloplibrary.BaseQuickAdapter; import com.xiaochao.lcrapiddeveloplibrary.BaseViewHolder; import java.util.Arrays; import java.util.List; import io.reactivex.Observer; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; public class MyRecommendAdapter extends BaseQuickAdapter<CustomerDto> { public MyRecommendAdapter(int layoutResId, List<CustomerDto> data) { super(layoutResId, data); } @Override protected void convert(final BaseViewHolder helper, final CustomerDto item) { helper.setText(R.id.name_tv,"推荐"+ item.getCommendCustomerName()+"给"+item.getRecommendName()); helper.setText(R.id.time_tv, DateUtils.formatDate(item.getCreateTime(), DateUtils.TYPE_06)); switch (item.getCommendStatus()) { //推荐状态(0:待接受,1:已拒绝,2:已接受) case 0: helper.getView(R.id.accept_btn).setVisibility(View.VISIBLE); helper.getView(R.id.reject_btn).setVisibility(View.VISIBLE); helper.getView(R.id.accept_status_btn).setVisibility(View.GONE); helper.getView(R.id.reject_status_btn).setVisibility(View.GONE); helper.getView(R.id.accept_btn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CommendCustomerVo commendCustomerVo = new CommendCustomerVo(2, item.getId(), ""); HttpData.getInstance().HttpDataUpdateRecommendNews(new Observer<HttpResult>() { @Override public void onSubscribe(@NonNull Disposable d) { } @Override public void onNext(@NonNull HttpResult httpResult) { if ("0".equals(httpResult.getStatus().getCode())) { ToastUtils.show(mContext, "已接受, \n 手动刷新下^_^"); // notify(); } } @Override public void onError(@NonNull Throwable e) { Log.e(TAG, "onError: "+e.getMessage() +"\n"+e.getCause() +"\n"+e.getLocalizedMessage() +"\n"+ Arrays.toString(e.getStackTrace())); } @Override public void onComplete() { } }, commendCustomerVo); } }); helper.getView(R.id.reject_btn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CommendCustomerVo commendCustomerVo = new CommendCustomerVo(1, item.getId(), ""); HttpData.getInstance().HttpDataUpdateRecommendNews(new Observer<HttpResult>() { @Override public void onSubscribe(@NonNull Disposable d) { } @Override public void onNext(@NonNull HttpResult httpResult) { if ("0".equals(httpResult.getStatus().getCode())) { ToastUtils.show(mContext, "已拒绝, \n 手动刷新下^_^"); notifyDataSetChanged(); } } @Override public void onError(@NonNull Throwable e) { Log.e(TAG, "onError: "+e.getMessage() +"\n"+e.getCause() +"\n"+e.getLocalizedMessage() +"\n"+ Arrays.toString(e.getStackTrace())); } @Override public void onComplete() { } }, commendCustomerVo); } }); break; case 1: helper.getView(R.id.accept_btn).setVisibility(View.GONE); helper.getView(R.id.reject_btn).setVisibility(View.GONE); helper.getView(R.id.accept_status_btn).setVisibility(View.GONE); helper.getView(R.id.reject_status_btn).setVisibility(View.VISIBLE); break; case 2: helper.getView(R.id.accept_btn).setVisibility(View.GONE); helper.getView(R.id.reject_btn).setVisibility(View.GONE); helper.getView(R.id.accept_status_btn).setVisibility(View.VISIBLE); helper.getView(R.id.reject_status_btn).setVisibility(View.GONE); break; } } }
UTF-8
Java
5,574
java
MyRecommendAdapter.java
Java
[]
null
[]
package com.winwin.android.UI.Adapter; import android.util.Log; import android.view.View; import com.winwin.android.Data.HttpData.HttpData; import com.winwin.android.R; import com.winwin.android.UI.Entity.CommendCustomerVo; import com.winwin.android.UI.Entity.CustomerDto; import com.winwin.android.UI.Entity.HttpResult; import com.winwin.android.Util.DateUtils; import com.winwin.android.Util.ToastUtils; import com.xiaochao.lcrapiddeveloplibrary.BaseQuickAdapter; import com.xiaochao.lcrapiddeveloplibrary.BaseViewHolder; import java.util.Arrays; import java.util.List; import io.reactivex.Observer; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; public class MyRecommendAdapter extends BaseQuickAdapter<CustomerDto> { public MyRecommendAdapter(int layoutResId, List<CustomerDto> data) { super(layoutResId, data); } @Override protected void convert(final BaseViewHolder helper, final CustomerDto item) { helper.setText(R.id.name_tv,"推荐"+ item.getCommendCustomerName()+"给"+item.getRecommendName()); helper.setText(R.id.time_tv, DateUtils.formatDate(item.getCreateTime(), DateUtils.TYPE_06)); switch (item.getCommendStatus()) { //推荐状态(0:待接受,1:已拒绝,2:已接受) case 0: helper.getView(R.id.accept_btn).setVisibility(View.VISIBLE); helper.getView(R.id.reject_btn).setVisibility(View.VISIBLE); helper.getView(R.id.accept_status_btn).setVisibility(View.GONE); helper.getView(R.id.reject_status_btn).setVisibility(View.GONE); helper.getView(R.id.accept_btn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CommendCustomerVo commendCustomerVo = new CommendCustomerVo(2, item.getId(), ""); HttpData.getInstance().HttpDataUpdateRecommendNews(new Observer<HttpResult>() { @Override public void onSubscribe(@NonNull Disposable d) { } @Override public void onNext(@NonNull HttpResult httpResult) { if ("0".equals(httpResult.getStatus().getCode())) { ToastUtils.show(mContext, "已接受, \n 手动刷新下^_^"); // notify(); } } @Override public void onError(@NonNull Throwable e) { Log.e(TAG, "onError: "+e.getMessage() +"\n"+e.getCause() +"\n"+e.getLocalizedMessage() +"\n"+ Arrays.toString(e.getStackTrace())); } @Override public void onComplete() { } }, commendCustomerVo); } }); helper.getView(R.id.reject_btn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CommendCustomerVo commendCustomerVo = new CommendCustomerVo(1, item.getId(), ""); HttpData.getInstance().HttpDataUpdateRecommendNews(new Observer<HttpResult>() { @Override public void onSubscribe(@NonNull Disposable d) { } @Override public void onNext(@NonNull HttpResult httpResult) { if ("0".equals(httpResult.getStatus().getCode())) { ToastUtils.show(mContext, "已拒绝, \n 手动刷新下^_^"); notifyDataSetChanged(); } } @Override public void onError(@NonNull Throwable e) { Log.e(TAG, "onError: "+e.getMessage() +"\n"+e.getCause() +"\n"+e.getLocalizedMessage() +"\n"+ Arrays.toString(e.getStackTrace())); } @Override public void onComplete() { } }, commendCustomerVo); } }); break; case 1: helper.getView(R.id.accept_btn).setVisibility(View.GONE); helper.getView(R.id.reject_btn).setVisibility(View.GONE); helper.getView(R.id.accept_status_btn).setVisibility(View.GONE); helper.getView(R.id.reject_status_btn).setVisibility(View.VISIBLE); break; case 2: helper.getView(R.id.accept_btn).setVisibility(View.GONE); helper.getView(R.id.reject_btn).setVisibility(View.GONE); helper.getView(R.id.accept_status_btn).setVisibility(View.VISIBLE); helper.getView(R.id.reject_status_btn).setVisibility(View.GONE); break; } } }
5,574
0.502911
0.500728
123
43.682926
31.081932
105
false
false
0
0
0
0
0
0
0.528455
false
false
5
85407dadbabec8e5cfdbc2c271405422d804f3b7
36,146,444,810,986
23217253be0b3033af85528964be527077d85285
/src/main/java/pl/coderslab/bk/service/RoleServiceImpl.java
5a105abae5d2e26ec4ac64d975b64e482dcac8c7
[]
no_license
maser0/BkRepoFinal
https://github.com/maser0/BkRepoFinal
2912c5abffce964d7ee0f54eae3dd859286cb8b4
e8b406785923c82421fd588e90860a936c23324c
refs/heads/master
2022-12-25T23:42:46.060000
2020-08-04T09:20:08
2020-08-04T09:20:08
267,273,402
1
0
null
false
2020-10-13T22:21:06
2020-05-27T09:12:43
2020-08-04T09:20:37
2020-10-13T22:21:05
173
1
0
1
Java
false
false
package pl.coderslab.bk.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pl.coderslab.bk.entity.Role; import pl.coderslab.bk.interfaces.RoleService; import pl.coderslab.bk.repository.RoleRepository; @Service public class RoleServiceImpl implements RoleService { private final RoleRepository roleRepository; @Autowired public RoleServiceImpl(RoleRepository roleRepository) { this.roleRepository = roleRepository; } @Override public void save(Role role) { this.roleRepository.save(role); } @Override public Role findOneByName(String roleName) { return this.roleRepository.findOneByName(roleName); } }
UTF-8
Java
778
java
RoleServiceImpl.java
Java
[]
null
[]
package pl.coderslab.bk.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pl.coderslab.bk.entity.Role; import pl.coderslab.bk.interfaces.RoleService; import pl.coderslab.bk.repository.RoleRepository; @Service public class RoleServiceImpl implements RoleService { private final RoleRepository roleRepository; @Autowired public RoleServiceImpl(RoleRepository roleRepository) { this.roleRepository = roleRepository; } @Override public void save(Role role) { this.roleRepository.save(role); } @Override public Role findOneByName(String roleName) { return this.roleRepository.findOneByName(roleName); } }
778
0.726221
0.726221
30
23.933332
22.531361
62
false
false
0
0
0
0
0
0
0.333333
false
false
5
761b6692ecae72f3da87450c9fb9e1207bf6459c
35,923,106,510,739
caa7b83109a1e0121e4778b00681cd022304dac4
/sales-service/src/main/java/com/dh/fullstack/project/salesservice/controller/Constants.java
f9047c947e9d604b7c9a32b4e9de5f57fabbaa69
[]
no_license
Julinho82/sales-service
https://github.com/Julinho82/sales-service
3a660d5670b0e41c0309f2bfdad3db2497d98905
015615994c68b7dd4af3894ce1217793d66cfab2
refs/heads/master
2020-07-04T09:34:23.110000
2019-08-14T01:20:55
2019-08-14T01:20:55
202,243,058
0
0
null
false
2019-08-14T01:20:56
2019-08-14T00:29:15
2019-08-14T00:30:53
2019-08-14T01:20:55
0
0
0
0
null
false
false
package com.dh.fullstack.project.salesservice.controller; /** * @author Julio Daviu */ public final class Constants { private Constants(){} public static class EmployeeTagCreate{ public static final String NAME = "Employee create"; public static final String DESCRIPTION = "creacion del empleado"; public static final String OPERATION = "Endpoint crear un empleado"; } public static class EmployeeTagRead{ public static final String NAME = "Employee read"; public static final String DESCRIPTION = "Listar empleados"; public static final String OPERATION_EMAIL = "Endpoint para encontrar emplado por su email"; public static final String OPERATION_GENDER = "Endpoint para obtener empleados por genero"; public static final String OPERATION_PAGINATION = "Endpoint para obtener empleados con paginacion"; } public static class BasePath{ public static final String SYSTEM = "/system"; public static final String SYSTEM_EMPLOYEE = SYSTEM + "/employees"; public static final String API = "/api"; public static final String API_EMPLOYEE = API + "/employees"; public static final String SYSTEM_EMPLOYEE_GENDER = SYSTEM_EMPLOYEE + "/gender"; public static final String API_EMPLOYEE_POSITION = API_EMPLOYEE + "/position"; } }
UTF-8
Java
1,379
java
Constants.java
Java
[ { "context": "k.project.salesservice.controller;\n\n/**\n * @author Julio Daviu\n */\n\npublic final class Constants {\n\n private ", "end": 85, "score": 0.9998346567153931, "start": 74, "tag": "NAME", "value": "Julio Daviu" } ]
null
[]
package com.dh.fullstack.project.salesservice.controller; /** * @author <NAME> */ public final class Constants { private Constants(){} public static class EmployeeTagCreate{ public static final String NAME = "Employee create"; public static final String DESCRIPTION = "creacion del empleado"; public static final String OPERATION = "Endpoint crear un empleado"; } public static class EmployeeTagRead{ public static final String NAME = "Employee read"; public static final String DESCRIPTION = "Listar empleados"; public static final String OPERATION_EMAIL = "Endpoint para encontrar emplado por su email"; public static final String OPERATION_GENDER = "Endpoint para obtener empleados por genero"; public static final String OPERATION_PAGINATION = "Endpoint para obtener empleados con paginacion"; } public static class BasePath{ public static final String SYSTEM = "/system"; public static final String SYSTEM_EMPLOYEE = SYSTEM + "/employees"; public static final String API = "/api"; public static final String API_EMPLOYEE = API + "/employees"; public static final String SYSTEM_EMPLOYEE_GENDER = SYSTEM_EMPLOYEE + "/gender"; public static final String API_EMPLOYEE_POSITION = API_EMPLOYEE + "/position"; } }
1,374
0.691806
0.691806
46
28.97826
34.897045
107
false
false
0
0
0
0
0
0
0.326087
false
false
5
2d21e396e9f9f07e79f0e32873bcefab95f16076
20,237,885,928,169
f4eca0d748293bc106992f9c60282cf9d418c2c6
/app/src/main/java/com/jasonstudio/viewanimationtesting1/customview/CustomImageView.java
411b77b61ccd4cd13480d71acb6403785ad5c93b
[]
no_license
jasonlam912/ViewAnimationTesting1
https://github.com/jasonlam912/ViewAnimationTesting1
1463c290d5329e07cbad2a2e422ad8604249e687
60e0ee1a1ebc78ed932caee9bba95399c5e0a03f
refs/heads/master
2023-05-04T15:53:12.857000
2021-05-28T12:10:30
2021-05-28T12:10:30
281,634,440
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jasonstudio.viewanimationtesting1.customview; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Color; import android.graphics.PorterDuff; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.animation.Animation; import android.view.animation.ScaleAnimation; import androidx.appcompat.widget.AppCompatImageView; import com.jasonstudio.viewanimationtesting1.R; import static android.view.MotionEvent.ACTION_DOWN; import static android.view.MotionEvent.ACTION_UP; public class CustomImageView extends AppCompatImageView { private Animation animationDown; private Animation animationUp; private int colorStart; private int colorEnd; private int duration; private ValueAnimator colorDownAnimator; private ValueAnimator colorUpAnimator; public CustomImageView(Context context) { super(context); } public CustomImageView(Context context, AttributeSet attrs) { super(context, attrs); duration = 200; animationDown = new ScaleAnimation(1f,0.8f,1f,0.8f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animationDown.setDuration(duration); animationDown.setFillAfter(true); animationUp = new ScaleAnimation(0.8f, 1f, 0.8f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animationUp.setDuration(duration); animationUp.setFillAfter(true); colorEnd = getResources().getColor(R.color.colorActionDown); colorStart = getResources().getColor(R.color.colorActionUp); colorDownAnimator = ValueAnimator.ofArgb(colorStart,colorEnd); colorDownAnimator.setDuration(duration); colorDownAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { //Log.d("onAnimationUpdate", animation.getAnimatedValue().toString()); CustomImageView.this.setColorFilter((int) animation.getAnimatedValue()); } }); colorUpAnimator = ValueAnimator.ofArgb(colorEnd,colorStart); colorUpAnimator.setDuration(duration); colorUpAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { CustomImageView.this.setColorFilter((int) animation.getAnimatedValue()); } }); } public CustomImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); switch (event.getAction()){ case ACTION_DOWN:{ //this.getDrawable().setColorFilter(0x12000000, PorterDuff.Mode.SRC_ATOP); //this.invalidate(); CustomImageView.this.startAnimation(animationDown); colorDownAnimator.start(); break; } case ACTION_UP: //this.getDrawable().clearColorFilter(); // // this.invalidate(); colorUpAnimator.start(); CustomImageView.this.startAnimation(animationUp); break; } return true; } }
UTF-8
Java
3,507
java
CustomImageView.java
Java
[]
null
[]
package com.jasonstudio.viewanimationtesting1.customview; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Color; import android.graphics.PorterDuff; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.animation.Animation; import android.view.animation.ScaleAnimation; import androidx.appcompat.widget.AppCompatImageView; import com.jasonstudio.viewanimationtesting1.R; import static android.view.MotionEvent.ACTION_DOWN; import static android.view.MotionEvent.ACTION_UP; public class CustomImageView extends AppCompatImageView { private Animation animationDown; private Animation animationUp; private int colorStart; private int colorEnd; private int duration; private ValueAnimator colorDownAnimator; private ValueAnimator colorUpAnimator; public CustomImageView(Context context) { super(context); } public CustomImageView(Context context, AttributeSet attrs) { super(context, attrs); duration = 200; animationDown = new ScaleAnimation(1f,0.8f,1f,0.8f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animationDown.setDuration(duration); animationDown.setFillAfter(true); animationUp = new ScaleAnimation(0.8f, 1f, 0.8f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animationUp.setDuration(duration); animationUp.setFillAfter(true); colorEnd = getResources().getColor(R.color.colorActionDown); colorStart = getResources().getColor(R.color.colorActionUp); colorDownAnimator = ValueAnimator.ofArgb(colorStart,colorEnd); colorDownAnimator.setDuration(duration); colorDownAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { //Log.d("onAnimationUpdate", animation.getAnimatedValue().toString()); CustomImageView.this.setColorFilter((int) animation.getAnimatedValue()); } }); colorUpAnimator = ValueAnimator.ofArgb(colorEnd,colorStart); colorUpAnimator.setDuration(duration); colorUpAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { CustomImageView.this.setColorFilter((int) animation.getAnimatedValue()); } }); } public CustomImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); switch (event.getAction()){ case ACTION_DOWN:{ //this.getDrawable().setColorFilter(0x12000000, PorterDuff.Mode.SRC_ATOP); //this.invalidate(); CustomImageView.this.startAnimation(animationDown); colorDownAnimator.start(); break; } case ACTION_UP: //this.getDrawable().clearColorFilter(); // // this.invalidate(); colorUpAnimator.start(); CustomImageView.this.startAnimation(animationUp); break; } return true; } }
3,507
0.680354
0.670659
97
35.15464
28.893456
129
false
false
0
0
0
0
0
0
0.814433
false
false
5
e28d71271360ec4133ca393050c46b1400642ae2
17,626,545,818,723
6d60ac2c3d8149326b402ee24b14e6c7bc48f1fc
/src/main/java/gov/lanl/micot/infrastructure/ep/model/ControlAreaImpl.java
7c3a64ad7446e5b339c2d796c90f56d326439280
[ "BSD-2-Clause" ]
permissive
lanl-ansi/micot
https://github.com/lanl-ansi/micot
141a99d160dc6f215ae8c9a19b2018961620fa0f
d84e40b1eade600cc6b817ac4bb275f3bb7c4714
refs/heads/master
2021-01-18T21:28:28.038000
2020-10-29T17:59:23
2020-10-29T17:59:23
84,364,230
3
4
NOASSERTION
false
2020-10-13T00:08:52
2017-03-08T20:42:24
2020-03-06T22:32:25
2019-06-12T15:10:16
186,866
3
3
20
Java
false
false
package gov.lanl.micot.infrastructure.ep.model; import gov.lanl.micot.infrastructure.model.ComponentImpl; /** * Some common bus implementation information * * @author Russell Bent */ public class ControlAreaImpl extends ComponentImpl implements ControlArea { protected static final long serialVersionUID = 1L; /** * Constructor * @param identifierKeys * @param oredKeys * @param additiveKeys * @param subtractiveKeys */ protected ControlAreaImpl(long assetId) { super(); setAttribute(ControlArea.ASSET_ID_KEY, assetId); } @Override public void setAttribute(Object key, Object object) { super.setAttribute(key,object); } @Override public ControlAreaImpl clone() { ControlAreaImpl newArea = new ControlAreaImpl(getAttribute(ASSET_ID_KEY,Long.class)); try { deepCopy(newArea); } catch (Exception e) { e.printStackTrace(); } return newArea; } }
UTF-8
Java
953
java
ControlAreaImpl.java
Java
[ { "context": "mmon bus implementation information\n * \n * @author Russell Bent\n */\npublic class ControlAreaImpl extends Componen", "end": 186, "score": 0.9998491406440735, "start": 174, "tag": "NAME", "value": "Russell Bent" } ]
null
[]
package gov.lanl.micot.infrastructure.ep.model; import gov.lanl.micot.infrastructure.model.ComponentImpl; /** * Some common bus implementation information * * @author <NAME> */ public class ControlAreaImpl extends ComponentImpl implements ControlArea { protected static final long serialVersionUID = 1L; /** * Constructor * @param identifierKeys * @param oredKeys * @param additiveKeys * @param subtractiveKeys */ protected ControlAreaImpl(long assetId) { super(); setAttribute(ControlArea.ASSET_ID_KEY, assetId); } @Override public void setAttribute(Object key, Object object) { super.setAttribute(key,object); } @Override public ControlAreaImpl clone() { ControlAreaImpl newArea = new ControlAreaImpl(getAttribute(ASSET_ID_KEY,Long.class)); try { deepCopy(newArea); } catch (Exception e) { e.printStackTrace(); } return newArea; } }
947
0.690451
0.689402
45
20.177778
22.261366
89
false
false
0
0
0
0
0
0
0.311111
false
false
5
ecedce08e70eca7075107c7fd113cecb2e7522fc
30,820,685,372,839
3d0c477111ef26872271fa27f80b95262bf6c816
/plugins/retry/src/main/java/forklift/retry/Retry.java
6ea154f97b8523e440015dc27a27853a419d0436
[ "MIT" ]
permissive
dcshock/forklift
https://github.com/dcshock/forklift
7af994aa800c832338ffa20cdb054b862f166afa
7bc560615c4ce1d3a232d04d7c18ee5de8d77f92
refs/heads/develop
2021-04-15T03:41:17.137000
2020-09-14T21:40:58
2020-09-14T21:40:58
13,137,355
20
30
MIT
false
2020-09-14T17:44:09
2013-09-27T00:08:15
2020-09-14T17:33:51
2020-09-14T17:44:08
2,346
15
24
8
Java
false
false
package forklift.retry; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Instructs forklift how many times a message should be replayed through a processor in the event of an exception. */ @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface Retry { /** * The number of times a message should be retried. Default is 1 * * @return number of retries. Default 1 */ int maxRetries() default 1; /** * The amount of time in seconds between retry attempts. Default is 12 hours * * @return timeout in seconds. Default 12 hrs */ long timeout() default 12 * 60 * 60; /** * The name of the role to use to write retry messages, if there is no * {@link forklift.source.decorators.RoleInput} annotation present on a consumer. * * @return the name of the fallback role for writing retry messages. */ String role() default ""; /** * Should the message be persisted between retries. Default is true * * @return true/false whether the message retry is persisted to disk. */ boolean persistent() default true; }
UTF-8
Java
1,368
java
Retry.java
Java
[]
null
[]
package forklift.retry; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Instructs forklift how many times a message should be replayed through a processor in the event of an exception. */ @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface Retry { /** * The number of times a message should be retried. Default is 1 * * @return number of retries. Default 1 */ int maxRetries() default 1; /** * The amount of time in seconds between retry attempts. Default is 12 hours * * @return timeout in seconds. Default 12 hrs */ long timeout() default 12 * 60 * 60; /** * The name of the role to use to write retry messages, if there is no * {@link forklift.source.decorators.RoleInput} annotation present on a consumer. * * @return the name of the fallback role for writing retry messages. */ String role() default ""; /** * Should the message be persisted between retries. Default is true * * @return true/false whether the message retry is persisted to disk. */ boolean persistent() default true; }
1,368
0.692982
0.68348
46
28.73913
28.316868
115
false
false
0
0
0
0
0
0
0.26087
false
false
5
b15078c580de91f66be35a60acfa78d3a802064b
21,114,059,283,002
07431f7b754418a765f0a400f89db2907e5e7212
/Sprint5/src/Board.java
9eb0e4a187588a7d0f233996aea21caf7b803763
[]
no_license
Vinz000/Risk
https://github.com/Vinz000/Risk
66e46d9405310d0983f799d28f9aa642419346b6
764edac01c3d3a2bc49d503535c3e3d33482666a
refs/heads/main
2023-08-23T01:34:05.821000
2021-09-22T16:17:40
2021-09-22T16:17:40
409,207,155
0
0
null
false
2021-09-22T16:17:41
2021-09-22T13:04:11
2021-09-22T14:37:16
2021-09-22T16:17:40
5,835
0
0
0
Java
false
false
package src; public class Board implements BoardAPI { private final boolean[] occupied = new boolean[GameData.NUM_COUNTRIES]; private final int[] occupier = new int[GameData.NUM_COUNTRIES]; private final int[] numUnits = new int[GameData.NUM_COUNTRIES]; private int winnerId; private boolean invasionSuccess; private int goldenCavalry = 0; Board() { for (int i = 0; i < GameData.NUM_COUNTRIES; i++) { occupied[i] = false; occupier[i] = 0; numUnits[i] = 0; } return; } public void occupy(int countryId, int playerId) { occupied[countryId] = true; occupier[countryId] = playerId; return; } public void addUnits(int countryId, int addNumUnits) { // prerequisite: country must already occupied numUnits[countryId] = numUnits[countryId] + addNumUnits; return; } public void subtractUnits(int countryId, int subNumUnits) { numUnits[countryId] = numUnits[countryId] - subNumUnits; if (numUnits[countryId] == 0) { occupied[countryId] = false; } return; } public int calcReinforcements(Player player) { int playerId = player.getId(); int numCountriesOccupied = 0, numUnits; boolean allOccupied; int[] countryIds; for (int i = 0; i < GameData.NUM_COUNTRIES; i++) { if (occupier[i] == playerId) { numCountriesOccupied++; } } numUnits = numCountriesOccupied / 3; if (numUnits < 3) { numUnits = 3; } for (int i = 0; i < GameData.NUM_CONTINENTS; i++) { countryIds = GameData.CONTINENT_COUNTRIES[i]; allOccupied = true; for (int j = 0; (j < countryIds.length) && (allOccupied); j++) { if (occupier[countryIds[j]] != playerId) { allOccupied = false; } } if (allOccupied) { numUnits = numUnits + GameData.CONTINENT_VALUES[i]; } } return numUnits; } public void calcBattle(Player attackPlayer, Player defencePlayer, int attackCountryId, int defenceCountryId, int attackNumUnits, int defenceNumUnits) { int numUnitsRemaining = attackNumUnits; attackPlayer.resetBattleLoss(); defencePlayer.resetBattleLoss(); attackPlayer.rollDice(attackNumUnits); defencePlayer.rollDice(defenceNumUnits); if (attackPlayer.getDie(0) > defencePlayer.getDie(0)) { subtractUnits(defenceCountryId, 1); defencePlayer.addBattleLoss(); } else { subtractUnits(attackCountryId, 1); attackPlayer.addBattleLoss(); numUnitsRemaining--; } if ((attackNumUnits >= 2) && (defenceNumUnits >= 2) && isOccupied(defenceCountryId)) { if (attackPlayer.getDie(1) > defencePlayer.getDie(1)) { subtractUnits(defenceCountryId, 1); defencePlayer.addBattleLoss(); } else { subtractUnits(attackCountryId, 1); attackPlayer.addBattleLoss(); } } if (!isOccupied(defenceCountryId)) { subtractUnits(attackCountryId, numUnitsRemaining); occupy(defenceCountryId, attackPlayer.getId()); addUnits(defenceCountryId, numUnitsRemaining); invasionSuccess = true; } else { invasionSuccess = false; } return; } public void calcCardExchange(Player player) { player.addUnits(GameData.GOLDEN_CAVALRY[goldenCavalry]); if (goldenCavalry < GameData.GOLDEN_CAVALRY.length - 1) { goldenCavalry++; } return; } public boolean isAdjacent(int fromCountry, int toCountry) { boolean found = false; int[] neighbours = GameData.ADJACENT[fromCountry]; for (int i = 0; (i < neighbours.length) && (!found); i++) { found = (neighbours[i] == toCountry); } return found; } public boolean isConnected(int fromCountry, int toCountry, boolean[] countriesChecked) { int[] neighbours; int currentCountry; boolean found = false; if (occupier[fromCountry] == occupier[toCountry]) { if (isAdjacent(fromCountry, toCountry)) { found = true; } else { neighbours = GameData.ADJACENT[fromCountry]; countriesChecked[fromCountry] = true; for (int i = 0; (i < neighbours.length) && (!found); i++) { currentCountry = neighbours[i]; if ((occupier[currentCountry] == occupier[toCountry]) && (!countriesChecked[currentCountry])) { found = isConnected(currentCountry, toCountry, countriesChecked); } } } } return found; } public boolean isConnected(int fromCountry, int toCountry) { boolean[] countriesChecked = new boolean[GameData.NUM_COUNTRIES]; for (int i = 0; i < GameData.NUM_COUNTRIES; i++) { countriesChecked[i] = false; } countriesChecked[fromCountry] = true; return isConnected(fromCountry, toCountry, countriesChecked); } public boolean isOccupied(int country) { return occupied[country]; } public boolean isInvasionSuccess() { return invasionSuccess; } public boolean isEliminated(int playerId) { boolean found = false; for (int i = 0; (i < GameData.NUM_COUNTRIES) && !found; i++) { if (occupied[i] && (playerId == occupier[i])) { found = true; } } return !found; } public boolean isGameOver() { boolean gameOver; boolean[] playerFound = {false, false}; int playerId; for (int i = 0; i < GameData.NUM_COUNTRIES; i++) { playerId = getOccupier(i); if (playerId < GameData.NUM_PLAYERS) { playerFound[playerId] = true; } } if (playerFound[0] && playerFound[1]) { gameOver = false; } else { gameOver = true; if (playerFound[0]) { winnerId = 0; } else { winnerId = 1; } } return gameOver; } public int getOccupier(int countryId) { return occupier[countryId]; } public int getNumUnits(int countryId) { return numUnits[countryId]; } public int getWinner() { return winnerId; } }
UTF-8
Java
6,735
java
Board.java
Java
[]
null
[]
package src; public class Board implements BoardAPI { private final boolean[] occupied = new boolean[GameData.NUM_COUNTRIES]; private final int[] occupier = new int[GameData.NUM_COUNTRIES]; private final int[] numUnits = new int[GameData.NUM_COUNTRIES]; private int winnerId; private boolean invasionSuccess; private int goldenCavalry = 0; Board() { for (int i = 0; i < GameData.NUM_COUNTRIES; i++) { occupied[i] = false; occupier[i] = 0; numUnits[i] = 0; } return; } public void occupy(int countryId, int playerId) { occupied[countryId] = true; occupier[countryId] = playerId; return; } public void addUnits(int countryId, int addNumUnits) { // prerequisite: country must already occupied numUnits[countryId] = numUnits[countryId] + addNumUnits; return; } public void subtractUnits(int countryId, int subNumUnits) { numUnits[countryId] = numUnits[countryId] - subNumUnits; if (numUnits[countryId] == 0) { occupied[countryId] = false; } return; } public int calcReinforcements(Player player) { int playerId = player.getId(); int numCountriesOccupied = 0, numUnits; boolean allOccupied; int[] countryIds; for (int i = 0; i < GameData.NUM_COUNTRIES; i++) { if (occupier[i] == playerId) { numCountriesOccupied++; } } numUnits = numCountriesOccupied / 3; if (numUnits < 3) { numUnits = 3; } for (int i = 0; i < GameData.NUM_CONTINENTS; i++) { countryIds = GameData.CONTINENT_COUNTRIES[i]; allOccupied = true; for (int j = 0; (j < countryIds.length) && (allOccupied); j++) { if (occupier[countryIds[j]] != playerId) { allOccupied = false; } } if (allOccupied) { numUnits = numUnits + GameData.CONTINENT_VALUES[i]; } } return numUnits; } public void calcBattle(Player attackPlayer, Player defencePlayer, int attackCountryId, int defenceCountryId, int attackNumUnits, int defenceNumUnits) { int numUnitsRemaining = attackNumUnits; attackPlayer.resetBattleLoss(); defencePlayer.resetBattleLoss(); attackPlayer.rollDice(attackNumUnits); defencePlayer.rollDice(defenceNumUnits); if (attackPlayer.getDie(0) > defencePlayer.getDie(0)) { subtractUnits(defenceCountryId, 1); defencePlayer.addBattleLoss(); } else { subtractUnits(attackCountryId, 1); attackPlayer.addBattleLoss(); numUnitsRemaining--; } if ((attackNumUnits >= 2) && (defenceNumUnits >= 2) && isOccupied(defenceCountryId)) { if (attackPlayer.getDie(1) > defencePlayer.getDie(1)) { subtractUnits(defenceCountryId, 1); defencePlayer.addBattleLoss(); } else { subtractUnits(attackCountryId, 1); attackPlayer.addBattleLoss(); } } if (!isOccupied(defenceCountryId)) { subtractUnits(attackCountryId, numUnitsRemaining); occupy(defenceCountryId, attackPlayer.getId()); addUnits(defenceCountryId, numUnitsRemaining); invasionSuccess = true; } else { invasionSuccess = false; } return; } public void calcCardExchange(Player player) { player.addUnits(GameData.GOLDEN_CAVALRY[goldenCavalry]); if (goldenCavalry < GameData.GOLDEN_CAVALRY.length - 1) { goldenCavalry++; } return; } public boolean isAdjacent(int fromCountry, int toCountry) { boolean found = false; int[] neighbours = GameData.ADJACENT[fromCountry]; for (int i = 0; (i < neighbours.length) && (!found); i++) { found = (neighbours[i] == toCountry); } return found; } public boolean isConnected(int fromCountry, int toCountry, boolean[] countriesChecked) { int[] neighbours; int currentCountry; boolean found = false; if (occupier[fromCountry] == occupier[toCountry]) { if (isAdjacent(fromCountry, toCountry)) { found = true; } else { neighbours = GameData.ADJACENT[fromCountry]; countriesChecked[fromCountry] = true; for (int i = 0; (i < neighbours.length) && (!found); i++) { currentCountry = neighbours[i]; if ((occupier[currentCountry] == occupier[toCountry]) && (!countriesChecked[currentCountry])) { found = isConnected(currentCountry, toCountry, countriesChecked); } } } } return found; } public boolean isConnected(int fromCountry, int toCountry) { boolean[] countriesChecked = new boolean[GameData.NUM_COUNTRIES]; for (int i = 0; i < GameData.NUM_COUNTRIES; i++) { countriesChecked[i] = false; } countriesChecked[fromCountry] = true; return isConnected(fromCountry, toCountry, countriesChecked); } public boolean isOccupied(int country) { return occupied[country]; } public boolean isInvasionSuccess() { return invasionSuccess; } public boolean isEliminated(int playerId) { boolean found = false; for (int i = 0; (i < GameData.NUM_COUNTRIES) && !found; i++) { if (occupied[i] && (playerId == occupier[i])) { found = true; } } return !found; } public boolean isGameOver() { boolean gameOver; boolean[] playerFound = {false, false}; int playerId; for (int i = 0; i < GameData.NUM_COUNTRIES; i++) { playerId = getOccupier(i); if (playerId < GameData.NUM_PLAYERS) { playerFound[playerId] = true; } } if (playerFound[0] && playerFound[1]) { gameOver = false; } else { gameOver = true; if (playerFound[0]) { winnerId = 0; } else { winnerId = 1; } } return gameOver; } public int getOccupier(int countryId) { return occupier[countryId]; } public int getNumUnits(int countryId) { return numUnits[countryId]; } public int getWinner() { return winnerId; } }
6,735
0.556941
0.552042
204
32.014706
24.868177
155
false
false
0
0
0
0
0
0
0.651961
false
false
5
f172382628fa1526951f0a5035834f50267e0940
4,337,917,029,675
674530dea79e325347ad3e558d1e78e130fc5305
/src/ch/hearc/ig/guideresto/persistence/dao/EvaluationCriteriaDAO.java
c590d7a443d0cae9a7756919df778b8f521fdbaa
[]
no_license
Djer43/schoolprojects
https://github.com/Djer43/schoolprojects
a29e9ceff7edaf1f80485803bc56fd909e12a501
5808d74adfffb74072599f387449d97374b4175e
refs/heads/master
2021-01-17T03:55:29.472000
2015-05-04T06:51:47
2015-05-04T06:51:47
35,018,608
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ch.hearc.ig.guideresto.persistence.dao; import ch.hearc.ig.guideresto.business.EvaluationCriteria; import ch.hearc.ig.guideresto.exceptions.ConnectionProblemException; import java.util.Set; /** * * @author julien.plumez */ public interface EvaluationCriteriaDAO { public Set<EvaluationCriteria> researchAll() throws ConnectionProblemException; public EvaluationCriteria researchById(Integer id) throws ConnectionProblemException; }
UTF-8
Java
464
java
EvaluationCriteriaDAO.java
Java
[ { "context": "xception;\nimport java.util.Set;\n\n/**\n *\n * @author julien.plumez \n */\npublic interface EvaluationCriteriaDAO {\n ", "end": 231, "score": 0.9991809129714966, "start": 218, "tag": "NAME", "value": "julien.plumez" } ]
null
[]
package ch.hearc.ig.guideresto.persistence.dao; import ch.hearc.ig.guideresto.business.EvaluationCriteria; import ch.hearc.ig.guideresto.exceptions.ConnectionProblemException; import java.util.Set; /** * * @author julien.plumez */ public interface EvaluationCriteriaDAO { public Set<EvaluationCriteria> researchAll() throws ConnectionProblemException; public EvaluationCriteria researchById(Integer id) throws ConnectionProblemException; }
464
0.797414
0.797414
16
28
30.805843
89
false
false
0
0
0
0
0
0
0.375
false
false
5
4b00dd5a512cd19261e2572dc32326d4de4791b9
24,137,716,235,910
fc28b6654e07e51f976110e13e918c596968daa5
/statham/src/main/java/classes/servlets/AllQuotes.java
9387f79104dc41576e6a06a8c7ea12a9d69ccdf6
[]
no_license
selectme/statham
https://github.com/selectme/statham
e4731d0889134c11326265fa1c08c9a10fdcfe01
28821bc520bfcb906c67cb9ee457288e28664054
refs/heads/master
2019-04-03T06:37:24.783000
2016-08-26T09:56:45
2016-08-26T09:56:45
66,636,163
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package classes.servlets; import service.QuoteService; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.SQLException; /** * Created by Vitek on 15.08.2016. */ public class AllQuotes extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { QuoteService quoteService = new QuoteService(); try { req.setAttribute("allQuotes", quoteService.getQuotesList()); } catch (SQLException e) { e.printStackTrace(); } req.getRequestDispatcher("allQuotes.jsp").forward(req, resp); } }
UTF-8
Java
804
java
AllQuotes.java
Java
[ { "context": ";\nimport java.sql.SQLException;\n\n/**\n * Created by Vitek on 15.08.2016.\n */\npublic class AllQuotes extends", "end": 310, "score": 0.9543886184692383, "start": 305, "tag": "USERNAME", "value": "Vitek" } ]
null
[]
package classes.servlets; import service.QuoteService; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.SQLException; /** * Created by Vitek on 15.08.2016. */ public class AllQuotes extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { QuoteService quoteService = new QuoteService(); try { req.setAttribute("allQuotes", quoteService.getQuotesList()); } catch (SQLException e) { e.printStackTrace(); } req.getRequestDispatcher("allQuotes.jsp").forward(req, resp); } }
804
0.723881
0.71393
28
27.714285
26.709892
113
false
false
0
0
0
0
0
0
0.571429
false
false
5
4bdac1949553fdd984001d6c0c22873b4a298356
23,330,262,405,296
bc69a69002039d3d08e41fe29bd26a4edc3fc6da
/app/src/main/java/com/tzidis/android/movienightpart1/MainActivity.java
8a4da028f48316a83d9d792bbc3814e3c4ac0151
[]
no_license
Kafetzidis/MovieNightpart1
https://github.com/Kafetzidis/MovieNightpart1
099e746f14734165cb7a00072aaa891aba44d7e3
08b78bef120be7c8fa7848524822da0ad2c24a11
refs/heads/master
2020-03-12T05:16:20.050000
2018-04-21T10:19:52
2018-04-21T10:19:52
130,460,518
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tzidis.android.movienightpart1; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.tzidis.android.movienightpart1.Adapters.SimpleFragmentPagerAdapter; public class MainActivity extends AppCompatActivity { public static final String LOG_TAG = MainActivity.class.getName(); private ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Find the view pager that will allow the user to swipe between fragments viewPager = findViewById(R.id.viewpager); // Create an adapter that knows which fragment should be shown on each page SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager(), this); // Set the adapter onto the view pager viewPager.setAdapter(adapter); // Give the TabLayout the ViewPager TabLayout tabLayout = findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); Toolbar myToolbar = findViewById(R.id.toolbar); setSupportActionBar(myToolbar); myToolbar.setTitleTextColor(getResources().getColor(R.color.textColorPrimary)); } @Override public boolean onCreateOptionsMenu(Menu menu) { /* Use AppCompatActivity's method getMenuInflater to get a handle on the menu inflater */ MenuInflater inflater = getMenuInflater(); /* Use the inflater's inflate method to inflate our menu layout to this menu */ inflater.inflate(R.menu.action_menu, menu); /* Return true so that the menu is displayed in the Toolbar */ return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.most_popular: item.setChecked(true); viewPager.setCurrentItem(0); return true; case R.id.highest_rated: item.setChecked(true); viewPager.setCurrentItem(1); return true; case R.id.now_playing: item.setChecked(true); viewPager.setCurrentItem(2); return true; case R.id.upcoming: item.setChecked(true); viewPager.setCurrentItem(3); return true; default: // If we got here, the user's action was not recognized. // Invoke the superclass to handle it. return super.onOptionsItemSelected(item); } } }
UTF-8
Java
2,898
java
MainActivity.java
Java
[]
null
[]
package com.tzidis.android.movienightpart1; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.tzidis.android.movienightpart1.Adapters.SimpleFragmentPagerAdapter; public class MainActivity extends AppCompatActivity { public static final String LOG_TAG = MainActivity.class.getName(); private ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Find the view pager that will allow the user to swipe between fragments viewPager = findViewById(R.id.viewpager); // Create an adapter that knows which fragment should be shown on each page SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager(), this); // Set the adapter onto the view pager viewPager.setAdapter(adapter); // Give the TabLayout the ViewPager TabLayout tabLayout = findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); Toolbar myToolbar = findViewById(R.id.toolbar); setSupportActionBar(myToolbar); myToolbar.setTitleTextColor(getResources().getColor(R.color.textColorPrimary)); } @Override public boolean onCreateOptionsMenu(Menu menu) { /* Use AppCompatActivity's method getMenuInflater to get a handle on the menu inflater */ MenuInflater inflater = getMenuInflater(); /* Use the inflater's inflate method to inflate our menu layout to this menu */ inflater.inflate(R.menu.action_menu, menu); /* Return true so that the menu is displayed in the Toolbar */ return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.most_popular: item.setChecked(true); viewPager.setCurrentItem(0); return true; case R.id.highest_rated: item.setChecked(true); viewPager.setCurrentItem(1); return true; case R.id.now_playing: item.setChecked(true); viewPager.setCurrentItem(2); return true; case R.id.upcoming: item.setChecked(true); viewPager.setCurrentItem(3); return true; default: // If we got here, the user's action was not recognized. // Invoke the superclass to handle it. return super.onOptionsItemSelected(item); } } }
2,898
0.655625
0.652519
91
30.846153
27.249327
111
false
false
0
0
0
0
0
0
0.450549
false
false
5
794aaf7f7700df437e945c8355ab5a9289a7bc44
15,229,954,091,782
72b8ba90c2197f5bb434631e368aedb7a13f4fd4
/src/main/java/fr/imag/themoviedatabase/SearchEngine.java
c013628e4ed548bfad0e33fd3540f3191d45cae3
[]
no_license
cataniaj/e-movies
https://github.com/cataniaj/e-movies
8cd8c18bcb336811824c4567bd6bc779222d14a5
df7951e3db569caa793e6cea92d3d244394b8dfb
refs/heads/master
2020-12-25T14:39:06.636000
2016-09-28T07:24:02
2016-09-28T07:24:02
67,129,887
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.imag.themoviedatabase; /* * Author: Jérémy Leyvraz * Date: 11 sept. 2016 */ import java.io.StringReader; import java.util.List; import javax.ejb.ConcurrencyManagement; import javax.ejb.ConcurrencyManagementType; import javax.ejb.EJB; import javax.ejb.Local; import javax.ejb.Singleton; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonReader; import fr.imag.ejb.dbaccess.MovieDatabaseAccessEJB; import fr.imag.entities.Movie; import fr.imag.entities.MovieList; /** * We want only one copy of this class for all the client * that will use it and it is thread-safe (allow concurrent access) * @author le06 * */ @Singleton @Local @ConcurrencyManagement(ConcurrencyManagementType.BEAN) public class SearchEngine { /// Exemple url = target/type/title @EJB private MovieDatabaseAccessEJB dbAccess; private final String defaultValue = "N/A"; // TARGET private final String allKeyword = "all"; private final String exactKeyword = "exact"; // TYPE private final String movieKeyword = "movie"; private final String tvKeyword = "tv"; private final String multiKeyword = "multi"; public SearchEngine(){ } public JsonObject search(String url){ String[] elementUrl = url.split("/"); String target = elementUrl[0]; String type = elementUrl[1]; String title = elementUrl[2].replace("+", " "); if(target.compareTo(allKeyword) == 0){ return searchAll(type, title); }else if(target.compareTo(exactKeyword) == 0){ return searchExact(type, title); }else { JsonReader r = Json.createReader(new StringReader("{}")); JsonObject obj = r.readObject(); return obj; } } private JsonObject searchAll(String type, String title){ if(type.compareTo(movieKeyword)==0){ return searchAllMovies(title); } return null; } private JsonObject searchExact(String type, String id){ if(type.compareTo(movieKeyword)==0){ return searchExactMovie(id); } return null; } private JsonObject searchAllMovies(String title){ MovieList movieList = findAllFilmInOurDataBase(); String lowerTitle = title.toLowerCase(); MovieList result = new MovieList(); for(Movie m : movieList){ String movieTitle = m.getTitle().toLowerCase(); if(movieTitle.contains(lowerTitle) && !result.contains(m.getIdTMDB())){ result.add(m); } } return result.convertToJsonArrayResultSiteWeb(); } private JsonObject searchExactMovie(String id){ String idProductDvd = defaultValue; String idProductBluray = defaultValue; String idProductNumeric = defaultValue; String dvdPrice = defaultValue; String blurayPrice = defaultValue; String numericPrice = defaultValue; String dvdStock = defaultValue; String blurayStock = defaultValue; int idTMDB = 0; String title = defaultValue; String year = defaultValue; String genre = defaultValue; String poster = defaultValue; String director = defaultValue; String actors = defaultValue; String overview = defaultValue; String runtime = defaultValue; String trailer = defaultValue; List<Movie> movieList = findAllFilmInOurDataBase(); // extraire les 2 stocks et les 3 prix for(Movie m : movieList){ if(m.getIdTMDB()!=Integer.parseInt(id)){ continue; } idTMDB = m.getIdTMDB(); title = m.getTitle(); year = m.getYear(); genre = m.getGenre(); poster = m.getPoster(); director = m.getDirector(); actors = m.getActors(); overview = m.getOverview(); runtime = m.getRuntime(); trailer = m.getTrailer(); if(m.getSupport().compareTo("DVD")==0){ idProductDvd = String.valueOf(m.getIdProduct()); dvdPrice = String.valueOf(m.getPrice()); dvdStock = String.valueOf(m.getStock()); }else if(m.getSupport().compareTo("BR")==0){ idProductBluray = String.valueOf(m.getIdProduct()); blurayPrice = String.valueOf(m.getPrice()); blurayStock = String.valueOf(m.getStock()); }else if(m.getSupport().compareTo("CN")==0){ idProductNumeric = String.valueOf(m.getIdProduct()); numericPrice = String.valueOf(m.getPrice()); } } // Construite le json JsonObject movie = Json.createObjectBuilder() .add("idProductDvd", idProductDvd) .add("idProductBR", idProductBluray) .add("idProductNumeric", idProductNumeric) .add("dvdStock", dvdStock) .add("blurayStock", blurayStock) .add("dvdPrice", dvdPrice) .add("blurayPrice", blurayPrice) .add("numericPrice", numericPrice) .add("title", title) .add("year", year) .add("genre", genre) .add("poster", poster) .add("director", director) .add("overview", overview) .add("runtime", runtime) .add("actors", actors) .add("trailer", trailer) .add("idTMDB", idTMDB) .build(); return movie; } private MovieList findAllFilmInOurDataBase(){ MovieList m = new MovieList(dbAccess.findAllFilmInOurDataBase()); return m; } }
UTF-8
Java
5,149
java
SearchEngine.java
Java
[ { "context": "kage fr.imag.themoviedatabase;\n\n/*\n *\tAuthor: Jérémy Leyvraz\n *\tDate: 11 sept. 2016\n */\n\n\nimport java.i", "end": 68, "score": 0.9998535513877869, "start": 54, "tag": "NAME", "value": "Jérémy Leyvraz" }, { "context": "s thread-safe (allow concurrent access)\n * @author le06\n *\n */\n\n@Singleton\n@Local\n@ConcurrencyManagement(", "end": 664, "score": 0.9989040493965149, "start": 660, "tag": "USERNAME", "value": "le06" } ]
null
[]
package fr.imag.themoviedatabase; /* * Author: <NAME> * Date: 11 sept. 2016 */ import java.io.StringReader; import java.util.List; import javax.ejb.ConcurrencyManagement; import javax.ejb.ConcurrencyManagementType; import javax.ejb.EJB; import javax.ejb.Local; import javax.ejb.Singleton; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonReader; import fr.imag.ejb.dbaccess.MovieDatabaseAccessEJB; import fr.imag.entities.Movie; import fr.imag.entities.MovieList; /** * We want only one copy of this class for all the client * that will use it and it is thread-safe (allow concurrent access) * @author le06 * */ @Singleton @Local @ConcurrencyManagement(ConcurrencyManagementType.BEAN) public class SearchEngine { /// Exemple url = target/type/title @EJB private MovieDatabaseAccessEJB dbAccess; private final String defaultValue = "N/A"; // TARGET private final String allKeyword = "all"; private final String exactKeyword = "exact"; // TYPE private final String movieKeyword = "movie"; private final String tvKeyword = "tv"; private final String multiKeyword = "multi"; public SearchEngine(){ } public JsonObject search(String url){ String[] elementUrl = url.split("/"); String target = elementUrl[0]; String type = elementUrl[1]; String title = elementUrl[2].replace("+", " "); if(target.compareTo(allKeyword) == 0){ return searchAll(type, title); }else if(target.compareTo(exactKeyword) == 0){ return searchExact(type, title); }else { JsonReader r = Json.createReader(new StringReader("{}")); JsonObject obj = r.readObject(); return obj; } } private JsonObject searchAll(String type, String title){ if(type.compareTo(movieKeyword)==0){ return searchAllMovies(title); } return null; } private JsonObject searchExact(String type, String id){ if(type.compareTo(movieKeyword)==0){ return searchExactMovie(id); } return null; } private JsonObject searchAllMovies(String title){ MovieList movieList = findAllFilmInOurDataBase(); String lowerTitle = title.toLowerCase(); MovieList result = new MovieList(); for(Movie m : movieList){ String movieTitle = m.getTitle().toLowerCase(); if(movieTitle.contains(lowerTitle) && !result.contains(m.getIdTMDB())){ result.add(m); } } return result.convertToJsonArrayResultSiteWeb(); } private JsonObject searchExactMovie(String id){ String idProductDvd = defaultValue; String idProductBluray = defaultValue; String idProductNumeric = defaultValue; String dvdPrice = defaultValue; String blurayPrice = defaultValue; String numericPrice = defaultValue; String dvdStock = defaultValue; String blurayStock = defaultValue; int idTMDB = 0; String title = defaultValue; String year = defaultValue; String genre = defaultValue; String poster = defaultValue; String director = defaultValue; String actors = defaultValue; String overview = defaultValue; String runtime = defaultValue; String trailer = defaultValue; List<Movie> movieList = findAllFilmInOurDataBase(); // extraire les 2 stocks et les 3 prix for(Movie m : movieList){ if(m.getIdTMDB()!=Integer.parseInt(id)){ continue; } idTMDB = m.getIdTMDB(); title = m.getTitle(); year = m.getYear(); genre = m.getGenre(); poster = m.getPoster(); director = m.getDirector(); actors = m.getActors(); overview = m.getOverview(); runtime = m.getRuntime(); trailer = m.getTrailer(); if(m.getSupport().compareTo("DVD")==0){ idProductDvd = String.valueOf(m.getIdProduct()); dvdPrice = String.valueOf(m.getPrice()); dvdStock = String.valueOf(m.getStock()); }else if(m.getSupport().compareTo("BR")==0){ idProductBluray = String.valueOf(m.getIdProduct()); blurayPrice = String.valueOf(m.getPrice()); blurayStock = String.valueOf(m.getStock()); }else if(m.getSupport().compareTo("CN")==0){ idProductNumeric = String.valueOf(m.getIdProduct()); numericPrice = String.valueOf(m.getPrice()); } } // Construite le json JsonObject movie = Json.createObjectBuilder() .add("idProductDvd", idProductDvd) .add("idProductBR", idProductBluray) .add("idProductNumeric", idProductNumeric) .add("dvdStock", dvdStock) .add("blurayStock", blurayStock) .add("dvdPrice", dvdPrice) .add("blurayPrice", blurayPrice) .add("numericPrice", numericPrice) .add("title", title) .add("year", year) .add("genre", genre) .add("poster", poster) .add("director", director) .add("overview", overview) .add("runtime", runtime) .add("actors", actors) .add("trailer", trailer) .add("idTMDB", idTMDB) .build(); return movie; } private MovieList findAllFilmInOurDataBase(){ MovieList m = new MovieList(dbAccess.findAllFilmInOurDataBase()); return m; } }
5,139
0.664465
0.660385
185
26.821621
18.672297
77
false
false
0
0
0
0
0
0
2.027027
false
false
5
576133ac85680f9ddfdb55fe79fe5c4a3a625f29
35,270,271,473,397
804b0f80019dcf275b30fb3a3bff4f75959af7b7
/src/test/java/adventofcode/Day21Test.java
e116936b8b96eba9622cc6350ddbbcd4e0574a5e
[ "Apache-2.0" ]
permissive
jwcarman/adventofcode2020
https://github.com/jwcarman/adventofcode2020
c43ba27b3321660674ee702b2ae4a5efd661185b
00b777b40adfaaf2c4232a2e4eb2b290710de89d
refs/heads/master
2023-06-30T17:46:40.118000
2020-12-25T14:18:31
2020-12-25T14:18:31
319,065,702
1
0
Apache-2.0
false
2023-06-14T22:36:09
2020-12-06T15:30:03
2020-12-25T14:18:39
2023-06-14T22:36:09
272
1
0
1
Java
false
false
/* * Copyright (c) 2020 James Carman * * 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 adventofcode; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import adventofcode.allergen.AllergenScanner; import adventofcode.allergen.Food; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import static adventofcode.io.Input.readLines; import static adventofcode.io.Input.readResource; import static org.assertj.core.api.Assertions.assertThat; @Slf4j public class Day21Test { private static final String INPUT = readResource("Day21.txt"); private static final String EXAMPLE_INPUT = """ mxmxvkd kfcds sqjhc nhms (contains dairy, fish) trh fvjkl sbzzf mxmxvkd (contains dairy) sqjhc fvjkl (contains soy) sqjhc mxmxvkd sbzzf (contains fish)"""; @Test void part1() { log.info("Part One: {}", calculateAnswerPart1(INPUT)); } @Test void part2() { log.info("Part Two: {}", calculateAnswerPart2(INPUT)); } @Test void example1() { assertThat(calculateAnswerPart1(EXAMPLE_INPUT)).isEqualTo(5); } @Test void example2() { assertThat(calculateAnswerPart2(EXAMPLE_INPUT)).isEqualTo("mxmxvkd,sqjhc,fvjkl"); } private List<Food> parseFoods(String input) { return readLines(input).stream() .map(Food::new) .collect(Collectors.toList()); } private String calculateAnswerPart2(String input) { final List<Food> foods = parseFoods(input); final Map<String, String> ingredientsToAllergen = AllergenScanner.scanAllergens(foods); return ingredientsToAllergen.entrySet().stream() .sorted(Map.Entry.comparingByValue()) .map(Map.Entry::getKey) .collect(Collectors.joining(",")); } private long calculateAnswerPart1(String input) { final List<Food> foods = parseFoods(input); final Map<String, String> ingredientsToAllergen = AllergenScanner.scanAllergens(foods); return foods.stream() .flatMap(food -> food.getIngredients().stream()) .filter(ingredient -> !ingredientsToAllergen.containsKey(ingredient)) .count(); } }
UTF-8
Java
2,813
java
Day21Test.java
Java
[ { "context": "/*\n * Copyright (c) 2020 James Carman\n *\n * Licensed under the Apache License, Version ", "end": 37, "score": 0.9997627139091492, "start": 25, "tag": "NAME", "value": "James Carman" } ]
null
[]
/* * Copyright (c) 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package adventofcode; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import adventofcode.allergen.AllergenScanner; import adventofcode.allergen.Food; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import static adventofcode.io.Input.readLines; import static adventofcode.io.Input.readResource; import static org.assertj.core.api.Assertions.assertThat; @Slf4j public class Day21Test { private static final String INPUT = readResource("Day21.txt"); private static final String EXAMPLE_INPUT = """ mxmxvkd kfcds sqjhc nhms (contains dairy, fish) trh fvjkl sbzzf mxmxvkd (contains dairy) sqjhc fvjkl (contains soy) sqjhc mxmxvkd sbzzf (contains fish)"""; @Test void part1() { log.info("Part One: {}", calculateAnswerPart1(INPUT)); } @Test void part2() { log.info("Part Two: {}", calculateAnswerPart2(INPUT)); } @Test void example1() { assertThat(calculateAnswerPart1(EXAMPLE_INPUT)).isEqualTo(5); } @Test void example2() { assertThat(calculateAnswerPart2(EXAMPLE_INPUT)).isEqualTo("mxmxvkd,sqjhc,fvjkl"); } private List<Food> parseFoods(String input) { return readLines(input).stream() .map(Food::new) .collect(Collectors.toList()); } private String calculateAnswerPart2(String input) { final List<Food> foods = parseFoods(input); final Map<String, String> ingredientsToAllergen = AllergenScanner.scanAllergens(foods); return ingredientsToAllergen.entrySet().stream() .sorted(Map.Entry.comparingByValue()) .map(Map.Entry::getKey) .collect(Collectors.joining(",")); } private long calculateAnswerPart1(String input) { final List<Food> foods = parseFoods(input); final Map<String, String> ingredientsToAllergen = AllergenScanner.scanAllergens(foods); return foods.stream() .flatMap(food -> food.getIngredients().stream()) .filter(ingredient -> !ingredientsToAllergen.containsKey(ingredient)) .count(); } }
2,807
0.672947
0.663704
86
31.709303
27.207157
95
false
false
0
0
0
0
0
0
0.430233
false
false
5
19b3eacd639fb1d30fb1bcad9cc60fee26080217
39,084,202,415,894
b3b530370857419f524e71851a0e81475e656a4b
/app/src/main/java/com/yajun/socketproject/activity/OrdersActivity.java
2c368c69c3cc76a6968271e4a6618b0397aaecc9
[]
no_license
wanlifengyun123/FangJD
https://github.com/wanlifengyun123/FangJD
15e5f90761bc8c05affc1afcb37ae5481cbc9db8
266ed62d067ad25adcee901adba12f2119b8e753
refs/heads/master
2021-01-17T11:10:25.303000
2017-03-06T03:40:27
2017-03-06T03:40:27
84,026,611
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yajun.socketproject.activity; import com.example.market.R; import android.os.Bundle; import android.app.Activity; import android.graphics.Color; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; public class OrdersActivity extends Activity implements OnClickListener { private TextView mTextView; private TextView mTextView2; private View indicator; private View indicator2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_orders); mTextView = (TextView) findViewById(R.id.TextView01); mTextView2 = (TextView) findViewById(R.id.TextView02); indicator = findViewById(R.id.indicator1); indicator2 = findViewById(R.id.indicator2); findViewById(R.id.img_back).setOnClickListener(this); findViewById(R.id.layout_order1).setOnClickListener(this); findViewById(R.id.layout_order2).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.img_back: finish(); break; case R.id.layout_order1: indicator.setVisibility(View.VISIBLE); indicator2.setVisibility(View.INVISIBLE); mTextView.setTextColor(Color.RED); mTextView2.setTextColor(getResources().getColor(R.color.dark)); break; case R.id.layout_order2: indicator2.setVisibility(View.VISIBLE); indicator.setVisibility(View.INVISIBLE); mTextView2.setTextColor(Color.RED); mTextView.setTextColor(getResources().getColor(R.color.dark)); break; default: break; } } }
UTF-8
Java
1,579
java
OrdersActivity.java
Java
[]
null
[]
package com.yajun.socketproject.activity; import com.example.market.R; import android.os.Bundle; import android.app.Activity; import android.graphics.Color; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; public class OrdersActivity extends Activity implements OnClickListener { private TextView mTextView; private TextView mTextView2; private View indicator; private View indicator2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_orders); mTextView = (TextView) findViewById(R.id.TextView01); mTextView2 = (TextView) findViewById(R.id.TextView02); indicator = findViewById(R.id.indicator1); indicator2 = findViewById(R.id.indicator2); findViewById(R.id.img_back).setOnClickListener(this); findViewById(R.id.layout_order1).setOnClickListener(this); findViewById(R.id.layout_order2).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.img_back: finish(); break; case R.id.layout_order1: indicator.setVisibility(View.VISIBLE); indicator2.setVisibility(View.INVISIBLE); mTextView.setTextColor(Color.RED); mTextView2.setTextColor(getResources().getColor(R.color.dark)); break; case R.id.layout_order2: indicator2.setVisibility(View.VISIBLE); indicator.setVisibility(View.INVISIBLE); mTextView2.setTextColor(Color.RED); mTextView.setTextColor(getResources().getColor(R.color.dark)); break; default: break; } } }
1,579
0.766941
0.755542
56
27.196428
20.588156
73
false
false
0
0
0
0
0
0
2.017857
false
false
5
edc14b85bddd4b51b04f2825f02b9d16d670010d
39,367,670,238,599
e323abb057f124d0aa4fd2c9ae245cc525df4040
/app/src/main/java/com/tineco/qrqc/presenter/show/IShowMeasureVerificationPresenter.java
971b6614a750178f74615dde5e970b9134b92a2f
[]
no_license
JustAlva/QRQCRecord
https://github.com/JustAlva/QRQCRecord
74298b95e0ec1428e9f38cb5500cce30c04e5d33
3e64b5c1e483fb196676f23ed49e2a89ba82d0b0
refs/heads/master
2020-04-09T10:59:48.787000
2019-01-09T00:27:51
2019-01-09T00:27:51
160,291,085
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tineco.qrqc.presenter.show; public interface IShowMeasureVerificationPresenter { void getDetail(int tableId); }
UTF-8
Java
130
java
IShowMeasureVerificationPresenter.java
Java
[]
null
[]
package com.tineco.qrqc.presenter.show; public interface IShowMeasureVerificationPresenter { void getDetail(int tableId); }
130
0.8
0.8
6
20.666666
21.163385
52
false
false
0
0
0
0
0
0
0.333333
false
false
5
dc44bc5fbd3c9e738aa3e1424829bc58b50538fc
35,888,746,769,113
96f7cb9355ff95a3f4c7ab6e6f496f16db8d1bdd
/src/com/shianqi/app/weather/Entity/ChatHolder.java
b66f8a08f5e02d6f52e27bb8502952b6b5c47a26
[]
no_license
shianqi/weather
https://github.com/shianqi/weather
8b288d19c3b13ebe48489a1329ec3866b2657302
5e0cc8385e2e4806cf2f94ec7e3e3af44d5be4f5
refs/heads/master
2021-01-06T20:45:06.496000
2017-08-26T04:50:40
2017-08-26T04:50:40
99,556,699
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.shianqi.app.weather.Entity; import android.widget.ImageView; import android.widget.TextView; /** * * Created by admin on 2017/8/11. */ public class ChatHolder { public ImageView userImgImageView; public TextView userNameTextView; public TextView contentTextView; public TextView updateTimeTextView; public TextView messageCountTextView; }
UTF-8
Java
376
java
ChatHolder.java
Java
[ { "context": "ort android.widget.TextView;\n\n/**\n *\n * Created by admin on 2017/8/11.\n */\npublic class ChatHolder {\n p", "end": 133, "score": 0.9935093522071838, "start": 128, "tag": "USERNAME", "value": "admin" }, { "context": "ic ImageView userImgImageView;\n public TextView userNameTextView;\n public TextView contentTextView;\n ", "end": 245, "score": 0.8606104850769043, "start": 237, "tag": "USERNAME", "value": "userName" } ]
null
[]
package com.shianqi.app.weather.Entity; import android.widget.ImageView; import android.widget.TextView; /** * * Created by admin on 2017/8/11. */ public class ChatHolder { public ImageView userImgImageView; public TextView userNameTextView; public TextView contentTextView; public TextView updateTimeTextView; public TextView messageCountTextView; }
376
0.765957
0.74734
16
22.5
16.684574
41
false
false
0
0
0
0
0
0
0.5
false
false
5
a09dff75eb8764a99ba886aa3971fb7c50a91c16
38,543,036,534,572
3efb207a3cb45917ccc023d9de70fd3586ae52ef
/src/br/com/moip/foobarcard/poc/controller/IndexController.java
0693586a8e3afdb7c1e40073be7e6222c11784f4
[]
no_license
araujofelipe/pocfoobarcard
https://github.com/araujofelipe/pocfoobarcard
1a9dc808dbd2b015cadb0fcb72df1eb824ed7be6
1d8155c4c9f0298b924c38e480096595b7507ac5
refs/heads/master
2016-09-09T21:16:59.075000
2011-10-12T20:15:06
2011-10-12T20:15:06
2,564,985
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.moip.foobarcard.poc.controller; import br.com.caelum.vraptor.Path; import br.com.caelum.vraptor.Resource; /** * * @author Felipe S. Araujo jfelipe.dev@gmail.com @feli_pao * http://github.com/araujofelipe * 12/10/2011 */ @Resource public class IndexController { @Path("/") public void index(){} @Path("/pagenotfound") public void pagenotfound(){} }
UTF-8
Java
379
java
IndexController.java
Java
[ { "context": "br.com.caelum.vraptor.Resource;\n/**\n * \n * @author Felipe S. Araujo jfelipe.dev@gmail.com @feli_pao\n * http://github", "end": 157, "score": 0.9998918175697327, "start": 141, "tag": "NAME", "value": "Felipe S. Araujo" }, { "context": "tor.Resource;\n/**\n * \n * @author Felipe S. Araujo jfelipe.dev@gmail.com @feli_pao\n * http://github.com/araujofelipe\n * 12", "end": 180, "score": 0.9999268651008606, "start": 159, "tag": "EMAIL", "value": "jfelipe.dev@gmail.com" }, { "context": " * @author Felipe S. Araujo jfelipe.dev@gmail.com @feli_pao\n * http://github.com/araujofelipe\n * 12/10/2011\n ", "end": 190, "score": 0.9984428286552429, "start": 181, "tag": "USERNAME", "value": "@feli_pao" }, { "context": "lipe.dev@gmail.com @feli_pao\n * http://github.com/araujofelipe\n * 12/10/2011\n */\n@Resource\npublic class IndexCon", "end": 224, "score": 0.9984384179115295, "start": 212, "tag": "USERNAME", "value": "araujofelipe" } ]
null
[]
package br.com.moip.foobarcard.poc.controller; import br.com.caelum.vraptor.Path; import br.com.caelum.vraptor.Resource; /** * * @author <NAME> <EMAIL> @feli_pao * http://github.com/araujofelipe * 12/10/2011 */ @Resource public class IndexController { @Path("/") public void index(){} @Path("/pagenotfound") public void pagenotfound(){} }
355
0.704485
0.683377
19
18.947369
17.379581
60
false
false
0
0
0
0
0
0
0.473684
false
false
5
d17f6307f9d39b50d6970ab3aa42f255b49a1bfd
35,862,976,965,476
b9c25f99f5633eaec9800df6fdda639c399f6ae7
/variable/StringVariable.java
1680117bd05363143bc9ad8dadafdd10245f8b92
[]
no_license
yardenTal1/oppCompiler
https://github.com/yardenTal1/oppCompiler
ce00f9be4dc9904e8c2c3e00367d772a7f4f2cab
c3e90aa56d77f287b5c631e9dba15a8ecb48f457
refs/heads/master
2020-04-15T03:26:11.503000
2019-01-07T09:07:57
2019-01-07T09:07:57
164,348,734
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package oop.ex6.variable; /** * the class of String type variable */ public class StringVariable extends Variable { public StringVariable(String type, String nameVar, boolean isFinal, int lineNum) { super(type, nameVar, isFinal, lineNum); } }
UTF-8
Java
263
java
StringVariable.java
Java
[]
null
[]
package oop.ex6.variable; /** * the class of String type variable */ public class StringVariable extends Variable { public StringVariable(String type, String nameVar, boolean isFinal, int lineNum) { super(type, nameVar, isFinal, lineNum); } }
263
0.707224
0.703422
11
22.90909
26.820801
86
false
false
0
0
0
0
0
0
0.727273
false
false
5
a333accd04e969fc9c2717814bd23b234e8b3b07
23,484,881,223,878
807d3100c64eb0c1ebb5562c7f83d5706241f1ec
/src/main/java/br/ufrn/imd/winecloud/entity/Sensor.java
69ca436a1232545d23a34ae134cdfee4da5c6615
[]
no_license
Telemaco98/wine-cloud
https://github.com/Telemaco98/wine-cloud
1f8cb33f7f66b05448e23058434920f9801429b0
d3a6b7b6356dc6ed67fe78279360573ef80149d3
refs/heads/master
2020-06-03T04:07:14.011000
2019-06-25T03:24:18
2019-06-25T03:24:18
191,431,879
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.ufrn.imd.winecloud.entity; /** * The class that represents a sensor. In this case, the sensor can be * of the humidity or the temperature, this is defined by the "type" field * named. Furthermore, the sensor has the id (named in the creation) and the * measure fields. * * @author Shirley Ohara (shirleyohara@ufrn.edu.br) * @version 18 de jun de 2019 | 23:00:59 */ public class Sensor { private String id; private SensorType type; private double measure; /** * Convenience constructor * @param id * @param type * @param measure */ public Sensor (String id, SensorType type, double measure) { this.id = id; this.type = type; this.measure = measure; } /** * Return the id field * @return id */ public String getId() { return id; } /** * Returns the type field * @return type */ public SensorType getType() { return type; } /** * Returns the measure field * @return measure */ public double getMeasure() { return measure; } /** * Changes the value of the measure field * @param measure */ public void setMeasure(double measure) { this.measure = measure; } }
UTF-8
Java
1,165
java
Sensor.java
Java
[ { "context": "eation) and the \n * measure fields.\n *\n * @author Shirley Ohara (shirleyohara@ufrn.edu.br)\n * @version 18 de jun ", "end": 316, "score": 0.9998810887336731, "start": 303, "tag": "NAME", "value": "Shirley Ohara" }, { "context": "\n * measure fields.\n *\n * @author Shirley Ohara (shirleyohara@ufrn.edu.br)\n * @version 18 de jun de 2019 | 23:00:59\n */\npub", "end": 342, "score": 0.999935507774353, "start": 318, "tag": "EMAIL", "value": "shirleyohara@ufrn.edu.br" } ]
null
[]
package br.ufrn.imd.winecloud.entity; /** * The class that represents a sensor. In this case, the sensor can be * of the humidity or the temperature, this is defined by the "type" field * named. Furthermore, the sensor has the id (named in the creation) and the * measure fields. * * @author <NAME> (<EMAIL>) * @version 18 de jun de 2019 | 23:00:59 */ public class Sensor { private String id; private SensorType type; private double measure; /** * Convenience constructor * @param id * @param type * @param measure */ public Sensor (String id, SensorType type, double measure) { this.id = id; this.type = type; this.measure = measure; } /** * Return the id field * @return id */ public String getId() { return id; } /** * Returns the type field * @return type */ public SensorType getType() { return type; } /** * Returns the measure field * @return measure */ public double getMeasure() { return measure; } /** * Changes the value of the measure field * @param measure */ public void setMeasure(double measure) { this.measure = measure; } }
1,141
0.651502
0.641202
60
18.433332
18.915926
77
false
false
0
0
0
0
0
0
1.3
false
false
5
dabae3d20641d01ec484ddd87155df535905e8d2
23,484,881,224,879
befae6a20c7b14c122e8cc3c68896eb855a1e5a9
/src/main/java/rating/controller/WidBlobController.java
438d339df120000a26b07476357ee9064ebfa1c8
[]
no_license
santono/Rating
https://github.com/santono/Rating
dee06370efb980465745cd21309f891d02107bf8
0d972a0aceaa26cff34d92aa8eff3684ecf94123
refs/heads/master
2020-03-23T07:59:20.390000
2018-10-18T17:46:15
2018-10-18T17:46:15
141,301,871
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package rating.controller; import rating.domain.WidBlobEntity; import rating.dto.ItemErrorDTO; import rating.service.WidBlobService; import rating.service.validators.WidBlobValidator; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpSession; import java.util.ArrayList; import java.util.List; @Controller @RequestMapping("/widblob") public class WidBlobController { @Autowired private WidBlobService widBlobService; protected static Logger logger = Logger.getLogger("controller"); @Autowired private WidBlobValidator widBlobValidator; @RequestMapping(method = RequestMethod.GET) public String browseWidBlobList(Model model) { List<WidBlobEntity> widBlobList = widBlobService.getAll(); WidBlobEntity widBlob=new WidBlobEntity(); model.addAttribute("wbList", widBlobList); model.addAttribute("wb", widBlob); logger.debug("Amnt of wb rec=" + widBlobList.size()); return "browseWidBlob"; } @RequestMapping(value = "/getrec", method = RequestMethod.POST) // @ResponseBody public String getTableRow(@RequestParam int id, Model model, HttpSession session) { // logger.debug("Request Ajax for group. For id = " + id); int idwb = id; logger.debug(" id wb for edit =" + idwb); WidBlobEntity wb; if (id > 0) { wb = widBlobService.getById(id); } else { wb = new WidBlobEntity(); } model.addAttribute("wb", wb); logger.debug("Response Ajax " + wb.toString()); String viewName = "widBlobFormBootstrap"; return viewName; } @RequestMapping(value = "/save", method = RequestMethod.POST, produces = "application/json") @ResponseBody public List<ItemErrorDTO> saveTableWDRow(@ModelAttribute("WidBlobEntity") WidBlobEntity widBlobEntity, BindingResult result, HttpSession session, Model model) { // if (result.hasErrors()) { // return "browseAllGroups"; // } logger.debug("----save started save WidBlobentity row for " + widBlobEntity.toString()); widBlobValidator.validate(widBlobEntity, result); if (result.hasErrors()) { return getErrList(result); } logger.debug("save WidBlobentity row for " + widBlobEntity.toString()); widBlobService.saveRecord(widBlobEntity); List<ItemErrorDTO> okList = new ArrayList<ItemErrorDTO>(); okList.add(new ItemErrorDTO(0, "Ok", "Ok")); // session.setAttribute("needRestPosition", 1); return okList; } @RequestMapping(value = "/delrec/{id}", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8") @ResponseBody public String delWidBlobRec(@PathVariable int id) { // logger.debug("Request Ajax for delete group. For id = " + id); widBlobService.deleteRecord(id); String viewName = "Запись удалена!"; return viewName; } private List<ItemErrorDTO> getErrList(BindingResult result) { if (result.hasErrors()) { List<ItemErrorDTO> errList = new ArrayList<ItemErrorDTO>(); int errCnt = result.getErrorCount(); if (errCnt > 0) { int i; i = 0; for (ObjectError oError : result.getAllErrors()) { ItemErrorDTO errDTO = new ItemErrorDTO(i++, oError.getDefaultMessage(), oError.getCode()); errList.add(errDTO); } } return errList; } else return null; } }
UTF-8
Java
3,932
java
WidBlobController.java
Java
[]
null
[]
package rating.controller; import rating.domain.WidBlobEntity; import rating.dto.ItemErrorDTO; import rating.service.WidBlobService; import rating.service.validators.WidBlobValidator; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpSession; import java.util.ArrayList; import java.util.List; @Controller @RequestMapping("/widblob") public class WidBlobController { @Autowired private WidBlobService widBlobService; protected static Logger logger = Logger.getLogger("controller"); @Autowired private WidBlobValidator widBlobValidator; @RequestMapping(method = RequestMethod.GET) public String browseWidBlobList(Model model) { List<WidBlobEntity> widBlobList = widBlobService.getAll(); WidBlobEntity widBlob=new WidBlobEntity(); model.addAttribute("wbList", widBlobList); model.addAttribute("wb", widBlob); logger.debug("Amnt of wb rec=" + widBlobList.size()); return "browseWidBlob"; } @RequestMapping(value = "/getrec", method = RequestMethod.POST) // @ResponseBody public String getTableRow(@RequestParam int id, Model model, HttpSession session) { // logger.debug("Request Ajax for group. For id = " + id); int idwb = id; logger.debug(" id wb for edit =" + idwb); WidBlobEntity wb; if (id > 0) { wb = widBlobService.getById(id); } else { wb = new WidBlobEntity(); } model.addAttribute("wb", wb); logger.debug("Response Ajax " + wb.toString()); String viewName = "widBlobFormBootstrap"; return viewName; } @RequestMapping(value = "/save", method = RequestMethod.POST, produces = "application/json") @ResponseBody public List<ItemErrorDTO> saveTableWDRow(@ModelAttribute("WidBlobEntity") WidBlobEntity widBlobEntity, BindingResult result, HttpSession session, Model model) { // if (result.hasErrors()) { // return "browseAllGroups"; // } logger.debug("----save started save WidBlobentity row for " + widBlobEntity.toString()); widBlobValidator.validate(widBlobEntity, result); if (result.hasErrors()) { return getErrList(result); } logger.debug("save WidBlobentity row for " + widBlobEntity.toString()); widBlobService.saveRecord(widBlobEntity); List<ItemErrorDTO> okList = new ArrayList<ItemErrorDTO>(); okList.add(new ItemErrorDTO(0, "Ok", "Ok")); // session.setAttribute("needRestPosition", 1); return okList; } @RequestMapping(value = "/delrec/{id}", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8") @ResponseBody public String delWidBlobRec(@PathVariable int id) { // logger.debug("Request Ajax for delete group. For id = " + id); widBlobService.deleteRecord(id); String viewName = "Запись удалена!"; return viewName; } private List<ItemErrorDTO> getErrList(BindingResult result) { if (result.hasErrors()) { List<ItemErrorDTO> errList = new ArrayList<ItemErrorDTO>(); int errCnt = result.getErrorCount(); if (errCnt > 0) { int i; i = 0; for (ObjectError oError : result.getAllErrors()) { ItemErrorDTO errDTO = new ItemErrorDTO(i++, oError.getDefaultMessage(), oError.getCode()); errList.add(errDTO); } } return errList; } else return null; } }
3,932
0.648125
0.646338
107
35.626167
28.786524
164
false
false
0
0
0
0
0
0
0.71028
false
false
5
93c8246c42b299c3090dd88d6df6d1f1c7366c18
23,484,881,223,616
bd18621b560931e19b30f9798a1d732d0be32da8
/app/src/main/java/com/example/maincities/MainActivity.java
f51f0fac4bef6d40b912366531450c42ea4ca287
[ "MIT" ]
permissive
Raandino/MainCtities
https://github.com/Raandino/MainCtities
146049765db5ae4bd6d9031692528513adfc7162
1e08bcafd0c678a3145c1ef38e173e33f079ffdd
refs/heads/master
2020-06-01T06:10:32.241000
2019-06-08T15:27:26
2019-06-08T15:27:26
190,672,370
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.maincities; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.android.volley.RequestQueue; import java.text.DecimalFormat; public class MainActivity extends AppCompatActivity { private TextView tiempo;//Aqui se almacena el tiempo private TextView t_descrip;//Aqui se almacena descripccion del tiempo private TextView temperatura; String icon, main_tiempo, description, temp_c; private RequestQueue mQueue;// DecimalFormat df = new DecimalFormat("#.00"); Button GoNew, GoMan, GoLon; EditText textBox; String textBoxText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textBox = (EditText) findViewById(R.id.textBox); GoLon = (Button) findViewById(R.id.GoLon); GoLon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this, London.class); textBoxText = textBox.getText().toString(); i.putExtra("dato01",textBoxText);///se crea variables dato01 que pasa //a la siguiente aquitvidad y el string //del textbox startActivity(i);//siguiente actividad } }); } }
UTF-8
Java
1,648
java
MainActivity.java
Java
[]
null
[]
package com.example.maincities; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.android.volley.RequestQueue; import java.text.DecimalFormat; public class MainActivity extends AppCompatActivity { private TextView tiempo;//Aqui se almacena el tiempo private TextView t_descrip;//Aqui se almacena descripccion del tiempo private TextView temperatura; String icon, main_tiempo, description, temp_c; private RequestQueue mQueue;// DecimalFormat df = new DecimalFormat("#.00"); Button GoNew, GoMan, GoLon; EditText textBox; String textBoxText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textBox = (EditText) findViewById(R.id.textBox); GoLon = (Button) findViewById(R.id.GoLon); GoLon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this, London.class); textBoxText = textBox.getText().toString(); i.putExtra("dato01",textBoxText);///se crea variables dato01 que pasa //a la siguiente aquitvidad y el string //del textbox startActivity(i);//siguiente actividad } }); } }
1,648
0.643811
0.639563
53
30.056604
25.561922
95
false
false
0
0
0
0
0
0
0.660377
false
false
5