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
sequence | 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
sequence | 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
afab480b2db1f843ef4b6aeb0662be4c9d77ad96 | 21,758,304,390,077 | 0b24cf99612ce74f354f2af5274888fc32b47e7b | /springboot-json-format/springboot-json-format-framework/src/main/java/com/github/lybgeek/jackson/env/CustomJacksonFormatEnvironmentApplicationContextInitializer.java | 1c76fc05a098836a7abb1503ca27bf6685bbb8fb | [] | no_license | lyb-geek/springboot-learning | https://github.com/lyb-geek/springboot-learning | 9c90706ffe4af8f14485d043c52bbb795f366bc0 | d441036b5969a8023b92b4c40b8a915cf524dba6 | refs/heads/master | 2023-07-25T13:43:46.685000 | 2023-07-22T12:41:42 | 2023-07-22T12:41:42 | 195,616,981 | 544 | 395 | null | false | 2023-03-11T02:17:31 | 2019-07-07T06:13:03 | 2023-03-07T10:00:13 | 2023-03-11T02:17:27 | 2,973 | 423 | 355 | 19 | Java | false | false | package com.github.lybgeek.jackson.env;
import com.github.lybgeek.jackson.env.util.EnvUtils;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
public class CustomJacksonFormatEnvironmentApplicationContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
ConfigurableEnvironment environment = applicationContext.getEnvironment();
EnvUtils.postProcessEnvironment(environment);
}
} | UTF-8 | Java | 645 | java | CustomJacksonFormatEnvironmentApplicationContextInitializer.java | Java | [
{
"context": "package com.github.lybgeek.jackson.env;\n\nimport com.github.lybgeek.jackson.e",
"end": 26,
"score": 0.999214231967926,
"start": 19,
"tag": "USERNAME",
"value": "lybgeek"
},
{
"context": "om.github.lybgeek.jackson.env;\n\nimport com.github.lybgeek.jackson.env.util.EnvUtils;\nimport org.springframe",
"end": 66,
"score": 0.9992513060569763,
"start": 59,
"tag": "USERNAME",
"value": "lybgeek"
}
] | null | [] | package com.github.lybgeek.jackson.env;
import com.github.lybgeek.jackson.env.util.EnvUtils;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
public class CustomJacksonFormatEnvironmentApplicationContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
ConfigurableEnvironment environment = applicationContext.getEnvironment();
EnvUtils.postProcessEnvironment(environment);
}
} | 645 | 0.843411 | 0.843411 | 16 | 39.375 | 36.050095 | 115 | true | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false | 2 |
be1e0fb14cc8dba9da5ff64effee46f417d59b3b | 35,296,041,254,124 | 5ab9930e49da532ed88c191d18b62a123b916a88 | /src/main/java/br/com/mercadolivre/calculametroquadrado/dto/ResponseComodoDto.java | 1758c33ee724a83081c99b17cb463df1dae00f57 | [] | no_license | bootcamp-meli-grupo-4/calcula-metro-quadrado | https://github.com/bootcamp-meli-grupo-4/calcula-metro-quadrado | 3cd87cebe7dd28f13f868762f9268c008f33c746 | 7da0689c046c510b3df1ffffc88835e0bc36da7c | refs/heads/master | 2023-05-08T21:15:13.721000 | 2021-05-28T12:14:32 | 2021-05-28T12:14:32 | 371,688,265 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.mercadolivre.calculametroquadrado.dto;
public class ResponseComodoDto {
private String nome;
private boolean ehMaior;
private Double metroQuadrado;
public ResponseComodoDto(String nome, boolean ehMaior, Double metroQuadrado) {
this.nome = nome;
this.ehMaior = ehMaior;
this.metroQuadrado = metroQuadrado;
}
public String getNome() {
return nome;
}
public boolean isEhMaior() {
return ehMaior;
}
public Double getMetroQuadrado() {
return metroQuadrado;
}
}
| UTF-8 | Java | 569 | java | ResponseComodoDto.java | Java | [] | null | [] | package br.com.mercadolivre.calculametroquadrado.dto;
public class ResponseComodoDto {
private String nome;
private boolean ehMaior;
private Double metroQuadrado;
public ResponseComodoDto(String nome, boolean ehMaior, Double metroQuadrado) {
this.nome = nome;
this.ehMaior = ehMaior;
this.metroQuadrado = metroQuadrado;
}
public String getNome() {
return nome;
}
public boolean isEhMaior() {
return ehMaior;
}
public Double getMetroQuadrado() {
return metroQuadrado;
}
}
| 569 | 0.660808 | 0.660808 | 26 | 20.884615 | 19.884912 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false | 2 |
53ab0d5f546339b9da6d397b07abc22b016c1987 | 34,969,623,740,621 | 2b69baa6d0a93cc3dc0116de736e4293cc41b1c9 | /src/main/java/ua/lviv/lgs/repository/PeopleRepo.java | eac6c17ede61b28011c6a63c43f219d65be32740 | [] | no_license | Shvachuchka/Fridge | https://github.com/Shvachuchka/Fridge | a60c7c4ab027271b8f546637bdd65c4b5fc9c7e6 | 1c9b3049584d2d874f3f38d5e8c891b754f4ca1e | refs/heads/master | 2021-01-16T21:04:00.184000 | 2016-08-10T17:28:32 | 2016-08-10T17:28:32 | 64,871,340 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ua.lviv.lgs.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import ua.lviv.lgs.entity.People;
/**
* Created by Sasha on 08.08.2016.
*/
public interface PeopleRepo extends JpaRepository<People, Integer> {
@Query("SELECT u FROM People u WHERE u.email LIKE :login OR u.phone LIKE :login")
People findByLogin(@Param("login") String login);
}
| UTF-8 | Java | 496 | java | PeopleRepo.java | Java | [
{
"context": "port ua.lviv.lgs.entity.People;\n\n/**\n * Created by Sasha on 08.08.2016.\n */\npublic interface PeopleRepo ex",
"end": 263,
"score": 0.9982242584228516,
"start": 258,
"tag": "NAME",
"value": "Sasha"
}
] | null | [] | package ua.lviv.lgs.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import ua.lviv.lgs.entity.People;
/**
* Created by Sasha on 08.08.2016.
*/
public interface PeopleRepo extends JpaRepository<People, Integer> {
@Query("SELECT u FROM People u WHERE u.email LIKE :login OR u.phone LIKE :login")
People findByLogin(@Param("login") String login);
}
| 496 | 0.768145 | 0.752016 | 16 | 30 | 28.546015 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false | 2 |
3c3d56cd5c4c76b36b1c9fe2f8b95fc0fc63dba7 | 36,017,595,761,731 | 305977229541a04e9d8229526e05945f814ad90e | /bank/NotEnoughMoneyInBankException.java | 27d9b0d253ffea251ac9d3bbaafa2fd88cbc61a1 | [] | no_license | DimitarLazarov/Homeworks | https://github.com/DimitarLazarov/Homeworks | c475a573e89fa626cf6694d32cec53725e511363 | e2460171bf50a96b630a1ed26883d5d9089f5bcd | refs/heads/master | 2020-04-10T21:31:25.022000 | 2016-02-14T15:41:31 | 2016-02-14T15:41:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bank;
public class NotEnoughMoneyInBankException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public NotEnoughMoneyInBankException() {
super();
}
public NotEnoughMoneyInBankException(String message, Throwable cause) {
super(message, cause);
}
public NotEnoughMoneyInBankException(String message) {
super(message);
}
public NotEnoughMoneyInBankException(Throwable cause) {
super(cause);
}
}
| UTF-8 | Java | 461 | java | NotEnoughMoneyInBankException.java | Java | [] | null | [] | package bank;
public class NotEnoughMoneyInBankException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public NotEnoughMoneyInBankException() {
super();
}
public NotEnoughMoneyInBankException(String message, Throwable cause) {
super(message, cause);
}
public NotEnoughMoneyInBankException(String message) {
super(message);
}
public NotEnoughMoneyInBankException(Throwable cause) {
super(cause);
}
}
| 461 | 0.748373 | 0.746204 | 26 | 16.73077 | 22.716578 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.076923 | false | false | 2 |
91675049194ec69dafc71897f543b7a6a81155a8 | 34,385,508,199,627 | 5ec4df88b5007bc0087398047b88f70e88de7cc1 | /btm/src/test/java/bitronix/tm/mock/resource/jms/MockConnectionFactory.java | b41fdbb3f9c260a47cf631fab58d9762a85099e8 | [] | no_license | mulesoft/btm | https://github.com/mulesoft/btm | 56070e3583d34d12c08d19f50c47606dad8d2d9c | 6d1193451403c203214a9eee8f64a55eebc38876 | refs/heads/support/2.1.x | 2023-08-29T03:09:23.416000 | 2023-08-25T18:13:54 | 2023-08-25T18:13:54 | 45,200,599 | 0 | 3 | null | true | 2023-08-25T18:13:56 | 2015-10-29T17:47:24 | 2023-03-16T14:25:34 | 2023-08-25T18:13:55 | 8,441 | 0 | 2 | 9 | Java | false | false | /*
* Bitronix Transaction Manager
*
* Copyright (c) 2010, Bitronix Software.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package bitronix.tm.mock.resource.jms;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/**
*
* @author lorban
*/
public class MockConnectionFactory implements ConnectionFactory {
public Connection createConnection() throws JMSException {
Answer<Session> sessionAnswer = new Answer<Session>() {
public Session answer(InvocationOnMock invocation) throws Throwable {
Session session = mock(Session.class);
MessageProducer producer = mock(MessageProducer.class);
when(session.createProducer((Destination) anyObject())).thenReturn(producer);
return session;
}
};
Connection connection = mock(Connection.class);
when(connection.createSession(anyBoolean(), anyInt())).thenAnswer(sessionAnswer);
return connection;
}
public Connection createConnection(String jndiName, String jndiName1) throws JMSException {
return createConnection();
}
@Override
public JMSContext createContext()
{
throw new RuntimeException("Method not supported");
}
@Override
public JMSContext createContext(String userName, String password)
{
throw new RuntimeException("Method not supported");
}
@Override
public JMSContext createContext(String userName, String password, int sessionMode)
{
throw new RuntimeException("Method not supported");
}
@Override
public JMSContext createContext(int sessionMode)
{
throw new RuntimeException("Method not supported");
}
} | UTF-8 | Java | 2,568 | java | MockConnectionFactory.java | Java | [
{
"context": "rt org.mockito.stubbing.Answer;\n\n/**\n *\n * @author lorban\n */\npublic class MockConnectionFactory implements",
"end": 1247,
"score": 0.9988863468170166,
"start": 1241,
"tag": "USERNAME",
"value": "lorban"
},
{
"context": "\t@Override\n\tpublic JMSContext createContext(String userName, String password, int sessionMode)\n\t{\n\t\tthrow new",
"end": 2349,
"score": 0.7453605532646179,
"start": 2341,
"tag": "USERNAME",
"value": "userName"
}
] | null | [] | /*
* Bitronix Transaction Manager
*
* Copyright (c) 2010, Bitronix Software.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package bitronix.tm.mock.resource.jms;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/**
*
* @author lorban
*/
public class MockConnectionFactory implements ConnectionFactory {
public Connection createConnection() throws JMSException {
Answer<Session> sessionAnswer = new Answer<Session>() {
public Session answer(InvocationOnMock invocation) throws Throwable {
Session session = mock(Session.class);
MessageProducer producer = mock(MessageProducer.class);
when(session.createProducer((Destination) anyObject())).thenReturn(producer);
return session;
}
};
Connection connection = mock(Connection.class);
when(connection.createSession(anyBoolean(), anyInt())).thenAnswer(sessionAnswer);
return connection;
}
public Connection createConnection(String jndiName, String jndiName1) throws JMSException {
return createConnection();
}
@Override
public JMSContext createContext()
{
throw new RuntimeException("Method not supported");
}
@Override
public JMSContext createContext(String userName, String password)
{
throw new RuntimeException("Method not supported");
}
@Override
public JMSContext createContext(String userName, String password, int sessionMode)
{
throw new RuntimeException("Method not supported");
}
@Override
public JMSContext createContext(int sessionMode)
{
throw new RuntimeException("Method not supported");
}
} | 2,568 | 0.758567 | 0.752336 | 85 | 29.22353 | 28.231554 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.094118 | false | false | 2 |
6929645e3c645928f7c8fbd67973a1b28ed6d2ca | 7,937,099,633,135 | 6b77fca8c8f3025fb0e47f7dbc3af5df56100e9c | /ServerGUI.java | 393cc178329f5c2eae211a5ed66fe49d81653eaf | [] | no_license | ahnzhx/instagram_java | https://github.com/ahnzhx/instagram_java | e41eb7d9639dcc5ecc2510f8894a66cac32dfe20 | cef659b2d169e24d5d3965a48348473b56cca888 | refs/heads/master | 2020-03-22T13:07:21.255000 | 2018-07-07T13:06:32 | 2018-07-07T13:06:32 | 140,084,782 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ig;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Scrollbar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.SystemColor;
public class ServerGUI extends JFrame implements ActionListener {
private JTextArea ta = new JTextArea();
private JTextField tf = new JTextField(18);
private Server server = new Server(); // Server Class와 연결시킴
private JPanel pl = new JPanel();
private JScrollPane sp;
private JButton btn = new JButton("Enter");
private JButton btn2 = new JButton("Exit");
public ServerGUI() {
setTitle("Direct");
setBounds(0, 0, 389, 435);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
getContentPane().setLayout(new BorderLayout());
pl.setBackground(Color.WHITE);
pl.add(tf);
pl.add(btn);
pl.add(btn2);
getContentPane().add(pl,"South");
ta.setBackground(SystemColor.activeCaption);
ta.setLineWrap(true); // 꽉차면 다음줄로 가게 해줌
ta.setEditable(false); // 수정불가능
pl.add(ta);
sp = new JScrollPane(ta, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
getContentPane().add(sp, BorderLayout.CENTER);
btn.setPreferredSize(new Dimension(80, 22));
btn2.setPreferredSize(new Dimension(80, 22));
tf.addActionListener(this);
btn.addActionListener(this);
btn2.addActionListener(this);
server.setGui(this);
server.setting(); // GUI가 실행될때 서버도 같이 동작함
}
public static void main(String[] args) {
new ServerGUI();
}
@Override
public void actionPerformed(ActionEvent e) {
String msg = "서버 : " + tf.getText()+"\n";
if(e.getSource()==tf || e.getSource()==btn) {
if(tf.getText().equals("")) {
return;
}
ta.append(msg);
tf.setText("");
server.sendMessage(msg);
sp.getVerticalScrollBar().setValue(sp.getVerticalScrollBar().getMaximum());//맨밑으로
}else if(e.getSource()==btn2){
System.exit(0);
}
}
public void appendMsg(String msg) {
ta.append(msg);
sp.getVerticalScrollBar().setValue(sp.getVerticalScrollBar().getMaximum());//맨밑으로
}
}
| UTF-8 | Java | 2,480 | java | ServerGUI.java | Java | [] | null | [] |
package ig;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Scrollbar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.SystemColor;
public class ServerGUI extends JFrame implements ActionListener {
private JTextArea ta = new JTextArea();
private JTextField tf = new JTextField(18);
private Server server = new Server(); // Server Class와 연결시킴
private JPanel pl = new JPanel();
private JScrollPane sp;
private JButton btn = new JButton("Enter");
private JButton btn2 = new JButton("Exit");
public ServerGUI() {
setTitle("Direct");
setBounds(0, 0, 389, 435);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
getContentPane().setLayout(new BorderLayout());
pl.setBackground(Color.WHITE);
pl.add(tf);
pl.add(btn);
pl.add(btn2);
getContentPane().add(pl,"South");
ta.setBackground(SystemColor.activeCaption);
ta.setLineWrap(true); // 꽉차면 다음줄로 가게 해줌
ta.setEditable(false); // 수정불가능
pl.add(ta);
sp = new JScrollPane(ta, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
getContentPane().add(sp, BorderLayout.CENTER);
btn.setPreferredSize(new Dimension(80, 22));
btn2.setPreferredSize(new Dimension(80, 22));
tf.addActionListener(this);
btn.addActionListener(this);
btn2.addActionListener(this);
server.setGui(this);
server.setting(); // GUI가 실행될때 서버도 같이 동작함
}
public static void main(String[] args) {
new ServerGUI();
}
@Override
public void actionPerformed(ActionEvent e) {
String msg = "서버 : " + tf.getText()+"\n";
if(e.getSource()==tf || e.getSource()==btn) {
if(tf.getText().equals("")) {
return;
}
ta.append(msg);
tf.setText("");
server.sendMessage(msg);
sp.getVerticalScrollBar().setValue(sp.getVerticalScrollBar().getMaximum());//맨밑으로
}else if(e.getSource()==btn2){
System.exit(0);
}
}
public void appendMsg(String msg) {
ta.append(msg);
sp.getVerticalScrollBar().setValue(sp.getVerticalScrollBar().getMaximum());//맨밑으로
}
}
| 2,480 | 0.686873 | 0.676839 | 88 | 25.15909 | 20.84133 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.147727 | false | false | 2 |
2a0062f68e47bfd428cfeb5e851a9ce5e8cbf36f | 19,344,532,716,566 | e320fa472619bd3dffb82d9ce53dae74d8e1222d | /src/java/servlets/AdminServlet.java | 8baa279045a979c95002f9c338e704f71cfe1866 | [
"MIT"
] | permissive | IvanOkh/Inventory-Tracker | https://github.com/IvanOkh/Inventory-Tracker | 50aa1e8e752b0060ca81f49986cfcacbeb97ae3f | ba5b6a6ac333e03fc99a8fc37fb6df4444030b06 | refs/heads/master | 2022-11-15T09:52:40.659000 | 2020-07-11T20:27:57 | 2020-07-11T20:27:57 | 268,371,775 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.Item;
import models.User;
import services.AccountService;
import services.InventoryService;
public class AdminServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
String email = (String) session.getAttribute("currentlyLoged");
AccountService accServ = new AccountService();
User y = accServ.getUser(email);
InventoryService invServ = new InventoryService();
if (email == null)
{
response.sendRedirect("login");
}
if (y.getRole().getRoleName().equalsIgnoreCase("system admin")
|| y.getRole().getRoleName().equalsIgnoreCase("company admin") )
{
try{
List <Item> itm = (List <Item>)session.getAttribute("searchList");
request.setAttribute ("displayItems", itm);
}
catch (Exception e)
{
}
request.setAttribute("show", email);
List <User> userList = accServ.getUsers();
request.setAttribute ("displayUsers", userList);
String edit = request.getParameter("edit");
String delete = request.getParameter("delete");
String reactivate = request.getParameter("activate");
if(edit != null)
{
User n = accServ.getUser(String.valueOf(edit));
request.setAttribute("user", n);
request.setAttribute("control", "Edit");
request.setAttribute("test", edit);
}
else if (delete != null)
{
User n = accServ.getUser(String.valueOf(delete));
request.setAttribute("user", n);
request.setAttribute("control", "Delete");
request.setAttribute("test", delete);
}
else
{
request.setAttribute("control", "Add");
}
getServletContext().getRequestDispatcher("/WEB-INF/admin.jsp").forward(request, response);
}
response.sendRedirect("login");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
AccountService accServ = new AccountService();
InventoryService invServ = new InventoryService();
HttpSession session = request.getSession();
String action = request.getParameter("option");
String email = request.getParameter("emailBox");
String fname = request.getParameter("fnameBox");
String lname = request.getParameter("lnameBox");
String password = request.getParameter("passwordBox");
try
{
if(action.equals("Save"))
{
String edit = request.getParameter("edit");
accServ.update(String.valueOf(edit), fname, lname, password);
}
else if(action.equals("Add"))
{
accServ.insert(email, fname, lname, password);
}
else if(action.equals("Activate"))
{
String activate = request.getParameter("activate");
accServ.reactivate(activate);
}
else if(action.equals("Delete"))
{
String edit = request.getParameter("delete");
accServ.delete(edit);
}
else if(action.equals("Search"))
{
String srch = request.getParameter("searchBox");
List <Item> items = invServ.getAllItems(srch);
session.setAttribute ("searchList", items);
request.setAttribute ("displayItems", items);
}
}
catch(Exception e)
{
}
response.sendRedirect("admin");
}
}
| UTF-8 | Java | 4,814 | java | AdminServlet.java | Java | [] | 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 servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.Item;
import models.User;
import services.AccountService;
import services.InventoryService;
public class AdminServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
String email = (String) session.getAttribute("currentlyLoged");
AccountService accServ = new AccountService();
User y = accServ.getUser(email);
InventoryService invServ = new InventoryService();
if (email == null)
{
response.sendRedirect("login");
}
if (y.getRole().getRoleName().equalsIgnoreCase("system admin")
|| y.getRole().getRoleName().equalsIgnoreCase("company admin") )
{
try{
List <Item> itm = (List <Item>)session.getAttribute("searchList");
request.setAttribute ("displayItems", itm);
}
catch (Exception e)
{
}
request.setAttribute("show", email);
List <User> userList = accServ.getUsers();
request.setAttribute ("displayUsers", userList);
String edit = request.getParameter("edit");
String delete = request.getParameter("delete");
String reactivate = request.getParameter("activate");
if(edit != null)
{
User n = accServ.getUser(String.valueOf(edit));
request.setAttribute("user", n);
request.setAttribute("control", "Edit");
request.setAttribute("test", edit);
}
else if (delete != null)
{
User n = accServ.getUser(String.valueOf(delete));
request.setAttribute("user", n);
request.setAttribute("control", "Delete");
request.setAttribute("test", delete);
}
else
{
request.setAttribute("control", "Add");
}
getServletContext().getRequestDispatcher("/WEB-INF/admin.jsp").forward(request, response);
}
response.sendRedirect("login");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
AccountService accServ = new AccountService();
InventoryService invServ = new InventoryService();
HttpSession session = request.getSession();
String action = request.getParameter("option");
String email = request.getParameter("emailBox");
String fname = request.getParameter("fnameBox");
String lname = request.getParameter("lnameBox");
String password = request.getParameter("passwordBox");
try
{
if(action.equals("Save"))
{
String edit = request.getParameter("edit");
accServ.update(String.valueOf(edit), fname, lname, password);
}
else if(action.equals("Add"))
{
accServ.insert(email, fname, lname, password);
}
else if(action.equals("Activate"))
{
String activate = request.getParameter("activate");
accServ.reactivate(activate);
}
else if(action.equals("Delete"))
{
String edit = request.getParameter("delete");
accServ.delete(edit);
}
else if(action.equals("Search"))
{
String srch = request.getParameter("searchBox");
List <Item> items = invServ.getAllItems(srch);
session.setAttribute ("searchList", items);
request.setAttribute ("displayItems", items);
}
}
catch(Exception e)
{
}
response.sendRedirect("admin");
}
}
| 4,814 | 0.544869 | 0.544869 | 150 | 31.093334 | 25.637823 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.573333 | false | false | 2 |
372ed1035d5895d8a5814cf04e740df8136404cf | 20,615,843,055,160 | 12ff45373e7bcb48ba85ab490042411df3eb81fd | /网易视频封装/netease.exe4j/src/cn/com/agree/ab/pab/netease/app/LogHandler.java | c5556598539fc5d2cb12bb537435602f5b60eeff | [] | no_license | liuyaoxing/StackOverflow | https://github.com/liuyaoxing/StackOverflow | 8b70aa029e22f306686dfb088f73f67da316037b | b0fcc6ae2cc6a56304d474458bff389be0c8c4f1 | refs/heads/master | 2021-12-20T19:37:10.163000 | 2021-12-09T08:58:35 | 2021-12-09T08:58:35 | 229,896,241 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.com.agree.ab.pab.netease.app;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
*
* @author 刘尧兴(liuyaoxing@gmail.com)
*/
public class LogHandler {
private static File logFile = null;
static {
try {
if (logFile == null) {
logFile = getLogFile();
}
// FileOutputStream fileOutputStream = new FileOutputStream(logFile, true);
// PrintStream printStream = new PrintStream(fileOutputStream, false, "GBK");
// System.setOut(printStream);
// System.setErr(printStream);
} catch (Exception e) {
e.printStackTrace();
}
}
private static File getLogFile() {
System.out.println("netease.exe4j.log");
String yyyyMMdd = new SimpleDateFormat("yyyyMMdd").format(new Date());
String HHmmss = new SimpleDateFormat("HHmmss").format(new Date());
File f = new File(String.format("../log/anychatClientLog/%s/anychat.exe4j.%s%s.log", yyyyMMdd, yyyyMMdd, HHmmss));
try {
if (!f.exists()) {
File parentFile = f.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
System.out.println("netease.exe4j.log1");
f.createNewFile();
}
} catch (Exception ex) {
ex.printStackTrace();
}
if (!f.exists()) {
System.out.println("netease.exe4j.log2");
f = new File(String.format("anychat.exe4j.%s%s.log", yyyyMMdd, HHmmss));
}
return f;
}
/**
* 保存错误信息到文件中
*
* @param ex
* @return 返回文件名称,便于将文件传送到服务器
* @throws Exception
*/
public static void debug(String message) {
StringBuffer sb = new StringBuffer();
try {
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String date = sDateFormat.format(new java.util.Date());
sb.append("\r\n" + date + " == ");
sb.append(message);
writeFile(sb.toString());
} catch (Exception e) {
sb.append("an error occured while writing file...\r\n");
writeFile(sb.toString());
}
}
private static void writeFile(String sb) {
try {
FileOutputStream fos = new FileOutputStream(logFile, true);
fos.write(sb.getBytes("GBK"));
fos.flush();
fos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
| UTF-8 | Java | 2,310 | java | LogHandler.java | Java | [
{
"context": "ate;\nimport java.util.Locale;\n\n/**\n * \n * @author 刘尧兴(liuyaoxing@gmail.com)\n */\npublic class LogHandler",
"end": 230,
"score": 0.9998656511306763,
"start": 227,
"tag": "NAME",
"value": "刘尧兴"
},
{
"context": "\nimport java.util.Locale;\n\n/**\n * \n * @author 刘尧兴(liuyaoxing@gmail.com)\n */\npublic class LogHandler {\n\n\tprivate static F",
"end": 251,
"score": 0.9999265670776367,
"start": 231,
"tag": "EMAIL",
"value": "liuyaoxing@gmail.com"
}
] | null | [] | package cn.com.agree.ab.pab.netease.app;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
*
* @author 刘尧兴(<EMAIL>)
*/
public class LogHandler {
private static File logFile = null;
static {
try {
if (logFile == null) {
logFile = getLogFile();
}
// FileOutputStream fileOutputStream = new FileOutputStream(logFile, true);
// PrintStream printStream = new PrintStream(fileOutputStream, false, "GBK");
// System.setOut(printStream);
// System.setErr(printStream);
} catch (Exception e) {
e.printStackTrace();
}
}
private static File getLogFile() {
System.out.println("netease.exe4j.log");
String yyyyMMdd = new SimpleDateFormat("yyyyMMdd").format(new Date());
String HHmmss = new SimpleDateFormat("HHmmss").format(new Date());
File f = new File(String.format("../log/anychatClientLog/%s/anychat.exe4j.%s%s.log", yyyyMMdd, yyyyMMdd, HHmmss));
try {
if (!f.exists()) {
File parentFile = f.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
System.out.println("netease.exe4j.log1");
f.createNewFile();
}
} catch (Exception ex) {
ex.printStackTrace();
}
if (!f.exists()) {
System.out.println("netease.exe4j.log2");
f = new File(String.format("anychat.exe4j.%s%s.log", yyyyMMdd, HHmmss));
}
return f;
}
/**
* 保存错误信息到文件中
*
* @param ex
* @return 返回文件名称,便于将文件传送到服务器
* @throws Exception
*/
public static void debug(String message) {
StringBuffer sb = new StringBuffer();
try {
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String date = sDateFormat.format(new java.util.Date());
sb.append("\r\n" + date + " == ");
sb.append(message);
writeFile(sb.toString());
} catch (Exception e) {
sb.append("an error occured while writing file...\r\n");
writeFile(sb.toString());
}
}
private static void writeFile(String sb) {
try {
FileOutputStream fos = new FileOutputStream(logFile, true);
fos.write(sb.getBytes("GBK"));
fos.flush();
fos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
| 2,297 | 0.664444 | 0.661333 | 88 | 24.568182 | 23.655096 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.352273 | false | false | 2 |
f776d9441f10c656194a86cbcfae27ca40de56af | 10,067,403,383,454 | a3270ad55d799ffd72fd93e89604464ce98e80b5 | /src/com/comcast/objectRepository/OppInfo.java | e3888183e993d58bf7250f48af12d4abd690ab0b | [] | no_license | nitishsahoo1994/CRMFrameWork | https://github.com/nitishsahoo1994/CRMFrameWork | c93411c9ca5ab3cce1b80cf3b7846d3fb83e071e | 41905cbdb90c45483e077a53c1a54ec01864c76d | refs/heads/master | 2020-11-26T02:59:23.813000 | 2019-12-19T00:42:52 | 2019-12-19T00:42:52 | 228,945,533 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.comcast.objectRepository;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class OppInfo {
@FindBy(xpath="//span[@class='dvHeaderText']")
private WebElement oppnameDetail;
public WebElement getOppnameDetail() {
return oppnameDetail;
}
}
| UTF-8 | Java | 322 | java | OppInfo.java | Java | [] | null | [] | package com.comcast.objectRepository;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class OppInfo {
@FindBy(xpath="//span[@class='dvHeaderText']")
private WebElement oppnameDetail;
public WebElement getOppnameDetail() {
return oppnameDetail;
}
}
| 322 | 0.723602 | 0.723602 | 15 | 20.466667 | 18.492762 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 2 |
74e4fa8ed48cc3d9a95dddb9c9f2511abad35636 | 24,515,673,361,849 | 7e371c8ac04114de9931b45014b47935c366c17d | /jbpm/eStatement-ePayment-ejb/ejbModule/bg/bulsi/estatement/epayments/impl/DummyPaymentMediator.java | fd323c26d286a4e209fdca8b0b561766184d965f | [] | no_license | ilisan/yahoohdexport | https://github.com/ilisan/yahoohdexport | d905f0b5addbfe297ebab25813801886448d7fbc | 361d3e69c66886604b95842f2b987e4e814ad5a5 | refs/heads/master | 2021-01-10T09:44:26.579000 | 2012-03-22T14:40:05 | 2012-03-22T14:40:05 | 43,013,436 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bg.bulsi.estatement.epayments.impl;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.log.Log;
import bg.bulsi.estatement.epayments.IPaymentMediator;
/**
* @author tzvetan.stefanov@bul-si.bg
*
*/
@Name("DummyPaymentMediator")
public class DummyPaymentMediator implements IPaymentMediator {
@Logger
private Log log;
public void createPayment(String docId, int paymentCode) {
log.info("Create payment code: #0 document id #1.", paymentCode, docId);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 662 | java | DummyPaymentMediator.java | Java | [
{
"context": "ent.epayments.IPaymentMediator;\r\n\r\n/**\r\n * @author tzvetan.stefanov@bul-si.bg\r\n *\r\n */\r\n@Name(\"DummyPaymentMediator\")\r\npublic c",
"end": 265,
"score": 0.9990937113761902,
"start": 239,
"tag": "EMAIL",
"value": "tzvetan.stefanov@bul-si.bg"
}
] | null | [] | package bg.bulsi.estatement.epayments.impl;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.log.Log;
import bg.bulsi.estatement.epayments.IPaymentMediator;
/**
* @author <EMAIL>
*
*/
@Name("DummyPaymentMediator")
public class DummyPaymentMediator implements IPaymentMediator {
@Logger
private Log log;
public void createPayment(String docId, int paymentCode) {
log.info("Create payment code: #0 document id #1.", paymentCode, docId);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 643 | 0.702417 | 0.693353 | 29 | 20.827587 | 22.254126 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 2 |
54eb04c10a2186890583f96888080834fd52abe1 | 23,819,888,688,293 | 915077b73a0ca24bff11c1ca864bf9594bd3fca8 | /app/src/main/java/com/dragodideus/quickreminder/DbSQLiteAdapter.java | 3844046d68587212f0c78c4730df5495703324e2 | [
"MIT"
] | permissive | dragodideus/Quick-Reminder | https://github.com/dragodideus/Quick-Reminder | 7d9f6a5a4ab6c7453a05dfa6554a22026887844d | 001e0b54c344aea4ea13266a547bd3f28f0acbeb | refs/heads/master | 2016-09-13T12:07:51.596000 | 2016-04-24T14:49:23 | 2016-04-24T14:49:23 | 56,970,926 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dragodideus.quickreminder;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* Created by rakifsul on 3/24/2016.
*/
public class DbSQLiteAdapter {
static class DbSQLiteHelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "QuickReminder";
private static final int DATABASE_VERSION = 1;
private static final String REMINDER_EVENT_TABLE_NAME = "reminder_event";
private static final String REMINDER_EVENT_ID = "_id";
private static final String REMINDER_EVENT_TITLE = "title";
private static final String REMINDER_EVENT_DESCRIPTION = "description";
private static final String REMINDER_EVENT_DATE = "date";
private static final String REMINDER_EVENT_TIME = "time";
private static final String REMINDER_EVENT_USES_ALARM = "uses_alarm";
private static final String REMINDER_EVENT_RINGTONE_URI = "ringtone_uri";
/*
CREATE TABLE reminder_event (
_id INTEGER PRIMARY KEY AUTOINCREMENT,
title VARCHAR(255),
description TEXT,
date INTEGER,
time INTEGER,
uses_alarm INTEGER,
ringtone_uri TEXT,
status VARCHAR(10)
);
*/
private static final String REMINDER_EVENT_CREATE_TABLE =
"CREATE TABLE " + REMINDER_EVENT_TABLE_NAME + "(" +
REMINDER_EVENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
REMINDER_EVENT_TITLE + " VARCHAR(255), " +
REMINDER_EVENT_DESCRIPTION + " TEXT, " +
REMINDER_EVENT_DATE + " INTEGER, " +
REMINDER_EVENT_TIME + " VARCHAR(10), " +
REMINDER_EVENT_USES_ALARM + " INTEGER, " +
REMINDER_EVENT_RINGTONE_URI + " TEXT " +
");";
private static final String REMINDER_EVENT_DROP_TABLE =
"DROP TABLE IF EXISTS " + REMINDER_EVENT_TABLE_NAME;
private Context context;
//
public DbSQLiteHelper(Context context){
super(context,DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(REMINDER_EVENT_CREATE_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(REMINDER_EVENT_DROP_TABLE);
onCreate(db);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//
private DbSQLiteHelper dbSQLiteHelper;
private Context context;
//
public DbSQLiteAdapter(Context context){
dbSQLiteHelper = new DbSQLiteHelper(context);
this.context = context;
}
public long insertReminderEvent(ReminderEvent reminderEvent){
//
if(reminderEvent == null){
return -1;
}
//
SQLiteDatabase db = dbSQLiteHelper.getWritableDatabase();
//
ContentValues contentValues = new ContentValues();
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_TITLE, reminderEvent.getTitle());
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION, reminderEvent.getDescription());
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_DATE, Utils.dateAsLongCalendar(reminderEvent.getDate()));
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_TIME, Utils.timeAsStringCalendar(reminderEvent.getTime()));
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_USES_ALARM, Utils.boolToInt(reminderEvent.getUsesAlarm()));
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI, reminderEvent.getRingtoneUri().toString());
//
return db.insert(DbSQLiteHelper.REMINDER_EVENT_TABLE_NAME, null, contentValues);
}
public int deleteReminderEvent(int reminderEventID){
//
SQLiteDatabase db = dbSQLiteHelper.getWritableDatabase();
//
String[] selectionArgs = {Integer.toString(reminderEventID)};
//
return db.delete(
DbSQLiteHelper.REMINDER_EVENT_TABLE_NAME,
DbSQLiteHelper.REMINDER_EVENT_ID + "=?",
selectionArgs);
}
public int updateReminderEvent(ReminderEvent reminderEvent){
//
SQLiteDatabase db = dbSQLiteHelper.getWritableDatabase();
//
ContentValues contentValues = new ContentValues();
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_TITLE, reminderEvent.getTitle());
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION, reminderEvent.getDescription());
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_DATE, Utils.dateAsLongCalendar(reminderEvent.getDate()));
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_TIME, Utils.timeAsStringCalendar(reminderEvent.getTime()));
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_USES_ALARM, Utils.boolToInt(reminderEvent.getUsesAlarm()));
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI, reminderEvent.getRingtoneUri().toString());
//
String[] selectionArgs = {Integer.toString(reminderEvent.getID())};
return db.update(
DbSQLiteHelper.REMINDER_EVENT_TABLE_NAME,
contentValues,
DbSQLiteHelper.REMINDER_EVENT_ID + "=?",
selectionArgs);
}
public ReminderEvent getReminderEvent(int reminderEventID){
//
SQLiteDatabase db = dbSQLiteHelper.getWritableDatabase();
//
String[] columns = {
DbSQLiteHelper.REMINDER_EVENT_ID,
DbSQLiteHelper.REMINDER_EVENT_TITLE,
DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION,
DbSQLiteHelper.REMINDER_EVENT_DATE,
DbSQLiteHelper.REMINDER_EVENT_TIME,
DbSQLiteHelper.REMINDER_EVENT_USES_ALARM,
DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI
};
//
String[] selectionArgs = {Integer.toString(reminderEventID)};
//
Cursor cursor = db.query(
DbSQLiteHelper.REMINDER_EVENT_TABLE_NAME,
columns,
DbSQLiteHelper.REMINDER_EVENT_ID +"=?",
selectionArgs,
null, null, null);
if(cursor == null){
return null;
}
//
cursor.moveToFirst();
int id = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_ID));
String title = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_TITLE));
String description = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION));
int date = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_DATE));
String time = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_TIME));
int usesAlarm = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_USES_ALARM));
String ringtoneUri = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI));
//
ReminderEvent re = new ReminderEvent(
id,
title,
description,
Utils.longAsDateCalendar(date),
Utils.stringAsTimeCalendar(time),
Utils.intToBool(usesAlarm),
Uri.parse(ringtoneUri)
);
return re;
}
public ArrayList<ReminderEvent> getReminderEventsAtDate(Calendar reminderEventDate){
//
ArrayList<ReminderEvent> reminderEvents = new ArrayList<ReminderEvent>();
//
SQLiteDatabase db = dbSQLiteHelper.getWritableDatabase();
//
String[] columns = {
DbSQLiteHelper.REMINDER_EVENT_ID,
DbSQLiteHelper.REMINDER_EVENT_TITLE,
DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION,
DbSQLiteHelper.REMINDER_EVENT_DATE,
DbSQLiteHelper.REMINDER_EVENT_TIME,
DbSQLiteHelper.REMINDER_EVENT_USES_ALARM,
DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI
};
//
String[] selectionArgs = {Long.toString(Utils.dateAsLongCalendar(reminderEventDate))};
//
String orderBy = DbSQLiteHelper.REMINDER_EVENT_TIME + " ASC";
//
Cursor cursor = db.query(
DbSQLiteHelper.REMINDER_EVENT_TABLE_NAME,
columns,
DbSQLiteHelper.REMINDER_EVENT_DATE +"=?",
selectionArgs,
null, null, orderBy);
if(cursor == null){
return null;
}
//
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_ID));
String title = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_TITLE));
String description = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION));
int date = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_DATE));
String time = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_TIME));
int usesAlarm = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_USES_ALARM));
String ringtoneUri = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI));
//
ReminderEvent re = new ReminderEvent(
id,
title,
description,
Utils.longAsDateCalendar(date),
Utils.stringAsTimeCalendar(time),
Utils.intToBool(usesAlarm),
Uri.parse(ringtoneUri)
);
//
reminderEvents.add(re);
}
//
cursor.close();
//
return reminderEvents;
}
public ArrayList<ReminderEvent> getAllReminderEvents(){
//
ArrayList<ReminderEvent> reminderEvents = new ArrayList<ReminderEvent>();
//
SQLiteDatabase db = dbSQLiteHelper.getWritableDatabase();
//
String[] columns = {
DbSQLiteHelper.REMINDER_EVENT_ID,
DbSQLiteHelper.REMINDER_EVENT_TITLE,
DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION,
DbSQLiteHelper.REMINDER_EVENT_DATE,
DbSQLiteHelper.REMINDER_EVENT_TIME,
DbSQLiteHelper.REMINDER_EVENT_USES_ALARM,
DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI
};
//
Cursor cursor = db.query(DbSQLiteHelper.REMINDER_EVENT_TABLE_NAME, columns, null, null, null, null, null);
if(cursor == null){
return null;
}
//
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_ID));
String title = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_TITLE));
String description = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION));
int date = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_DATE));
String time = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_TIME));
int usesAlarm = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_USES_ALARM));
String ringtoneUri = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI));
//
ReminderEvent re = new ReminderEvent(
id,
title,
description,
Utils.longAsDateCalendar(date),
Utils.stringAsTimeCalendar(time),
Utils.intToBool(usesAlarm),
Uri.parse(ringtoneUri)
);
//
reminderEvents.add(re);
}
//
cursor.close();
//
return reminderEvents;
}
public String debugShowAllReminderEvents(){
//
SQLiteDatabase db = dbSQLiteHelper.getWritableDatabase();
//
String[] columns = {
DbSQLiteHelper.REMINDER_EVENT_ID,
DbSQLiteHelper.REMINDER_EVENT_TITLE,
DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION,
DbSQLiteHelper.REMINDER_EVENT_DATE,
DbSQLiteHelper.REMINDER_EVENT_TIME,
DbSQLiteHelper.REMINDER_EVENT_USES_ALARM,
DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI
};
//
Cursor cursor = db.query(DbSQLiteHelper.REMINDER_EVENT_TABLE_NAME, columns, null, null, null, null, null);
//
StringBuffer stringBuffer = new StringBuffer();
//
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_ID));
String title = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_TITLE));
String description = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION));
int date = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_DATE));
String time = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_TIME));
int usesAlarm = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_USES_ALARM));
String ringtoneUri = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI));
stringBuffer.append(id + "\n" +
title + "\n" +
description + "\n" +
date + "\n" +
time + "\n" +
usesAlarm + "\n" +
ringtoneUri + "\n ------- \n");
}
cursor.close();
return stringBuffer.toString();
}
}
| UTF-8 | Java | 14,651 | java | DbSQLiteAdapter.java | Java | [
{
"context": "il.Date;\nimport java.util.List;\n\n/**\n * Created by rakifsul on 3/24/2016.\n */\npublic class DbSQLiteAdapter {\n",
"end": 458,
"score": 0.9996790885925293,
"start": 450,
"tag": "USERNAME",
"value": "rakifsul"
}
] | null | [] | package com.dragodideus.quickreminder;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* Created by rakifsul on 3/24/2016.
*/
public class DbSQLiteAdapter {
static class DbSQLiteHelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "QuickReminder";
private static final int DATABASE_VERSION = 1;
private static final String REMINDER_EVENT_TABLE_NAME = "reminder_event";
private static final String REMINDER_EVENT_ID = "_id";
private static final String REMINDER_EVENT_TITLE = "title";
private static final String REMINDER_EVENT_DESCRIPTION = "description";
private static final String REMINDER_EVENT_DATE = "date";
private static final String REMINDER_EVENT_TIME = "time";
private static final String REMINDER_EVENT_USES_ALARM = "uses_alarm";
private static final String REMINDER_EVENT_RINGTONE_URI = "ringtone_uri";
/*
CREATE TABLE reminder_event (
_id INTEGER PRIMARY KEY AUTOINCREMENT,
title VARCHAR(255),
description TEXT,
date INTEGER,
time INTEGER,
uses_alarm INTEGER,
ringtone_uri TEXT,
status VARCHAR(10)
);
*/
private static final String REMINDER_EVENT_CREATE_TABLE =
"CREATE TABLE " + REMINDER_EVENT_TABLE_NAME + "(" +
REMINDER_EVENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
REMINDER_EVENT_TITLE + " VARCHAR(255), " +
REMINDER_EVENT_DESCRIPTION + " TEXT, " +
REMINDER_EVENT_DATE + " INTEGER, " +
REMINDER_EVENT_TIME + " VARCHAR(10), " +
REMINDER_EVENT_USES_ALARM + " INTEGER, " +
REMINDER_EVENT_RINGTONE_URI + " TEXT " +
");";
private static final String REMINDER_EVENT_DROP_TABLE =
"DROP TABLE IF EXISTS " + REMINDER_EVENT_TABLE_NAME;
private Context context;
//
public DbSQLiteHelper(Context context){
super(context,DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(REMINDER_EVENT_CREATE_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(REMINDER_EVENT_DROP_TABLE);
onCreate(db);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//
private DbSQLiteHelper dbSQLiteHelper;
private Context context;
//
public DbSQLiteAdapter(Context context){
dbSQLiteHelper = new DbSQLiteHelper(context);
this.context = context;
}
public long insertReminderEvent(ReminderEvent reminderEvent){
//
if(reminderEvent == null){
return -1;
}
//
SQLiteDatabase db = dbSQLiteHelper.getWritableDatabase();
//
ContentValues contentValues = new ContentValues();
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_TITLE, reminderEvent.getTitle());
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION, reminderEvent.getDescription());
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_DATE, Utils.dateAsLongCalendar(reminderEvent.getDate()));
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_TIME, Utils.timeAsStringCalendar(reminderEvent.getTime()));
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_USES_ALARM, Utils.boolToInt(reminderEvent.getUsesAlarm()));
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI, reminderEvent.getRingtoneUri().toString());
//
return db.insert(DbSQLiteHelper.REMINDER_EVENT_TABLE_NAME, null, contentValues);
}
public int deleteReminderEvent(int reminderEventID){
//
SQLiteDatabase db = dbSQLiteHelper.getWritableDatabase();
//
String[] selectionArgs = {Integer.toString(reminderEventID)};
//
return db.delete(
DbSQLiteHelper.REMINDER_EVENT_TABLE_NAME,
DbSQLiteHelper.REMINDER_EVENT_ID + "=?",
selectionArgs);
}
public int updateReminderEvent(ReminderEvent reminderEvent){
//
SQLiteDatabase db = dbSQLiteHelper.getWritableDatabase();
//
ContentValues contentValues = new ContentValues();
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_TITLE, reminderEvent.getTitle());
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION, reminderEvent.getDescription());
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_DATE, Utils.dateAsLongCalendar(reminderEvent.getDate()));
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_TIME, Utils.timeAsStringCalendar(reminderEvent.getTime()));
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_USES_ALARM, Utils.boolToInt(reminderEvent.getUsesAlarm()));
contentValues.put(DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI, reminderEvent.getRingtoneUri().toString());
//
String[] selectionArgs = {Integer.toString(reminderEvent.getID())};
return db.update(
DbSQLiteHelper.REMINDER_EVENT_TABLE_NAME,
contentValues,
DbSQLiteHelper.REMINDER_EVENT_ID + "=?",
selectionArgs);
}
public ReminderEvent getReminderEvent(int reminderEventID){
//
SQLiteDatabase db = dbSQLiteHelper.getWritableDatabase();
//
String[] columns = {
DbSQLiteHelper.REMINDER_EVENT_ID,
DbSQLiteHelper.REMINDER_EVENT_TITLE,
DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION,
DbSQLiteHelper.REMINDER_EVENT_DATE,
DbSQLiteHelper.REMINDER_EVENT_TIME,
DbSQLiteHelper.REMINDER_EVENT_USES_ALARM,
DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI
};
//
String[] selectionArgs = {Integer.toString(reminderEventID)};
//
Cursor cursor = db.query(
DbSQLiteHelper.REMINDER_EVENT_TABLE_NAME,
columns,
DbSQLiteHelper.REMINDER_EVENT_ID +"=?",
selectionArgs,
null, null, null);
if(cursor == null){
return null;
}
//
cursor.moveToFirst();
int id = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_ID));
String title = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_TITLE));
String description = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION));
int date = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_DATE));
String time = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_TIME));
int usesAlarm = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_USES_ALARM));
String ringtoneUri = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI));
//
ReminderEvent re = new ReminderEvent(
id,
title,
description,
Utils.longAsDateCalendar(date),
Utils.stringAsTimeCalendar(time),
Utils.intToBool(usesAlarm),
Uri.parse(ringtoneUri)
);
return re;
}
public ArrayList<ReminderEvent> getReminderEventsAtDate(Calendar reminderEventDate){
//
ArrayList<ReminderEvent> reminderEvents = new ArrayList<ReminderEvent>();
//
SQLiteDatabase db = dbSQLiteHelper.getWritableDatabase();
//
String[] columns = {
DbSQLiteHelper.REMINDER_EVENT_ID,
DbSQLiteHelper.REMINDER_EVENT_TITLE,
DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION,
DbSQLiteHelper.REMINDER_EVENT_DATE,
DbSQLiteHelper.REMINDER_EVENT_TIME,
DbSQLiteHelper.REMINDER_EVENT_USES_ALARM,
DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI
};
//
String[] selectionArgs = {Long.toString(Utils.dateAsLongCalendar(reminderEventDate))};
//
String orderBy = DbSQLiteHelper.REMINDER_EVENT_TIME + " ASC";
//
Cursor cursor = db.query(
DbSQLiteHelper.REMINDER_EVENT_TABLE_NAME,
columns,
DbSQLiteHelper.REMINDER_EVENT_DATE +"=?",
selectionArgs,
null, null, orderBy);
if(cursor == null){
return null;
}
//
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_ID));
String title = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_TITLE));
String description = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION));
int date = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_DATE));
String time = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_TIME));
int usesAlarm = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_USES_ALARM));
String ringtoneUri = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI));
//
ReminderEvent re = new ReminderEvent(
id,
title,
description,
Utils.longAsDateCalendar(date),
Utils.stringAsTimeCalendar(time),
Utils.intToBool(usesAlarm),
Uri.parse(ringtoneUri)
);
//
reminderEvents.add(re);
}
//
cursor.close();
//
return reminderEvents;
}
public ArrayList<ReminderEvent> getAllReminderEvents(){
//
ArrayList<ReminderEvent> reminderEvents = new ArrayList<ReminderEvent>();
//
SQLiteDatabase db = dbSQLiteHelper.getWritableDatabase();
//
String[] columns = {
DbSQLiteHelper.REMINDER_EVENT_ID,
DbSQLiteHelper.REMINDER_EVENT_TITLE,
DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION,
DbSQLiteHelper.REMINDER_EVENT_DATE,
DbSQLiteHelper.REMINDER_EVENT_TIME,
DbSQLiteHelper.REMINDER_EVENT_USES_ALARM,
DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI
};
//
Cursor cursor = db.query(DbSQLiteHelper.REMINDER_EVENT_TABLE_NAME, columns, null, null, null, null, null);
if(cursor == null){
return null;
}
//
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_ID));
String title = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_TITLE));
String description = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION));
int date = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_DATE));
String time = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_TIME));
int usesAlarm = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_USES_ALARM));
String ringtoneUri = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI));
//
ReminderEvent re = new ReminderEvent(
id,
title,
description,
Utils.longAsDateCalendar(date),
Utils.stringAsTimeCalendar(time),
Utils.intToBool(usesAlarm),
Uri.parse(ringtoneUri)
);
//
reminderEvents.add(re);
}
//
cursor.close();
//
return reminderEvents;
}
public String debugShowAllReminderEvents(){
//
SQLiteDatabase db = dbSQLiteHelper.getWritableDatabase();
//
String[] columns = {
DbSQLiteHelper.REMINDER_EVENT_ID,
DbSQLiteHelper.REMINDER_EVENT_TITLE,
DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION,
DbSQLiteHelper.REMINDER_EVENT_DATE,
DbSQLiteHelper.REMINDER_EVENT_TIME,
DbSQLiteHelper.REMINDER_EVENT_USES_ALARM,
DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI
};
//
Cursor cursor = db.query(DbSQLiteHelper.REMINDER_EVENT_TABLE_NAME, columns, null, null, null, null, null);
//
StringBuffer stringBuffer = new StringBuffer();
//
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_ID));
String title = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_TITLE));
String description = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_DESCRIPTION));
int date = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_DATE));
String time = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_TIME));
int usesAlarm = cursor.getInt(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_USES_ALARM));
String ringtoneUri = cursor.getString(cursor.getColumnIndex(DbSQLiteHelper.REMINDER_EVENT_RINGTONE_URI));
stringBuffer.append(id + "\n" +
title + "\n" +
description + "\n" +
date + "\n" +
time + "\n" +
usesAlarm + "\n" +
ringtoneUri + "\n ------- \n");
}
cursor.close();
return stringBuffer.toString();
}
}
| 14,651 | 0.610539 | 0.609242 | 381 | 37.454067 | 33.247993 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.598425 | false | false | 2 |
4f6552662f48c2674191a5a0a541a05ef275941f | 5,111,011,110,915 | e67bf17b790187637ed177d74fc80b6f1f8d2af6 | /angular-java-poc/java-server/facade/src/main/java/com/tasc/golden/poc/facade/impl/ClientFacade.java | 9709c425bea6ddce09c3bfb9559a15182be662df | [] | no_license | tasconline/spring-boot-poc | https://github.com/tasconline/spring-boot-poc | 1fd9a232023da79c9c966acd55c40bdc2357a008 | 709f4c190ffc49058a280e0c109667164aeecf4b | refs/heads/master | 2016-09-05T21:44:17.130000 | 2014-10-01T20:33:33 | 2014-10-01T20:33:33 | 23,640,980 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tasc.golden.poc.facade.impl;
import java.util.ArrayList;
import java.util.List;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tasc.golden.poc.business.IClientBusiness;
import com.tasc.golden.poc.dto.ClientDto;
import com.tasc.golden.poc.entity.Client;
import com.tasc.golden.poc.facade.IClientFacade;
@Service
public class ClientFacade implements IClientFacade {
@Autowired Mapper mapper;
@Autowired IClientBusiness clientBusiness;
@Override
public ClientDto save(ClientDto clientDto) {
Client savedClient = this.clientBusiness.save(this.mapper.map(clientDto, Client.class));
return mapper.map(savedClient, ClientDto.class);
}
@Override
public List<ClientDto> findAll() {
List<ClientDto> rlist = new ArrayList<ClientDto>();
for (Client client : this.clientBusiness.findAll()) {
rlist.add(this.mapper.map(client, ClientDto.class));
}
return rlist;
}
@Override
public ClientDto findById(Long id) {
return this.mapper.map(this.clientBusiness.findById(id), ClientDto.class);
}
}
| UTF-8 | Java | 1,126 | java | ClientFacade.java | Java | [] | null | [] | package com.tasc.golden.poc.facade.impl;
import java.util.ArrayList;
import java.util.List;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tasc.golden.poc.business.IClientBusiness;
import com.tasc.golden.poc.dto.ClientDto;
import com.tasc.golden.poc.entity.Client;
import com.tasc.golden.poc.facade.IClientFacade;
@Service
public class ClientFacade implements IClientFacade {
@Autowired Mapper mapper;
@Autowired IClientBusiness clientBusiness;
@Override
public ClientDto save(ClientDto clientDto) {
Client savedClient = this.clientBusiness.save(this.mapper.map(clientDto, Client.class));
return mapper.map(savedClient, ClientDto.class);
}
@Override
public List<ClientDto> findAll() {
List<ClientDto> rlist = new ArrayList<ClientDto>();
for (Client client : this.clientBusiness.findAll()) {
rlist.add(this.mapper.map(client, ClientDto.class));
}
return rlist;
}
@Override
public ClientDto findById(Long id) {
return this.mapper.map(this.clientBusiness.findById(id), ClientDto.class);
}
}
| 1,126 | 0.777975 | 0.777975 | 40 | 27.15 | 24.459711 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.325 | false | false | 2 |
ffbf12854fc23aab4c5ab8d932f5b25bb89a1798 | 16,836,271,852,008 | ad52b3ccc7444a7de71adbd23b64cb65de0db853 | /app/src/main/java/hr/foi/mjurinic/postter/dagger/modules/CacheInstanceModule.java | a87da13d0e4368b950ca51d2ea95ad3273a4bf07 | [] | no_license | mjurinic/Postter | https://github.com/mjurinic/Postter | bba9ce57b3fb734724efce36898a2490557e4a30 | 0daecb9b72cb4383333a6e9b462414cdcae731af | refs/heads/master | 2021-01-13T17:10:00.911000 | 2016-01-13T18:00:56 | 2016-01-13T18:00:56 | 49,124,662 | 0 | 0 | null | false | 2016-01-06T23:18:43 | 2016-01-06T09:03:29 | 2016-01-06T09:26:57 | 2016-01-06T23:18:43 | 186 | 0 | 0 | 0 | Java | null | null | package hr.foi.mjurinic.postter.dagger.modules;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import hr.foi.mjurinic.postter.mvp.interactors.CacheInteractor;
import hr.foi.mjurinic.postter.mvp.interactors.impl.CacheInteractorImpl;
/**
* Created by mjurinic on 27.10.15..
*/
@Module
public class CacheInstanceModule {
@Provides
@Singleton
public CacheInteractor cacheInteractor() {
return new CacheInteractorImpl();
}
}
| UTF-8 | Java | 480 | java | CacheInstanceModule.java | Java | [
{
"context": "ctors.impl.CacheInteractorImpl;\n\n/**\n * Created by mjurinic on 27.10.15..\n */\n@Module\npublic class CacheInsta",
"end": 291,
"score": 0.9996492266654968,
"start": 283,
"tag": "USERNAME",
"value": "mjurinic"
}
] | null | [] | package hr.foi.mjurinic.postter.dagger.modules;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import hr.foi.mjurinic.postter.mvp.interactors.CacheInteractor;
import hr.foi.mjurinic.postter.mvp.interactors.impl.CacheInteractorImpl;
/**
* Created by mjurinic on 27.10.15..
*/
@Module
public class CacheInstanceModule {
@Provides
@Singleton
public CacheInteractor cacheInteractor() {
return new CacheInteractorImpl();
}
}
| 480 | 0.758333 | 0.745833 | 21 | 21.857143 | 21.71961 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 2 |
8e41e833d06c79b972af41eca6db43c697c6d5d6 | 8,048,768,764,888 | c2fcb90bcd289eb98afd6ec6d6df6e38026e89be | /src/test/java/UiTest.java | 186f68266ab49367c735d1cd89bb1ab6167196c1 | [] | no_license | luo-git/ip | https://github.com/luo-git/ip | 410605a6eb671923517ca159ba1af2dcd9a654d7 | d95e465ab3792048fa18777ec9107c9649dadf34 | refs/heads/master | 2022-12-14T02:04:47.257000 | 2020-09-17T12:08:43 | 2020-09-17T12:08:43 | 287,890,791 | 0 | 1 | null | true | 2020-09-09T15:15:37 | 2020-08-16T06:53:49 | 2020-09-06T13:27:52 | 2020-09-09T15:15:36 | 4,025 | 0 | 0 | 0 | Java | false | false | import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import luoyi.duke.data.task.Deadline;
import luoyi.duke.data.task.Event;
import luoyi.duke.data.task.TaskList;
import luoyi.duke.data.task.ToDo;
import luoyi.duke.ui.Ui;
/**
* Test Ui class.
*/
public class UiTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
private final PrintStream originalErr = System.err;
@BeforeEach
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
}
@AfterEach
public void restoreStreams() {
System.setOut(originalOut);
System.setErr(originalErr);
}
@Test
public void greet_stringPrinted() {
Ui.greet();
String expectedOutput = "CAT BOT\n"
+ "------------------------------------------------------------------\n"
+ "|\tHi I'm Cat Bot.\n"
+ "|\tWhat can I do for you?\n"
+ "------------------------------------------------------------------\n";
assertEquals(expectedOutput, outContent.toString());
}
@Test
public void bye_stringPrinted() {
Ui.bye();
String expectedOutput = "------------------------------------------------------------------\n"
+ "|\tBye! Hope to see you again! (App closing in 5s)\n"
+ "------------------------------------------------------------------\n";
assertEquals(expectedOutput, outContent.toString());
}
@Test
public void displayTasks_emptyList_emptyListPromptPrinted() {
TaskList list = new TaskList(new ArrayList<>());
Ui.displayTasks(list);
String expectedOutput = "------------------------------------------------------------------\n"
+ "|\tOops! Looks like there's no task in the list!\n"
+ "------------------------------------------------------------------\n";
assertEquals(expectedOutput, outContent.toString());
}
@Test
public void displayTasks_correctTaskList_listPrinted() {
TaskList list = new TaskList(new ArrayList<>());
list.add(ToDo.getToDo("Have lunch."));
list.add(Deadline.getDeadline("Homework", "2020 11 11"));
list.add(Event.getEvent("Tutorial", "2020 11 11 11:22").markComplete());
Ui.displayTasks(list);
String expectedOutput = "------------------------------------------------------------------\n"
+ "|\tHere are the tasks in your list:\n"
+ "|\t 1. [T][\u2718] Have lunch.\n"
+ "|\t 2. [D][\u2718] Homework (by: 2020-11-11)\n"
+ "|\t 3. [E][\u2713] Tutorial (at: 2020-11-11T11:22)\n"
+ "------------------------------------------------------------------\n";
assertEquals(expectedOutput, outContent.toString());
}
@Test
public void displayTasks_correctDate_matchingTaskPrinted() {
TaskList list = setUpTestList();
Ui.displayTasks(list, new int[]{2, 3});
String expectedOutput = "------------------------------------------------------------------\n"
+ "|\tHere are the task on you are looking for:\n"
+ "|\t 3. [E][\u2713] Tutorial (at: 2020-11-11T11:22)\n"
+ "|\t 4. [E][\u2713] Lecture (at: 2020-11-12T10:45)\n"
+ "------------------------------------------------------------------\n";
assertEquals(expectedOutput, outContent.toString());
}
@Test
public void displayTasks_noMatch_noMatchPromptPrinted() {
TaskList list = setUpTestList();
Ui.displayTasks(list, new int[]{});
String expectedOutput = "------------------------------------------------------------------\n"
+ "|\tOops! Looks like there's no matching task!\n"
+ "------------------------------------------------------------------\n";
assertEquals(expectedOutput, outContent.toString());
}
private TaskList setUpTestList() {
TaskList list = new TaskList(new ArrayList<>());
list.add(ToDo.getToDo("Have lunch."));
list.add(Deadline.getDeadline("Homework", "2020 11 11"));
list.add(Event.getEvent("Tutorial", "2020 11 11 11:22").markComplete());
list.add(Event.getEvent("Lecture", "2020 11 12 10:45").markComplete());
return list;
}
}
| UTF-8 | Java | 4,795 | java | UiTest.java | Java | [] | null | [] | import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import luoyi.duke.data.task.Deadline;
import luoyi.duke.data.task.Event;
import luoyi.duke.data.task.TaskList;
import luoyi.duke.data.task.ToDo;
import luoyi.duke.ui.Ui;
/**
* Test Ui class.
*/
public class UiTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
private final PrintStream originalErr = System.err;
@BeforeEach
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
}
@AfterEach
public void restoreStreams() {
System.setOut(originalOut);
System.setErr(originalErr);
}
@Test
public void greet_stringPrinted() {
Ui.greet();
String expectedOutput = "CAT BOT\n"
+ "------------------------------------------------------------------\n"
+ "|\tHi I'm Cat Bot.\n"
+ "|\tWhat can I do for you?\n"
+ "------------------------------------------------------------------\n";
assertEquals(expectedOutput, outContent.toString());
}
@Test
public void bye_stringPrinted() {
Ui.bye();
String expectedOutput = "------------------------------------------------------------------\n"
+ "|\tBye! Hope to see you again! (App closing in 5s)\n"
+ "------------------------------------------------------------------\n";
assertEquals(expectedOutput, outContent.toString());
}
@Test
public void displayTasks_emptyList_emptyListPromptPrinted() {
TaskList list = new TaskList(new ArrayList<>());
Ui.displayTasks(list);
String expectedOutput = "------------------------------------------------------------------\n"
+ "|\tOops! Looks like there's no task in the list!\n"
+ "------------------------------------------------------------------\n";
assertEquals(expectedOutput, outContent.toString());
}
@Test
public void displayTasks_correctTaskList_listPrinted() {
TaskList list = new TaskList(new ArrayList<>());
list.add(ToDo.getToDo("Have lunch."));
list.add(Deadline.getDeadline("Homework", "2020 11 11"));
list.add(Event.getEvent("Tutorial", "2020 11 11 11:22").markComplete());
Ui.displayTasks(list);
String expectedOutput = "------------------------------------------------------------------\n"
+ "|\tHere are the tasks in your list:\n"
+ "|\t 1. [T][\u2718] Have lunch.\n"
+ "|\t 2. [D][\u2718] Homework (by: 2020-11-11)\n"
+ "|\t 3. [E][\u2713] Tutorial (at: 2020-11-11T11:22)\n"
+ "------------------------------------------------------------------\n";
assertEquals(expectedOutput, outContent.toString());
}
@Test
public void displayTasks_correctDate_matchingTaskPrinted() {
TaskList list = setUpTestList();
Ui.displayTasks(list, new int[]{2, 3});
String expectedOutput = "------------------------------------------------------------------\n"
+ "|\tHere are the task on you are looking for:\n"
+ "|\t 3. [E][\u2713] Tutorial (at: 2020-11-11T11:22)\n"
+ "|\t 4. [E][\u2713] Lecture (at: 2020-11-12T10:45)\n"
+ "------------------------------------------------------------------\n";
assertEquals(expectedOutput, outContent.toString());
}
@Test
public void displayTasks_noMatch_noMatchPromptPrinted() {
TaskList list = setUpTestList();
Ui.displayTasks(list, new int[]{});
String expectedOutput = "------------------------------------------------------------------\n"
+ "|\tOops! Looks like there's no matching task!\n"
+ "------------------------------------------------------------------\n";
assertEquals(expectedOutput, outContent.toString());
}
private TaskList setUpTestList() {
TaskList list = new TaskList(new ArrayList<>());
list.add(ToDo.getToDo("Have lunch."));
list.add(Deadline.getDeadline("Homework", "2020 11 11"));
list.add(Event.getEvent("Tutorial", "2020 11 11 11:22").markComplete());
list.add(Event.getEvent("Lecture", "2020 11 12 10:45").markComplete());
return list;
}
}
| 4,795 | 0.500104 | 0.474244 | 116 | 40.327587 | 30.640512 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.663793 | false | false | 2 |
9ecd39f9b039e6a13ef6868588acf9b0b0c1e29d | 7,421,703,519,837 | 26ca189d7454920c74e99a0fc806666be2cb0af5 | /quartz/src/main/java/spring/quartz/schedule/service/ITestService.java | 30a2b3395fdb6bffec0855e2c084b71dc6b08387 | [
"Apache-2.0"
] | permissive | codemonkeykings/study | https://github.com/codemonkeykings/study | d319a45a121fadc17b551373238d9a51339d5642 | a024692920339507bdd78b79e4cff8553a644f59 | refs/heads/master | 2021-01-22T18:58:56.825000 | 2017-05-29T13:32:59 | 2017-05-29T13:32:59 | 85,146,389 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package spring.quartz.schedule.service;
/**
* 一句话功能简述.
*
* <pre>
* 功能详细描述
* </pre>
*
* @author Zhang.Ge
* @version v1.0 2017年3月20日 下午3:34:06
*/
public interface ITestService {
public void sayHello();
}
| GB18030 | Java | 273 | java | ITestService.java | Java | [
{
"context": "\r\n * <pre>\r\n * 功能详细描述\r\n * </pre>\r\n * \r\n * @author Zhang.Ge\r\n * @version v1.0 2017年3月20日 下午3:34:06\r\n */\r\npub",
"end": 123,
"score": 0.9998700618743896,
"start": 115,
"tag": "NAME",
"value": "Zhang.Ge"
}
] | null | [] | package spring.quartz.schedule.service;
/**
* 一句话功能简述.
*
* <pre>
* 功能详细描述
* </pre>
*
* @author Zhang.Ge
* @version v1.0 2017年3月20日 下午3:34:06
*/
public interface ITestService {
public void sayHello();
}
| 273 | 0.582278 | 0.523207 | 16 | 12.8125 | 13.182464 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.125 | false | false | 2 |
deb79b0b72fac7737dda15fa6e74b9285dd1acf5 | 20,796,231,704,385 | e80afc77cb060e31bd43cdd7050bd62aec606f6e | /src/com/ipartek/formacion/hola/ejercicios/CalcularVueltas.java | 4f2075f25044cb2e0db70736741f2edc15d4307f | [] | no_license | ItsasoAguirre/holaMio | https://github.com/ItsasoAguirre/holaMio | 4cbf8faf6d8401e94bdaa38eb6693bb70097a64c | b14b5571429682192f1d8636d500f5e2b0888034 | refs/heads/master | 2021-01-11T20:23:48.222000 | 2017-01-19T12:30:24 | 2017-01-19T12:30:24 | 79,109,330 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ipartek.formacion.hola.ejercicios;
public class CalcularVueltas {
public static void main(String[] args) {
float compra = (float) 1326.24;
float pago = 4 * 500;
float vueltas = (pago - compra);
// billetes
float[] aBilletes = { 50, 20, 10, 5, 2, 1, 0.5f, 0.2f, 0.1f, 0.05f, 0.02f, 0.01f };
String[] aNombres = { "Billetes de 50", "Billetes de 20", "Billetes de 10", "Billetes de 5", "Monedas de 2",
"Monedas de 1", "Monedas de 0,5", "Monedas de 0,2", "Monedas de 0,1", "Monedas de 0,05",
"Monedas de 0,02", "Monedas de 0,01" };
int i = 0;
int cont = 0;
while (vueltas > 0 && i < aBilletes.length) {
if (vueltas - aBilletes[i] >= 0) {
cont++; // Incrementamos para saber que tiene uno de ese tipo
vueltas = vueltas - aBilletes[i]; // Restamos un billete del
// tipo que corresponda
} else {
aBilletes[i] = cont;
cont = 0;
i++;
}
}
System.out.println("-----------------------------");
System.out.println("-------TICKET----------------");
System.out.println("-----------------------------");
System.out.println("PAGO: " + compra + "€");
System.out.println("RETORNO: " + (pago - compra) + "€");
System.out.println("------------------------------");
System.out.println("Las vueltas");
for (int e = 0; e < aBilletes.length; e++) {
System.out.println(aNombres[e] + ": " + (int) aBilletes[e]);
}
System.out.println("------------------------------");
System.out.println("++ gracias por su visita ++");
System.out.println("------------------------------");
}
}
| WINDOWS-1252 | Java | 1,625 | java | CalcularVueltas.java | Java | [] | null | [] | package com.ipartek.formacion.hola.ejercicios;
public class CalcularVueltas {
public static void main(String[] args) {
float compra = (float) 1326.24;
float pago = 4 * 500;
float vueltas = (pago - compra);
// billetes
float[] aBilletes = { 50, 20, 10, 5, 2, 1, 0.5f, 0.2f, 0.1f, 0.05f, 0.02f, 0.01f };
String[] aNombres = { "Billetes de 50", "Billetes de 20", "Billetes de 10", "Billetes de 5", "Monedas de 2",
"Monedas de 1", "Monedas de 0,5", "Monedas de 0,2", "Monedas de 0,1", "Monedas de 0,05",
"Monedas de 0,02", "Monedas de 0,01" };
int i = 0;
int cont = 0;
while (vueltas > 0 && i < aBilletes.length) {
if (vueltas - aBilletes[i] >= 0) {
cont++; // Incrementamos para saber que tiene uno de ese tipo
vueltas = vueltas - aBilletes[i]; // Restamos un billete del
// tipo que corresponda
} else {
aBilletes[i] = cont;
cont = 0;
i++;
}
}
System.out.println("-----------------------------");
System.out.println("-------TICKET----------------");
System.out.println("-----------------------------");
System.out.println("PAGO: " + compra + "€");
System.out.println("RETORNO: " + (pago - compra) + "€");
System.out.println("------------------------------");
System.out.println("Las vueltas");
for (int e = 0; e < aBilletes.length; e++) {
System.out.println(aNombres[e] + ": " + (int) aBilletes[e]);
}
System.out.println("------------------------------");
System.out.println("++ gracias por su visita ++");
System.out.println("------------------------------");
}
}
| 1,625 | 0.51388 | 0.474399 | 49 | 31.081633 | 27.797253 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.122449 | false | false | 2 |
376f9591814eef27cc800c2d5e1da32401fd3c19 | 32,564,442,067,809 | 3e87fdbe5ed3990586fa5f3c2643fce3b21c5cb7 | /java_leetcode/src/com/jianzhi/findContinuousSequence_57_II.java | 2191a7bc4acbbca846b757c01b9370f07c603cb5 | [] | no_license | xiaomindog/leetcode | https://github.com/xiaomindog/leetcode | 5631837231e9b871ebcd01f3fcd4a69a3be330b2 | 4a5ec248685a2f838bcbb7fa057ecaa71053b957 | refs/heads/master | 2021-07-16T07:55:22.479000 | 2020-10-21T12:32:35 | 2020-10-21T12:32:35 | 217,455,945 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jianzhi;
import java.util.LinkedList;
import java.util.List;
/**
* 输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
* 序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
*/
public class findContinuousSequence_57_II {
//双指针
//我们用两个指针l和r表示当前枚举到的以l为起点到r的区间,sum表示[l,r]的区间和
// 起始 l=1,r=2。
public static int[][] findContinuousSequence(int target) {
List<int[]> list = new LinkedList<>();
int l = 1, r = 2;
while (l < r) {
int sum = (l + r) * (r - l + 1) / 2; //等差数列求和公式
if (sum == target) {
int ans[] = new int[r - l + 1];
for (int m = l, x = 0; m <= r; m++) {
ans[x++] = m;
}
list.add(ans);
l++;
} else if (sum > target) {
l++;
} else {
r++;
}
}
return list.toArray(new int[list.size()][]);
}
//暴力法 滑动窗口
//确定数组的上下界 下界为1 上界为 target/2
public static int[][] findContinuousSequence_1(int target) {
List<int[]> list = new LinkedList<>();
int left = 1, right = target / 2;
for (int i = left; i <= right; i++) {
int sum = 0;
int j;
for (j = i; sum < target; j++) {
sum += j;
}
if (sum == target) {
int ans[] = new int[j - i + 1];
for (int x = i, m = 0; x < j; x++) {
ans[m++] = x;
}
list.add(ans);
}
}
return list.toArray(new int[list.size()][]);
}
public static void main(String[] args) {
int[][] a = findContinuousSequence(9);
for (int i = 0; i < a.length; i++) {
System.out.println(a[i][0]);
}
}
}
| UTF-8 | Java | 2,068 | java | findContinuousSequence_57_II.java | Java | [] | null | [] | package com.jianzhi;
import java.util.LinkedList;
import java.util.List;
/**
* 输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
* 序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
*/
public class findContinuousSequence_57_II {
//双指针
//我们用两个指针l和r表示当前枚举到的以l为起点到r的区间,sum表示[l,r]的区间和
// 起始 l=1,r=2。
public static int[][] findContinuousSequence(int target) {
List<int[]> list = new LinkedList<>();
int l = 1, r = 2;
while (l < r) {
int sum = (l + r) * (r - l + 1) / 2; //等差数列求和公式
if (sum == target) {
int ans[] = new int[r - l + 1];
for (int m = l, x = 0; m <= r; m++) {
ans[x++] = m;
}
list.add(ans);
l++;
} else if (sum > target) {
l++;
} else {
r++;
}
}
return list.toArray(new int[list.size()][]);
}
//暴力法 滑动窗口
//确定数组的上下界 下界为1 上界为 target/2
public static int[][] findContinuousSequence_1(int target) {
List<int[]> list = new LinkedList<>();
int left = 1, right = target / 2;
for (int i = left; i <= right; i++) {
int sum = 0;
int j;
for (j = i; sum < target; j++) {
sum += j;
}
if (sum == target) {
int ans[] = new int[j - i + 1];
for (int x = i, m = 0; x < j; x++) {
ans[m++] = x;
}
list.add(ans);
}
}
return list.toArray(new int[list.size()][]);
}
public static void main(String[] args) {
int[][] a = findContinuousSequence(9);
for (int i = 0; i < a.length; i++) {
System.out.println(a[i][0]);
}
}
}
| 2,068 | 0.424393 | 0.412804 | 64 | 27.3125 | 18.064014 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 2 |
9d6ed88567f979c6f3e00ac5aa05223e27ebbd92 | 36,524,401,897,982 | 040ab5a68ff04e91376a0a2fb39d54ce63a956fc | /CellulantTest/src/cellulanttest/WriteLog.java | a954ba6f0c726a52b8dd9333335560f4f5ffcdc9 | [] | no_license | emuroiwa/Consume-WSDL-Java-Mysql | https://github.com/emuroiwa/Consume-WSDL-Java-Mysql | 08ed9b482a21a5c33de1896d1f73cb1b08b7b702 | 5d78217de13321026a5e7cd73fb4850a323fbc9e | refs/heads/master | 2021-09-02T00:44:48.097000 | 2017-12-29T13:30:18 | 2017-12-29T13:30:18 | 115,724,343 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cellulanttest;
/**
*
* @author Ernest
*
* * @author Ernest
* NAME: WriteLog
*
* Description: Class that writes activity
*
* List Of Methods:
* 1) LogNow
*/
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class WriteLog {
public void LogNow(String Log,String LogType)
{
try
{
boolean append = true;
//Creating Log File
FileHandler handler = new FileHandler("default.log", append);
Logger logger = Logger.getLogger(Log);
logger.addHandler(handler);
// Log type description
if (LogType=="severe")
{
logger.severe(Log);
}
else if (LogType=="warning")
{
logger.warning(Log);
}
else
{
logger.info(Log);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
} | UTF-8 | Java | 1,029 | java | WriteLog.java | Java | [
{
"context": "package cellulanttest;\n\n/**\n *\n * @author Ernest\n * \n * * @author Ernest\n * NAME: WriteLog\n * \n *",
"end": 48,
"score": 0.9998569488525391,
"start": 42,
"tag": "NAME",
"value": "Ernest"
},
{
"context": "nttest;\n\n/**\n *\n * @author Ernest\n * \n * * @author Ernest\n * NAME: WriteLog\n * \n * Description: Class that",
"end": 72,
"score": 0.9998410940170288,
"start": 66,
"tag": "NAME",
"value": "Ernest"
}
] | null | [] | package cellulanttest;
/**
*
* @author Ernest
*
* * @author Ernest
* NAME: WriteLog
*
* Description: Class that writes activity
*
* List Of Methods:
* 1) LogNow
*/
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class WriteLog {
public void LogNow(String Log,String LogType)
{
try
{
boolean append = true;
//Creating Log File
FileHandler handler = new FileHandler("default.log", append);
Logger logger = Logger.getLogger(Log);
logger.addHandler(handler);
// Log type description
if (LogType=="severe")
{
logger.severe(Log);
}
else if (LogType=="warning")
{
logger.warning(Log);
}
else
{
logger.info(Log);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
} | 1,029 | 0.504373 | 0.503401 | 52 | 18.807692 | 14.610373 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.442308 | false | false | 2 |
9f67bb4c1a7d5160dfe2200de42dded847091376 | 27,994,596,886,155 | 6183b2ed13796f398e8b14c7145079000829124b | /Springboot_Provider/src/main/java/com/softlab/provider/QiniuUtil.java | 0eb2503e6dd468d97ceef6f31f4568556f789c03 | [] | no_license | Ar1ess/xdzs2.0 | https://github.com/Ar1ess/xdzs2.0 | cf4b26fddbb3d60f79b371eab69ecfbe9e2e4ce2 | fa683ac0603ad75c6d81099cfb9d29caa8bf0ea9 | refs/heads/master | 2022-09-18T13:47:13.260000 | 2019-11-25T08:38:24 | 2019-11-25T08:38:24 | 220,405,962 | 2 | 0 | null | false | 2022-09-01T23:15:42 | 2019-11-08T06:57:53 | 2019-11-25T08:41:34 | 2022-09-01T23:15:39 | 235 | 2 | 0 | 11 | Java | false | false | package com.softlab.provider;
import com.softlab.common.util.ExecuteResult;
import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.GetPolicy;
import com.qiniu.api.rs.PutPolicy;
import com.qiniu.api.rs.RSClient;
import com.qiniu.api.rs.URLUtils;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* @author : Ar1es
* @date : 2019/11/11
* @since : Java 8
*/
public class QiniuUtil {
private static Logger logger = LoggerFactory.getLogger(QiniuUtil.class);
private static String bucketName = "xdzsnew";
private static String domain = "http://www.ar1es.cn/";
private static String ACCESS_KEY = "AdgNN6BnHLoVbZ-mTNKIPoBiNxz93lKMFRhub6Hy";
private static String SECRET_KEY = "RWEpsIojO1R7MSzLz3sth7bL2yNiHsIX7nIoCm3d";
/**
* 通过文件路径上传文件,是本地文件
*/
public ExecuteResult<String> uploadFile(String localFile) throws AuthException, JSONException {
File file = new File(localFile);
/**
* 文件后缀名 文件扩展名
*/
String filenameExtension = localFile.substring(localFile.lastIndexOf("."), localFile.length());
//调用下面的方法
return uploadFile(file, filenameExtension);
}
//通过File上传
public ExecuteResult<String> uploadFile(File file, String filenameExtension) throws AuthException, JSONException {
ExecuteResult<String> executeResult = new ExecuteResult<String>();
//获取上传凭证
String uptoken = getUpToken();
// 可选的上传选项,具体说明请参见使用手册。
PutExtra extra = new PutExtra();
SimpleDateFormat time = new SimpleDateFormat("yyyy/MM/dd");
// 上传文件
PutRet ret = IoApi.putFile(uptoken, time.format(new Date()) + "/" + UUID.randomUUID() + filenameExtension, file.getAbsolutePath(), extra);
if (ret.ok()) {
executeResult.setSuccessMessage("上传成功!");
executeResult.setResult(domain + ret.getKey());
} else {
executeResult.addErrorMessage("上传失败");
}
return executeResult;
}
/**
* 从 inputstream 中写入七牛
*
* @param key 文件名
* @param content 要写入的内容
* @return
* @throws AuthException
* @throws JSONException
*/
public boolean uploadFile(String key, String content) throws AuthException, JSONException {
// 读取的时候按的二进制,所以这里要同一
ByteArrayInputStream inputStream = new ByteArrayInputStream(content.getBytes());
String uptoken = getUpToken();
// 可选的上传选项,具体说明请参见使用手册。
PutExtra extra = new PutExtra();
// 上传文件
PutRet ret = IoApi.Put(uptoken, key, inputStream, extra);
if (ret.ok()) {
return true;
} else {
return false;
}
}
//获得下载地址
public String getDownloadFileUrl(String filename) throws Exception {
Mac mac = getMac();
String baseUrl = URLUtils.makeBaseUrl(domain, filename);
GetPolicy getPolicy = new GetPolicy();
String downloadUrl = getPolicy.makeRequest(baseUrl, mac);
return downloadUrl;
}
//删除文件
public void deleteFile(String filename) {
Mac mac = getMac();
RSClient client = new RSClient(mac);
client.delete(domain, filename);
}
//获取凭证
private String getUpToken() throws AuthException, JSONException, com.qiniu.api.auth.AuthException, org.json.JSONException {
Mac mac = getMac();
PutPolicy putPolicy = new PutPolicy(bucketName);
String uptoken = putPolicy.token(mac);
return uptoken;
}
private Mac getMac() {
Mac mac = new Mac(ACCESS_KEY, SECRET_KEY);
return mac;
}
}
| UTF-8 | Java | 4,189 | java | QiniuUtil.java | Java | [
{
"context": "til.Date;\nimport java.util.UUID;\n\n/**\n * @author : Ar1es\n * @date : 2019/11/11\n * @since : Java 8\n */\npubl",
"end": 641,
"score": 0.9987712502479553,
"start": 636,
"tag": "USERNAME",
"value": "Ar1es"
},
{
"context": "1es.cn/\";\n private static String ACCESS_KEY = \"AdgNN6BnHLoVbZ-mTNKIPoBiNxz93lKMFRhub6Hy\";\n private static String SECRET_KEY = \"RWEpsIo",
"end": 980,
"score": 0.9924008846282959,
"start": 940,
"tag": "KEY",
"value": "AdgNN6BnHLoVbZ-mTNKIPoBiNxz93lKMFRhub6Hy"
},
{
"context": "Rhub6Hy\";\n private static String SECRET_KEY = \"RWEpsIojO1R7MSzLz3sth7bL2yNiHsIX7nIoCm3d\";\n\n\n /**\n * 通过文件路径上传文件,是本地文件\n */\n\n ",
"end": 1063,
"score": 0.9996676445007324,
"start": 1023,
"tag": "KEY",
"value": "RWEpsIojO1R7MSzLz3sth7bL2yNiHsIX7nIoCm3d"
},
{
"context": "* 从 inputstream 中写入七牛\n *\n * @param key 文件名\n * @param content 要写入的内容\n * @return\n ",
"end": 2352,
"score": 0.644331693649292,
"start": 2349,
"tag": "KEY",
"value": "文件名"
}
] | null | [] | package com.softlab.provider;
import com.softlab.common.util.ExecuteResult;
import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.GetPolicy;
import com.qiniu.api.rs.PutPolicy;
import com.qiniu.api.rs.RSClient;
import com.qiniu.api.rs.URLUtils;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* @author : Ar1es
* @date : 2019/11/11
* @since : Java 8
*/
public class QiniuUtil {
private static Logger logger = LoggerFactory.getLogger(QiniuUtil.class);
private static String bucketName = "xdzsnew";
private static String domain = "http://www.ar1es.cn/";
private static String ACCESS_KEY = "<KEY>";
private static String SECRET_KEY = "<KEY>";
/**
* 通过文件路径上传文件,是本地文件
*/
public ExecuteResult<String> uploadFile(String localFile) throws AuthException, JSONException {
File file = new File(localFile);
/**
* 文件后缀名 文件扩展名
*/
String filenameExtension = localFile.substring(localFile.lastIndexOf("."), localFile.length());
//调用下面的方法
return uploadFile(file, filenameExtension);
}
//通过File上传
public ExecuteResult<String> uploadFile(File file, String filenameExtension) throws AuthException, JSONException {
ExecuteResult<String> executeResult = new ExecuteResult<String>();
//获取上传凭证
String uptoken = getUpToken();
// 可选的上传选项,具体说明请参见使用手册。
PutExtra extra = new PutExtra();
SimpleDateFormat time = new SimpleDateFormat("yyyy/MM/dd");
// 上传文件
PutRet ret = IoApi.putFile(uptoken, time.format(new Date()) + "/" + UUID.randomUUID() + filenameExtension, file.getAbsolutePath(), extra);
if (ret.ok()) {
executeResult.setSuccessMessage("上传成功!");
executeResult.setResult(domain + ret.getKey());
} else {
executeResult.addErrorMessage("上传失败");
}
return executeResult;
}
/**
* 从 inputstream 中写入七牛
*
* @param key 文件名
* @param content 要写入的内容
* @return
* @throws AuthException
* @throws JSONException
*/
public boolean uploadFile(String key, String content) throws AuthException, JSONException {
// 读取的时候按的二进制,所以这里要同一
ByteArrayInputStream inputStream = new ByteArrayInputStream(content.getBytes());
String uptoken = getUpToken();
// 可选的上传选项,具体说明请参见使用手册。
PutExtra extra = new PutExtra();
// 上传文件
PutRet ret = IoApi.Put(uptoken, key, inputStream, extra);
if (ret.ok()) {
return true;
} else {
return false;
}
}
//获得下载地址
public String getDownloadFileUrl(String filename) throws Exception {
Mac mac = getMac();
String baseUrl = URLUtils.makeBaseUrl(domain, filename);
GetPolicy getPolicy = new GetPolicy();
String downloadUrl = getPolicy.makeRequest(baseUrl, mac);
return downloadUrl;
}
//删除文件
public void deleteFile(String filename) {
Mac mac = getMac();
RSClient client = new RSClient(mac);
client.delete(domain, filename);
}
//获取凭证
private String getUpToken() throws AuthException, JSONException, com.qiniu.api.auth.AuthException, org.json.JSONException {
Mac mac = getMac();
PutPolicy putPolicy = new PutPolicy(bucketName);
String uptoken = putPolicy.token(mac);
return uptoken;
}
private Mac getMac() {
Mac mac = new Mac(ACCESS_KEY, SECRET_KEY);
return mac;
}
}
| 4,119 | 0.658117 | 0.651962 | 136 | 27.669117 | 28.490208 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.566176 | false | false | 2 |
3376d1bea411568984d70479883e7008cfc94877 | 34,522,947,151,474 | 942c5021817d284f47382433eee4a5c24ca781bf | /core/store/src/main/java/mil/nga/giat/geowave/core/store/memory/MemoryDataStoreFactory.java | add1e79234b3cb3faf3bcc083e42dcbd02cc5543 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain"
] | permissive | rfecher/geowave | https://github.com/rfecher/geowave | 9e41c93ec474db7b3c32e75ebb7c30f6f1f19c1a | b5dfb64abb6efdcdc75f46222ffd2d4c3f7d64a5 | refs/heads/master | 2022-06-28T02:03:32.509000 | 2017-02-15T17:56:32 | 2017-02-15T17:56:32 | 39,567,101 | 0 | 2 | Apache-2.0 | true | 2018-07-23T12:23:08 | 2015-07-23T12:50:18 | 2016-09-19T15:35:44 | 2018-07-20T18:29:07 | 770,883 | 0 | 0 | 0 | Java | false | null | package mil.nga.giat.geowave.core.store.memory;
import java.util.HashMap;
import java.util.Map;
import mil.nga.giat.geowave.core.store.DataStore;
import mil.nga.giat.geowave.core.store.StoreFactoryOptions;
public class MemoryDataStoreFactory extends
AbstractMemoryStoreFactory<DataStore>
{
private static final Map<String, DataStore> DATA_STORE_CACHE = new HashMap<String, DataStore>();
@Override
public DataStore createStore(
StoreFactoryOptions configOptions ) {
return createStore(configOptions.getGeowaveNamespace());
}
protected static synchronized DataStore createStore(
final String namespace ) {
DataStore store = DATA_STORE_CACHE.get(namespace);
if (store == null) {
store = new MemoryDataStore(
MemoryAdapterStoreFactory.createStore(namespace),
MemoryIndexStoreFactory.createStore(namespace),
MemoryDataStatisticsStoreFactory.createStore(namespace),
MemorySecondaryIndexStoreFactory.createStore(namespace),
MemoryAdapterIndexMappingStoreFactory.createStore(namespace));
DATA_STORE_CACHE.put(
namespace,
store);
}
return store;
}
}
| UTF-8 | Java | 1,111 | java | MemoryDataStoreFactory.java | Java | [] | null | [] | package mil.nga.giat.geowave.core.store.memory;
import java.util.HashMap;
import java.util.Map;
import mil.nga.giat.geowave.core.store.DataStore;
import mil.nga.giat.geowave.core.store.StoreFactoryOptions;
public class MemoryDataStoreFactory extends
AbstractMemoryStoreFactory<DataStore>
{
private static final Map<String, DataStore> DATA_STORE_CACHE = new HashMap<String, DataStore>();
@Override
public DataStore createStore(
StoreFactoryOptions configOptions ) {
return createStore(configOptions.getGeowaveNamespace());
}
protected static synchronized DataStore createStore(
final String namespace ) {
DataStore store = DATA_STORE_CACHE.get(namespace);
if (store == null) {
store = new MemoryDataStore(
MemoryAdapterStoreFactory.createStore(namespace),
MemoryIndexStoreFactory.createStore(namespace),
MemoryDataStatisticsStoreFactory.createStore(namespace),
MemorySecondaryIndexStoreFactory.createStore(namespace),
MemoryAdapterIndexMappingStoreFactory.createStore(namespace));
DATA_STORE_CACHE.put(
namespace,
store);
}
return store;
}
}
| 1,111 | 0.779478 | 0.779478 | 36 | 29.861111 | 24.910007 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.305556 | false | false | 2 |
5b5b25007d1d377cf2cbaba137e4c1ca2d76604e | 12,524,124,699,821 | cb6bad2c25b26140293c10593e458ecf3304e693 | /app/src/main/java/com/lzc/carefreeofficial/enity/LoginResult.java | c1355f790459b057e9864d396d8f76a0aee4f2ec | [] | no_license | save-the-baby/careFreee | https://github.com/save-the-baby/careFreee | 288d0f77c1da30e0443cf8e2d4961b16089710fd | f58ae2b69e2356d4b5430863d961608c06125cf0 | refs/heads/master | 2021-03-31T15:21:36.278000 | 2020-03-18T02:50:34 | 2020-03-18T02:56:13 | 248,115,941 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lzc.carefreeofficial.enity;
/**
* Date:2019/11/21
* Time:10:09
* author: lzc
*/
public class LoginResult {
public static final String COLUMN_USERNAME="username";//用户名key
public static final String COLUMN_USER_ICON="userIcon";//用户头像key
public static final String COLUMN_USER_EMAIL="email";//用户邮箱key
public static final String COLUMN_USER_GENDER="gender";//用户性别key
public static final String COLUMN_USER_CONTACT="contact";//联系方式key
public static final String COLUMN_PRAISE="praise";//赞同key
public static final String COLUMN_BELITTLE="belittle";//贬低key
public static final String COLUMN_REL="rel";//发布数量key
public static final String COLUMN_ACCEPT="accept";//接受数量key
/**
* result : true
* msg : 成功
* user : {"id":17,"username":"root","password":"123","gender":"女","iconUrl":"","iconPath":"","contact":"10001","email":"10001@gmail.com","praise":0,"belittle":0,"relCount":5,"acceptCount":0}
*/
private boolean result;
private String msg;
private UserBean user;
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public UserBean getUser() {
return user;
}
public void setUser(UserBean user) {
this.user = user;
}
public static class UserBean {
/**
* id : 17
* username : root
* password : 123
* gender : 女
* iconUrl :
* iconPath :
* contact : 10001
* email : 10001@gmail.com
* praise : 0
* belittle : 0
* relCount : 5
* acceptCount : 0
*/
private int id;
private String username;
private String password;
private String gender;
private String iconUrl;
private String iconPath;
private String contact;
private String email;
private int praise;
private int belittle;
private int relCount;
private int acceptCount;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getIconUrl() {
return iconUrl;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public String getIconPath() {
return iconPath;
}
public void setIconPath(String iconPath) {
this.iconPath = iconPath;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getPraise() {
return praise;
}
public void setPraise(int praise) {
this.praise = praise;
}
public int getBelittle() {
return belittle;
}
public void setBelittle(int belittle) {
this.belittle = belittle;
}
public int getRelCount() {
return relCount;
}
public void setRelCount(int relCount) {
this.relCount = relCount;
}
public int getAcceptCount() {
return acceptCount;
}
public void setAcceptCount(int acceptCount) {
this.acceptCount = acceptCount;
}
}
}
| UTF-8 | Java | 4,462 | java | LoginResult.java | Java | [
{
"context": "/**\r\n * Date:2019/11/21\r\n * Time:10:09\r\n * author: lzc\r\n */\r\npublic class LoginResult {\r\n public stat",
"end": 97,
"score": 0.9995871782302856,
"start": 94,
"tag": "USERNAME",
"value": "lzc"
},
{
"context": "\r\n public static final String COLUMN_USERNAME=\"username\";//用户名key\r\n public static final String COLUMN_",
"end": 188,
"score": 0.9994790554046631,
"start": 180,
"tag": "USERNAME",
"value": "username"
},
{
"context": " * msg : 成功\r\n * user : {\"id\":17,\"username\":\"root\",\"password\":\"123\",\"gender\":\"女\",\"iconUrl\":\"\",\"icon",
"end": 821,
"score": 0.9978551864624023,
"start": 817,
"tag": "USERNAME",
"value": "root"
},
{
"context": " * user : {\"id\":17,\"username\":\"root\",\"password\":\"123\",\"gender\":\"女\",\"iconUrl\":\"\",\"iconPath\":\"\",\"contact",
"end": 838,
"score": 0.9993581771850586,
"start": 835,
"tag": "PASSWORD",
"value": "123"
},
{
"context": "nUrl\":\"\",\"iconPath\":\"\",\"contact\":\"10001\",\"email\":\"10001@gmail.com\",\"praise\":0,\"belittle\":0,\"relCount\":5,\"acceptCoun",
"end": 922,
"score": 0.9999220967292786,
"start": 907,
"tag": "EMAIL",
"value": "10001@gmail.com"
},
{
"context": " /**\r\n * id : 17\r\n * username : root\r\n * password : 123\r\n * gender : 女",
"end": 1594,
"score": 0.9981630444526672,
"start": 1590,
"tag": "USERNAME",
"value": "root"
},
{
"context": " * username : root\r\n * password : 123\r\n * gender : 女\r\n * iconUrl :\r\n ",
"end": 1621,
"score": 0.9993014335632324,
"start": 1618,
"tag": "PASSWORD",
"value": "123"
},
{
"context": ":\r\n * contact : 10001\r\n * email : 10001@gmail.com\r\n * praise : 0\r\n * belittle : 0\r\n",
"end": 1753,
"score": 0.9999249577522278,
"start": 1738,
"tag": "EMAIL",
"value": "10001@gmail.com"
},
{
"context": "\n\r\n private int id;\r\n private String username;\r\n private String password;\r\n priva",
"end": 1927,
"score": 0.6836851239204407,
"start": 1919,
"tag": "USERNAME",
"value": "username"
},
{
"context": " public String getUsername() {\r\n return username;\r\n }\r\n\r\n public void setUsername(St",
"end": 2464,
"score": 0.9246475100517273,
"start": 2456,
"tag": "USERNAME",
"value": "username"
},
{
"context": "me(String username) {\r\n this.username = username;\r\n }\r\n\r\n public String getPassword(",
"end": 2568,
"score": 0.9266055226325989,
"start": 2560,
"tag": "USERNAME",
"value": "username"
}
] | null | [] | package com.lzc.carefreeofficial.enity;
/**
* Date:2019/11/21
* Time:10:09
* author: lzc
*/
public class LoginResult {
public static final String COLUMN_USERNAME="username";//用户名key
public static final String COLUMN_USER_ICON="userIcon";//用户头像key
public static final String COLUMN_USER_EMAIL="email";//用户邮箱key
public static final String COLUMN_USER_GENDER="gender";//用户性别key
public static final String COLUMN_USER_CONTACT="contact";//联系方式key
public static final String COLUMN_PRAISE="praise";//赞同key
public static final String COLUMN_BELITTLE="belittle";//贬低key
public static final String COLUMN_REL="rel";//发布数量key
public static final String COLUMN_ACCEPT="accept";//接受数量key
/**
* result : true
* msg : 成功
* user : {"id":17,"username":"root","password":"123","gender":"女","iconUrl":"","iconPath":"","contact":"10001","email":"<EMAIL>","praise":0,"belittle":0,"relCount":5,"acceptCount":0}
*/
private boolean result;
private String msg;
private UserBean user;
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public UserBean getUser() {
return user;
}
public void setUser(UserBean user) {
this.user = user;
}
public static class UserBean {
/**
* id : 17
* username : root
* password : 123
* gender : 女
* iconUrl :
* iconPath :
* contact : 10001
* email : <EMAIL>
* praise : 0
* belittle : 0
* relCount : 5
* acceptCount : 0
*/
private int id;
private String username;
private String password;
private String gender;
private String iconUrl;
private String iconPath;
private String contact;
private String email;
private int praise;
private int belittle;
private int relCount;
private int acceptCount;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getIconUrl() {
return iconUrl;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public String getIconPath() {
return iconPath;
}
public void setIconPath(String iconPath) {
this.iconPath = iconPath;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getPraise() {
return praise;
}
public void setPraise(int praise) {
this.praise = praise;
}
public int getBelittle() {
return belittle;
}
public void setBelittle(int belittle) {
this.belittle = belittle;
}
public int getRelCount() {
return relCount;
}
public void setRelCount(int relCount) {
this.relCount = relCount;
}
public int getAcceptCount() {
return acceptCount;
}
public void setAcceptCount(int acceptCount) {
this.acceptCount = acceptCount;
}
}
}
| 4,446 | 0.524363 | 0.512978 | 177 | 22.813559 | 22.048847 | 195 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.372881 | false | false | 2 |
e0ddfd8c9f69f3ef372d3abb6b7847ba5506d836 | 35,107,062,701,653 | 2497ef0797889ac8a88a685e6efac5ef079cfa04 | /src/test/java/com/cegedim/service/rest/controllers/TipoProductoControllerLayerIT.java | 8affb085f947c38f2e7302def2fde1d4b448e57f | [] | no_license | hdacostac/rest-admin-service | https://github.com/hdacostac/rest-admin-service | 36b703aae74abd7f131e174ff43492c2ae612c5d | b1c25e6bcccd9d09a2cb4d77e273a45585baf061 | refs/heads/master | 2020-06-11T06:43:05.035000 | 2019-10-13T20:33:40 | 2019-10-13T20:33:40 | 193,879,877 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cegedim.service.rest.controllers;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.util.UriComponentsBuilder;
import com.cegedim.service.RestServicesConfiguration;
import com.gvt.adminpanel.hibernate.model.TipoProducto;
import com.gvt.support.rest.handlers.CustomResponseErrorHandler;
import com.gvt.support.rest.handlers.URLRestHandler;
import swf.cegedim.rest.security.utils.JWTTestUtils;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {
RestServicesConfiguration.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc(secure = false)
public class TipoProductoControllerLayerIT {
private static final Logger LOGGER = LoggerFactory.getLogger(TipoProductoControllerLayerIT.class);
private static final String PREFIX = "/productType";
@Autowired
private MockMvc mockMvc;
@Value("${server.port}")
private String serverPort;
@Autowired
private TestRestTemplate restTemplate;
private URLRestHandler urlAdminTables;
public URLRestHandler urlAdminTables() {
URLRestHandler baseRestHandler = new URLRestHandler();
baseRestHandler.setRestContext("/");
baseRestHandler.setRestHost("localhost");
baseRestHandler.setRestPort(serverPort);
baseRestHandler.setRestScheme("http");
return baseRestHandler;
}
private UriComponentsBuilder uriComponents;
private HttpEntity<String> requestEntity;
@Before
public void setUp() {
uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("localhost").port(serverPort);
restTemplate.getRestTemplate().setInterceptors(new ArrayList<>());
restTemplate.getRestTemplate().setErrorHandler(new CustomResponseErrorHandler());
urlAdminTables = urlAdminTables();
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Authorization", "Bearer " + JWTTestUtils.createGenericToken());
requestEntity = new HttpEntity<>(requestHeaders);
}
// @Test
public void when_valid_person() throws Exception {
uriComponents.path(PREFIX + "/{id}");
ResponseEntity<TipoProducto> tipoProducto = restTemplate
.getForEntity(uriComponents.build("1").toURL().toString(), TipoProducto.class);
assertEquals("Gratis", tipoProducto.getBody().getNombre());
}
@Test
public void when_invalid_person() throws Exception {
mockMvc.perform(get(PREFIX + "/{id}", 687)).andExpect(status().is4xxClientError());
}
@Test(expected = ResourceAccessException.class)
public void whenURIBuilder() {
restTemplate.getForObject(urlAdminTables.buildURI(PREFIX + "/{id}"), TipoProducto.class, 123L);
}
}
| UTF-8 | Java | 3,660 | java | TipoProductoControllerLayerIT.java | Java | [] | null | [] | package com.cegedim.service.rest.controllers;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.util.UriComponentsBuilder;
import com.cegedim.service.RestServicesConfiguration;
import com.gvt.adminpanel.hibernate.model.TipoProducto;
import com.gvt.support.rest.handlers.CustomResponseErrorHandler;
import com.gvt.support.rest.handlers.URLRestHandler;
import swf.cegedim.rest.security.utils.JWTTestUtils;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {
RestServicesConfiguration.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc(secure = false)
public class TipoProductoControllerLayerIT {
private static final Logger LOGGER = LoggerFactory.getLogger(TipoProductoControllerLayerIT.class);
private static final String PREFIX = "/productType";
@Autowired
private MockMvc mockMvc;
@Value("${server.port}")
private String serverPort;
@Autowired
private TestRestTemplate restTemplate;
private URLRestHandler urlAdminTables;
public URLRestHandler urlAdminTables() {
URLRestHandler baseRestHandler = new URLRestHandler();
baseRestHandler.setRestContext("/");
baseRestHandler.setRestHost("localhost");
baseRestHandler.setRestPort(serverPort);
baseRestHandler.setRestScheme("http");
return baseRestHandler;
}
private UriComponentsBuilder uriComponents;
private HttpEntity<String> requestEntity;
@Before
public void setUp() {
uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("localhost").port(serverPort);
restTemplate.getRestTemplate().setInterceptors(new ArrayList<>());
restTemplate.getRestTemplate().setErrorHandler(new CustomResponseErrorHandler());
urlAdminTables = urlAdminTables();
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Authorization", "Bearer " + JWTTestUtils.createGenericToken());
requestEntity = new HttpEntity<>(requestHeaders);
}
// @Test
public void when_valid_person() throws Exception {
uriComponents.path(PREFIX + "/{id}");
ResponseEntity<TipoProducto> tipoProducto = restTemplate
.getForEntity(uriComponents.build("1").toURL().toString(), TipoProducto.class);
assertEquals("Gratis", tipoProducto.getBody().getNombre());
}
@Test
public void when_invalid_person() throws Exception {
mockMvc.perform(get(PREFIX + "/{id}", 687)).andExpect(status().is4xxClientError());
}
@Test(expected = ResourceAccessException.class)
public void whenURIBuilder() {
restTemplate.getForObject(urlAdminTables.buildURI(PREFIX + "/{id}"), TipoProducto.class, 123L);
}
}
| 3,660 | 0.785246 | 0.78224 | 100 | 34.599998 | 29.189383 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.27 | false | false | 2 |
693cdb4f2be91a376ca44b136ef2d418bdb57d9b | 12,249,246,770,983 | 81a5faa946e0c6894fdf9fc3bb421a2a2434d646 | /StarvingCodeMonkey/src/com/google/gwt/killers/client/ParkServiceAsync.java | 3eee4081389b98751d02cf4dcb95947fba321fc6 | [] | no_license | jimqi/CPSC310PublicMirror | https://github.com/jimqi/CPSC310PublicMirror | 9a82906fd8a851846ce4cb533eb4c2b09d09a37f | 03b525f27a46efb5b4da7dc38201f3c6e1e49017 | refs/heads/master | 2016-09-06T02:47:05.935000 | 2014-04-02T03:24:18 | 2014-04-02T03:24:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.gwt.killers.client;
import java.util.List;
import com.google.gwt.killers.entity.Park;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface ParkServiceAsync {
public void getParks(AsyncCallback<List<Park>> async);
} | UTF-8 | Java | 263 | java | ParkServiceAsync.java | Java | [] | null | [] | package com.google.gwt.killers.client;
import java.util.List;
import com.google.gwt.killers.entity.Park;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface ParkServiceAsync {
public void getParks(AsyncCallback<List<Park>> async);
} | 263 | 0.775665 | 0.775665 | 10 | 24.5 | 21.551102 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 2 |
b344ead46bd050d37a470815db39c6eac701521b | 37,701,222,931,279 | 68c7a83758e6d2ef2d7189577a8142645721ce58 | /app/src/main/java/com/app/aptap/fragment/GroupManagement.java | fc4760f0763633d711865902e5d87609b2ed2098 | [] | no_license | sateesh9491/Aptap_Android | https://github.com/sateesh9491/Aptap_Android | 1198de213b086bec652ff451c5ecaec66c470380 | 3d2b1b5c208fa012ce1a663a7e905591f31443c2 | refs/heads/master | 2021-05-14T05:27:21.457000 | 2018-01-04T06:05:17 | 2018-01-04T06:05:17 | 116,106,019 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.app.aptap.fragment;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.app.aptap.R;
import com.app.aptap.adapter.LatestGroupAdapter;
import com.app.aptap.adapter.ServiceUtilityBookingAdapter;
import com.app.aptap.util.Constants;
/**
* A simple {@link Fragment} subclass.
* Use the {@link GroupManagement#newInstance} factory method to
* create an instance of this fragment.
*/
public class GroupManagement extends MasterFragment implements View.OnClickListener {
public static String TAG = GroupManagement.class.getName();
private static final String ARG_FROM = "FROM";
private View mView;
private FloatingActionButton createGroup;
private int mFrom = -1;
public GroupManagement() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
* @return A new instance of fragment GroupManagement.
*/
// TODO: Rename and change types and number of parameters
public static GroupManagement newInstance(int fromIndex) {
GroupManagement fragment = new GroupManagement();
Bundle args = new Bundle();
args.putInt(ARG_FROM, fromIndex);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mFrom = getArguments().getInt(ARG_FROM);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_group_management, container, false);
createGroup = (FloatingActionButton) mView.findViewById(R.id.createGroup);
createGroup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mFrom==1) {
replaceChildHomeFragment(CreateGroupFragment.newInstance(), true, CreateGroupFragment.TAG);
} else if(mFrom==2) {
replaceChildSocietyFragment(CreateGroupFragment.newInstance(), true, CreateGroupFragment.TAG);
}
}
});
initServicesRecyclerView();
return mView;
}
@Override
public void onClick(View view) {
getHomeActivity().hideShowFabMenu();
int id = view.getId();
switch (id) {
case R.id.groupCircularRL:
if(mFrom==1) {
replaceChildHomeFragment(CreateGroupFragment.newInstance(), true, CreateGroupFragment.TAG);
} else if(mFrom==2) {
replaceChildSocietyFragment(CreateGroupFragment.newInstance(), true, CreateGroupFragment.TAG);
}
break;
}
}
private void initServicesRecyclerView() {
RecyclerView groupRecyclerView = (RecyclerView) mView.findViewById(R.id.groupRecyclerView);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3);
groupRecyclerView.setLayoutManager(mLayoutManager);
groupRecyclerView.setItemAnimator(new DefaultItemAnimator());
LatestGroupAdapter latestGroupAdapter = new LatestGroupAdapter(getHomeActivity(), this, Constants.getGroupData());
groupRecyclerView.setAdapter(latestGroupAdapter);
}
}
| UTF-8 | Java | 3,912 | java | GroupManagement.java | Java | [] | null | [] | package com.app.aptap.fragment;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.app.aptap.R;
import com.app.aptap.adapter.LatestGroupAdapter;
import com.app.aptap.adapter.ServiceUtilityBookingAdapter;
import com.app.aptap.util.Constants;
/**
* A simple {@link Fragment} subclass.
* Use the {@link GroupManagement#newInstance} factory method to
* create an instance of this fragment.
*/
public class GroupManagement extends MasterFragment implements View.OnClickListener {
public static String TAG = GroupManagement.class.getName();
private static final String ARG_FROM = "FROM";
private View mView;
private FloatingActionButton createGroup;
private int mFrom = -1;
public GroupManagement() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
* @return A new instance of fragment GroupManagement.
*/
// TODO: Rename and change types and number of parameters
public static GroupManagement newInstance(int fromIndex) {
GroupManagement fragment = new GroupManagement();
Bundle args = new Bundle();
args.putInt(ARG_FROM, fromIndex);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mFrom = getArguments().getInt(ARG_FROM);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_group_management, container, false);
createGroup = (FloatingActionButton) mView.findViewById(R.id.createGroup);
createGroup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mFrom==1) {
replaceChildHomeFragment(CreateGroupFragment.newInstance(), true, CreateGroupFragment.TAG);
} else if(mFrom==2) {
replaceChildSocietyFragment(CreateGroupFragment.newInstance(), true, CreateGroupFragment.TAG);
}
}
});
initServicesRecyclerView();
return mView;
}
@Override
public void onClick(View view) {
getHomeActivity().hideShowFabMenu();
int id = view.getId();
switch (id) {
case R.id.groupCircularRL:
if(mFrom==1) {
replaceChildHomeFragment(CreateGroupFragment.newInstance(), true, CreateGroupFragment.TAG);
} else if(mFrom==2) {
replaceChildSocietyFragment(CreateGroupFragment.newInstance(), true, CreateGroupFragment.TAG);
}
break;
}
}
private void initServicesRecyclerView() {
RecyclerView groupRecyclerView = (RecyclerView) mView.findViewById(R.id.groupRecyclerView);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3);
groupRecyclerView.setLayoutManager(mLayoutManager);
groupRecyclerView.setItemAnimator(new DefaultItemAnimator());
LatestGroupAdapter latestGroupAdapter = new LatestGroupAdapter(getHomeActivity(), this, Constants.getGroupData());
groupRecyclerView.setAdapter(latestGroupAdapter);
}
}
| 3,912 | 0.680982 | 0.67817 | 107 | 35.560749 | 29.962961 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.570093 | false | false | 2 |
3a98c56425d79dd6775e5e4afc8d972c71737bef | 34,437,047,805,524 | 1b5bd5bbec43f0609f0167cf3cd8d5e3bed9e830 | /src/main/java/com/example/skilltree/model/ItemLevel.java | 37d0252012e7cabc7a7d246e3f4cf22d4a85e590 | [] | no_license | michofilip/SkillTree | https://github.com/michofilip/SkillTree | 9829b1a83f386294585119502fa0074bfd21933d | 2e68a48c6283e283c382074200f7c87d0e28aab0 | refs/heads/master | 2020-06-20T12:38:28.116000 | 2019-07-23T20:18:41 | 2019-07-23T20:18:41 | 197,125,258 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.skilltree.model;
import lombok.Data;
import javax.persistence.CascadeType;
import javax.persistence.Embeddable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Collection;
@Entity
@Table(name = "item_levels")
@Data
public class ItemLevel {
@Embeddable
@Data
public static class ItemLevelId implements Serializable {
@NotNull
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Item item;
@NotNull
@Min(1)
private Integer level;
}
@EmbeddedId
private ItemLevelId id;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(
name = "item_level_requirements",
joinColumns = {
@JoinColumn(name = "item_id"),
@JoinColumn(name = "level"),
},
inverseJoinColumns = {
@JoinColumn(name = "required_item_id"),
@JoinColumn(name = "required_level"),
}
)
private Collection<ItemLevel> requiredItemLevels;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "itemLevel")
private Collection<FeatureValue> featureValues;
}
| UTF-8 | Java | 1,632 | java | ItemLevel.java | Java | [] | null | [] | package com.example.skilltree.model;
import lombok.Data;
import javax.persistence.CascadeType;
import javax.persistence.Embeddable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Collection;
@Entity
@Table(name = "item_levels")
@Data
public class ItemLevel {
@Embeddable
@Data
public static class ItemLevelId implements Serializable {
@NotNull
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Item item;
@NotNull
@Min(1)
private Integer level;
}
@EmbeddedId
private ItemLevelId id;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(
name = "item_level_requirements",
joinColumns = {
@JoinColumn(name = "item_id"),
@JoinColumn(name = "level"),
},
inverseJoinColumns = {
@JoinColumn(name = "required_item_id"),
@JoinColumn(name = "required_level"),
}
)
private Collection<ItemLevel> requiredItemLevels;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "itemLevel")
private Collection<FeatureValue> featureValues;
}
| 1,632 | 0.679534 | 0.678922 | 58 | 27.137932 | 20.655172 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.551724 | false | false | 2 |
d5706447ddabcadcd95ef01383bce5cf17a345b8 | 34,102,040,359,697 | 7e5771665d3c1ca05bafd800cc4b84b09fc9ed7b | /dropwizard-logging/src/main/java/com/codahale/dropwizard/logging/FileAppenderFactory.java | 41dd777ca976cf165992c0a5d9f756a7b2822cb8 | [
"Apache-2.0"
] | permissive | dmt/dropwizard | https://github.com/dmt/dropwizard | 9d7497a9f04c5493178acdccc033d0ab85d47fc0 | 31d8cc44f16c98e19741816dfa684cd3ddc42023 | refs/heads/master | 2021-01-23T23:20:31.404000 | 2013-05-11T18:51:25 | 2013-05-11T18:51:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.codahale.dropwizard.logging;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.filter.ThresholdFilter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.FileAppender;
import ch.qos.logback.core.Layout;
import ch.qos.logback.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
import ch.qos.logback.core.spi.FilterAttachable;
import com.codahale.dropwizard.validation.ValidationMethod;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.base.Strings;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.TimeZone;
@JsonTypeName("file")
public class FileAppenderFactory implements AppenderFactory {
@NotNull
private Level threshold = Level.ALL;
@NotNull
private String currentLogFilename;
private boolean archive = true;
private String archivedLogFilenamePattern;
@Min(1)
@Max(50)
private int archivedFileCount = 5;
@NotNull
private TimeZone timeZone = TimeZone.getTimeZone("UTC");
private String logFormat;
@JsonProperty
public Level getThreshold() {
return threshold;
}
@JsonProperty
public void setThreshold(Level threshold) {
this.threshold = threshold;
}
@JsonProperty
public String getCurrentLogFilename() {
return currentLogFilename;
}
@JsonProperty
public void setCurrentLogFilename(String currentLogFilename) {
this.currentLogFilename = currentLogFilename;
}
@JsonProperty
public boolean isArchive() {
return archive;
}
@JsonProperty
public void setArchive(boolean archive) {
this.archive = archive;
}
@JsonProperty
public String getArchivedLogFilenamePattern() {
return archivedLogFilenamePattern;
}
@JsonProperty
public void setArchivedLogFilenamePattern(String archivedLogFilenamePattern) {
this.archivedLogFilenamePattern = archivedLogFilenamePattern;
}
@JsonProperty
public int getArchivedFileCount() {
return archivedFileCount;
}
@JsonProperty
public void setArchivedFileCount(int archivedFileCount) {
this.archivedFileCount = archivedFileCount;
}
@JsonProperty
public TimeZone getTimeZone() {
return timeZone;
}
@JsonProperty
public void setTimeZone(TimeZone timeZone) {
this.timeZone = timeZone;
}
@JsonProperty
public String getLogFormat() {
return logFormat;
}
@JsonProperty
public void setLogFormat(String logFormat) {
this.logFormat = logFormat;
}
@JsonIgnore
@ValidationMethod(message = "must have archivedLogFilenamePattern if archive is true")
public boolean isValidArchiveConfiguration() {
return !archive || (archivedLogFilenamePattern != null);
}
@Override
public Appender<ILoggingEvent> build(LoggerContext context, String applicationName, Layout<ILoggingEvent> layout) {
final FileAppender<ILoggingEvent> appender = archive ?
new RollingFileAppender<ILoggingEvent>() :
new FileAppender<ILoggingEvent>();
appender.setAppend(true);
appender.setContext(context);
if (layout == null) {
final LogFormatter formatter = new LogFormatter(context, timeZone);
if (!Strings.isNullOrEmpty(logFormat)) {
formatter.setPattern(logFormat);
}
formatter.start();
appender.setLayout(formatter);
} else {
appender.setLayout(layout);
}
appender.setFile(currentLogFilename);
appender.setPrudent(false);
addThresholdFilter(appender, threshold);
if (archive) {
final DefaultTimeBasedFileNamingAndTriggeringPolicy<ILoggingEvent> triggeringPolicy =
new DefaultTimeBasedFileNamingAndTriggeringPolicy<>();
triggeringPolicy.setContext(context);
final TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new TimeBasedRollingPolicy<>();
rollingPolicy.setContext(context);
rollingPolicy.setFileNamePattern(archivedLogFilenamePattern);
rollingPolicy.setTimeBasedFileNamingAndTriggeringPolicy(
triggeringPolicy);
triggeringPolicy.setTimeBasedRollingPolicy(rollingPolicy);
rollingPolicy.setMaxHistory(archivedFileCount);
((RollingFileAppender<ILoggingEvent>) appender).setRollingPolicy(rollingPolicy);
((RollingFileAppender<ILoggingEvent>) appender).setTriggeringPolicy(triggeringPolicy);
rollingPolicy.setParent(appender);
rollingPolicy.start();
}
appender.stop();
appender.start();
return appender;
}
private void addThresholdFilter(FilterAttachable<ILoggingEvent> appender, Level threshold) {
final ThresholdFilter filter = new ThresholdFilter();
filter.setLevel(threshold.toString());
filter.start();
appender.addFilter(filter);
}
}
| UTF-8 | Java | 5,480 | java | FileAppenderFactory.java | Java | [] | null | [] | package com.codahale.dropwizard.logging;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.filter.ThresholdFilter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.FileAppender;
import ch.qos.logback.core.Layout;
import ch.qos.logback.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
import ch.qos.logback.core.spi.FilterAttachable;
import com.codahale.dropwizard.validation.ValidationMethod;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.base.Strings;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.TimeZone;
@JsonTypeName("file")
public class FileAppenderFactory implements AppenderFactory {
@NotNull
private Level threshold = Level.ALL;
@NotNull
private String currentLogFilename;
private boolean archive = true;
private String archivedLogFilenamePattern;
@Min(1)
@Max(50)
private int archivedFileCount = 5;
@NotNull
private TimeZone timeZone = TimeZone.getTimeZone("UTC");
private String logFormat;
@JsonProperty
public Level getThreshold() {
return threshold;
}
@JsonProperty
public void setThreshold(Level threshold) {
this.threshold = threshold;
}
@JsonProperty
public String getCurrentLogFilename() {
return currentLogFilename;
}
@JsonProperty
public void setCurrentLogFilename(String currentLogFilename) {
this.currentLogFilename = currentLogFilename;
}
@JsonProperty
public boolean isArchive() {
return archive;
}
@JsonProperty
public void setArchive(boolean archive) {
this.archive = archive;
}
@JsonProperty
public String getArchivedLogFilenamePattern() {
return archivedLogFilenamePattern;
}
@JsonProperty
public void setArchivedLogFilenamePattern(String archivedLogFilenamePattern) {
this.archivedLogFilenamePattern = archivedLogFilenamePattern;
}
@JsonProperty
public int getArchivedFileCount() {
return archivedFileCount;
}
@JsonProperty
public void setArchivedFileCount(int archivedFileCount) {
this.archivedFileCount = archivedFileCount;
}
@JsonProperty
public TimeZone getTimeZone() {
return timeZone;
}
@JsonProperty
public void setTimeZone(TimeZone timeZone) {
this.timeZone = timeZone;
}
@JsonProperty
public String getLogFormat() {
return logFormat;
}
@JsonProperty
public void setLogFormat(String logFormat) {
this.logFormat = logFormat;
}
@JsonIgnore
@ValidationMethod(message = "must have archivedLogFilenamePattern if archive is true")
public boolean isValidArchiveConfiguration() {
return !archive || (archivedLogFilenamePattern != null);
}
@Override
public Appender<ILoggingEvent> build(LoggerContext context, String applicationName, Layout<ILoggingEvent> layout) {
final FileAppender<ILoggingEvent> appender = archive ?
new RollingFileAppender<ILoggingEvent>() :
new FileAppender<ILoggingEvent>();
appender.setAppend(true);
appender.setContext(context);
if (layout == null) {
final LogFormatter formatter = new LogFormatter(context, timeZone);
if (!Strings.isNullOrEmpty(logFormat)) {
formatter.setPattern(logFormat);
}
formatter.start();
appender.setLayout(formatter);
} else {
appender.setLayout(layout);
}
appender.setFile(currentLogFilename);
appender.setPrudent(false);
addThresholdFilter(appender, threshold);
if (archive) {
final DefaultTimeBasedFileNamingAndTriggeringPolicy<ILoggingEvent> triggeringPolicy =
new DefaultTimeBasedFileNamingAndTriggeringPolicy<>();
triggeringPolicy.setContext(context);
final TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new TimeBasedRollingPolicy<>();
rollingPolicy.setContext(context);
rollingPolicy.setFileNamePattern(archivedLogFilenamePattern);
rollingPolicy.setTimeBasedFileNamingAndTriggeringPolicy(
triggeringPolicy);
triggeringPolicy.setTimeBasedRollingPolicy(rollingPolicy);
rollingPolicy.setMaxHistory(archivedFileCount);
((RollingFileAppender<ILoggingEvent>) appender).setRollingPolicy(rollingPolicy);
((RollingFileAppender<ILoggingEvent>) appender).setTriggeringPolicy(triggeringPolicy);
rollingPolicy.setParent(appender);
rollingPolicy.start();
}
appender.stop();
appender.start();
return appender;
}
private void addThresholdFilter(FilterAttachable<ILoggingEvent> appender, Level threshold) {
final ThresholdFilter filter = new ThresholdFilter();
filter.setLevel(threshold.toString());
filter.start();
appender.addFilter(filter);
}
}
| 5,480 | 0.700547 | 0.699818 | 179 | 29.614525 | 26.218933 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.446927 | false | false | 2 |
45a035a1baf84043af34a58bbc3375267732eb32 | 23,656,679,901,248 | 852a55d1cffde7b9c497b6a2ef6745d6ea059853 | /PhysicsLibrary/src/physics/physics.java | 86f7be71f4af62609b255d0546c82bd9f3da9e5f | [] | no_license | 1567654/Physics_library | https://github.com/1567654/Physics_library | 26121628ee386c1c15ac17032033ee137db39915 | efa0619fa4daecbad16787e098d3cf284cafb595 | refs/heads/master | 2020-04-05T05:57:39.968000 | 2018-11-07T22:56:35 | 2018-11-07T22:56:35 | 156,619,274 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package physics;
import java.util.Scanner;
public class physics {
public static void main(String[] args) {
//fahrenheitToCelsius();
//kelvinToCelsius();
//fluidPressure();
//pressureUnderWater();
//kineticEnergy();
//potentialEnergy();
//fallspeed();
//delta();
//volumeToMass();
//volumeToMass2();
volumeToMass3();
//svtVelocity();
//svtDistance();
//svtTime();
//work();
//power();
//heat();
//heat2();
//heat3();
//velocityToHeight();
}
public static void fahrenheitToCelsius() {
Scanner input = new Scanner(System.in);
double fahrenheit = input.nextDouble();
double celsius = (fahrenheit - 32) / 1.8;
System.out.println(celsius);
input.close();
}
public static void kelvinToCelsius() {
Scanner input = new Scanner(System.in);
double kelvin = input.nextDouble();
double celsius = kelvin - 273.15;
System.out.println(celsius);
input.close();
}
public static void fluidPressure() {
Scanner input = new Scanner(System.in);
String fluid = input.nextLine();
String fluid2 = fluid.toUpperCase();
double deep = input.nextDouble();
System.out.println(library.fluidPressure(Fluid_table.valueOf(fluid2), deep));
input.close();
}
public static void pressureUnderWater() {
Scanner input = new Scanner(System.in);
double deep = input.nextDouble();
double pressureUnderWater = 998 * 9.82 * deep;
System.out.println(pressureUnderWater);
input.close();
}
public static void kineticEnergy() {
Scanner input = new Scanner(System.in);
double mass = input.nextDouble();
double velocity = input.nextDouble();
double kineticEnergy = mass * velocity;
System.out.println(kineticEnergy);
input.close();
}
public static void potentialEnergy() {
Scanner input = new Scanner(System.in);
double mass = input.nextDouble();
double height = input.nextDouble();
double potentialEnergy = mass * 9.82 * height;
System.out.println(potentialEnergy);
input.close();
}
public static void fallspeed() {
Scanner input = new Scanner(System.in);
double height = input.nextDouble();
double fallspeed = height * 2.802855688;
System.out.println(fallspeed);
input.close();
}
public static void delta() {
Scanner input = new Scanner(System.in);
double last = input.nextDouble();
double first = input.nextDouble();
double delta = first - last;
System.out.println(delta);
input.close();
}
public static void volumeToMass() {
Scanner input = new Scanner(System.in);
String fluid = input.nextLine();
String fluid2 = fluid.toUpperCase();
double volume = input.nextDouble();
System.out.println(library.volumeToMass(Fluid_table.valueOf(fluid2), volume));
input.close();
}
public static void volumeToMass2() {
Scanner input = new Scanner(System.in);
String gas = input.nextLine();
String gas2 = gas.toUpperCase();
double volume = input.nextDouble();
System.out.println(library.volumeToMass2(GasTable.valueOf(gas2), volume));
input.close();
}
public static void volumeToMass3() {
Scanner input = new Scanner(System.in);
String solid = input.nextLine();
String solid2 = solid.toUpperCase();
double volume = input.nextDouble();
System.out.println(library.volumeToMass3(SolidTable.valueOf(solid2), volume));
input.close();
}
public static void svtVelocity() {
Scanner input = new Scanner(System.in);
double distance = input.nextDouble();
double time = input.nextDouble();
double svtVelocity = distance / time;
System.out.println(svtVelocity);
input.close();
}
public static void svtDistance() {
Scanner input = new Scanner(System.in);
double velocity = input.nextDouble();
double time = input.nextDouble();
double svtDistance = velocity * time;
System.out.println(svtDistance);
input.close();
}
public static void svtTime() {
Scanner input = new Scanner(System.in);
double distance = input.nextDouble();
double velocity = input.nextDouble();
double svtTime = distance / velocity;
System.out.println(svtTime);
input.close();
}
public static void work() {
Scanner input = new Scanner(System.in);
double distance = input.nextDouble();
double force = input.nextDouble();
double work = distance * force;
System.out.println(work);
input.close();
}
public static void power() {
Scanner input = new Scanner(System.in);
double work = input.nextDouble();
double time = input.nextDouble();
double power = work / time;
System.out.println(power);
input.close();
}
public static void heat() {
Scanner input = new Scanner(System.in);
String solid = input.nextLine();
String solid2 = solid.toUpperCase();
double mass = input.nextDouble();
double deltaT = input.nextDouble();
System.out.println(library.heat(SolidTable.valueOf(solid2), mass, deltaT));
input.close();
}
public static void heat2() {
Scanner input = new Scanner(System.in);
String fluid = input.nextLine();
String fluid2 = fluid.toUpperCase();
double mass = input.nextDouble();
double deltaT = input.nextDouble();
System.out.println(library.heat2(Fluid_table.valueOf(fluid2), mass, deltaT));
input.close();
}
public static void heat3() {
Scanner input = new Scanner(System.in);
String gas = input.nextLine();
String gas2 = gas.toUpperCase();
double mass = input.nextDouble();
double deltaT = input.nextDouble();
System.out.println(library.heat3(GasTable.valueOf(gas2), mass, deltaT));
input.close();
}
public static void velocityToHeight() {
Scanner input = new Scanner(System.in);
double velocity = input.nextDouble();
double velocityToHeight = velocity / 2;
System.out.println(velocityToHeight);
input.close();
}
}
| UTF-8 | Java | 5,810 | java | physics.java | Java | [] | null | [] | package physics;
import java.util.Scanner;
public class physics {
public static void main(String[] args) {
//fahrenheitToCelsius();
//kelvinToCelsius();
//fluidPressure();
//pressureUnderWater();
//kineticEnergy();
//potentialEnergy();
//fallspeed();
//delta();
//volumeToMass();
//volumeToMass2();
volumeToMass3();
//svtVelocity();
//svtDistance();
//svtTime();
//work();
//power();
//heat();
//heat2();
//heat3();
//velocityToHeight();
}
public static void fahrenheitToCelsius() {
Scanner input = new Scanner(System.in);
double fahrenheit = input.nextDouble();
double celsius = (fahrenheit - 32) / 1.8;
System.out.println(celsius);
input.close();
}
public static void kelvinToCelsius() {
Scanner input = new Scanner(System.in);
double kelvin = input.nextDouble();
double celsius = kelvin - 273.15;
System.out.println(celsius);
input.close();
}
public static void fluidPressure() {
Scanner input = new Scanner(System.in);
String fluid = input.nextLine();
String fluid2 = fluid.toUpperCase();
double deep = input.nextDouble();
System.out.println(library.fluidPressure(Fluid_table.valueOf(fluid2), deep));
input.close();
}
public static void pressureUnderWater() {
Scanner input = new Scanner(System.in);
double deep = input.nextDouble();
double pressureUnderWater = 998 * 9.82 * deep;
System.out.println(pressureUnderWater);
input.close();
}
public static void kineticEnergy() {
Scanner input = new Scanner(System.in);
double mass = input.nextDouble();
double velocity = input.nextDouble();
double kineticEnergy = mass * velocity;
System.out.println(kineticEnergy);
input.close();
}
public static void potentialEnergy() {
Scanner input = new Scanner(System.in);
double mass = input.nextDouble();
double height = input.nextDouble();
double potentialEnergy = mass * 9.82 * height;
System.out.println(potentialEnergy);
input.close();
}
public static void fallspeed() {
Scanner input = new Scanner(System.in);
double height = input.nextDouble();
double fallspeed = height * 2.802855688;
System.out.println(fallspeed);
input.close();
}
public static void delta() {
Scanner input = new Scanner(System.in);
double last = input.nextDouble();
double first = input.nextDouble();
double delta = first - last;
System.out.println(delta);
input.close();
}
public static void volumeToMass() {
Scanner input = new Scanner(System.in);
String fluid = input.nextLine();
String fluid2 = fluid.toUpperCase();
double volume = input.nextDouble();
System.out.println(library.volumeToMass(Fluid_table.valueOf(fluid2), volume));
input.close();
}
public static void volumeToMass2() {
Scanner input = new Scanner(System.in);
String gas = input.nextLine();
String gas2 = gas.toUpperCase();
double volume = input.nextDouble();
System.out.println(library.volumeToMass2(GasTable.valueOf(gas2), volume));
input.close();
}
public static void volumeToMass3() {
Scanner input = new Scanner(System.in);
String solid = input.nextLine();
String solid2 = solid.toUpperCase();
double volume = input.nextDouble();
System.out.println(library.volumeToMass3(SolidTable.valueOf(solid2), volume));
input.close();
}
public static void svtVelocity() {
Scanner input = new Scanner(System.in);
double distance = input.nextDouble();
double time = input.nextDouble();
double svtVelocity = distance / time;
System.out.println(svtVelocity);
input.close();
}
public static void svtDistance() {
Scanner input = new Scanner(System.in);
double velocity = input.nextDouble();
double time = input.nextDouble();
double svtDistance = velocity * time;
System.out.println(svtDistance);
input.close();
}
public static void svtTime() {
Scanner input = new Scanner(System.in);
double distance = input.nextDouble();
double velocity = input.nextDouble();
double svtTime = distance / velocity;
System.out.println(svtTime);
input.close();
}
public static void work() {
Scanner input = new Scanner(System.in);
double distance = input.nextDouble();
double force = input.nextDouble();
double work = distance * force;
System.out.println(work);
input.close();
}
public static void power() {
Scanner input = new Scanner(System.in);
double work = input.nextDouble();
double time = input.nextDouble();
double power = work / time;
System.out.println(power);
input.close();
}
public static void heat() {
Scanner input = new Scanner(System.in);
String solid = input.nextLine();
String solid2 = solid.toUpperCase();
double mass = input.nextDouble();
double deltaT = input.nextDouble();
System.out.println(library.heat(SolidTable.valueOf(solid2), mass, deltaT));
input.close();
}
public static void heat2() {
Scanner input = new Scanner(System.in);
String fluid = input.nextLine();
String fluid2 = fluid.toUpperCase();
double mass = input.nextDouble();
double deltaT = input.nextDouble();
System.out.println(library.heat2(Fluid_table.valueOf(fluid2), mass, deltaT));
input.close();
}
public static void heat3() {
Scanner input = new Scanner(System.in);
String gas = input.nextLine();
String gas2 = gas.toUpperCase();
double mass = input.nextDouble();
double deltaT = input.nextDouble();
System.out.println(library.heat3(GasTable.valueOf(gas2), mass, deltaT));
input.close();
}
public static void velocityToHeight() {
Scanner input = new Scanner(System.in);
double velocity = input.nextDouble();
double velocityToHeight = velocity / 2;
System.out.println(velocityToHeight);
input.close();
}
}
| 5,810 | 0.677797 | 0.66833 | 188 | 29.904255 | 16.640804 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.175532 | false | false | 2 |
35f10bed9ef66687df6d771ee55b5f2770ad1b08 | 33,835,752,389,272 | 82227c35c6e84ac886ac5d409b75052303df2cf0 | /src/main/java/com/bluefly/gonzalo/service/ReminderService.java | 1f0a0f148957aa993d092abbaf1a8c4907c205e0 | [] | no_license | gonzalo-roberto-diaz/tps | https://github.com/gonzalo-roberto-diaz/tps | 2d635daf4d42db403c23458fb53cbd03844c8e31 | f1815916387a3181b9738bdceafb42f0434afa75 | refs/heads/master | 2016-09-06T19:25:16.700000 | 2015-07-17T15:42:20 | 2015-07-17T15:42:20 | 39,227,030 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bluefly.gonzalo.service;
import java.util.List;
import com.bluefly.gonzalo.model.Reminder;
public interface ReminderService {
Reminder findById(int id);
Reminder saveReminder(Reminder reminder);
Reminder updateReminder(Reminder reminder);
void delete(Reminder reminder);
List<Reminder> findAllReminders(long start, long size);
long count();
public void calculatePostingTime(Reminder reminder);
public void postDues();
}
| UTF-8 | Java | 489 | java | ReminderService.java | Java | [] | null | [] | package com.bluefly.gonzalo.service;
import java.util.List;
import com.bluefly.gonzalo.model.Reminder;
public interface ReminderService {
Reminder findById(int id);
Reminder saveReminder(Reminder reminder);
Reminder updateReminder(Reminder reminder);
void delete(Reminder reminder);
List<Reminder> findAllReminders(long start, long size);
long count();
public void calculatePostingTime(Reminder reminder);
public void postDues();
}
| 489 | 0.723926 | 0.723926 | 27 | 16.111111 | 19.120153 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.037037 | false | false | 2 |
19f5064c3dedc6e63ab990997f52afb439d11b7b | 33,835,752,388,775 | ca61252a46d5c843b8fb6dc845f4c9ca18524054 | /spring/jaxb-sample/src/main/java/edu/samples/jaxb/Run.java | 1ff663d4122cd97f8e4d155eda47e1e5daa8d0c5 | [] | no_license | alexflipren/spring-edu-samples | https://github.com/alexflipren/spring-edu-samples | 8a307cafcc5f0c816f2eb2df7e2ec1d52f2cd996 | 175af661c701f1802c323acdbffe6d3a985d1b3d | refs/heads/master | 2015-08-18T20:49:40.858000 | 2015-07-20T21:19:45 | 2015-07-20T21:19:45 | 28,809,879 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.samples.jaxb;
import edu.samples.jaxb.model.SingleItem;
import edu.samples.jaxb.model.XmlRoot;
import org.springframework.util.ResourceUtils;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.FileNotFoundException;
/**
* Created by alex on 29.04.15.
*/
public class Run {
public static void main(String args[]){
try {
File file = ResourceUtils.getFile("classpath:singleitem.xml");
SingleItem singleItem = parse(file, SingleItem.class);
System.out.println(singleItem);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
File file = ResourceUtils.getFile("classpath:items.xml");
XmlRoot singleItem = parse(file, XmlRoot.class);
System.out.println(singleItem);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static <T> T parse(File file, Class<T> clazz) {
JAXBContext context = null;
try {
context = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = context.createUnmarshaller();
return clazz.cast(unmarshaller.unmarshal(file));
} catch (JAXBException e) {
e.printStackTrace();
}
return null;
}
}
| UTF-8 | Java | 1,403 | java | Run.java | Java | [
{
"context": " java.io.FileNotFoundException;\n\n/**\n * Created by alex on 29.04.15.\n */\npublic class Run {\n\n public s",
"end": 346,
"score": 0.9990994930267334,
"start": 342,
"tag": "USERNAME",
"value": "alex"
}
] | null | [] | package edu.samples.jaxb;
import edu.samples.jaxb.model.SingleItem;
import edu.samples.jaxb.model.XmlRoot;
import org.springframework.util.ResourceUtils;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.FileNotFoundException;
/**
* Created by alex on 29.04.15.
*/
public class Run {
public static void main(String args[]){
try {
File file = ResourceUtils.getFile("classpath:singleitem.xml");
SingleItem singleItem = parse(file, SingleItem.class);
System.out.println(singleItem);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
File file = ResourceUtils.getFile("classpath:items.xml");
XmlRoot singleItem = parse(file, XmlRoot.class);
System.out.println(singleItem);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static <T> T parse(File file, Class<T> clazz) {
JAXBContext context = null;
try {
context = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = context.createUnmarshaller();
return clazz.cast(unmarshaller.unmarshal(file));
} catch (JAXBException e) {
e.printStackTrace();
}
return null;
}
}
| 1,403 | 0.631504 | 0.627227 | 48 | 28.229166 | 21.973696 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.541667 | false | false | 2 |
e12d3c78d829dcce1418a4bc1bb410a4c51f449c | 35,442,070,160,843 | 55b26f07a95ca2d8f7bb0aa4867131898e69db6b | /src/test/java/com/com/bunjlabs/largo/compiler/RuntimeTest.java | 9b119c1f01089f1cd1a32567a985dfca140097eb | [
"Apache-2.0"
] | permissive | bunjlabs/largo | https://github.com/bunjlabs/largo | 0e8a5021ae85eb2135160417a6415556f1b82dbd | 74930eeedcadae1a605f3a08b1457c7abdbb135c | refs/heads/master | 2020-05-25T03:00:19.994000 | 2019-11-09T04:09:00 | 2019-11-09T04:09:00 | 187,591,006 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.com.bunjlabs.largo.compiler;
import com.bunjlabs.largo.*;
import com.bunjlabs.largo.LargoMathModule;
import com.bunjlabs.largo.types.LargoFunction;
import com.bunjlabs.largo.types.LargoString;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class RuntimeTest {
String run(String source) throws Exception {
LargoRuntime runtime = LargoRuntime.createDefaultRuntime();
LargoModule testModule = new LargoModule();
final String[] result = new String[1];
testModule.export(LargoString.from("r"), LargoFunction.fromBiConsumer((ctx, value) -> result[0] = value.asJString()));
runtime.getEnvironment().addModule("t", testModule);
runtime.getEnvironment().addModule("math", new LargoMathModule());
runtime.load("test","import t;import math;let r=t.r;let m=math;" + source);
return result[0];
}
@Test
void basicCases() throws Exception {
assertEquals("null", run("r(null);"));
assertEquals("undefined", run("r(undefined);"));
assertEquals("true", run("r(true);"));
assertEquals("false", run("r(false);"));
assertEquals("3", run("r(3);"));
assertEquals("3.5", run("r(3.5);"));
assertEquals("asd", run("r('asd');"));
assertEquals("false", run("r(true == false);"));
assertEquals("true", run("r(true == true);"));
assertEquals("true", run("r(false == false);"));
}
@Test
void compareCases() throws Exception {
assertEquals("true", run("r('asd' == 'asd');"));
assertEquals("false", run("r('asd' == 3);"));
assertEquals("false", run("r('asd' == 3.3);"));
assertEquals("false", run("r('asd' == false);"));
assertEquals("false", run("r('asd' == true);"));
assertEquals("false", run("r('asd' == null);"));
assertEquals("false", run("r('asd' == undefined);"));
assertEquals("false", run("r('asd' == r);"));
assertEquals("false", run("r(3 == 'asd');"));
assertEquals("true", run("r(3 == 3);"));
assertEquals("false", run("r(3 == 3.3);"));
assertEquals("false", run("r(3 == false);"));
assertEquals("false", run("r(3 == true);"));
assertEquals("false", run("r(0 == false);"));
assertEquals("false", run("r(1 == true);"));
assertEquals("false", run("r(3 == null);"));
assertEquals("false", run("r(3 == undefined);"));
assertEquals("false", run("r(3 == r);"));
assertEquals("false", run("r(3.3 == 'asd');"));
assertEquals("false", run("r(3.3 == 3);"));
assertEquals("true", run("r(3.3 == 3.3);"));
assertEquals("false", run("r(3.3 == false);"));
assertEquals("false", run("r(3.3 == true);"));
assertEquals("false", run("r(0.3 == false);"));
assertEquals("false", run("r(1.3 == true);"));
assertEquals("false", run("r(3.3 == null);"));
assertEquals("false", run("r(3.3 == undefined);"));
assertEquals("false", run("r(3.3 == r);"));
assertEquals("false", run("r(false == 'asd');"));
assertEquals("false", run("r(false == 3);"));
assertEquals("false", run("r(false == 3.3);"));
assertEquals("false", run("r(false == true);"));
assertEquals("true", run("r(false == false);"));
assertEquals("false", run("r(false == true);"));
assertEquals("false", run("r(false == null);"));
assertEquals("false", run("r(false == undefined);"));
assertEquals("false", run("r(false == r);"));
assertEquals("false", run("r(true == 'asd');"));
assertEquals("false", run("r(true == 3);"));
assertEquals("false", run("r(true == 3.3);"));
assertEquals("false", run("r(true == false);"));
assertEquals("true", run("r(true == true);"));
assertEquals("false", run("r(true == null);"));
assertEquals("false", run("r(true == undefined);"));
assertEquals("false", run("r(true == r);"));
assertEquals("false", run("r(null == 'asd');"));
assertEquals("false", run("r(null == 3);"));
assertEquals("false", run("r(null == 3.3);"));
assertEquals("false", run("r(null == false);"));
assertEquals("false", run("r(null == true);"));
assertEquals("true", run("r(null == null);"));
assertEquals("false", run("r(null == undefined);"));
assertEquals("false", run("r(null == r);"));
assertEquals("false", run("r(undefined == 'asd');"));
assertEquals("false", run("r(undefined == 3);"));
assertEquals("false", run("r(undefined == 3.3);"));
assertEquals("false", run("r(undefined == false);"));
assertEquals("false", run("r(undefined == true);"));
assertEquals("false", run("r(undefined == null);"));
assertEquals("true", run("r(undefined == undefined);"));
assertEquals("false", run("r(undefined == r);"));
assertEquals("true", run("r(10 == 10);"));
assertEquals("false", run("r(10 < 10);"));
assertEquals("false", run("r(10 > 10);"));
assertEquals("false", run("r(11 <= 10);"));
assertEquals("false", run("r(10 >= 11);"));
assertEquals("true", run("r(10 < 11);"));
assertEquals("true", run("r(11 > 10);"));
assertEquals("true", run("r(10 <= 10);"));
assertEquals("true", run("r(10 >= 10);"));
}
@Test
void objectCases() throws Exception {
assertEquals("[[function]]", run("r(m.sqrt);"));
assertEquals("undefined", run("r(m.asd);"));
assertEquals("undefined", run("r(m.asd.sqrt);"));
assertEquals("undefined", run("r(m.asd.asd);"));
assertEquals("undefined", run("r('asd'.asd);"));
assertEquals("[[function]]", run("r('asd'.trim);"));
assertEquals("true", run("r('asd'.asd == undefined);"));
}
@Test
void functionCases() throws Exception {
assertEquals("asd", run("r('asd'.trim());"));
assertEquals("undefined", run("r('asd'.trim()());"));
}
}
| UTF-8 | Java | 6,230 | java | RuntimeTest.java | Java | [] | null | [] | package com.com.bunjlabs.largo.compiler;
import com.bunjlabs.largo.*;
import com.bunjlabs.largo.LargoMathModule;
import com.bunjlabs.largo.types.LargoFunction;
import com.bunjlabs.largo.types.LargoString;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class RuntimeTest {
String run(String source) throws Exception {
LargoRuntime runtime = LargoRuntime.createDefaultRuntime();
LargoModule testModule = new LargoModule();
final String[] result = new String[1];
testModule.export(LargoString.from("r"), LargoFunction.fromBiConsumer((ctx, value) -> result[0] = value.asJString()));
runtime.getEnvironment().addModule("t", testModule);
runtime.getEnvironment().addModule("math", new LargoMathModule());
runtime.load("test","import t;import math;let r=t.r;let m=math;" + source);
return result[0];
}
@Test
void basicCases() throws Exception {
assertEquals("null", run("r(null);"));
assertEquals("undefined", run("r(undefined);"));
assertEquals("true", run("r(true);"));
assertEquals("false", run("r(false);"));
assertEquals("3", run("r(3);"));
assertEquals("3.5", run("r(3.5);"));
assertEquals("asd", run("r('asd');"));
assertEquals("false", run("r(true == false);"));
assertEquals("true", run("r(true == true);"));
assertEquals("true", run("r(false == false);"));
}
@Test
void compareCases() throws Exception {
assertEquals("true", run("r('asd' == 'asd');"));
assertEquals("false", run("r('asd' == 3);"));
assertEquals("false", run("r('asd' == 3.3);"));
assertEquals("false", run("r('asd' == false);"));
assertEquals("false", run("r('asd' == true);"));
assertEquals("false", run("r('asd' == null);"));
assertEquals("false", run("r('asd' == undefined);"));
assertEquals("false", run("r('asd' == r);"));
assertEquals("false", run("r(3 == 'asd');"));
assertEquals("true", run("r(3 == 3);"));
assertEquals("false", run("r(3 == 3.3);"));
assertEquals("false", run("r(3 == false);"));
assertEquals("false", run("r(3 == true);"));
assertEquals("false", run("r(0 == false);"));
assertEquals("false", run("r(1 == true);"));
assertEquals("false", run("r(3 == null);"));
assertEquals("false", run("r(3 == undefined);"));
assertEquals("false", run("r(3 == r);"));
assertEquals("false", run("r(3.3 == 'asd');"));
assertEquals("false", run("r(3.3 == 3);"));
assertEquals("true", run("r(3.3 == 3.3);"));
assertEquals("false", run("r(3.3 == false);"));
assertEquals("false", run("r(3.3 == true);"));
assertEquals("false", run("r(0.3 == false);"));
assertEquals("false", run("r(1.3 == true);"));
assertEquals("false", run("r(3.3 == null);"));
assertEquals("false", run("r(3.3 == undefined);"));
assertEquals("false", run("r(3.3 == r);"));
assertEquals("false", run("r(false == 'asd');"));
assertEquals("false", run("r(false == 3);"));
assertEquals("false", run("r(false == 3.3);"));
assertEquals("false", run("r(false == true);"));
assertEquals("true", run("r(false == false);"));
assertEquals("false", run("r(false == true);"));
assertEquals("false", run("r(false == null);"));
assertEquals("false", run("r(false == undefined);"));
assertEquals("false", run("r(false == r);"));
assertEquals("false", run("r(true == 'asd');"));
assertEquals("false", run("r(true == 3);"));
assertEquals("false", run("r(true == 3.3);"));
assertEquals("false", run("r(true == false);"));
assertEquals("true", run("r(true == true);"));
assertEquals("false", run("r(true == null);"));
assertEquals("false", run("r(true == undefined);"));
assertEquals("false", run("r(true == r);"));
assertEquals("false", run("r(null == 'asd');"));
assertEquals("false", run("r(null == 3);"));
assertEquals("false", run("r(null == 3.3);"));
assertEquals("false", run("r(null == false);"));
assertEquals("false", run("r(null == true);"));
assertEquals("true", run("r(null == null);"));
assertEquals("false", run("r(null == undefined);"));
assertEquals("false", run("r(null == r);"));
assertEquals("false", run("r(undefined == 'asd');"));
assertEquals("false", run("r(undefined == 3);"));
assertEquals("false", run("r(undefined == 3.3);"));
assertEquals("false", run("r(undefined == false);"));
assertEquals("false", run("r(undefined == true);"));
assertEquals("false", run("r(undefined == null);"));
assertEquals("true", run("r(undefined == undefined);"));
assertEquals("false", run("r(undefined == r);"));
assertEquals("true", run("r(10 == 10);"));
assertEquals("false", run("r(10 < 10);"));
assertEquals("false", run("r(10 > 10);"));
assertEquals("false", run("r(11 <= 10);"));
assertEquals("false", run("r(10 >= 11);"));
assertEquals("true", run("r(10 < 11);"));
assertEquals("true", run("r(11 > 10);"));
assertEquals("true", run("r(10 <= 10);"));
assertEquals("true", run("r(10 >= 10);"));
}
@Test
void objectCases() throws Exception {
assertEquals("[[function]]", run("r(m.sqrt);"));
assertEquals("undefined", run("r(m.asd);"));
assertEquals("undefined", run("r(m.asd.sqrt);"));
assertEquals("undefined", run("r(m.asd.asd);"));
assertEquals("undefined", run("r('asd'.asd);"));
assertEquals("[[function]]", run("r('asd'.trim);"));
assertEquals("true", run("r('asd'.asd == undefined);"));
}
@Test
void functionCases() throws Exception {
assertEquals("asd", run("r('asd'.trim());"));
assertEquals("undefined", run("r('asd'.trim()());"));
}
}
| 6,230 | 0.527769 | 0.51236 | 142 | 41.873238 | 23.584986 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.049296 | false | false | 2 |
182289b2b8e0557c2820ae0036aae434360af5a9 | 35,356,170,807,790 | 9807fd9d035fc911eb57510edf85cc5027c0d0cb | /yahoo_weather/src/main/java/ru/bellintegrator/yahoo_weather/jms/JMSSender.java | 94403df2d2fb53890797b10c128cbfae2bfcbc64 | [] | no_license | AlinaZ/weatherbroker | https://github.com/AlinaZ/weatherbroker | 73ab91d30d8fca1003fa671b34600c920abb06d0 | 959f1fd5ae6a5af38cd352f77c027c296adbfb40 | refs/heads/master | 2022-12-10T18:56:27.407000 | 2020-09-03T11:07:29 | 2020-09-03T11:07:29 | 292,542,666 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.bellintegrator.yahoo_weather.jms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.bellintegrator.weatherparser.Result;
import javax.annotation.Resource;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.jms.JMSContext;
import javax.jms.Queue;
@ApplicationScoped
public class JMSSender {
private final Logger log = LoggerFactory.getLogger(JMSSender.class);
@Resource(mappedName = "java:jboss/exported/jms/queue/weather")
private Queue queue;
@Inject
private JMSContext context;
/**
* Отправить сообщение в очередь для модуля db_service
*
* @param weather для города
*/
public void send(Result weather) {
log.info("@@@@@@@@@@@@@@@@@@@@@");
context.createProducer().send(queue, weather);
log.info("Weather message has been sent");
}
} | UTF-8 | Java | 929 | java | JMSSender.java | Java | [] | null | [] | package ru.bellintegrator.yahoo_weather.jms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.bellintegrator.weatherparser.Result;
import javax.annotation.Resource;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.jms.JMSContext;
import javax.jms.Queue;
@ApplicationScoped
public class JMSSender {
private final Logger log = LoggerFactory.getLogger(JMSSender.class);
@Resource(mappedName = "java:jboss/exported/jms/queue/weather")
private Queue queue;
@Inject
private JMSContext context;
/**
* Отправить сообщение в очередь для модуля db_service
*
* @param weather для города
*/
public void send(Result weather) {
log.info("@@@@@@@@@@@@@@@@@@@@@");
context.createProducer().send(queue, weather);
log.info("Weather message has been sent");
}
} | 929 | 0.706215 | 0.703955 | 33 | 25.848484 | 21.015322 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.484848 | false | false | 2 |
79d975ba18fefd832b44e585d23bbc33ebb507cd | 13,769,665,190,916 | 75f66b952bd655139c5a096467626f464a8b487b | /Assignment3/src/main/java/edu/uw/ajs/broker/SimpleBrokerFactory.java | 4496b336e6d2290c2869fab91c10e4b07280e7f9 | [] | no_license | schr1554/Assignment3 | https://github.com/schr1554/Assignment3 | b2cfa9b7385e1a538b501fe0f3121f1ca1d9a92c | 197acf36a884f4d931ac9500181239ee5822e68b | refs/heads/master | 2020-03-11T12:31:04.155000 | 2018-04-18T03:38:58 | 2018-04-18T03:38:58 | 129,999,640 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package main.java.edu.uw.ajs.broker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.uw.ext.framework.account.AccountManager;
import edu.uw.ext.framework.broker.Broker;
import edu.uw.ext.framework.broker.BrokerFactory;
import edu.uw.ext.framework.exchange.StockExchange;
import main.java.edu.uw.ajs.account.SimpleAccount;
public class SimpleBrokerFactory implements BrokerFactory {
/** The logger to be used by this class */
private static final Logger logger = LoggerFactory.getLogger(SimpleAccount.class);
@Override
public Broker newBroker(String name, AccountManager acctMngr, StockExchange exch) {
logger.info("Name: " + name + " Account Manager: " + " Stock Exchange: " + exch);
return new SimpleBroker(name, acctMngr, exch);
}
}
| UTF-8 | Java | 799 | java | SimpleBrokerFactory.java | Java | [] | null | [] | package main.java.edu.uw.ajs.broker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.uw.ext.framework.account.AccountManager;
import edu.uw.ext.framework.broker.Broker;
import edu.uw.ext.framework.broker.BrokerFactory;
import edu.uw.ext.framework.exchange.StockExchange;
import main.java.edu.uw.ajs.account.SimpleAccount;
public class SimpleBrokerFactory implements BrokerFactory {
/** The logger to be used by this class */
private static final Logger logger = LoggerFactory.getLogger(SimpleAccount.class);
@Override
public Broker newBroker(String name, AccountManager acctMngr, StockExchange exch) {
logger.info("Name: " + name + " Account Manager: " + " Stock Exchange: " + exch);
return new SimpleBroker(name, acctMngr, exch);
}
}
| 799 | 0.748436 | 0.745932 | 26 | 28.73077 | 28.963581 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.923077 | false | false | 2 |
dba06f7a14d40829553b2acab19ce2f02cc9678b | 39,298,950,775,691 | c35ed9c77a9aee6ce400777279be49f78fedabe2 | /homework-csv/src/main/java/homework_csv/homework_csv/App.java | 98239f08b494de2095dcab4c8f3f7f61497c6a9f | [] | no_license | Petretooo/hadoop | https://github.com/Petretooo/hadoop | df0da75d0c1c7f0e8adbf00129bc3cbe3d28897b | 1936e7ccadee0f95858260866bd6aee5cafac8a5 | refs/heads/main | 2023-08-28T10:29:30.871000 | 2021-10-26T21:23:59 | 2021-10-26T21:23:59 | 421,587,808 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package homework_csv.homework_csv;
import java.io.IOException;
import homework_csv.homework_csv.firstTask.ConfigurationFirstTask;
import homework_csv.homework_csv.secondTask.ConfigurationSecondTask;
import homework_csv.homework_csv.thirdTask.ConfigurationThirdTask;
public class App
{
public static void main( String[] args ) throws IOException
{
ConfigurationThirdTask thirdTask = new ConfigurationThirdTask();
thirdTask.runThirdTask();
ConfigurationSecondTask secondTask = new ConfigurationSecondTask();
secondTask.runSecondTask();
ConfigurationFirstTask firstTask = new ConfigurationFirstTask();
firstTask.runFirstTask();
}
}
| UTF-8 | Java | 674 | java | App.java | Java | [] | null | [] | package homework_csv.homework_csv;
import java.io.IOException;
import homework_csv.homework_csv.firstTask.ConfigurationFirstTask;
import homework_csv.homework_csv.secondTask.ConfigurationSecondTask;
import homework_csv.homework_csv.thirdTask.ConfigurationThirdTask;
public class App
{
public static void main( String[] args ) throws IOException
{
ConfigurationThirdTask thirdTask = new ConfigurationThirdTask();
thirdTask.runThirdTask();
ConfigurationSecondTask secondTask = new ConfigurationSecondTask();
secondTask.runSecondTask();
ConfigurationFirstTask firstTask = new ConfigurationFirstTask();
firstTask.runFirstTask();
}
}
| 674 | 0.783383 | 0.783383 | 19 | 34.473682 | 27.606956 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.894737 | false | false | 2 |
a37918a636c47efceff853a5fea245bd1e41a108 | 38,878,043,998,077 | dd3c5142a092e6b59076c70c81209241e750581a | /src/main/java/com/lut/springsecurity/config/AntPath.java | bc8eba80c41097377d496aef0bb1fa97db07b652 | [] | no_license | wjzxc123/spring-security | https://github.com/wjzxc123/spring-security | 65b5a16ec87af778ea8ee88afe8c2494334df463 | 0b767ca97a67fcbf304da0f2f22d448352461cc8 | refs/heads/main | 2023-04-23T09:30:49.015000 | 2021-04-30T08:53:26 | 2021-04-30T08:53:26 | 353,654,664 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lut.springsecurity.config;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
/**
* Describe:
*
* @author Licon
* @date 2021/4/1 11:26
*/
@Getter
@Setter
@AllArgsConstructor
public class AntPath {
String path;
String method;
}
| UTF-8 | Java | 277 | java | AntPath.java | Java | [
{
"context": "rt lombok.Setter;\n\n\n/**\n * Describe:\n *\n * @author Licon\n * @date 2021/4/1 11:26\n */\n@Getter\n@Setter\n@AllA",
"end": 156,
"score": 0.9959021806716919,
"start": 151,
"tag": "NAME",
"value": "Licon"
}
] | null | [] | package com.lut.springsecurity.config;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
/**
* Describe:
*
* @author Licon
* @date 2021/4/1 11:26
*/
@Getter
@Setter
@AllArgsConstructor
public class AntPath {
String path;
String method;
}
| 277 | 0.729242 | 0.693141 | 21 | 12.190476 | 11.091047 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.380952 | false | false | 2 |
48ab72f3938382d26e0657c7881c16715cdf80f8 | 31,198,642,498,490 | b5e4c01a2ac61529a0a6a62bb487592f6394423f | /core/src/com/goatgames/GoatEngine/Input/Events/touch/PanEvent.java | 7018bbd7a33df4ef9184771ddc2661ac2a820699 | [] | no_license | jwillp/GoatEngine | https://github.com/jwillp/GoatEngine | 66ec619d62dcdede33238f383359edbbbebbce02 | c14dbf5c45ca262dcb4388d838d978f70234f692 | refs/heads/master | 2021-01-16T18:33:46.382000 | 2017-08-14T20:47:52 | 2017-08-14T20:47:52 | 100,092,965 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.goatgames.goatengine.input.events.touch;
/**
* Called when the user drags a finger over the screen.
*/
public class PanEvent extends TouchEvent {
public final float x;
public final float y;
public final float deltaX;
public final float deltaY;
public PanEvent(float x, float y, float deltaX, float deltaY) {
this.x = x;
this.y = y;
this.deltaX = deltaX;
this.deltaY = deltaY;
}
}
| UTF-8 | Java | 453 | java | PanEvent.java | Java | [] | null | [] | package com.goatgames.goatengine.input.events.touch;
/**
* Called when the user drags a finger over the screen.
*/
public class PanEvent extends TouchEvent {
public final float x;
public final float y;
public final float deltaX;
public final float deltaY;
public PanEvent(float x, float y, float deltaX, float deltaY) {
this.x = x;
this.y = y;
this.deltaX = deltaX;
this.deltaY = deltaY;
}
}
| 453 | 0.646799 | 0.646799 | 19 | 22.842106 | 19.955908 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631579 | false | false | 2 |
072906761ce2d00b005ba0e68288ae3726337e6f | 31,198,642,497,280 | f82d3b0f20fcca410ee52505534c7b500f6a5735 | /SpaceApp-master/src/main/java/com/spaceApplication/server/service/MainAppServiceImpl.java | 93244aae697b2d63a86d7acd949de48ad64072a5 | [] | no_license | ChrisGak/DissertationWork | https://github.com/ChrisGak/DissertationWork | ff2f600a22e061dbc551ac29663ac879121f06e7 | 8d4cd317bdb023b8798b66da09875a149672d4f5 | refs/heads/master | 2021-04-28T10:28:39.816000 | 2018-05-15T09:45:02 | 2018-05-15T09:45:02 | 121,520,396 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.spaceApplication.server.service;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.spaceApplication.client.exception.TetherSystemModelValueException;
import com.spaceApplication.client.space.controllers.SpaceApplicationService;
import com.spaceApplication.client.space.model.ElectrodynamicTetherSystemModelClient;
import com.spaceApplication.client.space.model.OrbitalElementsClient;
import com.spaceApplication.client.space.ui.components.UIConsts;
import com.spaceApplication.server.export.ExcelWritter;
import com.spaceApplication.server.modeling.differentiation.OrbitalElements;
import com.spaceApplication.server.modeling.differentiation.RungeKuttaMethodImpl;
import com.spaceApplication.server.modeling.model.BareElectrodynamicTether;
import com.spaceApplication.server.modeling.model.ElectrodynamicTetherSystemModel;
import jxl.write.WriteException;
import java.io.IOException;
public class MainAppServiceImpl extends RemoteServiceServlet implements SpaceApplicationService {
private ExcelWritter test = new ExcelWritter();
public String getMessage(String msg) {
return "Client said: \"" + msg + "\"<br>Server answered: \"Hi!\"";
}
public OrbitalElementsClient getTestModelIntegrationResult() throws TetherSystemModelValueException {
BareElectrodynamicTether tether = new BareElectrodynamicTether(0.4, 2000, 0.001, 0, 0.1);
ElectrodynamicTetherSystemModel testModel = new ElectrodynamicTetherSystemModel(tether, 6, 2, 500000, 0, 0.0167);
OrbitalElements serverResult = RungeKuttaMethodImpl.integrateWithVariableStep(testModel, 100, 10, 10, 0.001);
/**
* (Vector time, Vector tetta, Vector omega, Vector eps, Vector A, Vector ex, Vector step, Vector accuracy, Vector iter){
*/
OrbitalElementsClient clientResult = new OrbitalElementsClient(
serverResult.getTime(),
serverResult.getTetherVerticalDeflectionAngleDegrees(),
serverResult.getTetherVerticalDeflectionAngleDiff(),
serverResult.getTrueAnomalyDegrees(),
serverResult.getSemimajorAxis(),
serverResult.getEccentricity(),
serverResult.getStep(),
serverResult.getAccuracy(),
serverResult.getIteration());
return clientResult;
}
public OrbitalElementsClient getCalculationResult(ElectrodynamicTetherSystemModelClient clientModel) throws TetherSystemModelValueException {
BareElectrodynamicTether tether = new BareElectrodynamicTether(clientModel.getTether().getMass(), clientModel.getTether().getLength(),
clientModel.getTether().getDiameter(), clientModel.getTether().getDeflectionAngleDegrees(), clientModel.getTether().getElectricity());
ElectrodynamicTetherSystemModel systemModel = new ElectrodynamicTetherSystemModel(tether, clientModel.getMainSatelliteMass(),
clientModel.getNanoSatelliteMass(),
clientModel.getInitialHeight(), clientModel.getInitialTrueAnomalyRadians(),
clientModel.getInitialEccentricity());
// BareElectrodynamicTether tether = new BareElectrodynamicTether(0.4, 2000, 0.001, 0, 0.01);
// ElectrodynamicTetherSystemModel systemModel = new ElectrodynamicTetherSystemModel(tether,
// 6, 2, 500000, 0, 0.00001);
// int hours = 30;
// int seconds = hours * 60 * 60;
// seconds = 3600;
// OrbitalElements serverResult = RungeKuttaMethodImpl.integrateWithVariableStep(systemModel,
// seconds, 5, 10, 0.01);
OrbitalElements serverResult = RungeKuttaMethodImpl.integrateWithVariableStep(systemModel, clientModel.getMaxIterations(), clientModel.getIntegrationStep(),
clientModel.getIntegrationMaxStep(), clientModel.getCalculateAccuracy());
/**
* (Vector time, Vector tetta, Vector omega, Vector eps, Vector A, Vector ex, Vector step, Vector accuracy, Vector iter){
*/
OrbitalElementsClient clientResult = new OrbitalElementsClient(
serverResult.getTime(),
serverResult.getTetherVerticalDeflectionAngleDegrees(),
serverResult.getTetherVerticalDeflectionAngleDiff(),
serverResult.getTrueAnomalyDegrees(),
serverResult.getSemimajorAxis(),
serverResult.getEccentricity(),
serverResult.getStep(),
serverResult.getAccuracy(),
serverResult.getIteration());
clientResult.setForceValue(systemModel.getFullForce(serverResult.getLastSemimajor(), serverResult.getLastEccentricity(), serverResult.getLastTrueAnomaly()));
clientResult.setMomentValue(systemModel.getFullMoment(serverResult.getLastSemimajor(), serverResult.getLastEccentricity(), serverResult.getLastTrueAnomaly()));
clientResult.setTransversalAccelertionValue(systemModel.getTransversalAcceleration(serverResult.getLastSemimajor(),
serverResult.getLastEccentricity(), serverResult.getLastTrueAnomaly(), serverResult.getLastTetherVerticalDeflectionAngle()));
clientResult.setRadialAccelerationValue(systemModel.getRadialAcceleration(serverResult.getLastSemimajor(), serverResult.getLastEccentricity(),
serverResult.getLastTrueAnomaly(), serverResult.getLastTetherVerticalDeflectionAngle()));
return clientResult;
}
private void printIntegrResultToFile(OrbitalElements result) {
test.createFileIfNotExists(UIConsts.REPORT_RESULT_HREF);
try {
test.writeRungeKuttaResult(result);
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
} | UTF-8 | Java | 5,840 | java | MainAppServiceImpl.java | Java | [] | null | [] | package com.spaceApplication.server.service;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.spaceApplication.client.exception.TetherSystemModelValueException;
import com.spaceApplication.client.space.controllers.SpaceApplicationService;
import com.spaceApplication.client.space.model.ElectrodynamicTetherSystemModelClient;
import com.spaceApplication.client.space.model.OrbitalElementsClient;
import com.spaceApplication.client.space.ui.components.UIConsts;
import com.spaceApplication.server.export.ExcelWritter;
import com.spaceApplication.server.modeling.differentiation.OrbitalElements;
import com.spaceApplication.server.modeling.differentiation.RungeKuttaMethodImpl;
import com.spaceApplication.server.modeling.model.BareElectrodynamicTether;
import com.spaceApplication.server.modeling.model.ElectrodynamicTetherSystemModel;
import jxl.write.WriteException;
import java.io.IOException;
public class MainAppServiceImpl extends RemoteServiceServlet implements SpaceApplicationService {
private ExcelWritter test = new ExcelWritter();
public String getMessage(String msg) {
return "Client said: \"" + msg + "\"<br>Server answered: \"Hi!\"";
}
public OrbitalElementsClient getTestModelIntegrationResult() throws TetherSystemModelValueException {
BareElectrodynamicTether tether = new BareElectrodynamicTether(0.4, 2000, 0.001, 0, 0.1);
ElectrodynamicTetherSystemModel testModel = new ElectrodynamicTetherSystemModel(tether, 6, 2, 500000, 0, 0.0167);
OrbitalElements serverResult = RungeKuttaMethodImpl.integrateWithVariableStep(testModel, 100, 10, 10, 0.001);
/**
* (Vector time, Vector tetta, Vector omega, Vector eps, Vector A, Vector ex, Vector step, Vector accuracy, Vector iter){
*/
OrbitalElementsClient clientResult = new OrbitalElementsClient(
serverResult.getTime(),
serverResult.getTetherVerticalDeflectionAngleDegrees(),
serverResult.getTetherVerticalDeflectionAngleDiff(),
serverResult.getTrueAnomalyDegrees(),
serverResult.getSemimajorAxis(),
serverResult.getEccentricity(),
serverResult.getStep(),
serverResult.getAccuracy(),
serverResult.getIteration());
return clientResult;
}
public OrbitalElementsClient getCalculationResult(ElectrodynamicTetherSystemModelClient clientModel) throws TetherSystemModelValueException {
BareElectrodynamicTether tether = new BareElectrodynamicTether(clientModel.getTether().getMass(), clientModel.getTether().getLength(),
clientModel.getTether().getDiameter(), clientModel.getTether().getDeflectionAngleDegrees(), clientModel.getTether().getElectricity());
ElectrodynamicTetherSystemModel systemModel = new ElectrodynamicTetherSystemModel(tether, clientModel.getMainSatelliteMass(),
clientModel.getNanoSatelliteMass(),
clientModel.getInitialHeight(), clientModel.getInitialTrueAnomalyRadians(),
clientModel.getInitialEccentricity());
// BareElectrodynamicTether tether = new BareElectrodynamicTether(0.4, 2000, 0.001, 0, 0.01);
// ElectrodynamicTetherSystemModel systemModel = new ElectrodynamicTetherSystemModel(tether,
// 6, 2, 500000, 0, 0.00001);
// int hours = 30;
// int seconds = hours * 60 * 60;
// seconds = 3600;
// OrbitalElements serverResult = RungeKuttaMethodImpl.integrateWithVariableStep(systemModel,
// seconds, 5, 10, 0.01);
OrbitalElements serverResult = RungeKuttaMethodImpl.integrateWithVariableStep(systemModel, clientModel.getMaxIterations(), clientModel.getIntegrationStep(),
clientModel.getIntegrationMaxStep(), clientModel.getCalculateAccuracy());
/**
* (Vector time, Vector tetta, Vector omega, Vector eps, Vector A, Vector ex, Vector step, Vector accuracy, Vector iter){
*/
OrbitalElementsClient clientResult = new OrbitalElementsClient(
serverResult.getTime(),
serverResult.getTetherVerticalDeflectionAngleDegrees(),
serverResult.getTetherVerticalDeflectionAngleDiff(),
serverResult.getTrueAnomalyDegrees(),
serverResult.getSemimajorAxis(),
serverResult.getEccentricity(),
serverResult.getStep(),
serverResult.getAccuracy(),
serverResult.getIteration());
clientResult.setForceValue(systemModel.getFullForce(serverResult.getLastSemimajor(), serverResult.getLastEccentricity(), serverResult.getLastTrueAnomaly()));
clientResult.setMomentValue(systemModel.getFullMoment(serverResult.getLastSemimajor(), serverResult.getLastEccentricity(), serverResult.getLastTrueAnomaly()));
clientResult.setTransversalAccelertionValue(systemModel.getTransversalAcceleration(serverResult.getLastSemimajor(),
serverResult.getLastEccentricity(), serverResult.getLastTrueAnomaly(), serverResult.getLastTetherVerticalDeflectionAngle()));
clientResult.setRadialAccelerationValue(systemModel.getRadialAcceleration(serverResult.getLastSemimajor(), serverResult.getLastEccentricity(),
serverResult.getLastTrueAnomaly(), serverResult.getLastTetherVerticalDeflectionAngle()));
return clientResult;
}
private void printIntegrResultToFile(OrbitalElements result) {
test.createFileIfNotExists(UIConsts.REPORT_RESULT_HREF);
try {
test.writeRungeKuttaResult(result);
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
} | 5,840 | 0.726199 | 0.711986 | 100 | 57.41 | 45.620628 | 167 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.21 | false | false | 2 |
72b7ac6486f22178e5acc4d27be5e19025e824ac | 36,764,920,082,964 | 590cebae4483121569983808da1f91563254efed | /Router/schemas-src/eps-fts-schemas/src/main/java/ru/acs/fts/schemas/album/declarationconformity/GoodsType.java | 6655e502402f74e03d548907818ff80a6a8108bb | [] | no_license | ke-kontur/eps | https://github.com/ke-kontur/eps | 8b00f9c7a5f92edeaac2f04146bf0676a3a78e27 | 7f0580cd82022d36d99fb846c4025e5950b0c103 | refs/heads/master | 2020-05-16T23:53:03.163000 | 2014-11-26T07:00:34 | 2014-11-26T07:01:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ru.acs.fts.schemas.album.declarationconformity;
import java.util.ArrayList;
import java.util.List;
import ru.acs.fts.schemas.album.commonaggregatetypescust.DocumentBaseType;
/**
* Сведения о продукции
*/
public class GoodsType extends AppendsType
{
private String productCode;
private String goodsTNVEDCode;
private List<String> goodsDescriptionList = new ArrayList<String>();
private String seriesSign;
private String normDocs;
private List<ManufacturerType> manufacturerList = new ArrayList<ManufacturerType>();
private List<GoodsInformationType> goodsInformationList = new ArrayList<GoodsInformationType>();
private TypeDeclarationType typeDeclaration;
private DocumentBaseType contract;
/**
* Get the 'ProductCode' element value. Код продукции по ОК005 - Общероссийскому классификатору продукции
*
* @return value
*/
public String getProductCode() {
return productCode;
}
/**
* Set the 'ProductCode' element value. Код продукции по ОК005 - Общероссийскому классификатору продукции
*
* @param productCode
*/
public void setProductCode(String productCode) {
this.productCode = productCode;
}
/**
* Get the 'GoodsTNVEDCode' element value. Код товара по ТН ВЭД ТС
*
* @return value
*/
public String getGoodsTNVEDCode() {
return goodsTNVEDCode;
}
/**
* Set the 'GoodsTNVEDCode' element value. Код товара по ТН ВЭД ТС
*
* @param goodsTNVEDCode
*/
public void setGoodsTNVEDCode(String goodsTNVEDCode) {
this.goodsTNVEDCode = goodsTNVEDCode;
}
/**
* Get the list of 'GoodsDescription' element items. Описание товара текстовое (наименование, тип, вид, марка продукции, обозначение стандарта, технических условий или иного документа, по которому она выпускается (для импортной продукции ссылка на документ необязательна. Для партии и единичного изделия приводят номер и размер партии или номер изделия, номер и дату выдачи накладной, договора (контракта), документа о качестве и т.п.)
*
* @return list
*/
public List<String> getGoodsDescriptionList() {
return goodsDescriptionList;
}
/**
* Set the list of 'GoodsDescription' element items. Описание товара текстовое (наименование, тип, вид, марка продукции, обозначение стандарта, технических условий или иного документа, по которому она выпускается (для импортной продукции ссылка на документ необязательна. Для партии и единичного изделия приводят номер и размер партии или номер изделия, номер и дату выдачи накладной, договора (контракта), документа о качестве и т.п.)
*
* @param list
*/
public void setGoodsDescriptionList(List<String> list) {
goodsDescriptionList = list;
}
/**
* Get the 'SeriesSign' element value. Признак: 1 - "единичное изделие", 2 - "партия", 3 - "серийный выпуск"
*
* @return value
*/
public String getSeriesSign() {
return seriesSign;
}
/**
* Set the 'SeriesSign' element value. Признак: 1 - "единичное изделие", 2 - "партия", 3 - "серийный выпуск"
*
* @param seriesSign
*/
public void setSeriesSign(String seriesSign) {
this.seriesSign = seriesSign;
}
/**
* Get the 'NormDocs' element value. Обозначение документов, на основании которых изготовлена продукция
*
* @return value
*/
public String getNormDocs() {
return normDocs;
}
/**
* Set the 'NormDocs' element value. Обозначение документов, на основании которых изготовлена продукция
*
* @param normDocs
*/
public void setNormDocs(String normDocs) {
this.normDocs = normDocs;
}
/**
* Get the list of 'Manufacturer' element items. Сведения о изготовителе
*
* @return list
*/
public List<ManufacturerType> getManufacturerList() {
return manufacturerList;
}
/**
* Set the list of 'Manufacturer' element items. Сведения о изготовителе
*
* @param list
*/
public void setManufacturerList(List<ManufacturerType> list) {
manufacturerList = list;
}
/**
* Get the list of 'GoodsInformation' element items. Характеристика товара
*
* @return list
*/
public List<GoodsInformationType> getGoodsInformationList() {
return goodsInformationList;
}
/**
* Set the list of 'GoodsInformation' element items. Характеристика товара
*
* @param list
*/
public void setGoodsInformationList(List<GoodsInformationType> list) {
goodsInformationList = list;
}
/**
* Get the 'TypeDeclaration' element value. Сведения о типе объекта декларирования
*
* @return value
*/
public TypeDeclarationType getTypeDeclaration() {
return typeDeclaration;
}
/**
* Set the 'TypeDeclaration' element value. Сведения о типе объекта декларирования
*
* @param typeDeclaration
*/
public void setTypeDeclaration(TypeDeclarationType typeDeclaration) {
this.typeDeclaration = typeDeclaration;
}
/**
* Get the 'Contract' element value. Сведения о контракте
*
* @return value
*/
public DocumentBaseType getContract() {
return contract;
}
/**
* Set the 'Contract' element value. Сведения о контракте
*
* @param contract
*/
public void setContract(DocumentBaseType contract) {
this.contract = contract;
}
}
| WINDOWS-1251 | Java | 6,781 | java | GoodsType.java | Java | [] | null | [] |
package ru.acs.fts.schemas.album.declarationconformity;
import java.util.ArrayList;
import java.util.List;
import ru.acs.fts.schemas.album.commonaggregatetypescust.DocumentBaseType;
/**
* Сведения о продукции
*/
public class GoodsType extends AppendsType
{
private String productCode;
private String goodsTNVEDCode;
private List<String> goodsDescriptionList = new ArrayList<String>();
private String seriesSign;
private String normDocs;
private List<ManufacturerType> manufacturerList = new ArrayList<ManufacturerType>();
private List<GoodsInformationType> goodsInformationList = new ArrayList<GoodsInformationType>();
private TypeDeclarationType typeDeclaration;
private DocumentBaseType contract;
/**
* Get the 'ProductCode' element value. Код продукции по ОК005 - Общероссийскому классификатору продукции
*
* @return value
*/
public String getProductCode() {
return productCode;
}
/**
* Set the 'ProductCode' element value. Код продукции по ОК005 - Общероссийскому классификатору продукции
*
* @param productCode
*/
public void setProductCode(String productCode) {
this.productCode = productCode;
}
/**
* Get the 'GoodsTNVEDCode' element value. Код товара по ТН ВЭД ТС
*
* @return value
*/
public String getGoodsTNVEDCode() {
return goodsTNVEDCode;
}
/**
* Set the 'GoodsTNVEDCode' element value. Код товара по ТН ВЭД ТС
*
* @param goodsTNVEDCode
*/
public void setGoodsTNVEDCode(String goodsTNVEDCode) {
this.goodsTNVEDCode = goodsTNVEDCode;
}
/**
* Get the list of 'GoodsDescription' element items. Описание товара текстовое (наименование, тип, вид, марка продукции, обозначение стандарта, технических условий или иного документа, по которому она выпускается (для импортной продукции ссылка на документ необязательна. Для партии и единичного изделия приводят номер и размер партии или номер изделия, номер и дату выдачи накладной, договора (контракта), документа о качестве и т.п.)
*
* @return list
*/
public List<String> getGoodsDescriptionList() {
return goodsDescriptionList;
}
/**
* Set the list of 'GoodsDescription' element items. Описание товара текстовое (наименование, тип, вид, марка продукции, обозначение стандарта, технических условий или иного документа, по которому она выпускается (для импортной продукции ссылка на документ необязательна. Для партии и единичного изделия приводят номер и размер партии или номер изделия, номер и дату выдачи накладной, договора (контракта), документа о качестве и т.п.)
*
* @param list
*/
public void setGoodsDescriptionList(List<String> list) {
goodsDescriptionList = list;
}
/**
* Get the 'SeriesSign' element value. Признак: 1 - "единичное изделие", 2 - "партия", 3 - "серийный выпуск"
*
* @return value
*/
public String getSeriesSign() {
return seriesSign;
}
/**
* Set the 'SeriesSign' element value. Признак: 1 - "единичное изделие", 2 - "партия", 3 - "серийный выпуск"
*
* @param seriesSign
*/
public void setSeriesSign(String seriesSign) {
this.seriesSign = seriesSign;
}
/**
* Get the 'NormDocs' element value. Обозначение документов, на основании которых изготовлена продукция
*
* @return value
*/
public String getNormDocs() {
return normDocs;
}
/**
* Set the 'NormDocs' element value. Обозначение документов, на основании которых изготовлена продукция
*
* @param normDocs
*/
public void setNormDocs(String normDocs) {
this.normDocs = normDocs;
}
/**
* Get the list of 'Manufacturer' element items. Сведения о изготовителе
*
* @return list
*/
public List<ManufacturerType> getManufacturerList() {
return manufacturerList;
}
/**
* Set the list of 'Manufacturer' element items. Сведения о изготовителе
*
* @param list
*/
public void setManufacturerList(List<ManufacturerType> list) {
manufacturerList = list;
}
/**
* Get the list of 'GoodsInformation' element items. Характеристика товара
*
* @return list
*/
public List<GoodsInformationType> getGoodsInformationList() {
return goodsInformationList;
}
/**
* Set the list of 'GoodsInformation' element items. Характеристика товара
*
* @param list
*/
public void setGoodsInformationList(List<GoodsInformationType> list) {
goodsInformationList = list;
}
/**
* Get the 'TypeDeclaration' element value. Сведения о типе объекта декларирования
*
* @return value
*/
public TypeDeclarationType getTypeDeclaration() {
return typeDeclaration;
}
/**
* Set the 'TypeDeclaration' element value. Сведения о типе объекта декларирования
*
* @param typeDeclaration
*/
public void setTypeDeclaration(TypeDeclarationType typeDeclaration) {
this.typeDeclaration = typeDeclaration;
}
/**
* Get the 'Contract' element value. Сведения о контракте
*
* @return value
*/
public DocumentBaseType getContract() {
return contract;
}
/**
* Set the 'Contract' element value. Сведения о контракте
*
* @param contract
*/
public void setContract(DocumentBaseType contract) {
this.contract = contract;
}
}
| 6,781 | 0.662261 | 0.660118 | 183 | 29.590164 | 51.227356 | 439 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.300546 | false | false | 2 |
b1e33db59ac7e71adce211415b199d0e77339183 | 13,554,916,842,517 | d9fbb439e290a23943270d2722f894a620e3ad9e | /src/main/java/com/tsoft/core/media/ImgHandler.java | 6b67fba2bd8ace8b3ef8b6f49659f8e84396f876 | [
"MIT"
] | permissive | frankan0/tsoft-core | https://github.com/frankan0/tsoft-core | 6208aa8062d24c086deac06c1b15cb0a27fcc6e8 | 11c3224c3e1995e9dbe2a430ad4f29636205bbee | refs/heads/master | 2017-04-23T10:18:53.992000 | 2016-10-27T10:51:15 | 2016-10-27T10:51:15 | 62,784,480 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tsoft.core.media;
import java.io.File;
/**
* 图像处理接口
* @author Winter Lau
* @date 2010-4-26 上午09:15:10
*/
public interface ImgHandler {
/**
* 图像自动根据比例缩小到指定的方框中
* @param src
* @param dest
* @param size
* @return
* @throws ImgException
*/
int[] shrink(File src, File dest, int size) throws ImgException ;
/**
* 图像缩放
* @param src 源文件
* @param dest 目标文件
* @param w 缩放宽度
* @param h 缩放高度
* @exception
*/
void scale(File src, File dest, int w, int h) throws ImgException ;
/**
* 将图像缩放到某个正方形框内
* @param src 源文件
* @param dest 目标文件
* @param size 正方形大小
* @exception
*/
void scale(File src, File dest, int size) throws ImgException ;
/**
* 进行图像剪裁
* @param src 源文件
* @param dest 目标文件
* @param left 剪裁部分的左上角x轴
* @param top 剪裁部分的左上角y轴
* @param width 剪裁部分的宽度
* @param height 剪裁部分的高度
* @param w 目标大小宽度
* @param h 目标大小高度
* @throws ImgException
*/
void crop(File src, File dest, int left, int top, int width, int height, int w, int h) throws ImgException ;
/**
* 图像旋转
* @param src 源文件
* @param dest 目标文件
* @param degrees 旋转度数
* @throws ImgException
*/
void rotate(File src, File dest, double degrees) throws ImgException ;
} | UTF-8 | Java | 1,692 | java | ImgHandler.java | Java | [
{
"context": "\n \nimport java.io.File;\n \n/**\n * 图像处理接口\n * @author Winter Lau\n * @date 2010-4-26 上午09:15:10\n */\npublic interfac",
"end": 90,
"score": 0.9997929334640503,
"start": 80,
"tag": "NAME",
"value": "Winter Lau"
}
] | null | [] | package com.tsoft.core.media;
import java.io.File;
/**
* 图像处理接口
* @author <NAME>
* @date 2010-4-26 上午09:15:10
*/
public interface ImgHandler {
/**
* 图像自动根据比例缩小到指定的方框中
* @param src
* @param dest
* @param size
* @return
* @throws ImgException
*/
int[] shrink(File src, File dest, int size) throws ImgException ;
/**
* 图像缩放
* @param src 源文件
* @param dest 目标文件
* @param w 缩放宽度
* @param h 缩放高度
* @exception
*/
void scale(File src, File dest, int w, int h) throws ImgException ;
/**
* 将图像缩放到某个正方形框内
* @param src 源文件
* @param dest 目标文件
* @param size 正方形大小
* @exception
*/
void scale(File src, File dest, int size) throws ImgException ;
/**
* 进行图像剪裁
* @param src 源文件
* @param dest 目标文件
* @param left 剪裁部分的左上角x轴
* @param top 剪裁部分的左上角y轴
* @param width 剪裁部分的宽度
* @param height 剪裁部分的高度
* @param w 目标大小宽度
* @param h 目标大小高度
* @throws ImgException
*/
void crop(File src, File dest, int left, int top, int width, int height, int w, int h) throws ImgException ;
/**
* 图像旋转
* @param src 源文件
* @param dest 目标文件
* @param degrees 旋转度数
* @throws ImgException
*/
void rotate(File src, File dest, double degrees) throws ImgException ;
} | 1,688 | 0.551773 | 0.542553 | 64 | 21.046875 | 19.671862 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.359375 | false | false | 2 |
c94a5d362cbee304e9d88214585a9f04d950ca7c | 29,557,964,939,065 | 2b08cc9aeaec9eca1e4c5f50d1ecd5a00c7fbde9 | /exam-project-7/src/main/java/com/project/exam/controller/LoginLogOutController.java | ec2928cc7790af715fdd633c5d751f081f018efb | [] | no_license | KCC-Project/exam-project-7 | https://github.com/KCC-Project/exam-project-7 | 15c4c2a78afea987897b8f8fe37dde110d64d80d | af5aa83c4287b4784f37ded028f05f50fc9f8514 | refs/heads/master | 2021-09-11T09:52:11.986000 | 2018-04-06T14:54:24 | 2018-04-06T14:54:24 | 112,454,143 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.project.exam.controller;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.project.exam.model.Admin;
import com.project.exam.model.Student;
import com.project.exam.services.AdminService;
import com.project.exam.services.StudentService;
@Path("/")
@SessionAttributes("userName")
public class LoginLogOutController {
@Autowired
private AdminService adminService;
@Autowired
private StudentService studentService;
@POST
@Path("/ApiLoginOut")
public Response login(@FormParam("category") String category, @FormParam("InputEmail1User") String InputEmail1User,
@FormParam("InputPassword1") String InputPassword1, @FormParam("rememberMe") String rememberMe
,@Context HttpServletRequest req) throws URISyntaxException {
int categoryIndex = 0;
if (category.equalsIgnoreCase("Admin")) {
categoryIndex = 1;
} else if (category.equalsIgnoreCase("Student")) {
categoryIndex = 3;
}
if (categoryIndex == 1) {
List<Admin> admin = adminService.getAdminList();
for (Admin admin2 : admin) {
if (admin2.getAdmin_username().equalsIgnoreCase(InputEmail1User)
&& admin2.getAdmin_password().equals(InputPassword1)) {
//for session only if remember btn is checked
HttpSession session= req.getSession(true);
session.setAttribute("adminUserName", InputEmail1User);
if (rememberMe != null) {
session.setAttribute("adminPassword", InputPassword1);
}
System.out.println("Admin login sucess");
URI targetURIForRedirection = new URI("home");
return Response.seeOther(targetURIForRedirection).build();
}
}
}
if (categoryIndex == 3) {
List<Student> student = studentService.getStudentList();
for (Student student1 : student) {
if (student1.getUsername().equalsIgnoreCase(InputEmail1User)
&& student1.getPassword().equals(InputPassword1)) {
HttpSession session= req.getSession(true);
session.setAttribute("studentUserName", InputEmail1User);
session.setAttribute("studentID", student1.getS_id());
session.setAttribute("first_name", student1.getFirst_name());
session.setAttribute("middle_name", student1.getMiddle_name());
session.setAttribute("last_name", student1.getLast_name());
if (student1.getGender()==0) {
session.setAttribute("gender", "Male");
}else {
session.setAttribute("gender", "Female");
}
session.setAttribute("dob", student1.getDate_of_birth());
session.setAttribute("email", student1.getEmail());
session.setAttribute("status", student1.getStatus());
session.setAttribute("phone", student1.getPhone());
session.setAttribute("password", student1.getPassword());
//for session only if remember btn is checked
if (rememberMe != null) {
session.setAttribute("studentPassword", InputPassword1);
}
System.out.println("Student login sucess");
URI targetURIForRedirection = new URI("user");
return Response.seeOther(targetURIForRedirection).build();
}
}
}
return null;
}
@GET
@Path("/logoutAdmin")
public Response logoutAdmin(@Context HttpServletRequest req) throws URISyntaxException {
HttpSession session= req.getSession(true);
session.removeAttribute("adminUserName");
StringBuffer requestURL = req.getRequestURL();
System.out.println("full url="+requestURL);
String uri = req.getScheme() + "://" + // "http" + "://
req.getServerName() + // "myhost"
":" + // ":"
req.getServerPort() + "/exam-project-7/";
// req.getRequestURI() ;
System.out.println("url ="+uri);
URI targetURIForRedirection = new URI(uri);
return Response.seeOther(targetURIForRedirection).build();
}
@GET
@Path("/logoutStudent")
public Response logoutStudent(@Context HttpServletRequest req) throws URISyntaxException {
HttpSession session= req.getSession(true);
session.removeAttribute("studentUserName");
String uri = req.getScheme() + "://" + // "http" + "://
req.getServerName() + // "myhost"
":" + // ":"
req.getServerPort() + "/exam-project-7/";
URI targetURIForRedirection = new URI(uri);
return Response.seeOther(targetURIForRedirection).build();
}
}
| UTF-8 | Java | 4,924 | java | LoginLogOutController.java | Java | [
{
"context": "(admin2.getAdmin_username().equalsIgnoreCase(InputEmail1User)\r\n\t\t\t\t\t\t&& admin2.getAdmin_password().equals(Inpu",
"end": 1620,
"score": 0.8019750118255615,
"start": 1610,
"tag": "USERNAME",
"value": "Email1User"
},
{
"context": "etPhone());\r\n\t\t\t\t\tsession.setAttribute(\"password\", student1.getPassword());\r\n\t\t\t\t\t//for session only if remember btn is c",
"end": 3246,
"score": 0.9887828826904297,
"start": 3226,
"tag": "PASSWORD",
"value": "student1.getPassword"
},
{
"context": "\t\t\t\t\tsession.setAttribute(\"studentPassword\", InputPassword1);\r\n\t\t\t\t\t}\r\n\t\t\t\r\n\t\t\t\t\tSystem.out.println(\"Student ",
"end": 3403,
"score": 0.6196151971817017,
"start": 3394,
"tag": "PASSWORD",
"value": "Password1"
}
] | null | [] | package com.project.exam.controller;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.project.exam.model.Admin;
import com.project.exam.model.Student;
import com.project.exam.services.AdminService;
import com.project.exam.services.StudentService;
@Path("/")
@SessionAttributes("userName")
public class LoginLogOutController {
@Autowired
private AdminService adminService;
@Autowired
private StudentService studentService;
@POST
@Path("/ApiLoginOut")
public Response login(@FormParam("category") String category, @FormParam("InputEmail1User") String InputEmail1User,
@FormParam("InputPassword1") String InputPassword1, @FormParam("rememberMe") String rememberMe
,@Context HttpServletRequest req) throws URISyntaxException {
int categoryIndex = 0;
if (category.equalsIgnoreCase("Admin")) {
categoryIndex = 1;
} else if (category.equalsIgnoreCase("Student")) {
categoryIndex = 3;
}
if (categoryIndex == 1) {
List<Admin> admin = adminService.getAdminList();
for (Admin admin2 : admin) {
if (admin2.getAdmin_username().equalsIgnoreCase(InputEmail1User)
&& admin2.getAdmin_password().equals(InputPassword1)) {
//for session only if remember btn is checked
HttpSession session= req.getSession(true);
session.setAttribute("adminUserName", InputEmail1User);
if (rememberMe != null) {
session.setAttribute("adminPassword", InputPassword1);
}
System.out.println("Admin login sucess");
URI targetURIForRedirection = new URI("home");
return Response.seeOther(targetURIForRedirection).build();
}
}
}
if (categoryIndex == 3) {
List<Student> student = studentService.getStudentList();
for (Student student1 : student) {
if (student1.getUsername().equalsIgnoreCase(InputEmail1User)
&& student1.getPassword().equals(InputPassword1)) {
HttpSession session= req.getSession(true);
session.setAttribute("studentUserName", InputEmail1User);
session.setAttribute("studentID", student1.getS_id());
session.setAttribute("first_name", student1.getFirst_name());
session.setAttribute("middle_name", student1.getMiddle_name());
session.setAttribute("last_name", student1.getLast_name());
if (student1.getGender()==0) {
session.setAttribute("gender", "Male");
}else {
session.setAttribute("gender", "Female");
}
session.setAttribute("dob", student1.getDate_of_birth());
session.setAttribute("email", student1.getEmail());
session.setAttribute("status", student1.getStatus());
session.setAttribute("phone", student1.getPhone());
session.setAttribute("password", <PASSWORD>());
//for session only if remember btn is checked
if (rememberMe != null) {
session.setAttribute("studentPassword", Input<PASSWORD>);
}
System.out.println("Student login sucess");
URI targetURIForRedirection = new URI("user");
return Response.seeOther(targetURIForRedirection).build();
}
}
}
return null;
}
@GET
@Path("/logoutAdmin")
public Response logoutAdmin(@Context HttpServletRequest req) throws URISyntaxException {
HttpSession session= req.getSession(true);
session.removeAttribute("adminUserName");
StringBuffer requestURL = req.getRequestURL();
System.out.println("full url="+requestURL);
String uri = req.getScheme() + "://" + // "http" + "://
req.getServerName() + // "myhost"
":" + // ":"
req.getServerPort() + "/exam-project-7/";
// req.getRequestURI() ;
System.out.println("url ="+uri);
URI targetURIForRedirection = new URI(uri);
return Response.seeOther(targetURIForRedirection).build();
}
@GET
@Path("/logoutStudent")
public Response logoutStudent(@Context HttpServletRequest req) throws URISyntaxException {
HttpSession session= req.getSession(true);
session.removeAttribute("studentUserName");
String uri = req.getScheme() + "://" + // "http" + "://
req.getServerName() + // "myhost"
":" + // ":"
req.getServerPort() + "/exam-project-7/";
URI targetURIForRedirection = new URI(uri);
return Response.seeOther(targetURIForRedirection).build();
}
}
| 4,915 | 0.672015 | 0.664703 | 137 | 33.941605 | 24.917021 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.021898 | false | false | 2 |
d545e340c0b113a9d7c7df375d3ed378eeddc07e | 2,284,922,616,288 | b38cc26cd9fc84c2b8557a837ef7e8307d2414d0 | /app/src/main/java/razdob/cycler/ChooseCurrentSubjectsActivity.java | 7eb9476168ad1c6f3df8a07dba5596b055a20962 | [] | no_license | razdob15/cycler | https://github.com/razdob15/cycler | f1456214b6294992bdbc409de68ce4fc275735f9 | 0e3ff6fc7970d4c8fc33ef247157bcbe4231c0d2 | refs/heads/master | 2020-04-02T05:03:28.740000 | 2019-01-23T22:58:13 | 2019-01-23T22:58:13 | 154,050,313 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package razdob.cycler;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.util.ArrayList;
import razdob.cycler.adapters.CurrentSubjectsAdapter;
import razdob.cycler.feed.HomeActivity;
import razdob.cycler.myUtils.FirebaseMethods;
import razdob.cycler.myUtils.MyFonts;
/**
* Created by Raz on 02/07/2018, for project: PlacePicker2
*/
public class ChooseCurrentSubjectsActivity extends AppCompatActivity {
private static final String TAG = "ChoosePlaceTagsActivity";
final private Context mContext = ChooseCurrentSubjectsActivity.this;
/* ---------------------- FIREBASE ----------------------- */
private FirebaseApp mFireApp;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private DatabaseReference mRef;
/* ---------------------- FIREBASE ----------------------- */
// Widgets
private TextView placeNameTV;
private RecyclerView tagsRecyclerView;
private TextInputEditText tagsIT;
private Button finishBtn, clearBtn;
private ProgressBar mProgressBar;
private ImageView xIV;
// Fonts
private MyFonts mFonts;
// Vars
private ArrayList<String> mTags;
private ArrayList<String> mTagsKeeper;
private ArrayList<String> chosenSubjects;
private CurrentSubjectsAdapter mAdapter;
private FirebaseMethods mFirebaseMethods;
private TextWatcher mTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
Log.d(TAG, "afterTextChanged: input Changed: " + s);
String input = s.toString().toLowerCase();
Log.d(TAG, "afterTextChanged: input: " + input);
if (input.length() > 0) {
ArrayList<String> tempTags = new ArrayList<>();
for (String tag : mTagsKeeper) {
if (tag.length() >= input.length() && tag.toLowerCase().substring(0, input.length()).contentEquals(input)) {
tempTags.add(tag);
}
}
mTags = tempTags;
setupAdapter();
if (mTags.size() == 0) {
Log.d(TAG, "afterTextChanged: createFragment AddNewTagBtn");
}
} else {
mTags = mTagsKeeper;
setupAdapter();
}
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_place_tags);
mFonts = new MyFonts(mContext);
chosenSubjects = getIntent().getStringArrayListExtra(getString(R.string.intent_current_subjects));
if (chosenSubjects == null)
chosenSubjects = new ArrayList<>();
mTags = new ArrayList<>();
mTagsKeeper = new ArrayList<>();
mFirebaseMethods = new FirebaseMethods(mContext);
setupWidgets();
setupFirebaseStaff();
finishBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: Current Subjects From Adapter" + mAdapter.getCurrentSubjects());
Log.d(TAG, "onClick: Chosen Subjects From Activity" + chosenSubjects);
if (chosenSubjects == null || chosenSubjects.size() == 0) {
Log.d(TAG, "onClick: not chosenSubjects.");
Toast.makeText(mContext, "You can to choose what are you looking for, for giving good places.", Toast.LENGTH_SHORT).show();
}
HomeActivity.start(mContext, chosenSubjects, getString(R.string.choose_subjects_activity));
}
});
}
private void setupWidgets() {
placeNameTV = findViewById(R.id.place_name_tv);
tagsRecyclerView = findViewById(R.id.tags_gv);
tagsIT = findViewById(R.id.tags_text_input);
finishBtn = findViewById(R.id.finish_btn);
mProgressBar = findViewById(R.id.progress_bar);
xIV = findViewById(R.id.x_iv);
clearBtn = findViewById(R.id.clear_btn);
xIV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tagsIT.setText("");
}
});
clearBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
chosenSubjects = new ArrayList<>();
setupAdapter();
}
});
placeNameTV.setText("CYCLER");
placeNameTV.setTypeface(mFonts.getBoldItalicFont());
tagsIT.setHint(mContext.getString(R.string.choose_current_subjects_hint));
}
/**
* setting up the RecyclerView's adapter and make it 3-columns grid.
*/
private void setupAdapter() {
mAdapter = new CurrentSubjectsAdapter(mContext, mTags, chosenSubjects);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(mContext, 3);
tagsRecyclerView.setLayoutManager(layoutManager);
tagsRecyclerView.setItemAnimator(new DefaultItemAnimator());
tagsRecyclerView.setAdapter(mAdapter);
}
/*
* ----------------------------- Firebase ------------------------------------------
*/
private void setupFirebaseStaff() {
Log.d(TAG, "setupFirebaseStaff: called.");
mFireApp = FirebaseApp.getInstance("mFireApp");
mAuth = FirebaseAuth.getInstance(mFireApp);
mRef = FirebaseDatabase.getInstance(mFireApp).getReference();
// Init mAuthStateListener
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
// Check if user is logged in
if (user == null) {
Log.d(TAG, "onAuthStateChanged: User log-out");
} else {
Log.d(TAG, "onAuthStateChanged: User is logged-in :) uid = " + firebaseAuth.getCurrentUser().getUid());
}
}
};
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
mTags = mFirebaseMethods.getAllTags(dataSnapshot);
mTagsKeeper = mFirebaseMethods.getAllTags(dataSnapshot);
tagsIT.addTextChangedListener(mTextWatcher);
setupAdapter();
mProgressBar.setVisibility(View.GONE);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, "onCancelled: DatabaseError: " + databaseError.getMessage());
}
});
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthStateListener);
}
@Override
public void onPause() {
super.onPause();
if (mAuthStateListener != null)
mAuth.removeAuthStateListener(mAuthStateListener);
}
}
| UTF-8 | Java | 8,505 | java | ChooseCurrentSubjectsActivity.java | Java | [
{
"context": " razdob.cycler.myUtils.MyFonts;\n\n/**\n * Created by Raz on 02/07/2018, for project: PlacePicker2\n */\npubl",
"end": 1360,
"score": 0.993969202041626,
"start": 1357,
"tag": "NAME",
"value": "Raz"
},
{
"context": " }\n });\n\n placeNameTV.setText(\"CYCLER\");\n placeNameTV.setTypeface(mFonts.getBold",
"end": 5881,
"score": 0.639510989189148,
"start": 5875,
"tag": "NAME",
"value": "CYCLER"
}
] | null | [] | package razdob.cycler;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.util.ArrayList;
import razdob.cycler.adapters.CurrentSubjectsAdapter;
import razdob.cycler.feed.HomeActivity;
import razdob.cycler.myUtils.FirebaseMethods;
import razdob.cycler.myUtils.MyFonts;
/**
* Created by Raz on 02/07/2018, for project: PlacePicker2
*/
public class ChooseCurrentSubjectsActivity extends AppCompatActivity {
private static final String TAG = "ChoosePlaceTagsActivity";
final private Context mContext = ChooseCurrentSubjectsActivity.this;
/* ---------------------- FIREBASE ----------------------- */
private FirebaseApp mFireApp;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private DatabaseReference mRef;
/* ---------------------- FIREBASE ----------------------- */
// Widgets
private TextView placeNameTV;
private RecyclerView tagsRecyclerView;
private TextInputEditText tagsIT;
private Button finishBtn, clearBtn;
private ProgressBar mProgressBar;
private ImageView xIV;
// Fonts
private MyFonts mFonts;
// Vars
private ArrayList<String> mTags;
private ArrayList<String> mTagsKeeper;
private ArrayList<String> chosenSubjects;
private CurrentSubjectsAdapter mAdapter;
private FirebaseMethods mFirebaseMethods;
private TextWatcher mTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
Log.d(TAG, "afterTextChanged: input Changed: " + s);
String input = s.toString().toLowerCase();
Log.d(TAG, "afterTextChanged: input: " + input);
if (input.length() > 0) {
ArrayList<String> tempTags = new ArrayList<>();
for (String tag : mTagsKeeper) {
if (tag.length() >= input.length() && tag.toLowerCase().substring(0, input.length()).contentEquals(input)) {
tempTags.add(tag);
}
}
mTags = tempTags;
setupAdapter();
if (mTags.size() == 0) {
Log.d(TAG, "afterTextChanged: createFragment AddNewTagBtn");
}
} else {
mTags = mTagsKeeper;
setupAdapter();
}
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_place_tags);
mFonts = new MyFonts(mContext);
chosenSubjects = getIntent().getStringArrayListExtra(getString(R.string.intent_current_subjects));
if (chosenSubjects == null)
chosenSubjects = new ArrayList<>();
mTags = new ArrayList<>();
mTagsKeeper = new ArrayList<>();
mFirebaseMethods = new FirebaseMethods(mContext);
setupWidgets();
setupFirebaseStaff();
finishBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: Current Subjects From Adapter" + mAdapter.getCurrentSubjects());
Log.d(TAG, "onClick: Chosen Subjects From Activity" + chosenSubjects);
if (chosenSubjects == null || chosenSubjects.size() == 0) {
Log.d(TAG, "onClick: not chosenSubjects.");
Toast.makeText(mContext, "You can to choose what are you looking for, for giving good places.", Toast.LENGTH_SHORT).show();
}
HomeActivity.start(mContext, chosenSubjects, getString(R.string.choose_subjects_activity));
}
});
}
private void setupWidgets() {
placeNameTV = findViewById(R.id.place_name_tv);
tagsRecyclerView = findViewById(R.id.tags_gv);
tagsIT = findViewById(R.id.tags_text_input);
finishBtn = findViewById(R.id.finish_btn);
mProgressBar = findViewById(R.id.progress_bar);
xIV = findViewById(R.id.x_iv);
clearBtn = findViewById(R.id.clear_btn);
xIV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tagsIT.setText("");
}
});
clearBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
chosenSubjects = new ArrayList<>();
setupAdapter();
}
});
placeNameTV.setText("CYCLER");
placeNameTV.setTypeface(mFonts.getBoldItalicFont());
tagsIT.setHint(mContext.getString(R.string.choose_current_subjects_hint));
}
/**
* setting up the RecyclerView's adapter and make it 3-columns grid.
*/
private void setupAdapter() {
mAdapter = new CurrentSubjectsAdapter(mContext, mTags, chosenSubjects);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(mContext, 3);
tagsRecyclerView.setLayoutManager(layoutManager);
tagsRecyclerView.setItemAnimator(new DefaultItemAnimator());
tagsRecyclerView.setAdapter(mAdapter);
}
/*
* ----------------------------- Firebase ------------------------------------------
*/
private void setupFirebaseStaff() {
Log.d(TAG, "setupFirebaseStaff: called.");
mFireApp = FirebaseApp.getInstance("mFireApp");
mAuth = FirebaseAuth.getInstance(mFireApp);
mRef = FirebaseDatabase.getInstance(mFireApp).getReference();
// Init mAuthStateListener
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
// Check if user is logged in
if (user == null) {
Log.d(TAG, "onAuthStateChanged: User log-out");
} else {
Log.d(TAG, "onAuthStateChanged: User is logged-in :) uid = " + firebaseAuth.getCurrentUser().getUid());
}
}
};
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
mTags = mFirebaseMethods.getAllTags(dataSnapshot);
mTagsKeeper = mFirebaseMethods.getAllTags(dataSnapshot);
tagsIT.addTextChangedListener(mTextWatcher);
setupAdapter();
mProgressBar.setVisibility(View.GONE);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, "onCancelled: DatabaseError: " + databaseError.getMessage());
}
});
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthStateListener);
}
@Override
public void onPause() {
super.onPause();
if (mAuthStateListener != null)
mAuth.removeAuthStateListener(mAuthStateListener);
}
}
| 8,505 | 0.630923 | 0.628689 | 235 | 35.19149 | 27.793339 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.621277 | false | false | 2 |
e875e7544b1ebc80992808c1298aa3cbb8e7da82 | 21,741,124,485,043 | ef9ad57d7d99e681476a5e00e3a39223786f3983 | /demo/src/main/java/com/demo/dao/ScaTransactionRepository.java | 86eb94d65ae4d8fff943afc2cf534a6a1d0027cc | [] | no_license | o0hailang0o/Elasticsearch-easyClient | https://github.com/o0hailang0o/Elasticsearch-easyClient | fdd453754bafe05e1a9473b7947e237f0a4c33dc | d85538924900c19b4efb92dea9a6d69fc0600494 | refs/heads/master | 2020-05-07T01:10:40.827000 | 2019-04-09T01:55:18 | 2019-04-09T01:55:18 | 180,263,365 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.demo.dao;
import com.demo.model.ScaTransaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by liujian on 2018/11/24.
*/
@Repository
public class ScaTransactionRepository {
@Autowired
private ScaTransactionElasticSearch scaTransactionElasticSearch;
@Autowired
private ScaTransactionMapper scaTransactionMapper;
public void deleteScaTransaction() {
scaTransactionElasticSearch.deleteScaTransaction();
}
public Integer countScaTransaction() {
return scaTransactionMapper.countScaTransaction();
}
public void bulkScaTransaction(List<ScaTransaction> scaTransactionList) {
scaTransactionElasticSearch.bulkScaTransaction(scaTransactionList);
}
public List<ScaTransaction> findAll(Integer pageNum, int pageSize) {
return scaTransactionMapper.findAll((pageNum-1)*pageSize,(pageNum-1)*pageSize+pageSize);
}
}
| UTF-8 | Java | 1,009 | java | ScaTransactionRepository.java | Java | [
{
"context": "sitory;\n\nimport java.util.List;\n\n/**\n * Created by liujian on 2018/11/24.\n */\n@Repository\npublic class ScaTr",
"end": 224,
"score": 0.9985554814338684,
"start": 217,
"tag": "USERNAME",
"value": "liujian"
}
] | null | [] | package com.demo.dao;
import com.demo.model.ScaTransaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by liujian on 2018/11/24.
*/
@Repository
public class ScaTransactionRepository {
@Autowired
private ScaTransactionElasticSearch scaTransactionElasticSearch;
@Autowired
private ScaTransactionMapper scaTransactionMapper;
public void deleteScaTransaction() {
scaTransactionElasticSearch.deleteScaTransaction();
}
public Integer countScaTransaction() {
return scaTransactionMapper.countScaTransaction();
}
public void bulkScaTransaction(List<ScaTransaction> scaTransactionList) {
scaTransactionElasticSearch.bulkScaTransaction(scaTransactionList);
}
public List<ScaTransaction> findAll(Integer pageNum, int pageSize) {
return scaTransactionMapper.findAll((pageNum-1)*pageSize,(pageNum-1)*pageSize+pageSize);
}
}
| 1,009 | 0.766105 | 0.756194 | 36 | 27.027779 | 28.573965 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.361111 | false | false | 2 |
484c3fd26abdef4bcd56c7e2f5fa6396a8103cd4 | 24,129,126,283,186 | 1d02959a6cae05956a29ae4b8f4026e1a6390061 | /src/domain/org/net9/domain/model/blog/BlogEntry.java | 3907273fe96d186d248dc05671649b605aa75b19 | [] | no_license | FreeDao/ctba.cn | https://github.com/FreeDao/ctba.cn | d43326e82ad465fca3ded538d1d5e00103070ac2 | 9fe70e2c3138d6d96a5acca0e7c2892a2d61a751 | refs/heads/master | 2021-01-22T14:15:57.401000 | 2013-02-24T11:45:39 | 2013-02-24T11:45:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.net9.domain.model.blog;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.net9.domain.model.BaseModel;
import com.j2bb.common.search.Index;
@SuppressWarnings("serial")
@Entity
@Table(name = "blog_blogentry", uniqueConstraints = {})
public class BlogEntry extends BaseModel implements java.io.Serializable {
@Index(analyzed = false)
private Integer id;
private Blog blogBlog;
/** 未使用 */
private String permalink;
// @Index
private String body;
@Index(analyzed = false)
private String author;
@Index(analyzed = false)
private Integer hits;
@Index(analyzed = false)
private String date;
private String publishDate;
@Index
private String title;
/** 未使用 */
private String subtitle;
/** 未使用 */
private String tags;
/** 未使用 */
private Short commentsEnabled;
private Integer state;
@Index
private Integer categoryId;
private Integer type = 1000;
@Index
private Integer commentCnt = 0;
private Set<BlogComment> blogComments = new HashSet<BlogComment>(0);
@Column(name = "author", unique = false, nullable = false, insertable = true, updatable = true, length = 50)
public String getAuthor() {
return this.author;
}
@ManyToOne(cascade = {}, fetch = FetchType.LAZY)
@JoinColumn(name = "blogId", unique = false, nullable = false, insertable = true, updatable = true)
public Blog getBlogBlog() {
return this.blogBlog;
}
@OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY, mappedBy = "blogBlogentry")
public Set<BlogComment> getBlogComments() {
return this.blogComments;
}
@Column(name = "body", unique = false, nullable = false, insertable = true, updatable = true, length = 65535)
public String getBody() {
return this.body;
}
@Column(name = "categoryId", unique = false, nullable = true, insertable = true, updatable = true)
public Integer getCategoryId() {
return this.categoryId;
}
public Integer getCommentCnt() {
return commentCnt;
}
@Column(name = "commentsEnabled", unique = false, nullable = true, insertable = true, updatable = true)
public Short getCommentsEnabled() {
return this.commentsEnabled;
}
@Column(name = "date", unique = false, nullable = true, insertable = true, updatable = true, length = 80)
public String getDate() {
return this.date;
}
@Column(name = "hits", unique = false, nullable = true, insertable = true, updatable = true)
public Integer getHits() {
return this.hits;
}
@Id
@Column(name = "id", unique = true, nullable = false, insertable = true, updatable = true)
public Integer getId() {
return this.id;
}
@Column(name = "permalink", unique = false, nullable = true, insertable = true, updatable = true, length = 150)
public String getPermalink() {
return this.permalink;
}
@Column(name = "state", unique = false, nullable = true, insertable = true, updatable = true)
public Integer getState() {
return this.state;
}
@Column(name = "subtitle", unique = false, nullable = true, insertable = true, updatable = true, length = 200)
public String getSubtitle() {
return this.subtitle;
}
@Column(name = "tags", unique = false, nullable = true, insertable = true, updatable = true, length = 100)
public String getTags() {
return this.tags;
}
@Column(name = "title", unique = false, nullable = true, insertable = true, updatable = true, length = 50)
public String getTitle() {
return this.title;
}
public Integer getType() {
return type;
}
public void setAuthor(String author) {
this.author = author;
}
public void setBlogBlog(Blog blogBlog) {
this.blogBlog = blogBlog;
}
public void setBlogComments(Set<BlogComment> blogComments) {
this.blogComments = blogComments;
}
public void setBody(String body) {
this.body = body;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public void setCommentCnt(Integer commentCnt) {
this.commentCnt = commentCnt;
}
public void setCommentsEnabled(Short commentsEnabled) {
this.commentsEnabled = commentsEnabled;
}
public void setDate(String date) {
this.date = date;
}
public void setHits(Integer hits) {
this.hits = hits;
}
public void setId(Integer id) {
this.id = id;
}
public void setPermalink(String permalink) {
this.permalink = permalink;
}
public void setState(Integer state) {
this.state = state;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
public void setTags(String tags) {
this.tags = tags;
}
public void setTitle(String title) {
this.title = title;
}
public void setType(Integer type) {
this.type = type;
}
public String getPublishDate() {
return publishDate;
}
public void setPublishDate(String publishDate) {
this.publishDate = publishDate;
}
} | UTF-8 | Java | 5,292 | java | BlogEntry.java | Java | [] | null | [] | package org.net9.domain.model.blog;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.net9.domain.model.BaseModel;
import com.j2bb.common.search.Index;
@SuppressWarnings("serial")
@Entity
@Table(name = "blog_blogentry", uniqueConstraints = {})
public class BlogEntry extends BaseModel implements java.io.Serializable {
@Index(analyzed = false)
private Integer id;
private Blog blogBlog;
/** 未使用 */
private String permalink;
// @Index
private String body;
@Index(analyzed = false)
private String author;
@Index(analyzed = false)
private Integer hits;
@Index(analyzed = false)
private String date;
private String publishDate;
@Index
private String title;
/** 未使用 */
private String subtitle;
/** 未使用 */
private String tags;
/** 未使用 */
private Short commentsEnabled;
private Integer state;
@Index
private Integer categoryId;
private Integer type = 1000;
@Index
private Integer commentCnt = 0;
private Set<BlogComment> blogComments = new HashSet<BlogComment>(0);
@Column(name = "author", unique = false, nullable = false, insertable = true, updatable = true, length = 50)
public String getAuthor() {
return this.author;
}
@ManyToOne(cascade = {}, fetch = FetchType.LAZY)
@JoinColumn(name = "blogId", unique = false, nullable = false, insertable = true, updatable = true)
public Blog getBlogBlog() {
return this.blogBlog;
}
@OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY, mappedBy = "blogBlogentry")
public Set<BlogComment> getBlogComments() {
return this.blogComments;
}
@Column(name = "body", unique = false, nullable = false, insertable = true, updatable = true, length = 65535)
public String getBody() {
return this.body;
}
@Column(name = "categoryId", unique = false, nullable = true, insertable = true, updatable = true)
public Integer getCategoryId() {
return this.categoryId;
}
public Integer getCommentCnt() {
return commentCnt;
}
@Column(name = "commentsEnabled", unique = false, nullable = true, insertable = true, updatable = true)
public Short getCommentsEnabled() {
return this.commentsEnabled;
}
@Column(name = "date", unique = false, nullable = true, insertable = true, updatable = true, length = 80)
public String getDate() {
return this.date;
}
@Column(name = "hits", unique = false, nullable = true, insertable = true, updatable = true)
public Integer getHits() {
return this.hits;
}
@Id
@Column(name = "id", unique = true, nullable = false, insertable = true, updatable = true)
public Integer getId() {
return this.id;
}
@Column(name = "permalink", unique = false, nullable = true, insertable = true, updatable = true, length = 150)
public String getPermalink() {
return this.permalink;
}
@Column(name = "state", unique = false, nullable = true, insertable = true, updatable = true)
public Integer getState() {
return this.state;
}
@Column(name = "subtitle", unique = false, nullable = true, insertable = true, updatable = true, length = 200)
public String getSubtitle() {
return this.subtitle;
}
@Column(name = "tags", unique = false, nullable = true, insertable = true, updatable = true, length = 100)
public String getTags() {
return this.tags;
}
@Column(name = "title", unique = false, nullable = true, insertable = true, updatable = true, length = 50)
public String getTitle() {
return this.title;
}
public Integer getType() {
return type;
}
public void setAuthor(String author) {
this.author = author;
}
public void setBlogBlog(Blog blogBlog) {
this.blogBlog = blogBlog;
}
public void setBlogComments(Set<BlogComment> blogComments) {
this.blogComments = blogComments;
}
public void setBody(String body) {
this.body = body;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public void setCommentCnt(Integer commentCnt) {
this.commentCnt = commentCnt;
}
public void setCommentsEnabled(Short commentsEnabled) {
this.commentsEnabled = commentsEnabled;
}
public void setDate(String date) {
this.date = date;
}
public void setHits(Integer hits) {
this.hits = hits;
}
public void setId(Integer id) {
this.id = id;
}
public void setPermalink(String permalink) {
this.permalink = permalink;
}
public void setState(Integer state) {
this.state = state;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
public void setTags(String tags) {
this.tags = tags;
}
public void setTitle(String title) {
this.title = title;
}
public void setType(Integer type) {
this.type = type;
}
public String getPublishDate() {
return publishDate;
}
public void setPublishDate(String publishDate) {
this.publishDate = publishDate;
}
} | 5,292 | 0.682992 | 0.677487 | 220 | 21.954546 | 26.401751 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.404545 | false | false | 2 |
61ef4bc32d0f28929281d096ff95b9fa95e8fcb9 | 6,554,120,106,363 | cd476bfd09912c456109c5f6c79d171b7e63d14d | /app/src/main/java/com/you_tube/auto_subscribers/ExtraUtils/ViewPagerAdapter.java | bc8a89564c83279a3fc298598ced1c117757ed14 | [] | no_license | communicationmantra/OnTubeAutoSubscribers | https://github.com/communicationmantra/OnTubeAutoSubscribers | 4eb5e59920f0c8b60524a1832257a311b58174b1 | 560ec6df4b83aa41ed9d98e06d79bffcb506ce74 | refs/heads/master | 2020-09-06T11:39:03.632000 | 2019-11-08T07:22:09 | 2019-11-08T07:22:09 | 220,413,543 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.you_tube.auto_subscribers.ExtraUtils;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.you_tube.auto_subscribers.AlreadySubList.SubListFragment;
import com.you_tube.auto_subscribers.MainFragments.FirstFragment;
import com.you_tube.auto_subscribers.MainFragments.SecondFragment;
import com.you_tube.auto_subscribers.MainFragments.ThirdFragment;
import com.you_tube.auto_subscribers.MyChannelList.YourVideoFragment;
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm)
{
super(fm);
}
@Override
public Fragment getItem(int position)
{
if (position == 0)
{
return new FirstFragment();
}
else if (position == 1)
{
return new SecondFragment();
}
else if (position == 2)
{
return new ThirdFragment();
}
else if (position == 3)
{
return new YourVideoFragment();
}
else if (position == 4)
{
return new SubListFragment();
}
else return null;
}
@Override
public int getCount() {
return 5;
}
}
| UTF-8 | Java | 1,298 | java | ViewPagerAdapter.java | Java | [] | null | [] | package com.you_tube.auto_subscribers.ExtraUtils;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.you_tube.auto_subscribers.AlreadySubList.SubListFragment;
import com.you_tube.auto_subscribers.MainFragments.FirstFragment;
import com.you_tube.auto_subscribers.MainFragments.SecondFragment;
import com.you_tube.auto_subscribers.MainFragments.ThirdFragment;
import com.you_tube.auto_subscribers.MyChannelList.YourVideoFragment;
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm)
{
super(fm);
}
@Override
public Fragment getItem(int position)
{
if (position == 0)
{
return new FirstFragment();
}
else if (position == 1)
{
return new SecondFragment();
}
else if (position == 2)
{
return new ThirdFragment();
}
else if (position == 3)
{
return new YourVideoFragment();
}
else if (position == 4)
{
return new SubListFragment();
}
else return null;
}
@Override
public int getCount() {
return 5;
}
}
| 1,298 | 0.637134 | 0.632512 | 54 | 23.037037 | 21.656376 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.314815 | false | false | 2 |
d981801fa43fe928d5cc761709ae2ae35b45d798 | 24,257,975,314,709 | 4bda6d0c5302c41d718198c6bc0f834537ab07f3 | /cg-automation/exception/src/com/capgemini/exception/second/TestA.java | 3f05bcbb35392fb27ddd81ddc97ff338dd75c90c | [] | no_license | Renuka6997/MyJava | https://github.com/Renuka6997/MyJava | 5ac1596236a4f28f67d4d886705a9f377d8ec29c | 455e6bbb563b92be26266ed2c11d861e47cee944 | refs/heads/master | 2023-03-14T07:00:35.740000 | 2021-03-05T03:10:07 | 2021-03-05T03:10:07 | 344,677,821 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.capgemini.exception.second;
public class TestA {
public static void main(String[] args) {
System.out.println("main starts");
if (20 > 10) {
try {
throw new ArithmeticException("invalid number"); // it creates the object of exception
// and prints the error given by us
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
System.out.println("main ends");
}
}
| UTF-8 | Java | 460 | java | TestA.java | Java | [] | null | [] | package com.capgemini.exception.second;
public class TestA {
public static void main(String[] args) {
System.out.println("main starts");
if (20 > 10) {
try {
throw new ArithmeticException("invalid number"); // it creates the object of exception
// and prints the error given by us
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
System.out.println("main ends");
}
}
| 460 | 0.597826 | 0.58913 | 18 | 24.555555 | 27.154337 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.833333 | false | false | 2 |
a42715038abda92dcaddf1c1a793d6ef9cd871b1 | 13,469,017,443,167 | 68b3d254bcd26e75bd994a11eae39f72728b5cc8 | /src/main/java/com/rammp/stretchyourbody/service/dto/ProgramFeedBackDTO.java | 6b40bbd98b649d4cd3962e41fc7bac3565ac43cc | [] | no_license | MauricioAra/stretchcms | https://github.com/MauricioAra/stretchcms | b1409165d1a17f9524b2624e00ba8ce5c90e7ce8 | 11b588b0805185e506a47a7d00e964c4650f6376 | refs/heads/master | 2021-05-18T09:42:56.512000 | 2017-08-26T19:18:05 | 2017-08-26T19:18:05 | 94,649,523 | 0 | 1 | null | false | 2020-09-18T16:26:43 | 2017-06-17T21:14:36 | 2017-06-17T21:54:16 | 2020-09-18T16:26:41 | 4,779 | 0 | 1 | 1 | Java | false | false | package com.rammp.stretchyourbody.service.dto;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.Objects;
/**
* A DTO for the ProgramFeedBack entity.
*/
public class ProgramFeedBackDTO implements Serializable {
private Long id;
private Boolean isUseful;
private Boolean isHelpPain;
private Long programId;
private String programName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Boolean getIsUseful() {
return isUseful;
}
public void setIsUseful(Boolean isUseful) {
this.isUseful = isUseful;
}
public Boolean getIsHelpPain() {
return isHelpPain;
}
public void setIsHelpPain(Boolean isHelpPain) {
this.isHelpPain = isHelpPain;
}
public Long getProgramId() {
return programId;
}
public void setProgramId(Long programId) {
this.programId = programId;
}
public String getProgramName() {
return programName;
}
public void setProgramName(String programName) {
this.programName = programName;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProgramFeedBackDTO programFeedBackDTO = (ProgramFeedBackDTO) o;
if ( ! Objects.equals(id, programFeedBackDTO.id)) { return false; }
return true;
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return "ProgramFeedBackDTO{" +
"id=" + id +
", isUseful='" + isUseful + "'" +
", isHelpPain='" + isHelpPain + "'" +
'}';
}
}
| UTF-8 | Java | 1,871 | java | ProgramFeedBackDTO.java | Java | [] | null | [] | package com.rammp.stretchyourbody.service.dto;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.Objects;
/**
* A DTO for the ProgramFeedBack entity.
*/
public class ProgramFeedBackDTO implements Serializable {
private Long id;
private Boolean isUseful;
private Boolean isHelpPain;
private Long programId;
private String programName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Boolean getIsUseful() {
return isUseful;
}
public void setIsUseful(Boolean isUseful) {
this.isUseful = isUseful;
}
public Boolean getIsHelpPain() {
return isHelpPain;
}
public void setIsHelpPain(Boolean isHelpPain) {
this.isHelpPain = isHelpPain;
}
public Long getProgramId() {
return programId;
}
public void setProgramId(Long programId) {
this.programId = programId;
}
public String getProgramName() {
return programName;
}
public void setProgramName(String programName) {
this.programName = programName;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProgramFeedBackDTO programFeedBackDTO = (ProgramFeedBackDTO) o;
if ( ! Objects.equals(id, programFeedBackDTO.id)) { return false; }
return true;
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return "ProgramFeedBackDTO{" +
"id=" + id +
", isUseful='" + isUseful + "'" +
", isHelpPain='" + isHelpPain + "'" +
'}';
}
}
| 1,871 | 0.589524 | 0.589524 | 91 | 19.56044 | 18.429676 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.351648 | false | false | 2 |
ba96d803780b2f9eaf1b9ee5409deba1faf756ec | 10,668,698,781,875 | f9542b72b07c8566e0c1c48aef45e4e99225188a | /src/test/java/br/com/abevieiramota/service/preditor/PredicaoTest.java | 93819dc0f8f242f582ddb5e5b5234e5475b9edf2 | [] | no_license | abevieiramota/app-loteria-de-cristal | https://github.com/abevieiramota/app-loteria-de-cristal | e27439371a8234d5b53de0d7f4957ac9382dd237 | a2d86bfd5aaf39fd464adccdef5bed256b13e57e | refs/heads/master | 2022-12-07T20:09:10.296000 | 2020-07-22T00:05:33 | 2020-07-22T00:05:33 | 98,750,619 | 1 | 0 | null | false | 2022-11-24T08:48:50 | 2017-07-29T18:08:00 | 2020-07-22T00:05:42 | 2022-11-24T08:48:47 | 36,670 | 1 | 0 | 3 | Java | false | false | package br.com.abevieiramota.service.preditor;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import br.com.abevieiramota.model.Loteria;
import br.com.abevieiramota.model.Resultado;
import br.com.abevieiramota.model.Resultado.ResultadoBuilder;
import br.com.abevieiramota.model.Turno;
@RunWith(JUnit4.class)
public class PredicaoTest {
private static final Turno TURNO_NOTURNO = new Turno();
static {
// TURNO_NOTURNO.setId(0);
// TURNO_NOTURNO.setLabel("Noturno");
// TURNO_NOTURNO.setHoraMinima(10);
// TURNO_NOTURNO.setHoraMinima(14);
}
private static final Loteria LOTERIA_FEDERAL = new Loteria();
static {
// LOTERIA_FEDERAL.setId(0);
// LOTERIA_FEDERAL.setLabel("Federal");
}
private static Resultado resultado1 = new ResultadoBuilder().data("27/07/2013")
.premios(new String[] { "0728", "0383", "8157", "0863", "7532", "0874", "4668", "3967", "5237", "0375"
}).turno(TURNO_NOTURNO).loteria(LOTERIA_FEDERAL).build();
private static Resultado resultado2 = new ResultadoBuilder().data("27/07/2013")
.premios(new String[] { "6865", "0383", "8157", "0863", "7532", "0874", "4668", "3967", "5237", "0375"
}).turno(TURNO_NOTURNO).loteria(LOTERIA_FEDERAL).build();
// @Test
// public void predicaoMaisVelhosTamanho25() {
// Resultado[] maisVelhos = new PredicaoBuilder(Premio._1,
// Dezena.TERCEIRA).build().ordenadoPorVelhice();
//
// assertEquals(0, maisVelhos.length);
// }
//
// @Test
// public void predicaoVazia() {
// Predicao predicao = new PredicaoBuilder(Premio._1,
// Dezena.TERCEIRA).atualizar(resultado1).build();
//
// Resultado[] maisVelhos = predicao.ordenadoPorVelhice();
//
// assertEquals(resultado1.premio(Premio._1), maisVelhos[0].premio(Premio._1));
// }
//
// @Test
// public void predicaoVaziaDoisResultadosIguais() {
// Predicao predicao = new PredicaoBuilder(Premio._1,
// Dezena.TERCEIRA).atualizar(resultado1).atualizar(resultado2)
// .build();
//
// Resultado[] maisVelhos = predicao.ordenadoPorVelhice();
//
// assertEquals(resultado1.premio(Premio._1), maisVelhos[0].premio(Premio._1));
// }
//
// @Test
// public void predicaoVaziaDoisResultadosDiferentes() {
// Predicao predicao = new PredicaoBuilder(Premio._1,
// Dezena.TERCEIRA).atualizar(resultado1).atualizar(resultado2)
// .build();
//
// Resultado[] maisVelhos = predicao.ordenadoPorVelhice();
//
// assertEquals(resultado1.premio(Premio._1), maisVelhos[0].premio(Premio._1));
// assertEquals(resultado2.premio(Premio._1), maisVelhos[1].premio(Premio._1));
// }
//
// @Test
// public void predicao10ResultadosIguais() {
// Predicao predicao = new PredicaoBuilder(Premio._1,
// Dezena.TERCEIRA).atualizar(resultado1).atualizar(resultado1)
// .atualizar(resultado1).atualizar(resultado1).atualizar(resultado1).atualizar(resultado1).build();
//
// Resultado[] maisVelhos = predicao.ordenadoPorVelhice();
//
// assertEquals(resultado1.premio(Premio._1), maisVelhos[0].premio(Premio._1));
// }
//
// // apenas para teste temporário
// // @Test
// public void predicaoAPartir01012013() throws ClassNotFoundException,
// SQLException {
// ResultadoDao resDAO = new ResultadoDao();
// List<Resultado> resultados = resDAO.all(LOTERIA_FEDERAL);
// PredicaoBuilder predicaoBuilder = new PredicaoBuilder(Premio._1,
// Dezena.TERCEIRA);
// for (Resultado resultado : resultados) {
// predicaoBuilder.atualizar(resultado);
// }
//
// Predicao predicao = predicaoBuilder.build();
//
// Set<Bicho> bichosNaPredicao = new HashSet<Bicho>();
// for (Resultado valorResultado : predicao.ordenadoPorVelhice()) {
// bichosNaPredicao.add(Bicho.fromResultado(valorResultado.premio(Premio._1),
// Dezena.TERCEIRA));
// System.out.println(Bicho.fromResultado(valorResultado.premio(Premio._1),
// Dezena.TERCEIRA) + " : "
// + valorResultado.getData());
// }
// assertEquals(25, bichosNaPredicao.size());
// }
}
| UTF-8 | Java | 3,906 | java | PredicaoTest.java | Java | [] | null | [] | package br.com.abevieiramota.service.preditor;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import br.com.abevieiramota.model.Loteria;
import br.com.abevieiramota.model.Resultado;
import br.com.abevieiramota.model.Resultado.ResultadoBuilder;
import br.com.abevieiramota.model.Turno;
@RunWith(JUnit4.class)
public class PredicaoTest {
private static final Turno TURNO_NOTURNO = new Turno();
static {
// TURNO_NOTURNO.setId(0);
// TURNO_NOTURNO.setLabel("Noturno");
// TURNO_NOTURNO.setHoraMinima(10);
// TURNO_NOTURNO.setHoraMinima(14);
}
private static final Loteria LOTERIA_FEDERAL = new Loteria();
static {
// LOTERIA_FEDERAL.setId(0);
// LOTERIA_FEDERAL.setLabel("Federal");
}
private static Resultado resultado1 = new ResultadoBuilder().data("27/07/2013")
.premios(new String[] { "0728", "0383", "8157", "0863", "7532", "0874", "4668", "3967", "5237", "0375"
}).turno(TURNO_NOTURNO).loteria(LOTERIA_FEDERAL).build();
private static Resultado resultado2 = new ResultadoBuilder().data("27/07/2013")
.premios(new String[] { "6865", "0383", "8157", "0863", "7532", "0874", "4668", "3967", "5237", "0375"
}).turno(TURNO_NOTURNO).loteria(LOTERIA_FEDERAL).build();
// @Test
// public void predicaoMaisVelhosTamanho25() {
// Resultado[] maisVelhos = new PredicaoBuilder(Premio._1,
// Dezena.TERCEIRA).build().ordenadoPorVelhice();
//
// assertEquals(0, maisVelhos.length);
// }
//
// @Test
// public void predicaoVazia() {
// Predicao predicao = new PredicaoBuilder(Premio._1,
// Dezena.TERCEIRA).atualizar(resultado1).build();
//
// Resultado[] maisVelhos = predicao.ordenadoPorVelhice();
//
// assertEquals(resultado1.premio(Premio._1), maisVelhos[0].premio(Premio._1));
// }
//
// @Test
// public void predicaoVaziaDoisResultadosIguais() {
// Predicao predicao = new PredicaoBuilder(Premio._1,
// Dezena.TERCEIRA).atualizar(resultado1).atualizar(resultado2)
// .build();
//
// Resultado[] maisVelhos = predicao.ordenadoPorVelhice();
//
// assertEquals(resultado1.premio(Premio._1), maisVelhos[0].premio(Premio._1));
// }
//
// @Test
// public void predicaoVaziaDoisResultadosDiferentes() {
// Predicao predicao = new PredicaoBuilder(Premio._1,
// Dezena.TERCEIRA).atualizar(resultado1).atualizar(resultado2)
// .build();
//
// Resultado[] maisVelhos = predicao.ordenadoPorVelhice();
//
// assertEquals(resultado1.premio(Premio._1), maisVelhos[0].premio(Premio._1));
// assertEquals(resultado2.premio(Premio._1), maisVelhos[1].premio(Premio._1));
// }
//
// @Test
// public void predicao10ResultadosIguais() {
// Predicao predicao = new PredicaoBuilder(Premio._1,
// Dezena.TERCEIRA).atualizar(resultado1).atualizar(resultado1)
// .atualizar(resultado1).atualizar(resultado1).atualizar(resultado1).atualizar(resultado1).build();
//
// Resultado[] maisVelhos = predicao.ordenadoPorVelhice();
//
// assertEquals(resultado1.premio(Premio._1), maisVelhos[0].premio(Premio._1));
// }
//
// // apenas para teste temporário
// // @Test
// public void predicaoAPartir01012013() throws ClassNotFoundException,
// SQLException {
// ResultadoDao resDAO = new ResultadoDao();
// List<Resultado> resultados = resDAO.all(LOTERIA_FEDERAL);
// PredicaoBuilder predicaoBuilder = new PredicaoBuilder(Premio._1,
// Dezena.TERCEIRA);
// for (Resultado resultado : resultados) {
// predicaoBuilder.atualizar(resultado);
// }
//
// Predicao predicao = predicaoBuilder.build();
//
// Set<Bicho> bichosNaPredicao = new HashSet<Bicho>();
// for (Resultado valorResultado : predicao.ordenadoPorVelhice()) {
// bichosNaPredicao.add(Bicho.fromResultado(valorResultado.premio(Premio._1),
// Dezena.TERCEIRA));
// System.out.println(Bicho.fromResultado(valorResultado.premio(Premio._1),
// Dezena.TERCEIRA) + " : "
// + valorResultado.getData());
// }
// assertEquals(25, bichosNaPredicao.size());
// }
}
| 3,906 | 0.707298 | 0.666325 | 113 | 33.557522 | 28.814308 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.619469 | false | false | 2 |
8f490812ee31ca22a555269445d76bb46e1d4268 | 18,519,898,994,565 | 168ed5bf8c22d11b43a177cef02795ecc0dde37c | /src/test/java/cn/devezhao/persist4j/query/compiler/SqlKeywordTest.java | 71f8a67133acc86292256854818db18f5a3d5fb1 | [] | no_license | MayBeWrong/persist4j | https://github.com/MayBeWrong/persist4j | 48ada97cfafb6d0a6f3bf07535ffb21f6fc97a7e | ee5acf482a60692b714303bf4babdc67d944f0ba | refs/heads/master | 2020-03-24T01:11:29.511000 | 2018-03-23T08:04:04 | 2018-03-23T08:04:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.devezhao.persist4j.query.compiler;
import org.junit.Test;
import cn.devezhao.persist4j.PersistManagerFactory;
import cn.devezhao.persist4j.dialect.Dialect;
import cn.devezhao.persist4j.dialect.MySQL5Dialect;
import cn.devezhao.persist4j.engine.PersistManagerFactoryImpl;
import cn.devezhao.persist4j.metadata.MetadataFactory;
import cn.devezhao.persist4j.metadata.impl.ConfigurationMetadataFactory;
/**
*
* @author zhaofang123@gmail.com
* @since 03/05/2018
*/
public class SqlKeywordTest {
@Test
public void testDistinct() {
String ajql = "select distinct tString from TestAllType where tString is null";
String sql = compile(ajql);
System.out.println(ajql + "\n>>\n" + sql);
}
String compile(String ajql) {
Dialect dialect = new MySQL5Dialect();
MetadataFactory metadataFactory = new ConfigurationMetadataFactory("metadata-test.xml", dialect);
PersistManagerFactory persistManagerFactory = new PersistManagerFactoryImpl(null, dialect, metadataFactory);
QueryCompiler queryCompiler = new QueryCompiler(ajql);
String rawSql = queryCompiler.compile(persistManagerFactory.getSQLExecutorContext());
return rawSql;
}
}
| UTF-8 | Java | 1,159 | java | SqlKeywordTest.java | Java | [
{
"context": ".ConfigurationMetadataFactory;\n\n/**\n * \n * @author zhaofang123@gmail.com\n * @since 03/05/2018\n */\npublic class SqlKeywordT",
"end": 453,
"score": 0.999342679977417,
"start": 432,
"tag": "EMAIL",
"value": "zhaofang123@gmail.com"
}
] | null | [] | package cn.devezhao.persist4j.query.compiler;
import org.junit.Test;
import cn.devezhao.persist4j.PersistManagerFactory;
import cn.devezhao.persist4j.dialect.Dialect;
import cn.devezhao.persist4j.dialect.MySQL5Dialect;
import cn.devezhao.persist4j.engine.PersistManagerFactoryImpl;
import cn.devezhao.persist4j.metadata.MetadataFactory;
import cn.devezhao.persist4j.metadata.impl.ConfigurationMetadataFactory;
/**
*
* @author <EMAIL>
* @since 03/05/2018
*/
public class SqlKeywordTest {
@Test
public void testDistinct() {
String ajql = "select distinct tString from TestAllType where tString is null";
String sql = compile(ajql);
System.out.println(ajql + "\n>>\n" + sql);
}
String compile(String ajql) {
Dialect dialect = new MySQL5Dialect();
MetadataFactory metadataFactory = new ConfigurationMetadataFactory("metadata-test.xml", dialect);
PersistManagerFactory persistManagerFactory = new PersistManagerFactoryImpl(null, dialect, metadataFactory);
QueryCompiler queryCompiler = new QueryCompiler(ajql);
String rawSql = queryCompiler.compile(persistManagerFactory.getSQLExecutorContext());
return rawSql;
}
}
| 1,145 | 0.792062 | 0.774806 | 34 | 33.088234 | 30.838638 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.294118 | false | false | 2 |
e2c86d0dfc905afc31048ac3499e9506f4fa0b5a | 1,752,346,698,261 | 3f9f2c865413b8410098b72579cec0c8361a322d | /app/src/main/java/com/ardian/moviecatalogue/Service/Service.java | d6d9611b8dfdfa357aac98bbe0a5e3d017dd3661 | [] | no_license | ardianff/moveicatalogtiga | https://github.com/ardianff/moveicatalogtiga | 56ca6204f1d501e909c939e9567b72abb3601581 | 05be4d90ec66a4867d1bc018d8bf975d361e5e85 | refs/heads/master | 2020-09-19T13:26:35.506000 | 2019-11-26T15:55:26 | 2019-11-26T15:55:26 | 224,230,366 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ardian.moviecatalogue.Service;
import com.ardian.moviecatalogue.Parcelable.Movie;
import com.ardian.moviecatalogue.Parcelable.TV;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface Service {
@GET("movie")
Call<Movie> getMovie(@Query("api_key") String apiKey);
@GET("tv")
Call<TV> getShow(@Query("api_key") String apiKey);
}
| UTF-8 | Java | 403 | java | Service.java | Java | [] | null | [] | package com.ardian.moviecatalogue.Service;
import com.ardian.moviecatalogue.Parcelable.Movie;
import com.ardian.moviecatalogue.Parcelable.TV;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface Service {
@GET("movie")
Call<Movie> getMovie(@Query("api_key") String apiKey);
@GET("tv")
Call<TV> getShow(@Query("api_key") String apiKey);
}
| 403 | 0.739454 | 0.73201 | 18 | 21.388889 | 20.580841 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 2 |
e6e8720dc36cfcd2504ad2b325b5bbc66926c05d | 21,028,159,931,784 | 87321ee11cb82ebfc60253a895f45479b88940cc | /how2j/study/src/main/java/how2j/javathread/chapter1/TryConcurrency.java | 9d7c2bb018a32e71e00dfe9670a3af02301dca90 | [] | no_license | ymjrchx/myProject | https://github.com/ymjrchx/myProject | a1675b848e1e7fbec98374a87823b7c1c76a111f | 284cd0355597607bf002fb066100c6a87a4d750a | refs/heads/master | 2022-07-09T16:39:50.990000 | 2020-02-14T01:52:46 | 2020-02-14T01:52:46 | 220,406,157 | 0 | 0 | null | false | 2022-06-21T02:11:42 | 2019-11-08T06:59:16 | 2020-02-14T01:52:46 | 2022-06-21T02:11:40 | 23,283 | 0 | 0 | 17 | Python | false | false | package how2j.javathread.chapter1;
import java.util.concurrent.TimeUnit;
public class TryConcurrency {
private static void browseNews()
{
for(;;)
{
System.out.println("uh-hum,the good nows");
sleep(1);
}
}
private static void sleep(int seconds)
{
try{
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void enjoyMusic(){
for (;;){
System.out.println("uh-huh,this nice musice");
sleep(1);
}
}
public static void main(String[] args) throws InterruptedException {
// thread1();
//thread2();
thread3();
}
private static void thread1(){
new Thread(TryConcurrency::enjoyMusic).start();
browseNews();
}
private static void thread2() throws InterruptedException {
Thread thread = new Thread(){
@Override
public void run(){
try{
TimeUnit.SECONDS.sleep(1);
System.out.println("over");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
TimeUnit.SECONDS.sleep(2);
thread.start();
}
public static class TicketWindow extends Thread{
private final String name;
private static final int Max=40;
private int index=1;
public TicketWindow(String name) {
this.name=name;
}
@Override
public void run() {
while (index<= Max){
System.out.println("柜台:"+name+"当前号码是: "+(index++));
}
}
}
private static void thread3(){
TicketWindow ticketWindow= new TicketWindow("一号出号机");
TicketWindow ticketWindow2= new TicketWindow("二号出号机");
TicketWindow ticketWindow3= new TicketWindow("三号出号机");
TicketWindow ticketWindow4= new TicketWindow("四号出号机");
ticketWindow.start();
ticketWindow2.start();
ticketWindow3.start();
ticketWindow4.start();
}
}
| UTF-8 | Java | 2,271 | java | TryConcurrency.java | Java | [] | null | [] | package how2j.javathread.chapter1;
import java.util.concurrent.TimeUnit;
public class TryConcurrency {
private static void browseNews()
{
for(;;)
{
System.out.println("uh-hum,the good nows");
sleep(1);
}
}
private static void sleep(int seconds)
{
try{
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void enjoyMusic(){
for (;;){
System.out.println("uh-huh,this nice musice");
sleep(1);
}
}
public static void main(String[] args) throws InterruptedException {
// thread1();
//thread2();
thread3();
}
private static void thread1(){
new Thread(TryConcurrency::enjoyMusic).start();
browseNews();
}
private static void thread2() throws InterruptedException {
Thread thread = new Thread(){
@Override
public void run(){
try{
TimeUnit.SECONDS.sleep(1);
System.out.println("over");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
TimeUnit.SECONDS.sleep(2);
thread.start();
}
public static class TicketWindow extends Thread{
private final String name;
private static final int Max=40;
private int index=1;
public TicketWindow(String name) {
this.name=name;
}
@Override
public void run() {
while (index<= Max){
System.out.println("柜台:"+name+"当前号码是: "+(index++));
}
}
}
private static void thread3(){
TicketWindow ticketWindow= new TicketWindow("一号出号机");
TicketWindow ticketWindow2= new TicketWindow("二号出号机");
TicketWindow ticketWindow3= new TicketWindow("三号出号机");
TicketWindow ticketWindow4= new TicketWindow("四号出号机");
ticketWindow.start();
ticketWindow2.start();
ticketWindow3.start();
ticketWindow4.start();
}
}
| 2,271 | 0.532251 | 0.522327 | 93 | 22.838709 | 19.893961 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.419355 | false | false | 2 |
c9cf482a82bb75219853aadd1d5ca0c9ae7bc447 | 12,781,822,688,013 | ca4d073463695a244251c1743ec177c098be7edb | /src/uta/ak/usttmp/common/model/MiningTaskLog.java | 2575b58e179bd08460191ca30696d63d21873153 | [] | no_license | zhangcong2711/usttmp_common | https://github.com/zhangcong2711/usttmp_common | c417573a1b41e4f05b08a285cd1cec6ed20ae7a6 | 79965ced370be3eb2c435b74cd1b73e8e755e1f9 | refs/heads/master | 2020-12-25T14:24:16.958000 | 2016-10-13T16:50:23 | 2016-10-13T16:50:23 | 63,511,051 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package uta.ak.usttmp.common.model;
import java.util.Date;
/**
*
* @author zhangcong
*/
public class MiningTaskLog {
public final static int TYPE_INFO=1;
public final static int TYPE_EXCEPTION=2;
private long id;
private int type;
private Date occurrenceTime;
private String info;
private long miningTaskId;
/**
* @return the id
*/
public long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the type
*/
public int getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(int type) {
this.type = type;
}
/**
* @return the occurrenceTime
*/
public Date getOccurrenceTime() {
return occurrenceTime;
}
/**
* @param occurrenceTime the occurrenceTime to set
*/
public void setOccurrenceTime(Date occurrenceTime) {
this.occurrenceTime = occurrenceTime;
}
/**
* @return the info
*/
public String getInfo() {
return info.replaceAll("[\\t\\n\\r]", " ");
}
/**
* @param info the info to set
*/
public void setInfo(String info) {
this.info = info;
}
/**
* @return the miningTaskId
*/
public long getMiningTaskId() {
return miningTaskId;
}
/**
* @param miningTaskId the miningTaskId to set
*/
public void setMiningTaskId(long miningTaskId) {
this.miningTaskId = miningTaskId;
}
}
| UTF-8 | Java | 1,830 | java | MiningTaskLog.java | Java | [
{
"context": ".model;\n\nimport java.util.Date;\n\n/**\n *\n * @author zhangcong\n */\npublic class MiningTaskLog {\n \n public ",
"end": 273,
"score": 0.9996047019958496,
"start": 264,
"tag": "USERNAME",
"value": "zhangcong"
}
] | 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 uta.ak.usttmp.common.model;
import java.util.Date;
/**
*
* @author zhangcong
*/
public class MiningTaskLog {
public final static int TYPE_INFO=1;
public final static int TYPE_EXCEPTION=2;
private long id;
private int type;
private Date occurrenceTime;
private String info;
private long miningTaskId;
/**
* @return the id
*/
public long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the type
*/
public int getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(int type) {
this.type = type;
}
/**
* @return the occurrenceTime
*/
public Date getOccurrenceTime() {
return occurrenceTime;
}
/**
* @param occurrenceTime the occurrenceTime to set
*/
public void setOccurrenceTime(Date occurrenceTime) {
this.occurrenceTime = occurrenceTime;
}
/**
* @return the info
*/
public String getInfo() {
return info.replaceAll("[\\t\\n\\r]", " ");
}
/**
* @param info the info to set
*/
public void setInfo(String info) {
this.info = info;
}
/**
* @return the miningTaskId
*/
public long getMiningTaskId() {
return miningTaskId;
}
/**
* @param miningTaskId the miningTaskId to set
*/
public void setMiningTaskId(long miningTaskId) {
this.miningTaskId = miningTaskId;
}
}
| 1,830 | 0.561202 | 0.560109 | 99 | 17.484848 | 17.22364 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.232323 | false | false | 2 |
cebac610c609a7a27c620ad33fbeb78108eed5a5 | 31,061,203,541,935 | d71e879b3517cf4fccde29f7bf82cff69856cfcd | /ExtractedJars/Ibotta_com.ibotta.android/javafiles/com/apollographql/apollo/exception/ApolloHttpException.java | 4985ee307432d2dc6ec536a853b4fa1d25545fa2 | [
"MIT"
] | permissive | Andreas237/AndroidPolicyAutomation | https://github.com/Andreas237/AndroidPolicyAutomation | b8e949e072d08cf6c6166c3f15c9c63379b8f6ce | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | refs/heads/master | 2020-04-10T02:14:08.789000 | 2019-05-16T19:29:11 | 2019-05-16T19:29:11 | 160,739,088 | 5 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.apollographql.apollo.exception;
import okhttp3.Response;
// Referenced classes of package com.apollographql.apollo.exception:
// ApolloException
public final class ApolloHttpException extends ApolloException
{
public ApolloHttpException(Response response)
{
super(formatMessage(response));
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokestatic #17 <Method String formatMessage(Response)>
// 3 5:invokespecial #20 <Method void ApolloException(String)>
int i;
if(response != null)
//* 4 8:aload_1
//* 5 9:ifnull 20
i = response.code();
// 6 12:aload_1
// 7 13:invokevirtual #25 <Method int Response.code()>
// 8 16:istore_2
else
//* 9 17:goto 22
i = 0;
// 10 20:iconst_0
// 11 21:istore_2
code = i;
// 12 22:aload_0
// 13 23:iload_2
// 14 24:putfield #27 <Field int code>
String s;
if(response != null)
//* 15 27:aload_1
//* 16 28:ifnull 39
s = response.message();
// 17 31:aload_1
// 18 32:invokevirtual #30 <Method String Response.message()>
// 19 35:astore_3
else
//* 20 36:goto 42
s = "";
// 21 39:ldc1 #32 <String "">
// 22 41:astore_3
message = s;
// 23 42:aload_0
// 24 43:aload_3
// 25 44:putfield #34 <Field String message>
rawResponse = response;
// 26 47:aload_0
// 27 48:aload_1
// 28 49:putfield #36 <Field Response rawResponse>
// 29 52:return
}
private static String formatMessage(Response response)
{
if(response == null)
//* 0 0:aload_0
//* 1 1:ifnonnull 7
{
return "Empty HTTP response";
// 2 4:ldc1 #40 <String "Empty HTTP response">
// 3 6:areturn
} else
{
StringBuilder stringbuilder = new StringBuilder();
// 4 7:new #42 <Class StringBuilder>
// 5 10:dup
// 6 11:invokespecial #45 <Method void StringBuilder()>
// 7 14:astore_1
stringbuilder.append("HTTP ");
// 8 15:aload_1
// 9 16:ldc1 #47 <String "HTTP ">
// 10 18:invokevirtual #51 <Method StringBuilder StringBuilder.append(String)>
// 11 21:pop
stringbuilder.append(response.code());
// 12 22:aload_1
// 13 23:aload_0
// 14 24:invokevirtual #25 <Method int Response.code()>
// 15 27:invokevirtual #54 <Method StringBuilder StringBuilder.append(int)>
// 16 30:pop
stringbuilder.append(" ");
// 17 31:aload_1
// 18 32:ldc1 #56 <String " ">
// 19 34:invokevirtual #51 <Method StringBuilder StringBuilder.append(String)>
// 20 37:pop
stringbuilder.append(response.message());
// 21 38:aload_1
// 22 39:aload_0
// 23 40:invokevirtual #30 <Method String Response.message()>
// 24 43:invokevirtual #51 <Method StringBuilder StringBuilder.append(String)>
// 25 46:pop
return stringbuilder.toString();
// 26 47:aload_1
// 27 48:invokevirtual #59 <Method String StringBuilder.toString()>
// 28 51:areturn
}
}
public Response rawResponse()
{
return rawResponse;
// 0 0:aload_0
// 1 1:getfield #36 <Field Response rawResponse>
// 2 4:areturn
}
private final int code;
private final String message;
private final transient Response rawResponse;
}
| UTF-8 | Java | 3,923 | java | ApolloHttpException.java | Java | [
{
"context": "// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.kpdus.com/jad.html\n",
"end": 61,
"score": 0.9995894432067871,
"start": 45,
"tag": "NAME",
"value": "Pavel Kouznetsov"
}
] | null | [] | // Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.apollographql.apollo.exception;
import okhttp3.Response;
// Referenced classes of package com.apollographql.apollo.exception:
// ApolloException
public final class ApolloHttpException extends ApolloException
{
public ApolloHttpException(Response response)
{
super(formatMessage(response));
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokestatic #17 <Method String formatMessage(Response)>
// 3 5:invokespecial #20 <Method void ApolloException(String)>
int i;
if(response != null)
//* 4 8:aload_1
//* 5 9:ifnull 20
i = response.code();
// 6 12:aload_1
// 7 13:invokevirtual #25 <Method int Response.code()>
// 8 16:istore_2
else
//* 9 17:goto 22
i = 0;
// 10 20:iconst_0
// 11 21:istore_2
code = i;
// 12 22:aload_0
// 13 23:iload_2
// 14 24:putfield #27 <Field int code>
String s;
if(response != null)
//* 15 27:aload_1
//* 16 28:ifnull 39
s = response.message();
// 17 31:aload_1
// 18 32:invokevirtual #30 <Method String Response.message()>
// 19 35:astore_3
else
//* 20 36:goto 42
s = "";
// 21 39:ldc1 #32 <String "">
// 22 41:astore_3
message = s;
// 23 42:aload_0
// 24 43:aload_3
// 25 44:putfield #34 <Field String message>
rawResponse = response;
// 26 47:aload_0
// 27 48:aload_1
// 28 49:putfield #36 <Field Response rawResponse>
// 29 52:return
}
private static String formatMessage(Response response)
{
if(response == null)
//* 0 0:aload_0
//* 1 1:ifnonnull 7
{
return "Empty HTTP response";
// 2 4:ldc1 #40 <String "Empty HTTP response">
// 3 6:areturn
} else
{
StringBuilder stringbuilder = new StringBuilder();
// 4 7:new #42 <Class StringBuilder>
// 5 10:dup
// 6 11:invokespecial #45 <Method void StringBuilder()>
// 7 14:astore_1
stringbuilder.append("HTTP ");
// 8 15:aload_1
// 9 16:ldc1 #47 <String "HTTP ">
// 10 18:invokevirtual #51 <Method StringBuilder StringBuilder.append(String)>
// 11 21:pop
stringbuilder.append(response.code());
// 12 22:aload_1
// 13 23:aload_0
// 14 24:invokevirtual #25 <Method int Response.code()>
// 15 27:invokevirtual #54 <Method StringBuilder StringBuilder.append(int)>
// 16 30:pop
stringbuilder.append(" ");
// 17 31:aload_1
// 18 32:ldc1 #56 <String " ">
// 19 34:invokevirtual #51 <Method StringBuilder StringBuilder.append(String)>
// 20 37:pop
stringbuilder.append(response.message());
// 21 38:aload_1
// 22 39:aload_0
// 23 40:invokevirtual #30 <Method String Response.message()>
// 24 43:invokevirtual #51 <Method StringBuilder StringBuilder.append(String)>
// 25 46:pop
return stringbuilder.toString();
// 26 47:aload_1
// 27 48:invokevirtual #59 <Method String StringBuilder.toString()>
// 28 51:areturn
}
}
public Response rawResponse()
{
return rawResponse;
// 0 0:aload_0
// 1 1:getfield #36 <Field Response rawResponse>
// 2 4:areturn
}
private final int code;
private final String message;
private final transient Response rawResponse;
}
| 3,913 | 0.539383 | 0.462146 | 119 | 31.966387 | 21.851652 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.386555 | false | false | 2 |
c59242dd71d6a2ab497d90a2dba1d9984811d3d4 | 30,554,397,377,457 | 3f7028cc89a79582266a19acbde0d6b066a568de | /mobile/library/java/org/chromium/net/impl/CronvoyUrlRequestContext.java | 3abb0927dfad000cbe1bf945a147472361ba1a62 | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | envoyproxy/envoy | https://github.com/envoyproxy/envoy | 882d3c7f316bf755889fb628bee514bb2f6f66f0 | 72f129d273fa32f49581db3abbaf4b62e3e3703c | refs/heads/main | 2023-08-31T09:20:01.278000 | 2023-08-31T08:58:36 | 2023-08-31T08:58:36 | 65,214,191 | 21,404 | 4,756 | Apache-2.0 | false | 2023-09-14T21:56:37 | 2016-08-08T15:07:24 | 2023-09-14T19:23:27 | 2023-09-14T21:56:37 | 224,766 | 22,716 | 4,459 | 1,554 | C++ | false | false | package org.chromium.net.impl;
import static android.os.Process.THREAD_PRIORITY_BACKGROUND;
import static android.os.Process.THREAD_PRIORITY_MORE_FAVORABLE;
import android.os.ConditionVariable;
import androidx.annotation.GuardedBy;
import androidx.annotation.VisibleForTesting;
import io.envoyproxy.envoymobile.engine.EnvoyEngine;
import java.io.IOException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandlerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.chromium.net.BidirectionalStream;
import org.chromium.net.ExperimentalBidirectionalStream;
import org.chromium.net.NetworkQualityRttListener;
import org.chromium.net.NetworkQualityThroughputListener;
import org.chromium.net.RequestFinishedInfo;
import org.chromium.net.UrlRequest;
import org.chromium.net.impl.CronvoyVersionSafeCallbacks.RequestFinishedInfoListener;
import org.chromium.net.urlconnection.CronvoyHttpURLConnection;
import org.chromium.net.urlconnection.CronvoyURLStreamHandlerFactory;
/**
* Cronvoy engine shim.
*
* <p>Does not support yet netlogs, transferred data measurement, bidistream, cache, or priority.
*/
public final class CronvoyUrlRequestContext extends CronvoyEngineBase {
static final String LOG_TAG = CronvoyUrlRequestContext.class.getSimpleName();
/**
* Synchronize access to mUrlRequestContextAdapter and shutdown routine.
*/
private final Object mLock = new Object();
private final ConditionVariable mInitCompleted = new ConditionVariable(false);
private final AtomicInteger mActiveRequestCount = new AtomicInteger(0);
@GuardedBy("mLock") private EnvoyEngine mEngine;
/**
* This field is accessed without synchronization, but only for the purposes of reference
* equality comparison with other threads. If such a comparison is performed on the network
* thread, then there is a happens-before edge between the write of this field and the
* subsequent read; if it's performed on another thread, then observing a value of null won't
* change the result of the comparison.
*/
private Thread mNetworkThread;
private final String mUserAgent;
private final CronvoyEngineBuilderImpl mBuilder;
private final AtomicReference<Runnable> mInitializationCompleter = new AtomicReference<>();
/**
* Locks operations on the list of RequestFinishedInfo.Listeners, because operations can happen
* on any thread. This should be used for fine-grained locking only. In particular, don't call
* any UrlRequest methods that acquire mUrlRequestAdapterLock while holding this lock.
*/
private final Object mFinishedListenerLock = new Object();
@GuardedBy("mFinishedListenerLock")
private final Map<RequestFinishedInfo.Listener,
CronvoyVersionSafeCallbacks.RequestFinishedInfoListener> mFinishedListenerMap =
new HashMap<>();
public CronvoyUrlRequestContext(NativeCronvoyEngineBuilderImpl builder) {
mBuilder = builder;
// On android, all background threads (and all threads that are part
// of background processes) are put in a cgroup that is allowed to
// consume up to 5% of CPU - these worker threads spend the vast
// majority of their time waiting on I/O, so making them contend with
// background applications for a slice of CPU doesn't make much sense.
// We want to hurry up and get idle.
final int threadPriority =
builder.threadPriority(THREAD_PRIORITY_BACKGROUND + THREAD_PRIORITY_MORE_FAVORABLE);
mUserAgent = builder.getUserAgent();
synchronized (mLock) {
mEngine = builder.createEngine(() -> {
mNetworkThread = Thread.currentThread();
android.os.Process.setThreadPriority(threadPriority);
mInitCompleted.open();
Runnable taskToExecuteWhenInitializationIsCompleted =
mInitializationCompleter.getAndSet(() -> {});
if (taskToExecuteWhenInitializationIsCompleted != null) {
taskToExecuteWhenInitializationIsCompleted.run();
}
return null;
});
}
}
public EnvoyEngine getEnvoyEngine() {
synchronized (mLock) {
if (mEngine == null) {
throw new IllegalStateException("Engine is shut down.");
}
return mEngine;
}
}
CronvoyEngineBuilderImpl getBuilder() { return mBuilder; }
void setTaskToExecuteWhenInitializationIsCompleted(Runnable runnable) {
if (!mInitializationCompleter.compareAndSet(null, runnable)) {
// The fact that the initializationCompleter was not null implies that the initialization
// callback has already been executed. In this case, execute the task now - nothing else will
// ever execute it otherwise.
runnable.run();
}
}
@Override
public CronvoyUrlRequestBase
createRequest(String url, UrlRequest.Callback callback, Executor executor, int priority,
Collection<Object> requestAnnotations, boolean disableCache,
boolean disableConnectionMigration, boolean allowDirectExecutor,
boolean trafficStatsTagSet, int trafficStatsTag, boolean trafficStatsUidSet,
int trafficStatsUid, RequestFinishedInfo.Listener requestFinishedListener,
int idempotency) {
synchronized (mLock) {
checkHaveAdapter();
return new CronvoyUrlRequest(this, url, callback, executor, mUserAgent, allowDirectExecutor,
requestAnnotations, trafficStatsTagSet, trafficStatsTag,
trafficStatsUidSet, trafficStatsUid, requestFinishedListener);
}
}
@Override
protected ExperimentalBidirectionalStream
createBidirectionalStream(String url, BidirectionalStream.Callback callback, Executor executor,
String httpMethod, List<Map.Entry<String, String>> requestHeaders,
@StreamPriority int priority,
boolean delayRequestHeadersUntilFirstFlush,
Collection<Object> requestAnnotations, boolean trafficStatsTagSet,
int trafficStatsTag, boolean trafficStatsUidSet, int trafficStatsUid) {
synchronized (mLock) {
checkHaveAdapter();
return new CronvoyBidirectionalStream(
this, url, priority, callback, executor, mUserAgent, httpMethod, requestHeaders,
delayRequestHeadersUntilFirstFlush, requestAnnotations, trafficStatsTagSet,
trafficStatsTag, trafficStatsUidSet, trafficStatsUid);
}
}
@Override
public ExperimentalBidirectionalStream.Builder
newBidirectionalStreamBuilder(String url, BidirectionalStream.Callback callback,
Executor executor) {
return new CronvoyBidirectionalStreamBuilderImpl(url, callback, executor, this);
}
@Override
public String getVersionString() {
return "Cronet/" + CronvoyImplVersion.getCronetVersionWithLastChange();
}
@Override
public void shutdown() {
synchronized (mLock) {
checkHaveAdapter();
if (mActiveRequestCount.get() != 0) {
throw new IllegalStateException("Cannot shutdown with active requests.");
}
// Destroying adapter stops the network thread, so it cannot be
// called on network thread.
if (Thread.currentThread() == mNetworkThread) {
throw new IllegalThreadStateException("Cannot shutdown from network thread.");
}
}
// Wait for init to complete on init and network thread (without lock,
// so other thread could access it).
mInitCompleted.block();
// If not logging, this is a no-op.
stopNetLog();
synchronized (mLock) {
// It is possible that adapter is already destroyed on another thread.
if (!haveRequestContextAdapter()) {
return;
}
mEngine.terminate();
mEngine = null;
}
}
@Override
public void startNetLogToFile(String fileName, boolean logAll) {}
@Override
public void startNetLogToDisk(String dirPath, boolean logAll, int maxSize) {}
@Override
public void stopNetLog() {}
@Override
public byte[] getGlobalMetricsDeltas() {
return new byte[0];
}
@Override
public int getEffectiveConnectionType() {
return EFFECTIVE_CONNECTION_TYPE_UNKNOWN;
}
@Override
public int getHttpRttMs() {
return CONNECTION_METRIC_UNKNOWN;
}
@Override
public int getTransportRttMs() {
return CONNECTION_METRIC_UNKNOWN;
}
@Override
public int getDownstreamThroughputKbps() {
return CONNECTION_METRIC_UNKNOWN;
}
@Override
public void configureNetworkQualityEstimatorForTesting(boolean useLocalHostRequests,
boolean useSmallerResponses,
boolean disableOfflineCheck) {}
@Override
public void addRttListener(NetworkQualityRttListener listener) {}
@Override
public void removeRttListener(NetworkQualityRttListener listener) {}
@Override
public void addThroughputListener(NetworkQualityThroughputListener listener) {}
@Override
public void removeThroughputListener(NetworkQualityThroughputListener listener) {}
@Override
public void addRequestFinishedListener(RequestFinishedInfo.Listener listener) {
synchronized (mFinishedListenerLock) {
mFinishedListenerMap.put(
listener, new CronvoyVersionSafeCallbacks.RequestFinishedInfoListener(listener));
}
}
@Override
public void removeRequestFinishedListener(RequestFinishedInfo.Listener listener) {
synchronized (mFinishedListenerLock) { mFinishedListenerMap.remove(listener); }
}
boolean hasRequestFinishedListener() {
synchronized (mFinishedListenerLock) { return !mFinishedListenerMap.isEmpty(); }
}
@Override
public URLConnection openConnection(URL url) throws IOException {
return openConnection(url, Proxy.NO_PROXY);
}
@Override
public URLConnection openConnection(URL url, Proxy proxy) {
if (proxy.type() != Proxy.Type.DIRECT) {
throw new UnsupportedOperationException();
}
String protocol = url.getProtocol();
if ("http".equals(protocol) || "https".equals(protocol)) {
return new CronvoyHttpURLConnection(url, this);
}
throw new UnsupportedOperationException("Unexpected protocol:" + protocol);
}
@Override
public URLStreamHandlerFactory createURLStreamHandlerFactory() {
return new CronvoyURLStreamHandlerFactory(this);
}
/**
* Mark request as started to prevent shutdown when there are active
* requests.
*/
void onRequestStarted() { mActiveRequestCount.incrementAndGet(); }
/**
* Mark request as finished to allow shutdown when there are no active
* requests.
*/
void onRequestDestroyed() { mActiveRequestCount.decrementAndGet(); }
boolean isNetworkThread(Thread thread) { return thread == mNetworkThread; }
@VisibleForTesting
public boolean hasShutdown() {
synchronized (mLock) { return !haveRequestContextAdapter(); }
}
@GuardedBy("mLock")
private void checkHaveAdapter() throws IllegalStateException {
if (!haveRequestContextAdapter()) {
throw new IllegalStateException("Engine is shut down.");
}
}
@GuardedBy("mLock")
private boolean haveRequestContextAdapter() {
return mEngine != null;
}
void reportRequestFinished(final RequestFinishedInfo requestInfo) {
List<RequestFinishedInfoListener> currentListeners;
synchronized (mFinishedListenerLock) {
if (mFinishedListenerMap.isEmpty()) {
return;
}
currentListeners = new ArrayList<>(mFinishedListenerMap.values());
}
for (final CronvoyVersionSafeCallbacks.RequestFinishedInfoListener listener :
currentListeners) {
Runnable task = new Runnable() {
@Override
public void run() {
listener.onRequestFinished(requestInfo);
}
};
postObservationTaskToExecutor(listener.getExecutor(), task);
}
}
private static void postObservationTaskToExecutor(Executor executor, Runnable task) {
try {
executor.execute(task);
} catch (RejectedExecutionException failException) {
// TODO(https://github.com/envoyproxy/envoy-mobile/issues/2262): go with Cronet ways for logs.
android.util.Log.e(CronvoyUrlRequestContext.LOG_TAG, "Exception posting task to executor",
failException);
}
}
}
| UTF-8 | Java | 12,667 | java | CronvoyUrlRequestContext.java | Java | [
{
"context": "failException) {\n // TODO(https://github.com/envoyproxy/envoy-mobile/issues/2262): go with Cronet ways fo",
"end": 12459,
"score": 0.9985612034797668,
"start": 12449,
"tag": "USERNAME",
"value": "envoyproxy"
}
] | null | [] | package org.chromium.net.impl;
import static android.os.Process.THREAD_PRIORITY_BACKGROUND;
import static android.os.Process.THREAD_PRIORITY_MORE_FAVORABLE;
import android.os.ConditionVariable;
import androidx.annotation.GuardedBy;
import androidx.annotation.VisibleForTesting;
import io.envoyproxy.envoymobile.engine.EnvoyEngine;
import java.io.IOException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandlerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.chromium.net.BidirectionalStream;
import org.chromium.net.ExperimentalBidirectionalStream;
import org.chromium.net.NetworkQualityRttListener;
import org.chromium.net.NetworkQualityThroughputListener;
import org.chromium.net.RequestFinishedInfo;
import org.chromium.net.UrlRequest;
import org.chromium.net.impl.CronvoyVersionSafeCallbacks.RequestFinishedInfoListener;
import org.chromium.net.urlconnection.CronvoyHttpURLConnection;
import org.chromium.net.urlconnection.CronvoyURLStreamHandlerFactory;
/**
* Cronvoy engine shim.
*
* <p>Does not support yet netlogs, transferred data measurement, bidistream, cache, or priority.
*/
public final class CronvoyUrlRequestContext extends CronvoyEngineBase {
static final String LOG_TAG = CronvoyUrlRequestContext.class.getSimpleName();
/**
* Synchronize access to mUrlRequestContextAdapter and shutdown routine.
*/
private final Object mLock = new Object();
private final ConditionVariable mInitCompleted = new ConditionVariable(false);
private final AtomicInteger mActiveRequestCount = new AtomicInteger(0);
@GuardedBy("mLock") private EnvoyEngine mEngine;
/**
* This field is accessed without synchronization, but only for the purposes of reference
* equality comparison with other threads. If such a comparison is performed on the network
* thread, then there is a happens-before edge between the write of this field and the
* subsequent read; if it's performed on another thread, then observing a value of null won't
* change the result of the comparison.
*/
private Thread mNetworkThread;
private final String mUserAgent;
private final CronvoyEngineBuilderImpl mBuilder;
private final AtomicReference<Runnable> mInitializationCompleter = new AtomicReference<>();
/**
* Locks operations on the list of RequestFinishedInfo.Listeners, because operations can happen
* on any thread. This should be used for fine-grained locking only. In particular, don't call
* any UrlRequest methods that acquire mUrlRequestAdapterLock while holding this lock.
*/
private final Object mFinishedListenerLock = new Object();
@GuardedBy("mFinishedListenerLock")
private final Map<RequestFinishedInfo.Listener,
CronvoyVersionSafeCallbacks.RequestFinishedInfoListener> mFinishedListenerMap =
new HashMap<>();
public CronvoyUrlRequestContext(NativeCronvoyEngineBuilderImpl builder) {
mBuilder = builder;
// On android, all background threads (and all threads that are part
// of background processes) are put in a cgroup that is allowed to
// consume up to 5% of CPU - these worker threads spend the vast
// majority of their time waiting on I/O, so making them contend with
// background applications for a slice of CPU doesn't make much sense.
// We want to hurry up and get idle.
final int threadPriority =
builder.threadPriority(THREAD_PRIORITY_BACKGROUND + THREAD_PRIORITY_MORE_FAVORABLE);
mUserAgent = builder.getUserAgent();
synchronized (mLock) {
mEngine = builder.createEngine(() -> {
mNetworkThread = Thread.currentThread();
android.os.Process.setThreadPriority(threadPriority);
mInitCompleted.open();
Runnable taskToExecuteWhenInitializationIsCompleted =
mInitializationCompleter.getAndSet(() -> {});
if (taskToExecuteWhenInitializationIsCompleted != null) {
taskToExecuteWhenInitializationIsCompleted.run();
}
return null;
});
}
}
public EnvoyEngine getEnvoyEngine() {
synchronized (mLock) {
if (mEngine == null) {
throw new IllegalStateException("Engine is shut down.");
}
return mEngine;
}
}
CronvoyEngineBuilderImpl getBuilder() { return mBuilder; }
void setTaskToExecuteWhenInitializationIsCompleted(Runnable runnable) {
if (!mInitializationCompleter.compareAndSet(null, runnable)) {
// The fact that the initializationCompleter was not null implies that the initialization
// callback has already been executed. In this case, execute the task now - nothing else will
// ever execute it otherwise.
runnable.run();
}
}
@Override
public CronvoyUrlRequestBase
createRequest(String url, UrlRequest.Callback callback, Executor executor, int priority,
Collection<Object> requestAnnotations, boolean disableCache,
boolean disableConnectionMigration, boolean allowDirectExecutor,
boolean trafficStatsTagSet, int trafficStatsTag, boolean trafficStatsUidSet,
int trafficStatsUid, RequestFinishedInfo.Listener requestFinishedListener,
int idempotency) {
synchronized (mLock) {
checkHaveAdapter();
return new CronvoyUrlRequest(this, url, callback, executor, mUserAgent, allowDirectExecutor,
requestAnnotations, trafficStatsTagSet, trafficStatsTag,
trafficStatsUidSet, trafficStatsUid, requestFinishedListener);
}
}
@Override
protected ExperimentalBidirectionalStream
createBidirectionalStream(String url, BidirectionalStream.Callback callback, Executor executor,
String httpMethod, List<Map.Entry<String, String>> requestHeaders,
@StreamPriority int priority,
boolean delayRequestHeadersUntilFirstFlush,
Collection<Object> requestAnnotations, boolean trafficStatsTagSet,
int trafficStatsTag, boolean trafficStatsUidSet, int trafficStatsUid) {
synchronized (mLock) {
checkHaveAdapter();
return new CronvoyBidirectionalStream(
this, url, priority, callback, executor, mUserAgent, httpMethod, requestHeaders,
delayRequestHeadersUntilFirstFlush, requestAnnotations, trafficStatsTagSet,
trafficStatsTag, trafficStatsUidSet, trafficStatsUid);
}
}
@Override
public ExperimentalBidirectionalStream.Builder
newBidirectionalStreamBuilder(String url, BidirectionalStream.Callback callback,
Executor executor) {
return new CronvoyBidirectionalStreamBuilderImpl(url, callback, executor, this);
}
@Override
public String getVersionString() {
return "Cronet/" + CronvoyImplVersion.getCronetVersionWithLastChange();
}
@Override
public void shutdown() {
synchronized (mLock) {
checkHaveAdapter();
if (mActiveRequestCount.get() != 0) {
throw new IllegalStateException("Cannot shutdown with active requests.");
}
// Destroying adapter stops the network thread, so it cannot be
// called on network thread.
if (Thread.currentThread() == mNetworkThread) {
throw new IllegalThreadStateException("Cannot shutdown from network thread.");
}
}
// Wait for init to complete on init and network thread (without lock,
// so other thread could access it).
mInitCompleted.block();
// If not logging, this is a no-op.
stopNetLog();
synchronized (mLock) {
// It is possible that adapter is already destroyed on another thread.
if (!haveRequestContextAdapter()) {
return;
}
mEngine.terminate();
mEngine = null;
}
}
@Override
public void startNetLogToFile(String fileName, boolean logAll) {}
@Override
public void startNetLogToDisk(String dirPath, boolean logAll, int maxSize) {}
@Override
public void stopNetLog() {}
@Override
public byte[] getGlobalMetricsDeltas() {
return new byte[0];
}
@Override
public int getEffectiveConnectionType() {
return EFFECTIVE_CONNECTION_TYPE_UNKNOWN;
}
@Override
public int getHttpRttMs() {
return CONNECTION_METRIC_UNKNOWN;
}
@Override
public int getTransportRttMs() {
return CONNECTION_METRIC_UNKNOWN;
}
@Override
public int getDownstreamThroughputKbps() {
return CONNECTION_METRIC_UNKNOWN;
}
@Override
public void configureNetworkQualityEstimatorForTesting(boolean useLocalHostRequests,
boolean useSmallerResponses,
boolean disableOfflineCheck) {}
@Override
public void addRttListener(NetworkQualityRttListener listener) {}
@Override
public void removeRttListener(NetworkQualityRttListener listener) {}
@Override
public void addThroughputListener(NetworkQualityThroughputListener listener) {}
@Override
public void removeThroughputListener(NetworkQualityThroughputListener listener) {}
@Override
public void addRequestFinishedListener(RequestFinishedInfo.Listener listener) {
synchronized (mFinishedListenerLock) {
mFinishedListenerMap.put(
listener, new CronvoyVersionSafeCallbacks.RequestFinishedInfoListener(listener));
}
}
@Override
public void removeRequestFinishedListener(RequestFinishedInfo.Listener listener) {
synchronized (mFinishedListenerLock) { mFinishedListenerMap.remove(listener); }
}
boolean hasRequestFinishedListener() {
synchronized (mFinishedListenerLock) { return !mFinishedListenerMap.isEmpty(); }
}
@Override
public URLConnection openConnection(URL url) throws IOException {
return openConnection(url, Proxy.NO_PROXY);
}
@Override
public URLConnection openConnection(URL url, Proxy proxy) {
if (proxy.type() != Proxy.Type.DIRECT) {
throw new UnsupportedOperationException();
}
String protocol = url.getProtocol();
if ("http".equals(protocol) || "https".equals(protocol)) {
return new CronvoyHttpURLConnection(url, this);
}
throw new UnsupportedOperationException("Unexpected protocol:" + protocol);
}
@Override
public URLStreamHandlerFactory createURLStreamHandlerFactory() {
return new CronvoyURLStreamHandlerFactory(this);
}
/**
* Mark request as started to prevent shutdown when there are active
* requests.
*/
void onRequestStarted() { mActiveRequestCount.incrementAndGet(); }
/**
* Mark request as finished to allow shutdown when there are no active
* requests.
*/
void onRequestDestroyed() { mActiveRequestCount.decrementAndGet(); }
boolean isNetworkThread(Thread thread) { return thread == mNetworkThread; }
@VisibleForTesting
public boolean hasShutdown() {
synchronized (mLock) { return !haveRequestContextAdapter(); }
}
@GuardedBy("mLock")
private void checkHaveAdapter() throws IllegalStateException {
if (!haveRequestContextAdapter()) {
throw new IllegalStateException("Engine is shut down.");
}
}
@GuardedBy("mLock")
private boolean haveRequestContextAdapter() {
return mEngine != null;
}
void reportRequestFinished(final RequestFinishedInfo requestInfo) {
List<RequestFinishedInfoListener> currentListeners;
synchronized (mFinishedListenerLock) {
if (mFinishedListenerMap.isEmpty()) {
return;
}
currentListeners = new ArrayList<>(mFinishedListenerMap.values());
}
for (final CronvoyVersionSafeCallbacks.RequestFinishedInfoListener listener :
currentListeners) {
Runnable task = new Runnable() {
@Override
public void run() {
listener.onRequestFinished(requestInfo);
}
};
postObservationTaskToExecutor(listener.getExecutor(), task);
}
}
private static void postObservationTaskToExecutor(Executor executor, Runnable task) {
try {
executor.execute(task);
} catch (RejectedExecutionException failException) {
// TODO(https://github.com/envoyproxy/envoy-mobile/issues/2262): go with Cronet ways for logs.
android.util.Log.e(CronvoyUrlRequestContext.LOG_TAG, "Exception posting task to executor",
failException);
}
}
}
| 12,667 | 0.721086 | 0.720455 | 346 | 35.609825 | 31.367592 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.531792 | false | false | 2 |
6533779d88aa5e7e04197ddb95bffc38118b4c57 | 33,784,212,752,235 | c9f5959e9604f196ee0a20ddf39bb0bdeecf54b6 | /SkInfoReport/app/src/main/java/sdk/report/TagPlayHeartBeat.java | 11edb069bf06279b1666fdcfba43e744dea11acd | [
"Apache-2.0"
] | permissive | isuker/SdkReportCenter | https://github.com/isuker/SdkReportCenter | 4001d3256b295e4af23cdd9960717b7c1dce4587 | 0d61d586a3254e9fbd05dabad430a8ca80f58e4a | refs/heads/master | 2021-01-01T03:35:22.302000 | 2016-04-18T12:56:36 | 2016-04-18T12:56:36 | 55,977,595 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sdk.report;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by suker on 16-4-6.
*/
public class TagPlayHeartBeat {
private final static String TAG = "SdkReport_" + SysNetwork.class.getSimpleName();
private ReportCenter rcCtx = null;
public TagPlayHeartBeat(ReportCenter rc) {
rcCtx = rc;
}
public JSONObject toJson() {
// Log.w(TAG, "----run");
SystemInfo sysInfo = rcCtx.getSysInfo();
ParamPlay playIf = rcCtx.getParamPlay();
ParamMediaInfo mediaIf = rcCtx.getmediaPara();
JSONObject jsnObj = new JSONObject();
String usrOptTag = "playUrl";
try {
jsnObj.put("internetIp", playIf.getStrOutIp());// input from app server, net out ip address - nono
jsnObj.put("dnsIp", sysInfo.getStrDnsIp()); // get from app local, current device used dns ip address - okok
jsnObj.put("cdnIp", playIf.getStrCdnIp()); // get from app local, rtmp or http connect ip address - nono
jsnObj.put("pingms", sysInfo.getSysNet().getPingMs(playIf.getStrDomain())); // get from app local - okok
jsnObj.put("bindwidth", sysInfo.getSysNet().getAppNetRcvBw()); // get from app local - okok-0413
if (ReportCenter.SDK_REPORTER_TYPE_PUBLISH == rcCtx.getReporterType()) {
//strCtx.put("framesize", mediaIf.getWidth()); // get from app local - nono
jsnObj.put("diskfreespace", String.valueOf(sysInfo.getSdcardRate())+"%"); // get from app local - nono
jsnObj.put("width", mediaIf.getWidth()); // get from app local - nono
jsnObj.put("height", mediaIf.getHeight()); // get from app local - nono
jsnObj.put("currentfps", mediaIf.getFps()); // get from app local - nono
jsnObj.put("bitrates", mediaIf.getBitRates()); // get from app local - nono
jsnObj.put("lostfps", 10); // get from app local - nono
jsnObj.put("sendfailnum", 0); // get from app local - nono
usrOptTag = "pushUrl";
}
jsnObj.put(usrOptTag, playIf.getStrUrl()); // input from app server - nono
} catch (JSONException e) {
e.printStackTrace();
}
// Log.w(TAG, "----end");
return jsnObj;
}
}
| UTF-8 | Java | 2,431 | java | TagPlayHeartBeat.java | Java | [
{
"context": "on;\nimport org.json.JSONObject;\n\n/**\n * Created by suker on 16-4-6.\n */\npublic class TagPlayHeartBeat {\n ",
"end": 130,
"score": 0.9995548725128174,
"start": 125,
"tag": "USERNAME",
"value": "suker"
}
] | null | [] | package sdk.report;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by suker on 16-4-6.
*/
public class TagPlayHeartBeat {
private final static String TAG = "SdkReport_" + SysNetwork.class.getSimpleName();
private ReportCenter rcCtx = null;
public TagPlayHeartBeat(ReportCenter rc) {
rcCtx = rc;
}
public JSONObject toJson() {
// Log.w(TAG, "----run");
SystemInfo sysInfo = rcCtx.getSysInfo();
ParamPlay playIf = rcCtx.getParamPlay();
ParamMediaInfo mediaIf = rcCtx.getmediaPara();
JSONObject jsnObj = new JSONObject();
String usrOptTag = "playUrl";
try {
jsnObj.put("internetIp", playIf.getStrOutIp());// input from app server, net out ip address - nono
jsnObj.put("dnsIp", sysInfo.getStrDnsIp()); // get from app local, current device used dns ip address - okok
jsnObj.put("cdnIp", playIf.getStrCdnIp()); // get from app local, rtmp or http connect ip address - nono
jsnObj.put("pingms", sysInfo.getSysNet().getPingMs(playIf.getStrDomain())); // get from app local - okok
jsnObj.put("bindwidth", sysInfo.getSysNet().getAppNetRcvBw()); // get from app local - okok-0413
if (ReportCenter.SDK_REPORTER_TYPE_PUBLISH == rcCtx.getReporterType()) {
//strCtx.put("framesize", mediaIf.getWidth()); // get from app local - nono
jsnObj.put("diskfreespace", String.valueOf(sysInfo.getSdcardRate())+"%"); // get from app local - nono
jsnObj.put("width", mediaIf.getWidth()); // get from app local - nono
jsnObj.put("height", mediaIf.getHeight()); // get from app local - nono
jsnObj.put("currentfps", mediaIf.getFps()); // get from app local - nono
jsnObj.put("bitrates", mediaIf.getBitRates()); // get from app local - nono
jsnObj.put("lostfps", 10); // get from app local - nono
jsnObj.put("sendfailnum", 0); // get from app local - nono
usrOptTag = "pushUrl";
}
jsnObj.put(usrOptTag, playIf.getStrUrl()); // input from app server - nono
} catch (JSONException e) {
e.printStackTrace();
}
// Log.w(TAG, "----end");
return jsnObj;
}
}
| 2,431 | 0.584944 | 0.58042 | 52 | 45.75 | 40.192745 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.961538 | false | false | 2 |
4374d78cf61e43b8585401f4fc5c252d8640a2cf | 28,965,259,504,775 | 78c31cf0dd056decf4525a3e123fd39ca2cd91cc | /app/src/main/java/com/casl/Utility/MappingData.java | 5f13a120afd478e416559090f21e0fba76b44b8f | [] | no_license | pallaviwaghaye/CaslSurvey | https://github.com/pallaviwaghaye/CaslSurvey | be8139f52e8f1769adf4a62139e4986a743b3af1 | cfffc85fb671bb1439d38e93ec8beda5decfe2eb | refs/heads/master | 2020-05-19T01:32:45.744000 | 2019-08-06T13:27:43 | 2019-08-06T13:27:43 | 184,759,488 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.casl.Utility;
import com.casl.caslsurvey.R;
public class MappingData {
public String getTypeOfContact(String selected) {
String mappedStr = "";
switch (selected) {
case "In-person":
mappedStr = "inper";
break;
case "Telephone":
mappedStr = "telephone";
break;
case "Letter":
mappedStr = "letter";
break;
}
return mappedStr;
}
public String getPurposeOfContact(String selected) {
String mappedStr = "";
switch (selected) {
case "Request participation in a study activity":
mappedStr = "01";
break;
case "Schedule or confirm study appointment":
mappedStr = "02";
break;
case "Collect study data":
mappedStr = "03";
break;
case "Provide study information/Answer subject or family study questions":
mappedStr = "04";
break;
case "Contact requested or initiated by subject":
mappedStr = "05";
break;
case "Appointment cancellation":
mappedStr = "09";
break;
case "Gather subjects contact information from family members/trusted others":
mappedStr = "10";
break;
}
return mappedStr;
}
public String getIntMethod(String selected) {
String mappedStr = "";
switch (selected) {
case "In-person":
mappedStr = "inperson";
break;
case "Phone":
mappedStr = "phone";
break;
case "Mailed-in":
mappedStr = "mail";
break;
case "Online":
mappedStr = "online";
break;
}
return mappedStr;
}
public String getNoContactMethod(String selected) {
String mappedStr = "";
switch (selected) {
case "Not at home":
mappedStr = "outOfHome";
break;
case "Wrong telephone number":
mappedStr = "wrongPhoneNumber";
break;
case "Nobody pick up phone":
mappedStr = "nobodypickup";
break;
case "Not able to answer":
mappedStr = "notAbleToAnswer";
break;
case "Moved to other parts of city":
mappedStr = "movedOtherParts";
break;
case "Moved to suburbs":
mappedStr = "movedSuburbs";
break;
case "Moved out of state":
mappedStr = "movedOutState";
break;
case "Moved out of country":
mappedStr = "movedOutCountry";
break;
case "Moved unknown":
mappedStr = "movedUnknown";
break;
case "Other":
mappedStr = "other";
break;
}
return mappedStr;
}
public String getDieCause(String selected){
String mappedStr = "";
switch (selected) {
case "Heart Disease":
mappedStr = "hea";
break;
case "Cancer":
mappedStr = "can";
break;
case "Cerebrovascular Disease":
mappedStr = "cer";
break;
case "Lung Disease":
mappedStr = "lun";
break;
case "Kidney Disease":
mappedStr = "kid";
break;
case "Accident":
mappedStr = "acc";
break;
case "Infection":
mappedStr = "inf";
break;
case "Other":
mappedStr = "oth";
break;
}
return mappedStr;
}
public String getDiePlace(String selected){
String mappedStr = "";
switch (selected) {
case "Own home":
mappedStr = "home";
break;
case "Family members home":
mappedStr = "famhome";
break;
case "Nursing home":
mappedStr = "nursing";
break;
case "Hospital":
mappedStr = "hospital";
break;
case "Emergency Room":
mappedStr = "emergroom";
break;
case "Rehab center":
mappedStr = "rehabcen";
break;
case "Other":
mappedStr = "other";
break;
}
return mappedStr;
}
public String getDieState(String selected){
String mappedStr = "";
switch (selected) {
case "Alabama":
mappedStr = "AL";
break;
case "Alaska":
mappedStr = "AK";
break;
case "Arizona":
mappedStr = "AZ";
break;
case "Arkansas":
mappedStr = "AR";
break;
case "California":
mappedStr = "CA";
break;
case "Colorado":
mappedStr = "CO";
break;
case "Connecticut":
mappedStr = "CT";
break;
case "Delaware":
mappedStr = "DE";
break;
case "Florida":
mappedStr = "FL";
break;
case "Georgia":
mappedStr = "GA";
break;
case "Hawaii":
mappedStr = "HI";
break;
case "Idaho":
mappedStr = "ID";
break;
case "Illinois":
mappedStr = "IL";
break;
case "Indiana":
mappedStr = "IN";
break;
case "Iowa":
mappedStr = "IA";
break;
case "Kansas":
mappedStr = "KS";
break;
case "Kentucky":
mappedStr = "KY";
break;
case "Louisiana":
mappedStr = "LA";
break;
case "Maine":
mappedStr = "ME";
break;
case "Maryland":
mappedStr = "MD";
break;
case "Massachusetts":
mappedStr = "MA";
break;
case "Michigan":
mappedStr = "MI";
break;
case "Minnesota":
mappedStr = "MN";
break;
case "Mississippi":
mappedStr = "MS";
break;
case "Missouri":
mappedStr = "MO";
break;
case "Montana":
mappedStr = "MT";
break;
case "Nebraska":
mappedStr = "NE";
break;
case "Nevada":
mappedStr = "NV";
break;
case "New Hampshire":
mappedStr = "NH";
break;
case "New Jersey":
mappedStr = "NJ";
break;
case "New Mexico":
mappedStr = "NM";
break;
case "New York":
mappedStr = "NY";
break;
case "North Carolina":
mappedStr = "NC";
break;
case "North Dakota":
mappedStr = "ND";
break;
case "Ohio":
mappedStr = "OH";
break;
case "Oklahoma":
mappedStr = "OK";
break;
case "Oregon":
mappedStr = "OR";
break;
case "Pennsylvania":
mappedStr = "PA";
break;
case "Rhode Island":
mappedStr = "RI";
break;
case "South Carolina":
mappedStr = "SC";
break;
case "South Dakota":
mappedStr = "SD";
break;
case "Tennessee":
mappedStr = "TN";
break;
case "Texas":
mappedStr = "TX";
break;
case "Utah":
mappedStr = "UT";
break;
case "Vermont":
mappedStr = "VT";
break;
case "Virginia":
mappedStr = "VA";
break;
case "Washington":
mappedStr = "WA";
break;
case "West Virginia":
mappedStr = "WV";
break;
case "Wisconsin":
mappedStr = "WI";
break;
case "Wyoming":
mappedStr = "WY";
break;
case "Out of Country":
mappedStr = "OutofCountry";
break;
}
return mappedStr;
}
public String getDieWhome(String selected){
String mappedStr = "";
switch (selected) {
case "Spouse":
mappedStr = "spouse";
break;
case "Ex-spouse":
mappedStr = "exspouse";
break;
case "Romantic partner":
mappedStr = "partner";
break;
case "Son":
mappedStr = "son";
break;
case "Daughter":
mappedStr = "daughter";
break;
case "Son-in-law":
mappedStr = "soninlaw";
break;
case "Daughter-in-law":
mappedStr = "daughterinlaw";
break;
case "Step-child":
mappedStr = "stepchild";
break;
case "Grandson":
mappedStr = "grandson";
break;
case "Granddaughter":
mappedStr = "granddaughter";
break;
case "Father":
mappedStr = "father";
break;
case "Mother":
mappedStr = "mother";
break;
case "Father-in-law":
mappedStr = "fatherinlaw";
break;
case "Mother-in-law":
mappedStr = "mother-in-law";
break;
case "Brother":
mappedStr = "brother";
break;
case "Sister":
mappedStr = "sister";
break;
case "Other family member":
mappedStr = "otherfamily";
break;
case "Trusted friend":
mappedStr = "trustedfriend";
break;
case "Other trusted person":
mappedStr = "otherperson";
break;
case "Neighbor":
mappedStr = "neighbor";
break;
case "Caretaker from outside":
mappedStr = "caretakeroutside";
break;
case "Caretaker from nursing home":
mappedStr = "nursinghome";
break;
case "Banker":
mappedStr = "banker";
break;
case "Lawyer":
mappedStr = "lawyer";
break;
case "City or State worker":
mappedStr = "cityworker";
break;
case "Salesman":
mappedStr = "salesman";
break;
case "Contractor to fix house":
mappedStr = "contractor";
break;
case "Other":
mappedStr = "other";
break;
}
return mappedStr;
}
public String getPartRel2_FamRel2(String selected){
String mappedStr = "";
switch (selected) {
case "Mild unspoken reluctance":
mappedStr = "mild1";
break;
case "Mild overt reluctance":
mappedStr = "mild2";
break;
case "Moderate reluctance":
mappedStr = "moder";
break;
case "Strong reluctance":
mappedStr = "strong1";
break;
case "Strong reluctance with hostile comments":
mappedStr = "strong2";
break;
}
return mappedStr;
}
public String get_OthrContact_reluctance_partrel1_famrel1_famrel4(String selected) {
String mappedStr = "";
switch (selected) {
//case R.string.yes:
case "Yes":
mappedStr = "yes";
break;
case "No":
mappedStr = "no";
break;
}
return mappedStr;
}
public String get_Death_NursHome(String selected) {
String mappedStr = "";
switch (selected) {
case "Yes":
mappedStr = "yes";
break;
case "No":
mappedStr = "no";
break;
case "Dont know":
mappedStr = "dontknow";
break;
case "Refusal":
mappedStr = "refusal";
break;
}
return mappedStr;
}
/*public static String getNursHome(String selected) {
String mappedStr = "";
switch (selected) {
case "Yes":
mappedStr = "yes";
break;
case "No":
mappedStr = "no";
break;
case "Dont know":
mappedStr = "dontknow";
break;
case "Refusal":
mappedStr = "refusal";
break;
}
return mappedStr;
}*/
}
| UTF-8 | Java | 14,537 | java | MappingData.java | Java | [] | null | [] | package com.casl.Utility;
import com.casl.caslsurvey.R;
public class MappingData {
public String getTypeOfContact(String selected) {
String mappedStr = "";
switch (selected) {
case "In-person":
mappedStr = "inper";
break;
case "Telephone":
mappedStr = "telephone";
break;
case "Letter":
mappedStr = "letter";
break;
}
return mappedStr;
}
public String getPurposeOfContact(String selected) {
String mappedStr = "";
switch (selected) {
case "Request participation in a study activity":
mappedStr = "01";
break;
case "Schedule or confirm study appointment":
mappedStr = "02";
break;
case "Collect study data":
mappedStr = "03";
break;
case "Provide study information/Answer subject or family study questions":
mappedStr = "04";
break;
case "Contact requested or initiated by subject":
mappedStr = "05";
break;
case "Appointment cancellation":
mappedStr = "09";
break;
case "Gather subjects contact information from family members/trusted others":
mappedStr = "10";
break;
}
return mappedStr;
}
public String getIntMethod(String selected) {
String mappedStr = "";
switch (selected) {
case "In-person":
mappedStr = "inperson";
break;
case "Phone":
mappedStr = "phone";
break;
case "Mailed-in":
mappedStr = "mail";
break;
case "Online":
mappedStr = "online";
break;
}
return mappedStr;
}
public String getNoContactMethod(String selected) {
String mappedStr = "";
switch (selected) {
case "Not at home":
mappedStr = "outOfHome";
break;
case "Wrong telephone number":
mappedStr = "wrongPhoneNumber";
break;
case "Nobody pick up phone":
mappedStr = "nobodypickup";
break;
case "Not able to answer":
mappedStr = "notAbleToAnswer";
break;
case "Moved to other parts of city":
mappedStr = "movedOtherParts";
break;
case "Moved to suburbs":
mappedStr = "movedSuburbs";
break;
case "Moved out of state":
mappedStr = "movedOutState";
break;
case "Moved out of country":
mappedStr = "movedOutCountry";
break;
case "Moved unknown":
mappedStr = "movedUnknown";
break;
case "Other":
mappedStr = "other";
break;
}
return mappedStr;
}
public String getDieCause(String selected){
String mappedStr = "";
switch (selected) {
case "Heart Disease":
mappedStr = "hea";
break;
case "Cancer":
mappedStr = "can";
break;
case "Cerebrovascular Disease":
mappedStr = "cer";
break;
case "Lung Disease":
mappedStr = "lun";
break;
case "Kidney Disease":
mappedStr = "kid";
break;
case "Accident":
mappedStr = "acc";
break;
case "Infection":
mappedStr = "inf";
break;
case "Other":
mappedStr = "oth";
break;
}
return mappedStr;
}
public String getDiePlace(String selected){
String mappedStr = "";
switch (selected) {
case "Own home":
mappedStr = "home";
break;
case "Family members home":
mappedStr = "famhome";
break;
case "Nursing home":
mappedStr = "nursing";
break;
case "Hospital":
mappedStr = "hospital";
break;
case "Emergency Room":
mappedStr = "emergroom";
break;
case "Rehab center":
mappedStr = "rehabcen";
break;
case "Other":
mappedStr = "other";
break;
}
return mappedStr;
}
public String getDieState(String selected){
String mappedStr = "";
switch (selected) {
case "Alabama":
mappedStr = "AL";
break;
case "Alaska":
mappedStr = "AK";
break;
case "Arizona":
mappedStr = "AZ";
break;
case "Arkansas":
mappedStr = "AR";
break;
case "California":
mappedStr = "CA";
break;
case "Colorado":
mappedStr = "CO";
break;
case "Connecticut":
mappedStr = "CT";
break;
case "Delaware":
mappedStr = "DE";
break;
case "Florida":
mappedStr = "FL";
break;
case "Georgia":
mappedStr = "GA";
break;
case "Hawaii":
mappedStr = "HI";
break;
case "Idaho":
mappedStr = "ID";
break;
case "Illinois":
mappedStr = "IL";
break;
case "Indiana":
mappedStr = "IN";
break;
case "Iowa":
mappedStr = "IA";
break;
case "Kansas":
mappedStr = "KS";
break;
case "Kentucky":
mappedStr = "KY";
break;
case "Louisiana":
mappedStr = "LA";
break;
case "Maine":
mappedStr = "ME";
break;
case "Maryland":
mappedStr = "MD";
break;
case "Massachusetts":
mappedStr = "MA";
break;
case "Michigan":
mappedStr = "MI";
break;
case "Minnesota":
mappedStr = "MN";
break;
case "Mississippi":
mappedStr = "MS";
break;
case "Missouri":
mappedStr = "MO";
break;
case "Montana":
mappedStr = "MT";
break;
case "Nebraska":
mappedStr = "NE";
break;
case "Nevada":
mappedStr = "NV";
break;
case "New Hampshire":
mappedStr = "NH";
break;
case "New Jersey":
mappedStr = "NJ";
break;
case "New Mexico":
mappedStr = "NM";
break;
case "New York":
mappedStr = "NY";
break;
case "North Carolina":
mappedStr = "NC";
break;
case "North Dakota":
mappedStr = "ND";
break;
case "Ohio":
mappedStr = "OH";
break;
case "Oklahoma":
mappedStr = "OK";
break;
case "Oregon":
mappedStr = "OR";
break;
case "Pennsylvania":
mappedStr = "PA";
break;
case "Rhode Island":
mappedStr = "RI";
break;
case "South Carolina":
mappedStr = "SC";
break;
case "South Dakota":
mappedStr = "SD";
break;
case "Tennessee":
mappedStr = "TN";
break;
case "Texas":
mappedStr = "TX";
break;
case "Utah":
mappedStr = "UT";
break;
case "Vermont":
mappedStr = "VT";
break;
case "Virginia":
mappedStr = "VA";
break;
case "Washington":
mappedStr = "WA";
break;
case "West Virginia":
mappedStr = "WV";
break;
case "Wisconsin":
mappedStr = "WI";
break;
case "Wyoming":
mappedStr = "WY";
break;
case "Out of Country":
mappedStr = "OutofCountry";
break;
}
return mappedStr;
}
public String getDieWhome(String selected){
String mappedStr = "";
switch (selected) {
case "Spouse":
mappedStr = "spouse";
break;
case "Ex-spouse":
mappedStr = "exspouse";
break;
case "Romantic partner":
mappedStr = "partner";
break;
case "Son":
mappedStr = "son";
break;
case "Daughter":
mappedStr = "daughter";
break;
case "Son-in-law":
mappedStr = "soninlaw";
break;
case "Daughter-in-law":
mappedStr = "daughterinlaw";
break;
case "Step-child":
mappedStr = "stepchild";
break;
case "Grandson":
mappedStr = "grandson";
break;
case "Granddaughter":
mappedStr = "granddaughter";
break;
case "Father":
mappedStr = "father";
break;
case "Mother":
mappedStr = "mother";
break;
case "Father-in-law":
mappedStr = "fatherinlaw";
break;
case "Mother-in-law":
mappedStr = "mother-in-law";
break;
case "Brother":
mappedStr = "brother";
break;
case "Sister":
mappedStr = "sister";
break;
case "Other family member":
mappedStr = "otherfamily";
break;
case "Trusted friend":
mappedStr = "trustedfriend";
break;
case "Other trusted person":
mappedStr = "otherperson";
break;
case "Neighbor":
mappedStr = "neighbor";
break;
case "Caretaker from outside":
mappedStr = "caretakeroutside";
break;
case "Caretaker from nursing home":
mappedStr = "nursinghome";
break;
case "Banker":
mappedStr = "banker";
break;
case "Lawyer":
mappedStr = "lawyer";
break;
case "City or State worker":
mappedStr = "cityworker";
break;
case "Salesman":
mappedStr = "salesman";
break;
case "Contractor to fix house":
mappedStr = "contractor";
break;
case "Other":
mappedStr = "other";
break;
}
return mappedStr;
}
public String getPartRel2_FamRel2(String selected){
String mappedStr = "";
switch (selected) {
case "Mild unspoken reluctance":
mappedStr = "mild1";
break;
case "Mild overt reluctance":
mappedStr = "mild2";
break;
case "Moderate reluctance":
mappedStr = "moder";
break;
case "Strong reluctance":
mappedStr = "strong1";
break;
case "Strong reluctance with hostile comments":
mappedStr = "strong2";
break;
}
return mappedStr;
}
public String get_OthrContact_reluctance_partrel1_famrel1_famrel4(String selected) {
String mappedStr = "";
switch (selected) {
//case R.string.yes:
case "Yes":
mappedStr = "yes";
break;
case "No":
mappedStr = "no";
break;
}
return mappedStr;
}
public String get_Death_NursHome(String selected) {
String mappedStr = "";
switch (selected) {
case "Yes":
mappedStr = "yes";
break;
case "No":
mappedStr = "no";
break;
case "Dont know":
mappedStr = "dontknow";
break;
case "Refusal":
mappedStr = "refusal";
break;
}
return mappedStr;
}
/*public static String getNursHome(String selected) {
String mappedStr = "";
switch (selected) {
case "Yes":
mappedStr = "yes";
break;
case "No":
mappedStr = "no";
break;
case "Dont know":
mappedStr = "dontknow";
break;
case "Refusal":
mappedStr = "refusal";
break;
}
return mappedStr;
}*/
}
| 14,537 | 0.392309 | 0.390727 | 600 | 23.228333 | 15.090379 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.486667 | false | false | 2 |
1722de4d5ee0c6c304183eac59831b41d1e135ee | 30,863,635,029,559 | 0dcd5a8c3d7658e1ba9e559e432e11e6e255bdde | /springboot-study/springboot-demo/src/main/java/com/cptz/controller/LoginController.java | 337af11d7955aadfbccecb95be077756b6034b4e | [] | no_license | CarpenterZhang/StudyNotes | https://github.com/CarpenterZhang/StudyNotes | 0fde0e94c33c5e3927d3f52ffe919a9ebab6fd45 | dbdc4ad4a535ffe1f90532602f753733a1b4521f | refs/heads/master | 2022-12-31T18:29:52.836000 | 2020-10-20T16:57:31 | 2020-10-20T16:57:31 | 287,020,851 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cptz.controller;
import com.cptz.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController {
@RequestMapping("/login")
public String login(User user, HttpSession session) {
session.setAttribute("sessionId", session.getId());
return "redirect:dashboard";
}
@RequestMapping("dashboard")
public String dashboard() {
return "dashboard";
}
}
| UTF-8 | Java | 550 | java | LoginController.java | Java | [] | null | [] | package com.cptz.controller;
import com.cptz.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController {
@RequestMapping("/login")
public String login(User user, HttpSession session) {
session.setAttribute("sessionId", session.getId());
return "redirect:dashboard";
}
@RequestMapping("dashboard")
public String dashboard() {
return "dashboard";
}
}
| 550 | 0.725455 | 0.725455 | 22 | 24 | 20.491684 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 2 |
69f1a0f21c7460a7389dbd0e3b62331ed5948da3 | 31,361,851,206,923 | a2255ae576875703aa207451108b0816a8233d05 | /workspace_luna/LeetCode/src/maximum_subarray/Solution.java | 825b639e719b79234011852d24730d66f8d1a0f6 | [] | no_license | llincc/Eclipse | https://github.com/llincc/Eclipse | 670bad95812f2b4b96f6f2967c41c6d0c8aa9faa | 23b436c5f4cb4fccf2866d990e7cc8df76df5a76 | refs/heads/master | 2020-03-29T21:28:50.559000 | 2019-01-06T17:28:30 | 2019-01-06T17:28:30 | 150,369,020 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package maximum_subarray;
/*题目描述
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array[−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray[4,−1,2,1]has the largest sum =6.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.*/
public class Solution {
public int maxSubArray(int[] A) {
int maxsum = Integer.MIN_VALUE;
int sum = -1;
for(int i=0; i<A.length; i++){
if(sum < 0) sum = A[i];
else sum += A[i];
maxsum = Math.max(sum, maxsum);
}
return maxsum;
}
}
| UTF-8 | Java | 777 | java | Solution.java | Java | [] | null | [] | package maximum_subarray;
/*题目描述
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array[−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray[4,−1,2,1]has the largest sum =6.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.*/
public class Solution {
public int maxSubArray(int[] A) {
int maxsum = Integer.MIN_VALUE;
int sum = -1;
for(int i=0; i<A.length; i++){
if(sum < 0) sum = A[i];
else sum += A[i];
maxsum = Math.max(sum, maxsum);
}
return maxsum;
}
}
| 777 | 0.619236 | 0.596838 | 24 | 29.625 | 31.700174 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.166667 | false | false | 2 |
2f8cd5b1dc3db1d5e149221b6e55065511cd1920 | 1,752,346,699,707 | ccf105e7e3fc88a44cbac434a76058a0a1372af5 | /src/com/smv/service/file/db/dbobject/ItemDO.java | 787d12ac717981cb40322cd73f5f13db9bd67c37 | [] | no_license | timiblossom/ShareMyVision | https://github.com/timiblossom/ShareMyVision | a21db5f449ab6fe46a96b5dbd77ee9e297118649 | 025b70e261ed26bf72828248217932a417a90cdf | refs/heads/master | 2021-05-16T02:40:13.887000 | 2019-04-08T20:30:53 | 2019-04-08T20:30:53 | 8,025,764 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.smv.service.file.db.dbobject;
import java.util.Date;
import com.smv.util.db.AbstractVersionedDatedDO;
/**
* @author Minh Do
* 03/2010
*/
public class ItemDO extends AbstractVersionedDatedDO {
private String itemTitle;
private String itemCode;
private String description;
private String status;
private Long uid;
private Long aid;
private Boolean isPublic;
private Integer width;
private Integer height;
private String mimeType;
private Long size;
private Integer duration;
private Double latitude;
private Double longitude;
private Double altitude;
private String location;
private Long deviceId;
private String storageId;
private String storageId1;
private String storageId2;
private String storageId3;
private Boolean processDone;
private Long sequenceId;
private Long eventId;
private Date expiredOn;
private Date postedOn;
public ItemDO() {
super();
}
public ItemDO(Long itemId) {
super();
this.id = itemId;
}
public void setItemTitle(String itemTitle) {
this.itemTitle = itemTitle;
}
public String getItemTitle() {
return itemTitle;
}
public void setItemCode(String itemCode) {
this.itemCode = itemCode;
}
public String getItemCode() {
return itemCode;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public Long getUid() {
return this.uid;
}
public void setUid(Long uid) {
this.uid = uid;
}
public Long getAid() {
return this.aid;
}
public void setAid(Long aid) {
this.aid = aid;
}
public void setIsPublic(Boolean isPublic) {
this.isPublic = isPublic;
}
public Boolean getIsPublic() {
return isPublic;
}
public Long getEventId() {
return this.eventId;
}
public void setEventId(Long eventId) {
this.eventId = eventId;
}
public Integer getWidth() {
return this.width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Integer getHeight() {
return this.height;
}
public void setHeight(Integer height) {
this.height = height;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public String getMimeType() {
return mimeType;
}
public Long getSize() {
return this.size;
}
public void setSize(Long size) {
this.size = size;
}
public Integer getDuration() {
return this.duration;
}
public void setDuration(Integer duration) {
this.duration = duration;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLatitude() {
return latitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Double getLongitude() {
return longitude;
}
public void setAltitude(Double altitude) {
this.altitude = altitude;
}
public Double getAltitude() {
return altitude;
}
public void setLocation(String location) {
this.location = location;
}
public String getLocation() {
return location;
}
public void setDeviceId(Long deviceId) {
this.deviceId = deviceId;
}
public Long getDeviceId() {
return deviceId;
}
public void setStorageId(String storageId) {
this.storageId = storageId;
}
public String getStorageId() {
return storageId;
}
public void setStorageId1(String storageId1) {
this.storageId1 = storageId1;
}
public String getStorageId1() {
return storageId1;
}
public void setStorageId2(String storageId2) {
this.storageId2 = storageId2;
}
public String getStorageId2() {
return storageId2;
}
public void setStorageId3(String storageId3) {
this.storageId3 = storageId3;
}
public String getStorageId3() {
return storageId3;
}
public void setProcessDone(Boolean processDone) {
this.processDone = processDone;
}
public Boolean getProcessDone() {
return processDone;
}
public Long getSequenceId() {
return this.sequenceId;
}
public void setSequenceId(Long sequenceId) {
this.sequenceId = sequenceId;
}
public void setExpiredOn(Date expiredOn) {
this.expiredOn = expiredOn;
}
public Date getExpiredOn() {
return expiredOn;
}
public void setPostedOn(Date postedOn) {
this.postedOn = postedOn;
}
public Date getPostedOn() {
return postedOn;
}
}
| UTF-8 | Java | 4,619 | java | ItemDO.java | Java | [
{
"context": "il.db.AbstractVersionedDatedDO;\r\n\r\n/**\r\n * @author Minh Do\r\n * 03/2010\r\n */\r\npublic class ItemDO extends Abs",
"end": 146,
"score": 0.9995877146720886,
"start": 139,
"tag": "NAME",
"value": "Minh Do"
}
] | null | [] | package com.smv.service.file.db.dbobject;
import java.util.Date;
import com.smv.util.db.AbstractVersionedDatedDO;
/**
* @author <NAME>
* 03/2010
*/
public class ItemDO extends AbstractVersionedDatedDO {
private String itemTitle;
private String itemCode;
private String description;
private String status;
private Long uid;
private Long aid;
private Boolean isPublic;
private Integer width;
private Integer height;
private String mimeType;
private Long size;
private Integer duration;
private Double latitude;
private Double longitude;
private Double altitude;
private String location;
private Long deviceId;
private String storageId;
private String storageId1;
private String storageId2;
private String storageId3;
private Boolean processDone;
private Long sequenceId;
private Long eventId;
private Date expiredOn;
private Date postedOn;
public ItemDO() {
super();
}
public ItemDO(Long itemId) {
super();
this.id = itemId;
}
public void setItemTitle(String itemTitle) {
this.itemTitle = itemTitle;
}
public String getItemTitle() {
return itemTitle;
}
public void setItemCode(String itemCode) {
this.itemCode = itemCode;
}
public String getItemCode() {
return itemCode;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public Long getUid() {
return this.uid;
}
public void setUid(Long uid) {
this.uid = uid;
}
public Long getAid() {
return this.aid;
}
public void setAid(Long aid) {
this.aid = aid;
}
public void setIsPublic(Boolean isPublic) {
this.isPublic = isPublic;
}
public Boolean getIsPublic() {
return isPublic;
}
public Long getEventId() {
return this.eventId;
}
public void setEventId(Long eventId) {
this.eventId = eventId;
}
public Integer getWidth() {
return this.width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Integer getHeight() {
return this.height;
}
public void setHeight(Integer height) {
this.height = height;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public String getMimeType() {
return mimeType;
}
public Long getSize() {
return this.size;
}
public void setSize(Long size) {
this.size = size;
}
public Integer getDuration() {
return this.duration;
}
public void setDuration(Integer duration) {
this.duration = duration;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLatitude() {
return latitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Double getLongitude() {
return longitude;
}
public void setAltitude(Double altitude) {
this.altitude = altitude;
}
public Double getAltitude() {
return altitude;
}
public void setLocation(String location) {
this.location = location;
}
public String getLocation() {
return location;
}
public void setDeviceId(Long deviceId) {
this.deviceId = deviceId;
}
public Long getDeviceId() {
return deviceId;
}
public void setStorageId(String storageId) {
this.storageId = storageId;
}
public String getStorageId() {
return storageId;
}
public void setStorageId1(String storageId1) {
this.storageId1 = storageId1;
}
public String getStorageId1() {
return storageId1;
}
public void setStorageId2(String storageId2) {
this.storageId2 = storageId2;
}
public String getStorageId2() {
return storageId2;
}
public void setStorageId3(String storageId3) {
this.storageId3 = storageId3;
}
public String getStorageId3() {
return storageId3;
}
public void setProcessDone(Boolean processDone) {
this.processDone = processDone;
}
public Boolean getProcessDone() {
return processDone;
}
public Long getSequenceId() {
return this.sequenceId;
}
public void setSequenceId(Long sequenceId) {
this.sequenceId = sequenceId;
}
public void setExpiredOn(Date expiredOn) {
this.expiredOn = expiredOn;
}
public Date getExpiredOn() {
return expiredOn;
}
public void setPostedOn(Date postedOn) {
this.postedOn = postedOn;
}
public Date getPostedOn() {
return postedOn;
}
}
| 4,618 | 0.677419 | 0.671574 | 259 | 15.833977 | 15.156055 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.27027 | false | false | 2 |
0226c1baa7d6af578fb61762742266e19df627f0 | 27,728,308,877,976 | a524066e90a6a4cd240f3b9837d3506d54eb389d | /dozer-example/src/main/java/com/taoyuanx/dozer/convers/DateStringConverter.java | bd5d2bfb842de4761746c28891217c43e6aafdda | [] | no_license | dushitaoyuan/java_tool_test | https://github.com/dushitaoyuan/java_tool_test | 1d3a22295dab68881dee210b5b18921b41dd8f74 | 1ddc611f4099d3a0b9149f5a6fe6a9b581120c14 | refs/heads/master | 2022-05-29T17:24:14.256000 | 2021-03-22T08:58:28 | 2021-03-22T08:58:28 | 193,219,623 | 0 | 0 | null | false | 2022-05-25T06:50:39 | 2019-06-22T10:10:42 | 2021-03-22T09:02:43 | 2022-05-25T06:50:36 | 95 | 0 | 0 | 10 | Java | false | false | package com.taoyuanx.dozer.convers;
import com.vip.vjtools.vjkit.time.DateFormatUtil;
import org.dozer.DozerConverter;
import java.text.ParseException;
import java.util.Date;
/**
* @author 桃源
* @description date <->string 互转
* @date 2019/6/22
*/
public class DateStringConverter extends DozerConverter<Date, String> {
public static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
public DateStringConverter(Class<Date> prototypeA, Class<String> prototypeB) {
super(prototypeA, prototypeB);
}
public DateStringConverter() {
super(Date.class, String.class);
}
@Override
public String convertTo(Date source, String destination) {
if (null != source) {
return DateFormatUtil.formatDate(DEFAULT_FORMAT, source);
}
return null;
}
@Override
public Date convertFrom(String source, Date destination) {
try {
if (null != source && source.length() > 0) {
try {
return DateFormatUtil.parseDate(DEFAULT_FORMAT, source);
} catch (ParseException e) {
return DateFormatUtil.parseDate(ConverHelper.guessDateFormat(source), source);
}
}
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| UTF-8 | Java | 1,379 | java | DateStringConverter.java | Java | [
{
"context": "eException;\nimport java.util.Date;\n\n/**\n * @author 桃源\n * @description date <->string 互转\n * @date 2019/6",
"end": 195,
"score": 0.9997406005859375,
"start": 193,
"tag": "NAME",
"value": "桃源"
}
] | null | [] | package com.taoyuanx.dozer.convers;
import com.vip.vjtools.vjkit.time.DateFormatUtil;
import org.dozer.DozerConverter;
import java.text.ParseException;
import java.util.Date;
/**
* @author 桃源
* @description date <->string 互转
* @date 2019/6/22
*/
public class DateStringConverter extends DozerConverter<Date, String> {
public static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
public DateStringConverter(Class<Date> prototypeA, Class<String> prototypeB) {
super(prototypeA, prototypeB);
}
public DateStringConverter() {
super(Date.class, String.class);
}
@Override
public String convertTo(Date source, String destination) {
if (null != source) {
return DateFormatUtil.formatDate(DEFAULT_FORMAT, source);
}
return null;
}
@Override
public Date convertFrom(String source, Date destination) {
try {
if (null != source && source.length() > 0) {
try {
return DateFormatUtil.parseDate(DEFAULT_FORMAT, source);
} catch (ParseException e) {
return DateFormatUtil.parseDate(ConverHelper.guessDateFormat(source), source);
}
}
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 1,379 | 0.61415 | 0.608315 | 50 | 26.42 | 25.849634 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.46 | false | false | 2 |
3a9338120cb83a12708f0f03a2d14cfd1e95bf1f | 33,517,924,813,696 | bd6f0551917f3571ceefd0f7079293fb8a68e790 | /src/uk/ac/gre/ma8521e/privatehirecars/GUI/Controllers/EnquiryController.java | f1710e2790c44bc7dc3881bc3179fa4771a5d66c | [] | no_license | martyybu/PrivateHireCars | https://github.com/martyybu/PrivateHireCars | 2bcdce53b463f3354bb053579bfc8ad8fbc130f2 | a379864f1c2504a74d24f901cb71ad9548d5b53a | refs/heads/master | 2020-07-03T04:47:30.292000 | 2018-04-17T22:31:05 | 2018-04-17T22:31:05 | 201,787,437 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package uk.ac.gre.ma8521e.privatehirecars.GUI.Controllers;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import uk.ac.gre.ma8521e.privatehirecars.DaoImplementation.EnquiryDaoImpl;
import uk.ac.gre.ma8521e.privatehirecars.DaoImplementation.JourneyDaoImpl;
import uk.ac.gre.ma8521e.privatehirecars.Enquiry;
import uk.ac.gre.ma8521e.privatehirecars.GUI.Views.EnquiryView;
import uk.ac.gre.ma8521e.privatehirecars.Journey.Journey;
import uk.ac.gre.ma8521e.privatehirecars.PrivateHireCars;
/**
*
* @author micae
*/
public class EnquiryController {
private EnquiryView view;
public EnquiryController() {
}
void addView(EnquiryView v2) {
view = v2;
setupListeners();
view.getAnswerTexBox().setFocusable(false);
view.getTextBox().setFocusable(false);
loadEnquiries();
}
void setupListeners() {
view.getlistOfEnquiries().addActionListener(evt -> changeListOfEnquiries(evt));
}
/**
* void sendBtn(ActionEvent evt) { Enquiry enquiry = new
* EnquiryDaoImpl().getEnquiry(((Enquiry)
* view.getlistOfEnquiries().getSelectedItem()).getID()); if (enquiry !=
* null) { if (enquiry.getEnquiry() != null); } }*
*/
void changeListOfEnquiries(ActionEvent evt) {
view.getTextBox().setText(((Enquiry) view.getlistOfEnquiries().getSelectedItem()).getEnquiry());
view.getAnswerTexBox().setText(((Enquiry) view.getlistOfEnquiries().getSelectedItem()).getAnswer());
if (((Enquiry) view.getlistOfEnquiries().getSelectedItem()).getJourney() != null) {
view.getLblTrip().setText(((Enquiry) view.getlistOfEnquiries().getSelectedItem()).getJourney().toString());
}
}
/**
* *
* public void loadTrips() { List<Journey> journeys = new
* JourneyDaoImpl().getAllJourneys(); //looping through the journeys to get
* the ones that belong to the user journeys.stream().filter((journey) ->
* (journey.getPassenger().getID() == null ?
* PrivateHireCars.getPerson().getID() == null :
* journey.getPassenger().getID().equals(PrivateHireCars.getPerson().getID()))).forEachOrdered((journey)
* -> { view.getlistofTrips().addItem(journey); }); }*
*/
void loadEnquiries() {
List<Enquiry> enquiries = new EnquiryDaoImpl().getPersonEnquiries(PrivateHireCars.getPerson().getID());
System.out.println("e" + enquiries);
for (int i = 0; i < enquiries.size(); i++) {
view.getlistOfEnquiries().addItem(enquiries.get(i));
}
}
}
| UTF-8 | Java | 2,878 | java | EnquiryController.java | Java | [
{
"context": "tehirecars.PrivateHireCars;\r\n\r\n/**\r\n *\r\n * @author micae\r\n */\r\npublic class EnquiryController {\r\n\r\n pri",
"end": 796,
"score": 0.9951861500740051,
"start": 791,
"tag": "USERNAME",
"value": "micae"
}
] | 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 uk.ac.gre.ma8521e.privatehirecars.GUI.Controllers;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import uk.ac.gre.ma8521e.privatehirecars.DaoImplementation.EnquiryDaoImpl;
import uk.ac.gre.ma8521e.privatehirecars.DaoImplementation.JourneyDaoImpl;
import uk.ac.gre.ma8521e.privatehirecars.Enquiry;
import uk.ac.gre.ma8521e.privatehirecars.GUI.Views.EnquiryView;
import uk.ac.gre.ma8521e.privatehirecars.Journey.Journey;
import uk.ac.gre.ma8521e.privatehirecars.PrivateHireCars;
/**
*
* @author micae
*/
public class EnquiryController {
private EnquiryView view;
public EnquiryController() {
}
void addView(EnquiryView v2) {
view = v2;
setupListeners();
view.getAnswerTexBox().setFocusable(false);
view.getTextBox().setFocusable(false);
loadEnquiries();
}
void setupListeners() {
view.getlistOfEnquiries().addActionListener(evt -> changeListOfEnquiries(evt));
}
/**
* void sendBtn(ActionEvent evt) { Enquiry enquiry = new
* EnquiryDaoImpl().getEnquiry(((Enquiry)
* view.getlistOfEnquiries().getSelectedItem()).getID()); if (enquiry !=
* null) { if (enquiry.getEnquiry() != null); } }*
*/
void changeListOfEnquiries(ActionEvent evt) {
view.getTextBox().setText(((Enquiry) view.getlistOfEnquiries().getSelectedItem()).getEnquiry());
view.getAnswerTexBox().setText(((Enquiry) view.getlistOfEnquiries().getSelectedItem()).getAnswer());
if (((Enquiry) view.getlistOfEnquiries().getSelectedItem()).getJourney() != null) {
view.getLblTrip().setText(((Enquiry) view.getlistOfEnquiries().getSelectedItem()).getJourney().toString());
}
}
/**
* *
* public void loadTrips() { List<Journey> journeys = new
* JourneyDaoImpl().getAllJourneys(); //looping through the journeys to get
* the ones that belong to the user journeys.stream().filter((journey) ->
* (journey.getPassenger().getID() == null ?
* PrivateHireCars.getPerson().getID() == null :
* journey.getPassenger().getID().equals(PrivateHireCars.getPerson().getID()))).forEachOrdered((journey)
* -> { view.getlistofTrips().addItem(journey); }); }*
*/
void loadEnquiries() {
List<Enquiry> enquiries = new EnquiryDaoImpl().getPersonEnquiries(PrivateHireCars.getPerson().getID());
System.out.println("e" + enquiries);
for (int i = 0; i < enquiries.size(); i++) {
view.getlistOfEnquiries().addItem(enquiries.get(i));
}
}
}
| 2,878 | 0.66574 | 0.654969 | 74 | 36.891891 | 32.915356 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.459459 | false | false | 2 |
4a09ccea250dccfbb277aba865028207024d4842 | 33,517,924,813,989 | 6776d9261ead0a42fe70bd7612be4ff5434814e8 | /src/main/java/com/arturskowronski/naivechain/p2p/messages/QueryAllMessage.java | 0981ed79aaf4e43ac94e34c1712257aeedb8da17 | [] | no_license | ArturSkowronski/naivechain-java | https://github.com/ArturSkowronski/naivechain-java | f1019be2d0109c0dfcc8202311aaf14b252b9ea0 | 1bc54fab1c40f4a84a84142073e0a7c0f9b9d520 | refs/heads/master | 2021-04-28T15:25:53.682000 | 2018-02-18T21:47:03 | 2018-02-18T21:47:03 | 121,989,490 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.arturskowronski.naivechain.p2p.messages;
import lombok.Getter;
@Getter
public class QueryAllMessage {
}
| UTF-8 | Java | 118 | java | QueryAllMessage.java | Java | [
{
"context": "package com.arturskowronski.naivechain.p2p.messages;\n\nimport lombok.Getter;\n\n",
"end": 27,
"score": 0.984427273273468,
"start": 12,
"tag": "USERNAME",
"value": "arturskowronski"
}
] | null | [] | package com.arturskowronski.naivechain.p2p.messages;
import lombok.Getter;
@Getter
public class QueryAllMessage {
}
| 118 | 0.813559 | 0.805085 | 7 | 15.857142 | 18.26338 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 2 |
b0abd6bbbbc7287d473f1f36b8bd34b1c2f5cae6 | 10,084,583,257,877 | 65b7491526a4da97f8441a81d7342f84fa186c1c | /AbstractFactory/src/Account.java | 9a44f558c00044be6c24d5d389bbd10b907b3040 | [] | no_license | NirdeshikaP/DesignPatterns | https://github.com/NirdeshikaP/DesignPatterns | ecc3a13cf62cfc181ce96bcfb8733ccd3e2bb7f9 | ce839a90653bf667dda931524e0dc5ade457eb3a | refs/heads/master | 2021-04-27T02:32:10.648000 | 2018-02-27T06:16:38 | 2018-02-27T06:16:38 | 122,697,210 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public interface Account {
public int getHours();
public int getSpeed();
public int getNumberOfMailboxes();
public int getStorage();
}
| UTF-8 | Java | 151 | java | Account.java | Java | [] | null | [] | public interface Account {
public int getHours();
public int getSpeed();
public int getNumberOfMailboxes();
public int getStorage();
}
| 151 | 0.688742 | 0.688742 | 6 | 24.166666 | 11.201438 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 2 |
00b10e759534527919040d3407496c7e20fb1e25 | 22,522,808,531,019 | 92a7feddf1ac9af9c2e6e39292f820a03504599f | /video/src/main/java/com/sybd/znld/video/service/VideoService.java | 8d617479df6209a35aa11dbbd5895f1b630409d7 | [] | no_license | xiamu126/parent | https://github.com/xiamu126/parent | db74381cc613c5829c5b3b91e3b54d254f4d5155 | e670e1a7fba3088479ed1078c80b144cc6b78ca0 | refs/heads/dev | 2023-08-14T16:26:32.493000 | 2020-01-10T06:02:36 | 2020-01-10T06:02:36 | 232,977,647 | 2 | 0 | null | false | 2023-07-23T02:24:40 | 2020-01-10T06:06:41 | 2021-01-18T11:36:17 | 2023-07-23T02:24:40 | 6,102 | 2 | 0 | 1 | JavaScript | false | false | package com.sybd.znld.video.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sybd.znld.config.ProjectConfig;
import com.sybd.znld.service.BaseService;
import com.sybd.znld.mapper.lamp.CameraMapper;
import com.sybd.znld.model.lamp.CameraModel;
import com.sybd.znld.util.MyString;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@Slf4j
@Service
public class VideoService extends BaseService implements IVideoService {
private final RedissonClient redissonClient;
private final CameraMapper cameraMapper;
private final VideoAsyncTask videoAsyncTask;
private final ObjectMapper objectMapper;
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Autowired
public VideoService(CameraMapper cameraMapper,
CacheManager cacheManager,
TaskScheduler taskScheduler, ProjectConfig projectConfig,
RedissonClient redissonClient,
VideoAsyncTask videoAsyncTask, ObjectMapper objectMapper) {
super(cacheManager, taskScheduler, projectConfig, redissonClient, objectMapper);
this.cameraMapper = cameraMapper;
this.redissonClient = redissonClient;
this.videoAsyncTask = videoAsyncTask;
this.objectMapper = objectMapper;
}
@PreDestroy
public void preDestroy(){
log.debug("VideoService关闭所有正在执行的任务");
//this.stopAll();
}
@PostConstruct
public void postConstruct(){
log.debug("postConstruct");
}
@Override
public CameraModel getCameraById(String cameraId) {
if(!MyString.isUuid(cameraId)) return null;
return this.cameraMapper.selectById(cameraId);
}
@Override
public CameraModel setCameraById(CameraModel model) {
if(model == null || !MyString.isUuid(model.id)) return null;
if(cameraMapper.updateById(model) > 0) return model;
return null;
}
@Override
public boolean push(String channelGuid) {
if(!MyString.isUuid(channelGuid)) {
log.error("channelGuid错误,"+channelGuid);
return false;
}
try {
var camera = cameraMapper.selectById(channelGuid);
if(camera == null){
log.error("获取摄像头配置为空,"+channelGuid);
return false;
}
var rtspUrl = camera.rtspUrl;
var rtmp = objectMapper.readValue(camera.rtmp, CameraModel.Rtmp.class);
if(rtmp == null) return false;
var recordAudio = camera.recordAudio;
this.videoAsyncTask.push(channelGuid, rtspUrl, rtmp.liveUrl, recordAudio ? 1 : 0);
try{
Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 3000));
}catch (InterruptedException ex) {
log.error(ex.getMessage()); // 发生超时异常,意味着推流成功,进入了循环状态
}
var tmp = this.videoAsyncTask.isChannelInUsing(channelGuid);
if(!tmp){
log.error("已经推送,但isChannelInUsing返回false");
}
return tmp;
} catch (IOException ex) {
log.error(ex.getMessage());
}
return false;
}
@Override
public void stop(String channelGuid){
this.videoAsyncTask.stop(channelGuid);
}
@Override
public void stopAll(){
this.videoAsyncTask.stopAll();
}
@Override
public boolean isChannelInUsing(String channelGuid) {
return this.videoAsyncTask.isChannelInUsing(channelGuid);
}
@Override
public BufferedImage pickImage(String channelGuid){
if(!MyString.isUuid(channelGuid)) {
log.error("channelGuid错误,"+channelGuid);
return null;
}
try {
var camera = cameraMapper.selectById(channelGuid);
if(camera == null){
log.error("获取摄像头配置为空,"+channelGuid);
return null;
}
var rtspUrl = camera.rtspUrl;
var ret = this.videoAsyncTask.pickImage(channelGuid, rtspUrl);
return ret.get(30, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException ex) {
log.error(ex.getMessage());
}
return null;
}
@Override
public boolean heartbeat(String channelGuid) {
return this.videoAsyncTask.heartbeat(channelGuid);
}
}
| UTF-8 | Java | 5,091 | java | VideoService.java | Java | [] | null | [] | package com.sybd.znld.video.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sybd.znld.config.ProjectConfig;
import com.sybd.znld.service.BaseService;
import com.sybd.znld.mapper.lamp.CameraMapper;
import com.sybd.znld.model.lamp.CameraModel;
import com.sybd.znld.util.MyString;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@Slf4j
@Service
public class VideoService extends BaseService implements IVideoService {
private final RedissonClient redissonClient;
private final CameraMapper cameraMapper;
private final VideoAsyncTask videoAsyncTask;
private final ObjectMapper objectMapper;
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Autowired
public VideoService(CameraMapper cameraMapper,
CacheManager cacheManager,
TaskScheduler taskScheduler, ProjectConfig projectConfig,
RedissonClient redissonClient,
VideoAsyncTask videoAsyncTask, ObjectMapper objectMapper) {
super(cacheManager, taskScheduler, projectConfig, redissonClient, objectMapper);
this.cameraMapper = cameraMapper;
this.redissonClient = redissonClient;
this.videoAsyncTask = videoAsyncTask;
this.objectMapper = objectMapper;
}
@PreDestroy
public void preDestroy(){
log.debug("VideoService关闭所有正在执行的任务");
//this.stopAll();
}
@PostConstruct
public void postConstruct(){
log.debug("postConstruct");
}
@Override
public CameraModel getCameraById(String cameraId) {
if(!MyString.isUuid(cameraId)) return null;
return this.cameraMapper.selectById(cameraId);
}
@Override
public CameraModel setCameraById(CameraModel model) {
if(model == null || !MyString.isUuid(model.id)) return null;
if(cameraMapper.updateById(model) > 0) return model;
return null;
}
@Override
public boolean push(String channelGuid) {
if(!MyString.isUuid(channelGuid)) {
log.error("channelGuid错误,"+channelGuid);
return false;
}
try {
var camera = cameraMapper.selectById(channelGuid);
if(camera == null){
log.error("获取摄像头配置为空,"+channelGuid);
return false;
}
var rtspUrl = camera.rtspUrl;
var rtmp = objectMapper.readValue(camera.rtmp, CameraModel.Rtmp.class);
if(rtmp == null) return false;
var recordAudio = camera.recordAudio;
this.videoAsyncTask.push(channelGuid, rtspUrl, rtmp.liveUrl, recordAudio ? 1 : 0);
try{
Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 3000));
}catch (InterruptedException ex) {
log.error(ex.getMessage()); // 发生超时异常,意味着推流成功,进入了循环状态
}
var tmp = this.videoAsyncTask.isChannelInUsing(channelGuid);
if(!tmp){
log.error("已经推送,但isChannelInUsing返回false");
}
return tmp;
} catch (IOException ex) {
log.error(ex.getMessage());
}
return false;
}
@Override
public void stop(String channelGuid){
this.videoAsyncTask.stop(channelGuid);
}
@Override
public void stopAll(){
this.videoAsyncTask.stopAll();
}
@Override
public boolean isChannelInUsing(String channelGuid) {
return this.videoAsyncTask.isChannelInUsing(channelGuid);
}
@Override
public BufferedImage pickImage(String channelGuid){
if(!MyString.isUuid(channelGuid)) {
log.error("channelGuid错误,"+channelGuid);
return null;
}
try {
var camera = cameraMapper.selectById(channelGuid);
if(camera == null){
log.error("获取摄像头配置为空,"+channelGuid);
return null;
}
var rtspUrl = camera.rtspUrl;
var ret = this.videoAsyncTask.pickImage(channelGuid, rtspUrl);
return ret.get(30, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException ex) {
log.error(ex.getMessage());
}
return null;
}
@Override
public boolean heartbeat(String channelGuid) {
return this.videoAsyncTask.heartbeat(channelGuid);
}
}
| 5,091 | 0.658059 | 0.654832 | 144 | 33.423611 | 23.530294 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 2 |
6c5a64aade7c589c614eebb6bb84a2cea0f1e9b4 | 15,616,501,102,503 | 07a63e065cb309fc005bb10e8e9e90487ffde317 | /src/main/java/indi/mzt/toppahs/entity/Scramble.java | 1270d6034a9a5268b8e99a7ee382826d832624ff | [
"MIT"
] | permissive | CodeMzt/Toppahs | https://github.com/CodeMzt/Toppahs | b7fcd3110b41be9e42f006caf81a2bdabe9125a9 | cb0e8b45e31c98edcff6bb8f1d6808128431b6b9 | refs/heads/master | 2023-05-14T07:23:16.991000 | 2021-06-05T05:37:27 | 2021-06-05T05:37:27 | 361,150,357 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package indi.mzt.toppahs.entity;
import indi.mzt.toppahs.service.ScramblesService;
import net.mamoe.mirai.utils.ExternalResource;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.worldcubeassociation.tnoodle.scrambles.Puzzle;
import java.io.File;
public class Scramble {
private Puzzle puzzle;
private String scramble;
private File puzzleImage;
public File getPuzzleImage() {
return puzzleImage;
}
public String getScramble() {
return scramble;
}
public Puzzle getPuzzle() {
return puzzle;
}
public void setPuzzle(Puzzle puzzle) {
this.puzzle = puzzle;
this.scramble =this.puzzle.generateScramble();
}
public void setPuzzleImage(File puzzleImage) {
this.puzzleImage = puzzleImage;
}
}
| UTF-8 | Java | 837 | java | Scramble.java | Java | [] | null | [] | package indi.mzt.toppahs.entity;
import indi.mzt.toppahs.service.ScramblesService;
import net.mamoe.mirai.utils.ExternalResource;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.worldcubeassociation.tnoodle.scrambles.Puzzle;
import java.io.File;
public class Scramble {
private Puzzle puzzle;
private String scramble;
private File puzzleImage;
public File getPuzzleImage() {
return puzzleImage;
}
public String getScramble() {
return scramble;
}
public Puzzle getPuzzle() {
return puzzle;
}
public void setPuzzle(Puzzle puzzle) {
this.puzzle = puzzle;
this.scramble =this.puzzle.generateScramble();
}
public void setPuzzleImage(File puzzleImage) {
this.puzzleImage = puzzleImage;
}
}
| 837 | 0.707288 | 0.707288 | 33 | 24.363636 | 17.871288 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.484848 | false | false | 2 |
c444044c081b67bfc91f0310c6403234d2f52713 | 30,975,304,190,122 | 3c5d605667c758f4047622317b8893e41ee1c434 | /src/main/java/com/christchurchcitylibraries/maze/common/CommonProxy.java | 525c273809bae6a68000f6a71e4f57051756814e | [] | no_license | eccentricdevotion/CCLMaze | https://github.com/eccentricdevotion/CCLMaze | 6f18978db3e691761d1b8b431f08df51cd436ac4 | d1bb450e834dddb741cde6a267c0180ef5cc95a6 | refs/heads/master | 2021-01-23T22:19:24.031000 | 2017-12-22T01:00:04 | 2017-12-22T01:00:04 | 101,532,352 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.christchurchcitylibraries.maze.common;
import java.io.File;
import com.christchurchcitylibraries.maze.CCLMaze;
import com.christchurchcitylibraries.maze.block.MazeBlocks;
import com.christchurchcitylibraries.maze.config.MazeConfigChangedHandler;
import com.christchurchcitylibraries.maze.config.MazeConfigHandler;
import com.christchurchcitylibraries.maze.crafting.MazeCrafting;
import com.christchurchcitylibraries.maze.gui.MazeGuiHandler;
import com.christchurchcitylibraries.maze.item.MazeItems;
import com.christchurchcitylibraries.maze.server.MazePacketDispatcher;
import com.christchurchcitylibraries.maze.server.MazePlayerEntityEvent;
import com.christchurchcitylibraries.maze.server.MazePlayerServerLogin;
import com.christchurchcitylibraries.maze.tileentity.MazeTileEntities;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.common.MinecraftForge;
public class CommonProxy {
private static File configDir;
public static File getConfigDir() {
return configDir;
}
public void preInit(FMLPreInitializationEvent e) {
MazeBlocks.createBlocks();
MazeItems.createItems();
MazeTileEntities.createTileEntities();
configDir = new File(e.getModConfigurationDirectory() + "/CCLMaze");
configDir.mkdirs();
MazeConfigHandler.initOptions(new File(configDir.getPath(), CCLMaze.MODID + ".cfg"));
MazeConfigHandler.initDoors(new File(configDir.getPath(), "doors.cfg"));
}
public void init(FMLInitializationEvent e) {
MazeCrafting.initCrafting();
MazeConfigChangedHandler configChanged = new MazeConfigChangedHandler();
MinecraftForge.EVENT_BUS.register(configChanged);
FMLCommonHandler.instance().bus().register(configChanged);
MazePlayerServerLogin serverLogin = new MazePlayerServerLogin();
MinecraftForge.EVENT_BUS.register(serverLogin);
FMLCommonHandler.instance().bus().register(serverLogin);
MazePlayerEntityEvent playerEvent = new MazePlayerEntityEvent();
MinecraftForge.EVENT_BUS.register(playerEvent);
FMLCommonHandler.instance().bus().register(playerEvent);
NetworkRegistry.INSTANCE.registerGuiHandler(CCLMaze.instance, new MazeGuiHandler());
MazePacketDispatcher.registerPackets();
}
public void postInit(FMLPostInitializationEvent e) {
CCLMaze.EDU = Loader.isModLoaded("MinecraftEDU");
}
/**
* Returns a side-appropriate EntityPlayer for use during message handling
*/
public EntityPlayer getPlayerEntity(MessageContext ctx) {
return ctx.getServerHandler().playerEntity;
}
}
| UTF-8 | Java | 2,928 | java | CommonProxy.java | Java | [] | null | [] | package com.christchurchcitylibraries.maze.common;
import java.io.File;
import com.christchurchcitylibraries.maze.CCLMaze;
import com.christchurchcitylibraries.maze.block.MazeBlocks;
import com.christchurchcitylibraries.maze.config.MazeConfigChangedHandler;
import com.christchurchcitylibraries.maze.config.MazeConfigHandler;
import com.christchurchcitylibraries.maze.crafting.MazeCrafting;
import com.christchurchcitylibraries.maze.gui.MazeGuiHandler;
import com.christchurchcitylibraries.maze.item.MazeItems;
import com.christchurchcitylibraries.maze.server.MazePacketDispatcher;
import com.christchurchcitylibraries.maze.server.MazePlayerEntityEvent;
import com.christchurchcitylibraries.maze.server.MazePlayerServerLogin;
import com.christchurchcitylibraries.maze.tileentity.MazeTileEntities;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.common.MinecraftForge;
public class CommonProxy {
private static File configDir;
public static File getConfigDir() {
return configDir;
}
public void preInit(FMLPreInitializationEvent e) {
MazeBlocks.createBlocks();
MazeItems.createItems();
MazeTileEntities.createTileEntities();
configDir = new File(e.getModConfigurationDirectory() + "/CCLMaze");
configDir.mkdirs();
MazeConfigHandler.initOptions(new File(configDir.getPath(), CCLMaze.MODID + ".cfg"));
MazeConfigHandler.initDoors(new File(configDir.getPath(), "doors.cfg"));
}
public void init(FMLInitializationEvent e) {
MazeCrafting.initCrafting();
MazeConfigChangedHandler configChanged = new MazeConfigChangedHandler();
MinecraftForge.EVENT_BUS.register(configChanged);
FMLCommonHandler.instance().bus().register(configChanged);
MazePlayerServerLogin serverLogin = new MazePlayerServerLogin();
MinecraftForge.EVENT_BUS.register(serverLogin);
FMLCommonHandler.instance().bus().register(serverLogin);
MazePlayerEntityEvent playerEvent = new MazePlayerEntityEvent();
MinecraftForge.EVENT_BUS.register(playerEvent);
FMLCommonHandler.instance().bus().register(playerEvent);
NetworkRegistry.INSTANCE.registerGuiHandler(CCLMaze.instance, new MazeGuiHandler());
MazePacketDispatcher.registerPackets();
}
public void postInit(FMLPostInitializationEvent e) {
CCLMaze.EDU = Loader.isModLoaded("MinecraftEDU");
}
/**
* Returns a side-appropriate EntityPlayer for use during message handling
*/
public EntityPlayer getPlayerEntity(MessageContext ctx) {
return ctx.getServerHandler().playerEntity;
}
}
| 2,928 | 0.804303 | 0.804303 | 70 | 39.828571 | 26.920504 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.514286 | false | false | 2 |
d9a5d3df9c9384f49dc85b9e30ed5e826f95b769 | 8,211,977,503,358 | 48232103d525e506f971209a970d6e9ac396c252 | /app/src/main/java/com/kuding/superball/Utils/BaseModelComparator.java | b608a4d5cabb821a85d44166cf4e52c30f7a50b0 | [] | no_license | kudingcarshop/NowKey | https://github.com/kudingcarshop/NowKey | a673046b5f282cf0e09a6cb9fb92446141557a70 | c184ace3d324b33a52467bf59dde5c089e862399 | refs/heads/master | 2020-03-18T04:11:26.416000 | 2018-05-30T07:48:22 | 2018-05-30T07:48:22 | 134,274,735 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kuding.superball.Utils;
import com.kuding.superball.info.BaseItemInfo;
import java.util.Comparator;
/**
* Created by user on 17-1-12.
*/
public class BaseModelComparator implements Comparator<BaseItemInfo> {
@Override
public int compare(BaseItemInfo baseItemInfo, BaseItemInfo t1) {
int index1 = baseItemInfo.getIndex();
int index2 = t1.getIndex();
if (index1 < index2) return -1;
if (index1 > index2) return 1;
return 0;
}
}
| UTF-8 | Java | 498 | java | BaseModelComparator.java | Java | [
{
"context": ";\n\nimport java.util.Comparator;\n\n/**\n * Created by user on 17-1-12.\n */\n\npublic class BaseModelComparator",
"end": 137,
"score": 0.9311869144439697,
"start": 133,
"tag": "USERNAME",
"value": "user"
}
] | null | [] | package com.kuding.superball.Utils;
import com.kuding.superball.info.BaseItemInfo;
import java.util.Comparator;
/**
* Created by user on 17-1-12.
*/
public class BaseModelComparator implements Comparator<BaseItemInfo> {
@Override
public int compare(BaseItemInfo baseItemInfo, BaseItemInfo t1) {
int index1 = baseItemInfo.getIndex();
int index2 = t1.getIndex();
if (index1 < index2) return -1;
if (index1 > index2) return 1;
return 0;
}
}
| 498 | 0.672691 | 0.640562 | 20 | 23.9 | 22.358219 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false | 2 |
1c84a9b23649a536b6660fb26e528f89e4c4017b | 27,977,416,981,284 | f9fae227166329a597848efd33eaa1296985d947 | /RatingsApp/src/Connections/DatabaseConnection.java | 329246ad9d9d63b850749b4a54507621ac084ed9 | [] | no_license | prabhu-maniraj/Social-Networking-Application-for-Ratings-and-Reviews | https://github.com/prabhu-maniraj/Social-Networking-Application-for-Ratings-and-Reviews | d24190d8b295c88cac56d3c3601f410507fb61eb | 241b027efcc42f0016008c32e38036f087ad20f9 | refs/heads/master | 2016-09-06T01:51:45.440000 | 2015-01-20T10:16:08 | 2015-01-20T10:16:08 | 29,523,618 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Connections;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.Date;
import java.sql.*;
import java.text.SimpleDateFormat;
import Connections.ManagedBeanAdmin;;
public class DatabaseConnection {
Connection con = null;
Statement stmt = null;
DatabaseConnection(){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("hello inside db construt");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/yelp","root","$pBu195986");
stmt = con.createStatement();
if(!con.isClosed())
System.out.println("Successfully Connected!!!");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ManagedBean signInUser(String emailid, String pwd){
ManagedBean arylst=new ManagedBean();
// int rowcount;
try {
String query="Select * from user where emailid='"+emailid+"'"+"and password='"+pwd+"'";
System.out.println("inside Sign in");
System.out.println(emailid+pwd);
//String query = "Insert into customer (username, password) values ('" + userName + "', '" + pwd + "')";
ResultSet rs=stmt.executeQuery(query);
System.out.println("+++"+rs);
if(rs.isBeforeFirst())
{
System.out.println("my if");
while(rs.next()){
arylst.setFirstname(rs.getString("firstname"));
arylst.setLastname(rs.getString("lastname"));
arylst.setEmailid(rs.getString("emailid"));
arylst.setLogintime(rs.getString("logintime"));
System.out.println(rs.getString("firstname"));
System.out.println("Signin Successful");
arylst.setReturnmsg("True");
}
Date logintime=new Date();
String queryTimeUpdate="update User set logintime='"+logintime+"' where emailid='"+emailid+"' and password='"+pwd+"' ";
int i = 0;
try {
i = stmt.executeUpdate(queryTimeUpdate);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(i>0)
{
System.out.println("Time updated sucessfully");
}
}
else{
arylst.setReturnmsg("False");
//result="false: The data could not be inserted in the database.";
System.out.println("Signin failed");
}
} catch (Exception e) {
// TODO Auto-generated catch block
//throw new SQLException("Entered user name or password is wrong");
e.printStackTrace();
}
return arylst;
}
public String[] viewAdminCatecory(){
String rest[]=new String [10];
try {
/*List<ManagedBeanAdmin> result=new ArrayList<ManagedBeanAdmin>();
ManagedBeanAdmin mb=new ManagedBeanAdmin();*/
int rowcount=0;
String query2="Select * from adminreviewsnew";
System.out.println("inside view admin Category");
ResultSet rs=stmt.executeQuery(query2);
while(rs.next()){
rowcount++;
}
rs.beforeFirst();
System.out.println(rowcount);
rest=new String[rowcount];
System.out.println(rest[0]);
int i=0;
while(rs.next()){
rest[i]=rs.getString("ename");
System.out.println(rest[i]);
System.out.println(rs.getString("ename"));
i++;
}
System.out.println("after get string");
if(rs.getRow()>=0){
System.out.println("Signin Successful");
}
else{
//result="false: The data could not be inserted in the database.";
System.out.println("Signin failed");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rest;
}
public String viewUserReviews(String email){
String rest=new String();
try {
/*List<ManagedBeanAdmin> result=new ArrayList<ManagedBeanAdmin>();
ManagedBeanAdmin mb=new ManagedBeanAdmin();*/
int rowcount=0;
String query2="Select * from userreviewsnew where emailid='"+email+"'";
System.out.println("inside view userreviews Category");
ResultSet rs=stmt.executeQuery(query2);
while(rs.next()){
rowcount++;
}
rs.beforeFirst();
System.out.println(rowcount);
System.out.println(rest);
int i=0;
while(rs.next()){
rest=rest+"Category:"+" "+rs.getString("ename")+" "+"Description:"+" "+rs.getString("edescription")+" "+"Ratings:"+" "+rs.getString("eratings")+" "+"Reviews"+" "+rs.getString("ereviews")+"-";
System.out.println(rest);
i++;
}
System.out.println("after get string");
if(rs.getRow()>=0){
System.out.println("Signin Successful");
}
else{
//result="false: The data could not be inserted in the database.";
System.out.println("Signin failed");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rest;
}
public String signUpUser(String firstname, String lastname,String emailid,String password){
String result = "";
String logintime=null;
int rowcount;
try {
Date date=new Date();
logintime=date.toString();
SimpleDateFormat ft =
new SimpleDateFormat ("hh:mm:ss");
ft.format(date);
System.out.println("Date is "+logintime);
String query = "Insert into user (firstname,lastname,emailid,password,logintime) values ('" + firstname + "', '" + lastname+"','" + emailid+"','"+password+"','"+logintime+"')";
//String query="Insert into user() emailid='"+emailid+"'"+"and password='"+pwd+"'";
rowcount=stmt.executeUpdate(query);
if(rowcount > 0){
result="true";
System.out.println("Insert Successful");
}
else{
result="false: The data could not be inserted in the database.";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public String createCategory(String ename, String edescription,String eratings, String ereviews, String mailid) {
// TODO Auto-generated method stub
String result="";
String logintime=null;
System.out.println("create cateogry");
int rowcount;
try {
System.out.println("Date is "+logintime);
String query = "Insert into adminreviewsnew (ename,edescription,eratings,ereviews,mailid) values ('" + ename+ "', '" +edescription+"','" +eratings+"','"+ereviews+"','"+mailid+"')";
//String query="Insert into user() emailid='"+emailid+"'"+"and password='"+pwd+"'";
//int i=0;
System.out.println("hi");
int i=stmt.executeUpdate(query);
/*while(rs.next())
{
i++;
}*/
if( i> 0){
result="true";
System.out.println("Insert Successful");
}
else{
result="false: The data could not be inserted in the database.";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public String deleteCategory(String ename) {
// TODO Auto-generated method stub
String result = "";
String logintime=null;
int rowcount;
try {
Date date=new Date();
logintime=date.toString();
SimpleDateFormat ft =
new SimpleDateFormat ("hh:mm:ss");
ft.format(date);
System.out.println("Date is "+logintime);
String query = "Delete from adminreviewsnew where ename='"+ename+"'";
//String query="Insert into user() emailid='"+emailid+"'"+"and password='"+pwd+"'";
rowcount=stmt.executeUpdate(query);
System.out.println(rowcount);
if(rowcount > 0){
result="true";
System.out.println("Delete Successful");
}
else{
result="false: The data could not be deleted from the database.";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public String updateCategory(String ename, String edescription,String eratings,String ereviews,String mailid) {
// TODO Auto-generated method stub
String result = "";
String logintime=null;
int rowcount;
try {
Date date=new Date();
logintime=date.toString();
SimpleDateFormat ft =
new SimpleDateFormat ("hh:mm:ss");
ft.format(date);
System.out.println("Date is "+logintime);
String query = "Update adminreviewsnew set ename='"+ename+"',"+"edescription='"+edescription+"',"+"eratings='"+eratings+"',"+"ereviews='"+ereviews+"',"+"mailid='"+mailid+"'"+"where mailid='"+mailid+"'"+"and ename='"+ename+"'";
//String query="Insert into user() emailid='"+emailid+"'"+"and password='"+pwd+"'";
rowcount=stmt.executeUpdate(query);
if(rowcount > 0){
result="true";
System.out.println("Update Successful");
}
else{
result="false: The data could not be inserted in the database.";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public ManagedBean signInAdmin(String emailid, String pwd){
ManagedBean arylst=new ManagedBean();
// int rowcount;
try {
String query="Select * from admin where emailid='"+emailid+"'"+"and password='"+pwd+"'";
System.out.println("inside Sign in");
System.out.println(emailid+pwd);
//String query = "Insert into customer (username, password) values ('" + userName + "', '" + pwd + "')";
ResultSet rs=stmt.executeQuery(query);
System.out.println("+++"+rs);
if(rs.isBeforeFirst())
{
while(rs.next()){
arylst.setFirstname(rs.getString("firstname"));
arylst.setLastname(rs.getString("lastname"));
arylst.setEmailid(rs.getString("emailid"));
arylst.setLogintime(rs.getString("logintime"));
System.out.println(rs.getString("firstname"));
System.out.println("Signin Successful");
arylst.setReturnmsg("True");
}
Date logintime=new Date();
String queryTimeUpdate="update admin set logintime='"+logintime+"' where emailid='"+emailid+"' and password='"+pwd+"' ";
int i = 0;
try {
i = stmt.executeUpdate(queryTimeUpdate);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(i>0)
{
System.out.println("Time updated sucessfully");
}
}
else{
arylst.setReturnmsg("False");
//result="false: The data could not be inserted in the database.";
System.out.println("Signin failed");
}
} catch (Exception e) {
// TODO Auto-generated catch block
//throw new SQLException("Entered user name or password is wrong");
e.printStackTrace();
}
return arylst;
}
}
| UTF-8 | Java | 10,457 | java | DatabaseConnection.java | Java | [
{
"context": "ction(\"jdbc:mysql://localhost:3306/yelp\",\"root\",\"$pBu195986\");\n\t\t\tstmt = con.createStatement();\n\t\t\tif(!con.is",
"end": 536,
"score": 0.7911957502365112,
"start": 527,
"tag": "PASSWORD",
"value": "pBu195986"
},
{
"context": "rt into customer (username, password) values ('\" + userName + \"', '\" + pwd + \"')\";\n\t\t\tResultSet rs=stmt.execu",
"end": 1430,
"score": 0.8853313326835632,
"start": 1422,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "me+\"' where emailid='\"+emailid+\"' and password='\"+pwd+\"' \";\n\t\t\t\tint i = 0;\n\t\t\t\ttry {\n\t\t\t\t\ti = stmt.exec",
"end": 2115,
"score": 0.9984246492385864,
"start": 2112,
"tag": "PASSWORD",
"value": "pwd"
},
{
"context": "to user() emailid='\"+emailid+\"'\"+\"and password='\"+pwd+\"'\";\n\n\t\t\trowcount=stmt.executeUpdate(query);\n\t\t\ti",
"end": 5562,
"score": 0.981590747833252,
"start": 5559,
"tag": "PASSWORD",
"value": "pwd"
},
{
"context": "to user() emailid='\"+emailid+\"'\"+\"and password='\"+pwd+\"'\";\n\t\t\t//int i=0;\n\t\t\tSystem.out.println(\"hi\");\n\t",
"end": 6472,
"score": 0.9976065158843994,
"start": 6469,
"tag": "PASSWORD",
"value": "pwd"
},
{
"context": "to user() emailid='\"+emailid+\"'\"+\"and password='\"+pwd+\"'\";\n\n\t\t\trowcount=stmt.executeUpdate(query);\n\t\t\tS",
"end": 7379,
"score": 0.9890495538711548,
"start": 7376,
"tag": "PASSWORD",
"value": "pwd"
},
{
"context": "to user() emailid='\"+emailid+\"'\"+\"and password='\"+pwd+\"'\";\n\n\t\t\trowcount=stmt.executeUpdate(query);\n\t\t\ti",
"end": 8468,
"score": 0.9881349802017212,
"start": 8465,
"tag": "PASSWORD",
"value": "pwd"
},
{
"context": "min where emailid='\"+emailid+\"'\"+\"and password='\"+pwd+\"'\";\n\t\t\tSystem.out.println(\"inside Sign in\");\n\t\t\t",
"end": 9017,
"score": 0.7030678391456604,
"start": 9014,
"tag": "PASSWORD",
"value": "pwd"
},
{
"context": "rt into customer (username, password) values ('\" + userName + \"', '\" + pwd + \"')\";\n\t\t\tResultSet rs=stmt.execu",
"end": 9184,
"score": 0.9674659967422485,
"start": 9176,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "ername, password) values ('\" + userName + \"', '\" + pwd + \"')\";\n\t\t\tResultSet rs=stmt.executeQuery(query);",
"end": 9199,
"score": 0.9060841798782349,
"start": 9196,
"tag": "PASSWORD",
"value": "pwd"
},
{
"context": "me+\"' where emailid='\"+emailid+\"' and password='\"+pwd+\"' \";\n\t\t\t\tint i = 0;\n\t\t\t\ttry {\n\t\t\t\t\ti = stmt.exec",
"end": 9842,
"score": 0.9699076414108276,
"start": 9839,
"tag": "PASSWORD",
"value": "pwd"
}
] | null | [] | package Connections;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.Date;
import java.sql.*;
import java.text.SimpleDateFormat;
import Connections.ManagedBeanAdmin;;
public class DatabaseConnection {
Connection con = null;
Statement stmt = null;
DatabaseConnection(){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("hello inside db construt");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/yelp","root","$<PASSWORD>");
stmt = con.createStatement();
if(!con.isClosed())
System.out.println("Successfully Connected!!!");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ManagedBean signInUser(String emailid, String pwd){
ManagedBean arylst=new ManagedBean();
// int rowcount;
try {
String query="Select * from user where emailid='"+emailid+"'"+"and password='"+pwd+"'";
System.out.println("inside Sign in");
System.out.println(emailid+pwd);
//String query = "Insert into customer (username, password) values ('" + userName + "', '" + pwd + "')";
ResultSet rs=stmt.executeQuery(query);
System.out.println("+++"+rs);
if(rs.isBeforeFirst())
{
System.out.println("my if");
while(rs.next()){
arylst.setFirstname(rs.getString("firstname"));
arylst.setLastname(rs.getString("lastname"));
arylst.setEmailid(rs.getString("emailid"));
arylst.setLogintime(rs.getString("logintime"));
System.out.println(rs.getString("firstname"));
System.out.println("Signin Successful");
arylst.setReturnmsg("True");
}
Date logintime=new Date();
String queryTimeUpdate="update User set logintime='"+logintime+"' where emailid='"+emailid+"' and password='"+pwd+"' ";
int i = 0;
try {
i = stmt.executeUpdate(queryTimeUpdate);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(i>0)
{
System.out.println("Time updated sucessfully");
}
}
else{
arylst.setReturnmsg("False");
//result="false: The data could not be inserted in the database.";
System.out.println("Signin failed");
}
} catch (Exception e) {
// TODO Auto-generated catch block
//throw new SQLException("Entered user name or password is wrong");
e.printStackTrace();
}
return arylst;
}
public String[] viewAdminCatecory(){
String rest[]=new String [10];
try {
/*List<ManagedBeanAdmin> result=new ArrayList<ManagedBeanAdmin>();
ManagedBeanAdmin mb=new ManagedBeanAdmin();*/
int rowcount=0;
String query2="Select * from adminreviewsnew";
System.out.println("inside view admin Category");
ResultSet rs=stmt.executeQuery(query2);
while(rs.next()){
rowcount++;
}
rs.beforeFirst();
System.out.println(rowcount);
rest=new String[rowcount];
System.out.println(rest[0]);
int i=0;
while(rs.next()){
rest[i]=rs.getString("ename");
System.out.println(rest[i]);
System.out.println(rs.getString("ename"));
i++;
}
System.out.println("after get string");
if(rs.getRow()>=0){
System.out.println("Signin Successful");
}
else{
//result="false: The data could not be inserted in the database.";
System.out.println("Signin failed");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rest;
}
public String viewUserReviews(String email){
String rest=new String();
try {
/*List<ManagedBeanAdmin> result=new ArrayList<ManagedBeanAdmin>();
ManagedBeanAdmin mb=new ManagedBeanAdmin();*/
int rowcount=0;
String query2="Select * from userreviewsnew where emailid='"+email+"'";
System.out.println("inside view userreviews Category");
ResultSet rs=stmt.executeQuery(query2);
while(rs.next()){
rowcount++;
}
rs.beforeFirst();
System.out.println(rowcount);
System.out.println(rest);
int i=0;
while(rs.next()){
rest=rest+"Category:"+" "+rs.getString("ename")+" "+"Description:"+" "+rs.getString("edescription")+" "+"Ratings:"+" "+rs.getString("eratings")+" "+"Reviews"+" "+rs.getString("ereviews")+"-";
System.out.println(rest);
i++;
}
System.out.println("after get string");
if(rs.getRow()>=0){
System.out.println("Signin Successful");
}
else{
//result="false: The data could not be inserted in the database.";
System.out.println("Signin failed");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rest;
}
public String signUpUser(String firstname, String lastname,String emailid,String password){
String result = "";
String logintime=null;
int rowcount;
try {
Date date=new Date();
logintime=date.toString();
SimpleDateFormat ft =
new SimpleDateFormat ("hh:mm:ss");
ft.format(date);
System.out.println("Date is "+logintime);
String query = "Insert into user (firstname,lastname,emailid,password,logintime) values ('" + firstname + "', '" + lastname+"','" + emailid+"','"+password+"','"+logintime+"')";
//String query="Insert into user() emailid='"+emailid+"'"+"and password='"+pwd+"'";
rowcount=stmt.executeUpdate(query);
if(rowcount > 0){
result="true";
System.out.println("Insert Successful");
}
else{
result="false: The data could not be inserted in the database.";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public String createCategory(String ename, String edescription,String eratings, String ereviews, String mailid) {
// TODO Auto-generated method stub
String result="";
String logintime=null;
System.out.println("create cateogry");
int rowcount;
try {
System.out.println("Date is "+logintime);
String query = "Insert into adminreviewsnew (ename,edescription,eratings,ereviews,mailid) values ('" + ename+ "', '" +edescription+"','" +eratings+"','"+ereviews+"','"+mailid+"')";
//String query="Insert into user() emailid='"+emailid+"'"+"and password='"+pwd+"'";
//int i=0;
System.out.println("hi");
int i=stmt.executeUpdate(query);
/*while(rs.next())
{
i++;
}*/
if( i> 0){
result="true";
System.out.println("Insert Successful");
}
else{
result="false: The data could not be inserted in the database.";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public String deleteCategory(String ename) {
// TODO Auto-generated method stub
String result = "";
String logintime=null;
int rowcount;
try {
Date date=new Date();
logintime=date.toString();
SimpleDateFormat ft =
new SimpleDateFormat ("hh:mm:ss");
ft.format(date);
System.out.println("Date is "+logintime);
String query = "Delete from adminreviewsnew where ename='"+ename+"'";
//String query="Insert into user() emailid='"+emailid+"'"+"and password='"+pwd+"'";
rowcount=stmt.executeUpdate(query);
System.out.println(rowcount);
if(rowcount > 0){
result="true";
System.out.println("Delete Successful");
}
else{
result="false: The data could not be deleted from the database.";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public String updateCategory(String ename, String edescription,String eratings,String ereviews,String mailid) {
// TODO Auto-generated method stub
String result = "";
String logintime=null;
int rowcount;
try {
Date date=new Date();
logintime=date.toString();
SimpleDateFormat ft =
new SimpleDateFormat ("hh:mm:ss");
ft.format(date);
System.out.println("Date is "+logintime);
String query = "Update adminreviewsnew set ename='"+ename+"',"+"edescription='"+edescription+"',"+"eratings='"+eratings+"',"+"ereviews='"+ereviews+"',"+"mailid='"+mailid+"'"+"where mailid='"+mailid+"'"+"and ename='"+ename+"'";
//String query="Insert into user() emailid='"+emailid+"'"+"and password='"+pwd+"'";
rowcount=stmt.executeUpdate(query);
if(rowcount > 0){
result="true";
System.out.println("Update Successful");
}
else{
result="false: The data could not be inserted in the database.";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public ManagedBean signInAdmin(String emailid, String pwd){
ManagedBean arylst=new ManagedBean();
// int rowcount;
try {
String query="Select * from admin where emailid='"+emailid+"'"+"and password='"+pwd+"'";
System.out.println("inside Sign in");
System.out.println(emailid+pwd);
//String query = "Insert into customer (username, password) values ('" + userName + "', '" + pwd + "')";
ResultSet rs=stmt.executeQuery(query);
System.out.println("+++"+rs);
if(rs.isBeforeFirst())
{
while(rs.next()){
arylst.setFirstname(rs.getString("firstname"));
arylst.setLastname(rs.getString("lastname"));
arylst.setEmailid(rs.getString("emailid"));
arylst.setLogintime(rs.getString("logintime"));
System.out.println(rs.getString("firstname"));
System.out.println("Signin Successful");
arylst.setReturnmsg("True");
}
Date logintime=new Date();
String queryTimeUpdate="update admin set logintime='"+logintime+"' where emailid='"+emailid+"' and password='"+pwd+"' ";
int i = 0;
try {
i = stmt.executeUpdate(queryTimeUpdate);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(i>0)
{
System.out.println("Time updated sucessfully");
}
}
else{
arylst.setReturnmsg("False");
//result="false: The data could not be inserted in the database.";
System.out.println("Signin failed");
}
} catch (Exception e) {
// TODO Auto-generated catch block
//throw new SQLException("Entered user name or password is wrong");
e.printStackTrace();
}
return arylst;
}
}
| 10,458 | 0.653342 | 0.650282 | 389 | 25.881748 | 29.549948 | 229 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.989717 | false | false | 2 |
197c1a06841a3f9fa96656679a619f876530902c | 24,129,126,310,661 | 7ef66bb12d0a0c8a721df339f1ab65c704a3b314 | /src/com/preppa/web/data/LongPassageDAO.java | cc5a7edc6eace1d8bae0998ac0a99475b5da3249 | [] | no_license | newtonik/preppa | https://github.com/newtonik/preppa | 89f47d424e8e20c514289af380094f1d28ed110b | ade2019a891a711f4d098cd1957e658b5364dfeb | refs/heads/master | 2020-05-20T06:49:30.117000 | 2009-10-13T04:00:40 | 2009-10-13T04:00:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.preppa.web.data;
import com.preppa.web.entities.LongPassage;
import java.util.List;
import org.chenillekit.hibernate.daos.GenericDAO;
/**
*
* @author nwt
*/
public interface LongPassageDAO extends GenericDAO<LongPassage, Integer> {
LongPassage findById(Integer id);
List<LongPassage> findByUserId(Integer id);
List<LongPassage> findByUserIds(List<Integer> ids);
List<LongPassage> findAllByAwaiting();
List<LongPassage> findAllByApproved();
}
| UTF-8 | Java | 584 | java | LongPassageDAO.java | Java | [
{
"context": "ekit.hibernate.daos.GenericDAO;\n\n/**\n *\n * @author nwt\n */\npublic interface LongPassageDAO extends Gener",
"end": 269,
"score": 0.9996218085289001,
"start": 266,
"tag": "USERNAME",
"value": "nwt"
}
] | null | [] | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.preppa.web.data;
import com.preppa.web.entities.LongPassage;
import java.util.List;
import org.chenillekit.hibernate.daos.GenericDAO;
/**
*
* @author nwt
*/
public interface LongPassageDAO extends GenericDAO<LongPassage, Integer> {
LongPassage findById(Integer id);
List<LongPassage> findByUserId(Integer id);
List<LongPassage> findByUserIds(List<Integer> ids);
List<LongPassage> findAllByAwaiting();
List<LongPassage> findAllByApproved();
}
| 584 | 0.741438 | 0.741438 | 26 | 21.461538 | 22.876307 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false | 2 |
d8c2e929b4b6b80801887722c22b91ea932725d3 | 24,129,126,314,169 | 546f5b6f2046d6c499939b1d124973473722ebb1 | /labQ01.java | 8e91578ee0a5a88daa5a3187fccf89ebb7cae689 | [] | no_license | nskonuk/Lab-1 | https://github.com/nskonuk/Lab-1 | c517a48f568429b2039b258cf262582066a4da6d | e547b0186e24228bad25fbf6ad3c5210b7e89a4c | refs/heads/main | 2022-12-27T16:47:51.811000 | 2020-10-14T15:14:22 | 2020-10-14T15:14:22 | 304,053,047 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package methods.sub;
public class labQ01 {
public static void main(String[] args) {
/* Question-1
Write a method that accepts a string and a non-negative number, and prints a larger string that is number copies of the original String
stringTimes("Hi", 2); = > HiHi
stringTimes("Hi", 3); = > HiHiHi
stringTimes("Hi", 1); = > Hi*/
stringTimes("Hi", 6);
}
public static void stringTimes(String copy, int num) {
copy="Hi"; //Alternative: String str="";
for (int i=1; i<=num; i++) {
System.out.print(copy); //str= copy+str
}
//System.out.print(str)
}
}
| UTF-8 | Java | 612 | java | labQ01.java | Java | [] | null | [] | package methods.sub;
public class labQ01 {
public static void main(String[] args) {
/* Question-1
Write a method that accepts a string and a non-negative number, and prints a larger string that is number copies of the original String
stringTimes("Hi", 2); = > HiHi
stringTimes("Hi", 3); = > HiHiHi
stringTimes("Hi", 1); = > Hi*/
stringTimes("Hi", 6);
}
public static void stringTimes(String copy, int num) {
copy="Hi"; //Alternative: String str="";
for (int i=1; i<=num; i++) {
System.out.print(copy); //str= copy+str
}
//System.out.print(str)
}
}
| 612 | 0.617647 | 0.604575 | 24 | 23.5 | 29.485872 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.208333 | false | false | 2 |
63ff120a600cb8894f049c23dc5546dae64e61df | 22,204,980,970,100 | a8266eda3a50c0a157fa42e81dd116c006085bdc | /WebSocket/src/main/java/com/vlad/www/webSocket/sessionStorage/SessionStorage.java | 3599a5e86b6b677fd7711afcea93ce90b5490310 | [] | no_license | VladislavBuglaev/ozonproject | https://github.com/VladislavBuglaev/ozonproject | cf93cf81247671f4277b0c54a31c41de81d8e8d4 | c410c50fea81ae33e4c8e7ecaf8de2f2d555d00b | refs/heads/master | 2019-07-31T15:38:12.140000 | 2016-12-16T08:17:22 | 2016-12-16T08:17:22 | 75,814,637 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vlad.www.webSocket.sessionStorage;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
import java.util.ArrayList;
import java.util.List;
@Component
public class SessionStorage {
private List<WebSocketSession> webSocketSessions = new ArrayList<>();
public List<WebSocketSession> getWebSocketSessions() {
return webSocketSessions;
}
}
| UTF-8 | Java | 425 | java | SessionStorage.java | Java | [] | null | [] | package com.vlad.www.webSocket.sessionStorage;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
import java.util.ArrayList;
import java.util.List;
@Component
public class SessionStorage {
private List<WebSocketSession> webSocketSessions = new ArrayList<>();
public List<WebSocketSession> getWebSocketSessions() {
return webSocketSessions;
}
}
| 425 | 0.781176 | 0.781176 | 18 | 22.611111 | 23.809753 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false | 2 |
d6f838c573cd355509331c41adcfa178dcd031d4 | 10,256,381,941,244 | adc2d9ae7d86ecbbff65672314614c169de979eb | /app/src/main/java/com/izrael/coronaindonesia/MapsFragment.java | da737efea60627ce81a33b1e91f6403a1e43818a | [] | no_license | IzraelAA/CoronaIndonesia | https://github.com/IzraelAA/CoronaIndonesia | deae882e0e5037acaf9ac9ced99fd5d110783cd7 | 4b6e8c48fa0387a49e6a6736f40c6d01a7938e44 | refs/heads/master | 2021-03-28T09:35:09.181000 | 2020-04-29T13:41:47 | 2020-04-29T13:41:47 | 247,854,712 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.izrael.coronaindonesia;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.Dash;
import com.google.android.gms.maps.model.Dot;
import com.google.android.gms.maps.model.Gap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PatternItem;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class MapsFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 5445;
public static final int PATTERN_DASH_LENGTH_PX = 10;
public static final int PATTERN_GAP_LENGTH_PX = 10;
public static final PatternItem DOT = new Dot();
public static final PatternItem DASH = new Dash(PATTERN_DASH_LENGTH_PX);
public static final PatternItem GAP = new Gap(PATTERN_GAP_LENGTH_PX);
ScrollView mScrollView;
public static final List<PatternItem> PATTERN_POLYGON_ALPHA = Arrays.asList(GAP, DASH);
DatabaseReference reference;
private Marker currentLocationMarker;
private Location currentLocation;
private boolean firstTimeFlag = true;
private double latitude, longitude;
private TextView setLokasi;
Polyline polyline = null;
PolylineOptions polylineOptions;
List<LatLng> latLngList = new ArrayList<>();
LatLng setsatu = null;
List<Marker> markerList = new ArrayList<>();
Button btnodp, pdp, positive;
TextView sembuh, meninggal;
private FusedLocationProviderClient fusedLocationProviderClient;
LatLng latLng = new LatLng(-6.2758471, 107.2544972);
LatLng latLng1 = new LatLng(-6.3053208, 106.8996445);
LatLng latLng2 = new LatLng(-6.533905, 107.448048);
LatLng latLng3 = new LatLng(-6.3410215, 107.1801674);
LatLng latLng4 = new LatLng(-6.956922, 107.584691);
LatLng latLng5 = new LatLng(-6.927209, 107.614859);
LatLng latLng6 = new LatLng(-6.961360, 107.561492);
LatLng latLng7 = new LatLng(-6.597611, 106.805470);
LatLng latLng8 = new LatLng(-6.340507, 107.1939298);
LatLng latLng9 = new LatLng(-6.598582, 106.801119);
LatLng latLng10 = new LatLng(-6.382692, 106.769069);
LatLng latLng11 = new LatLng(-6.381226, 106.760376);
LatLng latLng12 = new LatLng(-6.404720, 106.796021);
FirebaseUser user;
private Context mContext;
private MarkerOptions options = new MarkerOptions();
private ArrayList<String> latlngs = new ArrayList<>();
private ArrayList<LatLng> latlngPositif = new ArrayList<>();
private ArrayList<String> latlngprofensi = new ArrayList<>();
private ArrayList<String> latlngjumlah = new ArrayList<>();
FloatingActionButton halodoc;
public MapsFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View vi = inflater.inflate(R.layout.fragment_maps, container, false);
halodoc = vi.findViewById(R.id.halo);
final TextView textpdp = vi.findViewById(R.id.pdptext);
final TextView textodp = vi.findViewById(R.id.odptext);
textodp.setVisibility(View.GONE);
textpdp.setVisibility(View.GONE);
mContext = getActivity().getApplicationContext();
halodoc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "maintance halo doc ", Toast.LENGTH_SHORT).show();
}
});
btnodp = vi.findViewById(R.id.btnOdp);
pdp = vi.findViewById(R.id.btnPdp);
positive = vi.findViewById(R.id.btnPositive);
meninggal = vi.findViewById(R.id.meninggal);
sembuh = vi.findViewById(R.id.sembuh1);
user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference22 = FirebaseDatabase.getInstance().getReference("Jumlah");
reference22.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Log.d("", "onDataChange: " + dataSnapshot.child("Sembuh").getValue());
// Log.d("", "onDataChange:datasnap "+dataSnapshot);
Jumlah jumlah = dataSnapshot.getValue(Jumlah.class);
// assert jumlah != null;
String o = jumlah.getOdp();
String p = jumlah.getPdp();
Log.d("", "onDataChange11: " + o + " " + p);
if (o.equals("maintance")) {
btnodp.setVisibility(View.GONE);
} else {
btnodp.setVisibility(View.VISIBLE);
textodp.setVisibility(View.VISIBLE);
btnodp.setText(o + "\n" + "ODP");
}
if (p.equals("maintance")) {
pdp.setVisibility(View.GONE);
} else {
pdp.setVisibility(View.VISIBLE);
textpdp.setVisibility(View.VISIBLE);
pdp.setText(jumlah.getPdp() + "\n" + "PDP");
}
meninggal.setText(jumlah.getMeninggal() + "\n" + "Meninggal");
positive.setText(jumlah.getPositif() + "\n" + "Positif");
sembuh.setText(jumlah.getSembuh() + "\n" + "Sembuh");
// Toast.makeText(getActivity().getApplicationContext(), jumlah.getMeninggal().toString(), Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("", "onDataChange:datasnap " + databaseError);
}
});
if (mMap == null) {
SupportMapFragment mapFragment = (WorkaroundMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
try {
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
getContext(), R.raw.style_json));
if (!success) {
Log.e("", "Style parsing failed.");
}
} catch (Resources.NotFoundException e) {
Log.e("", "Can't find style. Error: ", e);
}
DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference("Maps");
reference1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Log.d("hh", "onDataChange:22 " + snapshot.child("Latitude").getValue(Double.class));
Maps map = snapshot.getValue(Maps.class);
Log.d("data snapshot", "onDataChange: " + snapshot);
Log.d("hh", "onDataChange: " + dataSnapshot);
Log.d("testlat", "onDataChange lat: " + map.getLatitude());
Log.d("testlat", "onDataChange lat: " + map.getLongtitude());
Log.d("testlat", "onDataChange lat: " + map.getProvensi());
Log.d("testlat", "onDataChange lat: " + map.getStatus());
latlngs.add(map.getStatus());
latlngprofensi.add(map.getProvensi());
latlngjumlah.add(map.getJumlahorang());
latlngPositif.add(new LatLng(map.getLongtitude(), map.getLatitude()));
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker marker) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
LinearLayout info = new LinearLayout(getActivity().getApplicationContext());
info.setOrientation(LinearLayout.VERTICAL);
TextView title = new TextView(getActivity().getApplicationContext());
title.setTextColor(Color.BLACK);
title.setGravity(Gravity.CENTER);
title.setTypeface(null, Typeface.BOLD);
title.setText(marker.getTitle());
TextView snippet = new TextView(getActivity().getApplicationContext());
snippet.setTextColor(Color.GRAY);
snippet.setText(marker.getSnippet());
info.addView(title);
info.addView(snippet);
return info;
}
});
Log.d("", "onDataChange:fen " + latlngprofensi.size());
Log.d("", "onDataChange:tiv " + latlngPositif.size());
for (int i = 0; i < latlngPositif.size(); i++) {
@DrawableRes int vectorDrawableResourceId = R.drawable.ic_location_on_red_24dp;
if (latlngs.get(i).equals("Positif")) {
vectorDrawableResourceId = R.drawable.ic_location_on_red_24dp;
mMap.addMarker(new MarkerOptions().position(latlngPositif.get(i)).title(latlngprofensi.get(i)).snippet(latlngs.get(i) + "" + "\n" + latlngjumlah.get(i) + " Orang").icon(bitmapDescriptorFromVector(mContext,R.drawable.ic_positiveicon)));
mMap.getUiSettings().setZoomControlsEnabled(true);
}
if (latlngs.get(i).equals("PDP")) {
vectorDrawableResourceId = R.drawable.ic_place_black_24dp;
mMap.addMarker(new MarkerOptions().position(latlngPositif.get(i)).title(latlngprofensi.get(i)).snippet(latlngs.get(i) + "" + "\n" + latlngjumlah.get(i) + " Orang").icon(bitmapDescriptorFromVector1(mContext, R.drawable.ic_pdpicon)));
mMap.getUiSettings().setZoomControlsEnabled(true);
}
if (latlngs.get(i).equals("ODP")) {
vectorDrawableResourceId = R.drawable.ic_place_blue_24dp;
mMap.addMarker(new MarkerOptions().position(latlngPositif.get(i)).title(latlngprofensi.get(i)).snippet(latlngs.get(i) + "" + "\n" + latlngjumlah.get(i) + " Orang").icon(bitmapDescriptorFromVector2(mContext, R.drawable.ic_odpicon)));
mMap.getUiSettings().setZoomControlsEnabled(true);
}
Log.d("", "onDataChange: maps 1" + latlngPositif.toString());
Log.d("", "onDataChange: maps 1" + latlngPositif.get(0).latitude);
Log.d("2", "onMapReady: " + latlngPositif);
}
//// for (int i = 0; i < latlngs.size(); i++) {
//// mMap.addMarker(new MarkerOptions().position(latlngs.get(i)).title("Terindekasi"));
//// mMap.getUiSettings().setZoomControlsEnabled(true);
//// mMap.moveCamera(CameraUpdateFactory.newLatLng(latlngs.get(i)));
// }
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng2));
mMap.animateCamera(CameraUpdateFactory.zoomIn());
// Zoom out to zoom level 10, animating with a duration of 2 seconds.
mMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
// Add a marker in Sydney and move the camera
mScrollView = vi.findViewById(R.id.scrollMap); //parent scrollview in xml, give your scrollview id value
((WorkaroundMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map))
.setListener(new WorkaroundMapFragment.OnTouchListener() {
@Override
public void onTouch() {
mScrollView.requestDisallowInterceptTouchEvent(true);
}
});
}
});
}
final LocationManager locationM = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (!locationM.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Harap Nyalakan GPS Terlebih Dahulu")
.setTitle("Tidak Dapat Menemukan Lokasi")
.setCancelable(false)
.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent openLocationSettings = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
getActivity().startActivity(openLocationSettings);
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startCurrentLocationUpdates();
}
}
);
AlertDialog alert = builder.create();
alert.show();
}
return vi;
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
private BitmapDescriptor bitmapDescriptorFromVector(Context context, @DrawableRes int vectorDrawableResourceId) {
Drawable background = ContextCompat.getDrawable(context, R.drawable.ic_positiveicon);
background.setBounds(0, 0, background.getIntrinsicWidth(), background.getIntrinsicHeight());
Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorDrawableResourceId);
vectorDrawable.setBounds(40, 20, vectorDrawable.getIntrinsicWidth() + 40, vectorDrawable.getIntrinsicHeight() + 20);
Bitmap bitmap = Bitmap.createBitmap(background.getIntrinsicWidth(), background.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
background.draw(canvas);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
private BitmapDescriptor bitmapDescriptorFromVector1(Context context, @DrawableRes int vectorDrawableResourceId) {
Drawable background = ContextCompat.getDrawable(context, R.drawable.ic_pdpicon);
background.setBounds(0, 0, background.getIntrinsicWidth(), background.getIntrinsicHeight());
Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorDrawableResourceId);
vectorDrawable.setBounds(40, 20, vectorDrawable.getIntrinsicWidth() + 40, vectorDrawable.getIntrinsicHeight() + 20);
Bitmap bitmap = Bitmap.createBitmap(background.getIntrinsicWidth(), background.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
background.draw(canvas);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
private BitmapDescriptor bitmapDescriptorFromVector2(Context context, @DrawableRes int vectorDrawableResourceId) {
Drawable background = ContextCompat.getDrawable(context, R.drawable.ic_odpicon);
background.setBounds(0, 0, background.getIntrinsicWidth(), background.getIntrinsicHeight());
Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorDrawableResourceId);
vectorDrawable.setBounds(40, 20, vectorDrawable.getIntrinsicWidth() + 40, vectorDrawable.getIntrinsicHeight() + 20);
Bitmap bitmap = Bitmap.createBitmap(background.getIntrinsicWidth(), background.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
background.draw(canvas);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
private final LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult.getLastLocation() == null)
return;
currentLocation = locationResult.getLastLocation();
if (firstTimeFlag && mMap != null) {
animateCamera(currentLocation);
firstTimeFlag = false;
}
showMarker(currentLocation);
upload(currentLocation);
}
};
private void showMarker(@NonNull Location currentLocation) {
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
Log.d("ceklogtitude", "showMarker: " + currentLocation.getLatitude() + "&" + currentLocation.getLongitude());
if (currentLocationMarker == null) {
Log.d("", "showMarker: " + currentLocationMarker);
// currentLocationMarker = mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_my_location)).position(latLng));
// currentLocationMarker = googleMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_pin_location)).anchor(0.5f, 0.5f));
} else
MarkerAnimation.animateMarkerToGB(currentLocationMarker, latLng, new LatLngInterpolator.Spherical());
}
private void animateCamera(@NonNull Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(getCameraPositionWithBearing(latLng)));
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(getActivity());
if (ConnectionResult.SUCCESS == status)
return true;
else {
if (googleApiAvailability.isUserResolvableError(status))
Toast.makeText(getActivity(), "Please Install google play services to use this application", Toast.LENGTH_LONG).show();
}
return false;
}
private void startCurrentLocationUpdates() {
//Untuk permission Lokasi GPS
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(3000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
return;
}
}
//Untuk data internet
String status = null;
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Kamu Tidak Memiliki Koneksi Internet, Harap Nyalakan Data Seluler atau Wi-Fi")
.setTitle("Tidak Ada Koneksi")
.setCancelable(false)
.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startCurrentLocationUpdates();
}
}
);
AlertDialog alert = builder.create();
alert.show();
}
//untuk cek apakah gps on/off
final LocationManager locationM = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (!locationM.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Harap Nyalakan GPS Terlebih Dahulu")
.setTitle("Tidak Dapat Menemukan Lokasi")
.setCancelable(false)
.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent openLocationSettings = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
getActivity().startActivity(openLocationSettings);
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startCurrentLocationUpdates();
}
}
);
AlertDialog alert = builder.create();
alert.show();
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, mLocationCallback, Looper.myLooper());
}
public void upload(@NonNull Location currentLocation) {
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
String userid = user.getUid();
reference = FirebaseDatabase.getInstance().getReference("Test").child(userid);
HashMap<String, Object> hashmap = new HashMap<>();
hashmap.put("location", latLng.toString());
hashmap.put("latitude", currentLocation.getLatitude());
hashmap.put("longtitude", currentLocation.getLongitude());
reference.updateChildren(hashmap);
}
@Override
public void onStop() {
super.onStop();
if (fusedLocationProviderClient != null)
fusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
}
@Override
public void onResume() {
super.onResume();
if (isGooglePlayServicesAvailable()) {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
startCurrentLocationUpdates();
}
}
@NonNull
private CameraPosition getCameraPositionWithBearing(LatLng latLng) {
return new CameraPosition.Builder().target(latLng).zoom(6).build();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED)
Toast.makeText(getActivity(), "Permission denied by uses", Toast.LENGTH_SHORT).show();
else if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
startCurrentLocationUpdates();
}
}
}
| UTF-8 | Java | 29,113 | java | MapsFragment.java | Java | [] | null | [] | package com.izrael.coronaindonesia;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.Dash;
import com.google.android.gms.maps.model.Dot;
import com.google.android.gms.maps.model.Gap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PatternItem;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class MapsFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 5445;
public static final int PATTERN_DASH_LENGTH_PX = 10;
public static final int PATTERN_GAP_LENGTH_PX = 10;
public static final PatternItem DOT = new Dot();
public static final PatternItem DASH = new Dash(PATTERN_DASH_LENGTH_PX);
public static final PatternItem GAP = new Gap(PATTERN_GAP_LENGTH_PX);
ScrollView mScrollView;
public static final List<PatternItem> PATTERN_POLYGON_ALPHA = Arrays.asList(GAP, DASH);
DatabaseReference reference;
private Marker currentLocationMarker;
private Location currentLocation;
private boolean firstTimeFlag = true;
private double latitude, longitude;
private TextView setLokasi;
Polyline polyline = null;
PolylineOptions polylineOptions;
List<LatLng> latLngList = new ArrayList<>();
LatLng setsatu = null;
List<Marker> markerList = new ArrayList<>();
Button btnodp, pdp, positive;
TextView sembuh, meninggal;
private FusedLocationProviderClient fusedLocationProviderClient;
LatLng latLng = new LatLng(-6.2758471, 107.2544972);
LatLng latLng1 = new LatLng(-6.3053208, 106.8996445);
LatLng latLng2 = new LatLng(-6.533905, 107.448048);
LatLng latLng3 = new LatLng(-6.3410215, 107.1801674);
LatLng latLng4 = new LatLng(-6.956922, 107.584691);
LatLng latLng5 = new LatLng(-6.927209, 107.614859);
LatLng latLng6 = new LatLng(-6.961360, 107.561492);
LatLng latLng7 = new LatLng(-6.597611, 106.805470);
LatLng latLng8 = new LatLng(-6.340507, 107.1939298);
LatLng latLng9 = new LatLng(-6.598582, 106.801119);
LatLng latLng10 = new LatLng(-6.382692, 106.769069);
LatLng latLng11 = new LatLng(-6.381226, 106.760376);
LatLng latLng12 = new LatLng(-6.404720, 106.796021);
FirebaseUser user;
private Context mContext;
private MarkerOptions options = new MarkerOptions();
private ArrayList<String> latlngs = new ArrayList<>();
private ArrayList<LatLng> latlngPositif = new ArrayList<>();
private ArrayList<String> latlngprofensi = new ArrayList<>();
private ArrayList<String> latlngjumlah = new ArrayList<>();
FloatingActionButton halodoc;
public MapsFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View vi = inflater.inflate(R.layout.fragment_maps, container, false);
halodoc = vi.findViewById(R.id.halo);
final TextView textpdp = vi.findViewById(R.id.pdptext);
final TextView textodp = vi.findViewById(R.id.odptext);
textodp.setVisibility(View.GONE);
textpdp.setVisibility(View.GONE);
mContext = getActivity().getApplicationContext();
halodoc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "maintance halo doc ", Toast.LENGTH_SHORT).show();
}
});
btnodp = vi.findViewById(R.id.btnOdp);
pdp = vi.findViewById(R.id.btnPdp);
positive = vi.findViewById(R.id.btnPositive);
meninggal = vi.findViewById(R.id.meninggal);
sembuh = vi.findViewById(R.id.sembuh1);
user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference22 = FirebaseDatabase.getInstance().getReference("Jumlah");
reference22.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Log.d("", "onDataChange: " + dataSnapshot.child("Sembuh").getValue());
// Log.d("", "onDataChange:datasnap "+dataSnapshot);
Jumlah jumlah = dataSnapshot.getValue(Jumlah.class);
// assert jumlah != null;
String o = jumlah.getOdp();
String p = jumlah.getPdp();
Log.d("", "onDataChange11: " + o + " " + p);
if (o.equals("maintance")) {
btnodp.setVisibility(View.GONE);
} else {
btnodp.setVisibility(View.VISIBLE);
textodp.setVisibility(View.VISIBLE);
btnodp.setText(o + "\n" + "ODP");
}
if (p.equals("maintance")) {
pdp.setVisibility(View.GONE);
} else {
pdp.setVisibility(View.VISIBLE);
textpdp.setVisibility(View.VISIBLE);
pdp.setText(jumlah.getPdp() + "\n" + "PDP");
}
meninggal.setText(jumlah.getMeninggal() + "\n" + "Meninggal");
positive.setText(jumlah.getPositif() + "\n" + "Positif");
sembuh.setText(jumlah.getSembuh() + "\n" + "Sembuh");
// Toast.makeText(getActivity().getApplicationContext(), jumlah.getMeninggal().toString(), Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("", "onDataChange:datasnap " + databaseError);
}
});
if (mMap == null) {
SupportMapFragment mapFragment = (WorkaroundMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
try {
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
getContext(), R.raw.style_json));
if (!success) {
Log.e("", "Style parsing failed.");
}
} catch (Resources.NotFoundException e) {
Log.e("", "Can't find style. Error: ", e);
}
DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference("Maps");
reference1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Log.d("hh", "onDataChange:22 " + snapshot.child("Latitude").getValue(Double.class));
Maps map = snapshot.getValue(Maps.class);
Log.d("data snapshot", "onDataChange: " + snapshot);
Log.d("hh", "onDataChange: " + dataSnapshot);
Log.d("testlat", "onDataChange lat: " + map.getLatitude());
Log.d("testlat", "onDataChange lat: " + map.getLongtitude());
Log.d("testlat", "onDataChange lat: " + map.getProvensi());
Log.d("testlat", "onDataChange lat: " + map.getStatus());
latlngs.add(map.getStatus());
latlngprofensi.add(map.getProvensi());
latlngjumlah.add(map.getJumlahorang());
latlngPositif.add(new LatLng(map.getLongtitude(), map.getLatitude()));
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker marker) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
LinearLayout info = new LinearLayout(getActivity().getApplicationContext());
info.setOrientation(LinearLayout.VERTICAL);
TextView title = new TextView(getActivity().getApplicationContext());
title.setTextColor(Color.BLACK);
title.setGravity(Gravity.CENTER);
title.setTypeface(null, Typeface.BOLD);
title.setText(marker.getTitle());
TextView snippet = new TextView(getActivity().getApplicationContext());
snippet.setTextColor(Color.GRAY);
snippet.setText(marker.getSnippet());
info.addView(title);
info.addView(snippet);
return info;
}
});
Log.d("", "onDataChange:fen " + latlngprofensi.size());
Log.d("", "onDataChange:tiv " + latlngPositif.size());
for (int i = 0; i < latlngPositif.size(); i++) {
@DrawableRes int vectorDrawableResourceId = R.drawable.ic_location_on_red_24dp;
if (latlngs.get(i).equals("Positif")) {
vectorDrawableResourceId = R.drawable.ic_location_on_red_24dp;
mMap.addMarker(new MarkerOptions().position(latlngPositif.get(i)).title(latlngprofensi.get(i)).snippet(latlngs.get(i) + "" + "\n" + latlngjumlah.get(i) + " Orang").icon(bitmapDescriptorFromVector(mContext,R.drawable.ic_positiveicon)));
mMap.getUiSettings().setZoomControlsEnabled(true);
}
if (latlngs.get(i).equals("PDP")) {
vectorDrawableResourceId = R.drawable.ic_place_black_24dp;
mMap.addMarker(new MarkerOptions().position(latlngPositif.get(i)).title(latlngprofensi.get(i)).snippet(latlngs.get(i) + "" + "\n" + latlngjumlah.get(i) + " Orang").icon(bitmapDescriptorFromVector1(mContext, R.drawable.ic_pdpicon)));
mMap.getUiSettings().setZoomControlsEnabled(true);
}
if (latlngs.get(i).equals("ODP")) {
vectorDrawableResourceId = R.drawable.ic_place_blue_24dp;
mMap.addMarker(new MarkerOptions().position(latlngPositif.get(i)).title(latlngprofensi.get(i)).snippet(latlngs.get(i) + "" + "\n" + latlngjumlah.get(i) + " Orang").icon(bitmapDescriptorFromVector2(mContext, R.drawable.ic_odpicon)));
mMap.getUiSettings().setZoomControlsEnabled(true);
}
Log.d("", "onDataChange: maps 1" + latlngPositif.toString());
Log.d("", "onDataChange: maps 1" + latlngPositif.get(0).latitude);
Log.d("2", "onMapReady: " + latlngPositif);
}
//// for (int i = 0; i < latlngs.size(); i++) {
//// mMap.addMarker(new MarkerOptions().position(latlngs.get(i)).title("Terindekasi"));
//// mMap.getUiSettings().setZoomControlsEnabled(true);
//// mMap.moveCamera(CameraUpdateFactory.newLatLng(latlngs.get(i)));
// }
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng2));
mMap.animateCamera(CameraUpdateFactory.zoomIn());
// Zoom out to zoom level 10, animating with a duration of 2 seconds.
mMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
// Add a marker in Sydney and move the camera
mScrollView = vi.findViewById(R.id.scrollMap); //parent scrollview in xml, give your scrollview id value
((WorkaroundMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map))
.setListener(new WorkaroundMapFragment.OnTouchListener() {
@Override
public void onTouch() {
mScrollView.requestDisallowInterceptTouchEvent(true);
}
});
}
});
}
final LocationManager locationM = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (!locationM.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Harap Nyalakan GPS Terlebih Dahulu")
.setTitle("Tidak Dapat Menemukan Lokasi")
.setCancelable(false)
.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent openLocationSettings = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
getActivity().startActivity(openLocationSettings);
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startCurrentLocationUpdates();
}
}
);
AlertDialog alert = builder.create();
alert.show();
}
return vi;
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
private BitmapDescriptor bitmapDescriptorFromVector(Context context, @DrawableRes int vectorDrawableResourceId) {
Drawable background = ContextCompat.getDrawable(context, R.drawable.ic_positiveicon);
background.setBounds(0, 0, background.getIntrinsicWidth(), background.getIntrinsicHeight());
Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorDrawableResourceId);
vectorDrawable.setBounds(40, 20, vectorDrawable.getIntrinsicWidth() + 40, vectorDrawable.getIntrinsicHeight() + 20);
Bitmap bitmap = Bitmap.createBitmap(background.getIntrinsicWidth(), background.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
background.draw(canvas);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
private BitmapDescriptor bitmapDescriptorFromVector1(Context context, @DrawableRes int vectorDrawableResourceId) {
Drawable background = ContextCompat.getDrawable(context, R.drawable.ic_pdpicon);
background.setBounds(0, 0, background.getIntrinsicWidth(), background.getIntrinsicHeight());
Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorDrawableResourceId);
vectorDrawable.setBounds(40, 20, vectorDrawable.getIntrinsicWidth() + 40, vectorDrawable.getIntrinsicHeight() + 20);
Bitmap bitmap = Bitmap.createBitmap(background.getIntrinsicWidth(), background.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
background.draw(canvas);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
private BitmapDescriptor bitmapDescriptorFromVector2(Context context, @DrawableRes int vectorDrawableResourceId) {
Drawable background = ContextCompat.getDrawable(context, R.drawable.ic_odpicon);
background.setBounds(0, 0, background.getIntrinsicWidth(), background.getIntrinsicHeight());
Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorDrawableResourceId);
vectorDrawable.setBounds(40, 20, vectorDrawable.getIntrinsicWidth() + 40, vectorDrawable.getIntrinsicHeight() + 20);
Bitmap bitmap = Bitmap.createBitmap(background.getIntrinsicWidth(), background.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
background.draw(canvas);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
private final LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult.getLastLocation() == null)
return;
currentLocation = locationResult.getLastLocation();
if (firstTimeFlag && mMap != null) {
animateCamera(currentLocation);
firstTimeFlag = false;
}
showMarker(currentLocation);
upload(currentLocation);
}
};
private void showMarker(@NonNull Location currentLocation) {
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
Log.d("ceklogtitude", "showMarker: " + currentLocation.getLatitude() + "&" + currentLocation.getLongitude());
if (currentLocationMarker == null) {
Log.d("", "showMarker: " + currentLocationMarker);
// currentLocationMarker = mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_my_location)).position(latLng));
// currentLocationMarker = googleMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_pin_location)).anchor(0.5f, 0.5f));
} else
MarkerAnimation.animateMarkerToGB(currentLocationMarker, latLng, new LatLngInterpolator.Spherical());
}
private void animateCamera(@NonNull Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(getCameraPositionWithBearing(latLng)));
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(getActivity());
if (ConnectionResult.SUCCESS == status)
return true;
else {
if (googleApiAvailability.isUserResolvableError(status))
Toast.makeText(getActivity(), "Please Install google play services to use this application", Toast.LENGTH_LONG).show();
}
return false;
}
private void startCurrentLocationUpdates() {
//Untuk permission Lokasi GPS
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(3000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
return;
}
}
//Untuk data internet
String status = null;
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Kamu Tidak Memiliki Koneksi Internet, Harap Nyalakan Data Seluler atau Wi-Fi")
.setTitle("Tidak Ada Koneksi")
.setCancelable(false)
.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startCurrentLocationUpdates();
}
}
);
AlertDialog alert = builder.create();
alert.show();
}
//untuk cek apakah gps on/off
final LocationManager locationM = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (!locationM.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Harap Nyalakan GPS Terlebih Dahulu")
.setTitle("Tidak Dapat Menemukan Lokasi")
.setCancelable(false)
.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent openLocationSettings = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
getActivity().startActivity(openLocationSettings);
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startCurrentLocationUpdates();
}
}
);
AlertDialog alert = builder.create();
alert.show();
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, mLocationCallback, Looper.myLooper());
}
public void upload(@NonNull Location currentLocation) {
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
String userid = user.getUid();
reference = FirebaseDatabase.getInstance().getReference("Test").child(userid);
HashMap<String, Object> hashmap = new HashMap<>();
hashmap.put("location", latLng.toString());
hashmap.put("latitude", currentLocation.getLatitude());
hashmap.put("longtitude", currentLocation.getLongitude());
reference.updateChildren(hashmap);
}
@Override
public void onStop() {
super.onStop();
if (fusedLocationProviderClient != null)
fusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
}
@Override
public void onResume() {
super.onResume();
if (isGooglePlayServicesAvailable()) {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
startCurrentLocationUpdates();
}
}
@NonNull
private CameraPosition getCameraPositionWithBearing(LatLng latLng) {
return new CameraPosition.Builder().target(latLng).zoom(6).build();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED)
Toast.makeText(getActivity(), "Permission denied by uses", Toast.LENGTH_SHORT).show();
else if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
startCurrentLocationUpdates();
}
}
}
| 29,113 | 0.591763 | 0.580394 | 547 | 52.223034 | 38.735188 | 297 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.808044 | false | false | 2 |
0dab431aca9dd7b6ab7cf89cf4bd6bb5923d091a | 13,975,823,595,992 | 195fd2f130def57690aa182e57bb7cf8b5e4c5dc | /src/test/java/chap01/crud/TestTable.java | 113cfeac9e72fe47848e3994d4a91954fee25b2c | [] | no_license | yunsu504/HibernateTutorial | https://github.com/yunsu504/HibernateTutorial | 68883e9e13f6e1ac49ca2d6e34b64af1818c8cc8 | 08c9c12b31b089400c6a9f63dfcd28f728468227 | refs/heads/master | 2023-02-25T21:02:12.265000 | 2021-02-02T02:39:58 | 2021-02-02T02:39:58 | 331,572,916 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package chap01.crud;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class TestTable {
@Id
@GeneratedValue
private int tableSeq;
public TestTable() {
}
}
| UTF-8 | Java | 239 | java | TestTable.java | Java | [] | null | [] | package chap01.crud;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class TestTable {
@Id
@GeneratedValue
private int tableSeq;
public TestTable() {
}
}
| 239 | 0.753138 | 0.74477 | 18 | 12.277778 | 12.753238 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false | 2 |
6375024bad7d6c050a80be95879ff04dd0579b3f | 15,874,199,161,171 | 0429530be4eb698b83f127d925e0c7e84ddf97a0 | /sport/src/main/java/org/cd/sport/dao/SubjectRwsDao.java | c71ab221761588ae42bc6c0dfc5e7bec7a5d6fca | [] | no_license | caoruitan/sport | https://github.com/caoruitan/sport | 0616dd2936de2cc4397ae03cff7d16572b0716c8 | 77a19d5f661b1dd658e91921ff9d722c1551e2d5 | refs/heads/master | 2021-01-10T22:57:03.547000 | 2017-03-21T16:14:14 | 2017-03-21T16:14:14 | 70,439,465 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.cd.sport.dao;
import org.cd.sport.domain.SubjectRws;
import org.cd.sport.hibernate.IBaseDao;
public interface SubjectRwsDao extends IBaseDao {
public boolean deleteById(String id);
public SubjectRws getRwsBySubjectId(String subjectId);
}
| UTF-8 | Java | 269 | java | SubjectRwsDao.java | Java | [] | null | [] | package org.cd.sport.dao;
import org.cd.sport.domain.SubjectRws;
import org.cd.sport.hibernate.IBaseDao;
public interface SubjectRwsDao extends IBaseDao {
public boolean deleteById(String id);
public SubjectRws getRwsBySubjectId(String subjectId);
}
| 269 | 0.769517 | 0.769517 | 12 | 20.416666 | 21.328613 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 2 |
84deaccec74b9a8803b546733f0014a5f3f47a84 | 31,542,239,851,570 | 65dd55f181ddeddff95893abbc06e049d5434e59 | /Back-End/src/main/java/br/jus/stj/siscovi/dao/sql/DeleteTSQL.java | e8ec09a9518255a8f575189254432ac0d64bda41 | [] | no_license | VSSantana/SISCOVI | https://github.com/VSSantana/SISCOVI | 1805a2aa6f9c9204d669ba60c4c0c5c6947d3f27 | e9132ccfa6220b1bac7fa30e4082e550cd4a74f5 | refs/heads/master | 2021-06-30T06:12:41.674000 | 2019-02-04T18:06:14 | 2019-02-04T18:06:14 | 102,145,041 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.jus.stj.siscovi.dao.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DeleteTSQL {
private Connection connection;
public DeleteTSQL(Connection connection) {
this.connection = connection;
}
/**
* Método que exclui um registro da tabela de restituição de férias.
*
* @param pCodRestituicaoFerias;
*/
public void DeleteRestituicaoFerias (int pCodRestituicaoFerias) {
PreparedStatement preparedStatement;
String query = "DELETE FROM tb_restituicao_ferias WHERE cod = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCodRestituicaoFerias);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro solicitado da restituição de férias.");
}
}
/**
* Método que exclui um registro da tabela de saldo residual de férias.
*
* @param pCodRestituicaoFerias;
*/
public void DeleteSaldoResidualFerias (int pCodRestituicaoFerias) {
PreparedStatement preparedStatement;
String query = "DELETE FROM tb_saldo_residual_ferias WHERE cod_restituicao_ferias = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCodRestituicaoFerias);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro solicitado do saldo residual de férias.");
}
}
/**
* Método que exclui um registro da tabela de restituição de décimo terceiro.
*
* @param pCodRestituicaoDecimoTerceiro;
*/
public void DeleteRestituicaoDecimoTerceiro (int pCodRestituicaoDecimoTerceiro) {
PreparedStatement preparedStatement;
String query = "DELETE FROM tb_restituicao_decimo_terceiro WHERE cod = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCodRestituicaoDecimoTerceiro);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro solicitado da restituição de décimo terceiro.");
}
}
/**
* Método que exclui um registro da tabela de saldo residual de décimo terceiro.
*
* @param pCodRestituicaoDecimoTerceiro;
*/
public void DeleteSaldoResidualDecimoTerceiro (int pCodRestituicaoDecimoTerceiro) {
PreparedStatement preparedStatement;
String query = "DELETE FROM tb_saldo_residual_dec_ter WHERE COD_RESTITUICAO_DEC_TERCEIRO = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCodRestituicaoDecimoTerceiro);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro solicitado do saldo residual de décimo terceiro.");
}
}
/**
* Método que exclui um registro da tabela de restituição de rescisão.
*
* @param pCodRestituicaoRescisao;
*/
public void DeleteRestituicaoRescisao (int pCodRestituicaoRescisao) {
PreparedStatement preparedStatement;
String query = "DELETE FROM tb_restituicao_rescisao WHERE cod = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCodRestituicaoRescisao);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro solicitado da restituição de rescisão.");
}
}
/**
* Método que exclui um registro da tabela de saldo residual de rescisão.
*
* @param pCodRestituicaoRescisao;
*/
public void DeleteSaldoResidualRescisao (int pCodRestituicaoRescisao) {
PreparedStatement preparedStatement;
String query = "DELETE FROM tb_saldo_residual_rescisao WHERE COD_RESTITUICAO_RESCISAO = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCodRestituicaoRescisao);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro solicitado do saldo residual de rescisão.");
}
}
/**
* Método que exclui um registro da tabela de histórico de restituição de férias.
*
* @param pCodRestituicaoFerias;
*/
public void DeleteHistRestituicaoFerias (int pCodRestituicaoFerias) {
PreparedStatement preparedStatement;
String query = "DELETE FROM tb_hist_restituicao_ferias WHERE COD_RESTITUICAO_FERIAS = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCodRestituicaoFerias);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro solicitado do histórico de restituição de férias.");
}
}
/**
* Método que exclui um registro da tabela de histórico de restituição de décimo terceiro.
*
* @param pCodRestituicaoDecimoTerceiro;
*/
public void DeleteHistRestituicaoDecimoTerceiro (int pCodRestituicaoDecimoTerceiro) {
PreparedStatement preparedStatement;
String query = "DELETE FROM tb_hist_restituicao_dec_ter WHERE COD_RESTITUICAO_DEC_TERCEIRO = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCodRestituicaoDecimoTerceiro);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro solicitado do histórico de restituição de décimo terceiro.");
}
}
/**
* Método que exclui um registro da tabela de histórico de restituição de rescisão.
*
* @param pCodRestituicaoRescisao;
*/
public void DeleteHistRestituicaoRescisao (int pCodRestituicaoRescisao) {
PreparedStatement preparedStatement;
String query = "DELETE FROM tb_hist_restituicao_rescisao WHERE COD_RESTITUICAO_RESCISAO = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCodRestituicaoRescisao);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro solicitado do histórico de restituição de rescisão.");
}
}
/**
* Método que exclui um registro de uma tabela.
*
* @param pCod;
* @param pTabela;
*/
public int DeleteRegistro (int pCod, String pTabela) {
PreparedStatement preparedStatement;
int vRetorno = 1;
String query = "DELETE FROM " + pTabela + " WHERE COD = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCod);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro da tabela " + pTabela + ".");
}
vRetorno = 0;
return vRetorno;
}
}
| UTF-8 | Java | 7,825 | java | DeleteTSQL.java | Java | [] | null | [] | package br.jus.stj.siscovi.dao.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DeleteTSQL {
private Connection connection;
public DeleteTSQL(Connection connection) {
this.connection = connection;
}
/**
* Método que exclui um registro da tabela de restituição de férias.
*
* @param pCodRestituicaoFerias;
*/
public void DeleteRestituicaoFerias (int pCodRestituicaoFerias) {
PreparedStatement preparedStatement;
String query = "DELETE FROM tb_restituicao_ferias WHERE cod = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCodRestituicaoFerias);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro solicitado da restituição de férias.");
}
}
/**
* Método que exclui um registro da tabela de saldo residual de férias.
*
* @param pCodRestituicaoFerias;
*/
public void DeleteSaldoResidualFerias (int pCodRestituicaoFerias) {
PreparedStatement preparedStatement;
String query = "DELETE FROM tb_saldo_residual_ferias WHERE cod_restituicao_ferias = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCodRestituicaoFerias);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro solicitado do saldo residual de férias.");
}
}
/**
* Método que exclui um registro da tabela de restituição de décimo terceiro.
*
* @param pCodRestituicaoDecimoTerceiro;
*/
public void DeleteRestituicaoDecimoTerceiro (int pCodRestituicaoDecimoTerceiro) {
PreparedStatement preparedStatement;
String query = "DELETE FROM tb_restituicao_decimo_terceiro WHERE cod = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCodRestituicaoDecimoTerceiro);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro solicitado da restituição de décimo terceiro.");
}
}
/**
* Método que exclui um registro da tabela de saldo residual de décimo terceiro.
*
* @param pCodRestituicaoDecimoTerceiro;
*/
public void DeleteSaldoResidualDecimoTerceiro (int pCodRestituicaoDecimoTerceiro) {
PreparedStatement preparedStatement;
String query = "DELETE FROM tb_saldo_residual_dec_ter WHERE COD_RESTITUICAO_DEC_TERCEIRO = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCodRestituicaoDecimoTerceiro);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro solicitado do saldo residual de décimo terceiro.");
}
}
/**
* Método que exclui um registro da tabela de restituição de rescisão.
*
* @param pCodRestituicaoRescisao;
*/
public void DeleteRestituicaoRescisao (int pCodRestituicaoRescisao) {
PreparedStatement preparedStatement;
String query = "DELETE FROM tb_restituicao_rescisao WHERE cod = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCodRestituicaoRescisao);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro solicitado da restituição de rescisão.");
}
}
/**
* Método que exclui um registro da tabela de saldo residual de rescisão.
*
* @param pCodRestituicaoRescisao;
*/
public void DeleteSaldoResidualRescisao (int pCodRestituicaoRescisao) {
PreparedStatement preparedStatement;
String query = "DELETE FROM tb_saldo_residual_rescisao WHERE COD_RESTITUICAO_RESCISAO = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCodRestituicaoRescisao);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro solicitado do saldo residual de rescisão.");
}
}
/**
* Método que exclui um registro da tabela de histórico de restituição de férias.
*
* @param pCodRestituicaoFerias;
*/
public void DeleteHistRestituicaoFerias (int pCodRestituicaoFerias) {
PreparedStatement preparedStatement;
String query = "DELETE FROM tb_hist_restituicao_ferias WHERE COD_RESTITUICAO_FERIAS = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCodRestituicaoFerias);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro solicitado do histórico de restituição de férias.");
}
}
/**
* Método que exclui um registro da tabela de histórico de restituição de décimo terceiro.
*
* @param pCodRestituicaoDecimoTerceiro;
*/
public void DeleteHistRestituicaoDecimoTerceiro (int pCodRestituicaoDecimoTerceiro) {
PreparedStatement preparedStatement;
String query = "DELETE FROM tb_hist_restituicao_dec_ter WHERE COD_RESTITUICAO_DEC_TERCEIRO = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCodRestituicaoDecimoTerceiro);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro solicitado do histórico de restituição de décimo terceiro.");
}
}
/**
* Método que exclui um registro da tabela de histórico de restituição de rescisão.
*
* @param pCodRestituicaoRescisao;
*/
public void DeleteHistRestituicaoRescisao (int pCodRestituicaoRescisao) {
PreparedStatement preparedStatement;
String query = "DELETE FROM tb_hist_restituicao_rescisao WHERE COD_RESTITUICAO_RESCISAO = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCodRestituicaoRescisao);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro solicitado do histórico de restituição de rescisão.");
}
}
/**
* Método que exclui um registro de uma tabela.
*
* @param pCod;
* @param pTabela;
*/
public int DeleteRegistro (int pCod, String pTabela) {
PreparedStatement preparedStatement;
int vRetorno = 1;
String query = "DELETE FROM " + pTabela + " WHERE COD = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, pCod);
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Não foi possível deletar o registro da tabela " + pTabela + ".");
}
vRetorno = 0;
return vRetorno;
}
}
| 7,825 | 0.658448 | 0.656899 | 303 | 24.567657 | 33.482491 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.30033 | false | false | 2 |
bfdb5b397fa2d2849a1d8c3ae50968fdbc2e525c | 25,778,393,736,443 | fb4cd22027a960f18ebedbb0fa90f11645dc376b | /src/main/java/com/mycompany/samplewebserviceapp/dealerResource.java | f9b44a4c9cd5629342580ac0a870dd6dced94f28 | [] | no_license | vikasv5/Assignment1 | https://github.com/vikasv5/Assignment1 | 910918f5ff7f4e1c0eee37fb0ba65a4301d8ae5d | aceae9c14df4f75b5782f1816c7375418dec6bdc | refs/heads/master | 2020-03-19T04:47:58.306000 | 2018-07-28T02:10:19 | 2018-07-28T02:10:19 | 135,867,855 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.samplewebserviceapp;
/**
*
* @author Vikas
*
*/
import com.mycompany.model.Dealer;
import com.mycompany.model.Order;
import com.mycompany.model.OrderError;
import com.mycompany.model.OrderMessage;
import com.mycompany.service.DealerService;
import com.mycompany.service.OrderService;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/*
* 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.
*/
/**
*
* @author Vikas
*/
@Path("/dealerAdmin")
public class dealerResource {
//MessageService service= new MessageService();
OrderService orderService= new OrderService();
DealerService dsvc= new DealerService();
@GET
@Produces(value={MediaType.APPLICATION_XML,MediaType.TEXT_XML})
public List<Dealer> getMessages(){
return dsvc.getAllDealersList();
}
@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Dealer addDealer(Dealer dealer) throws URISyntaxException{
//OrderMessage orderMsg= orderService.processOrder(dealer);
Map<String,Dealer> dMap=dsvc.getAllDealersMap();
if(dMap.containsKey(dealer.getDealerId())){
return dMap.get(dealer.getDealerId());
}
//OrderError error= new OrderError("failure","not authorized", null);
dMap.put(dealer.getDealerId(),dealer);
return dealer;
}
// @DELETE
// @Consumes(MediaType.APPLICATION_XML)
// @Produces(MediaType.APPLICATION_XML)
// public Dealer removeDealer(Dealer dealer) throws URISyntaxException{
// //OrderMessage orderMsg= orderService.processOrder(dealer);
// Map<String,Dealer> dMap=dsvc.getAllDealersMap();
//
// if(dMap.containsKey(dealer.getDealerId())){
// return dMap.get(dealer.getDealerId());
//
// }
// //OrderError error= new OrderError("failure","not authorized", null);
// dMap.put(dealer.getDealerId(),dealer);
//
// return dealer;
// }
@PUT
@Path("{orderId}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Order updateOrder(@PathParam("orderId") long id,Order order){
order.setId(id);
return orderService.updateOrder(order);
}
@GET
@Path("{orderId}")
@Produces(MediaType.APPLICATION_JSON)
public Order getTestString(@PathParam("orderId") long id){
return orderService.getOrder(id);
}
}
| UTF-8 | Java | 3,195 | java | dealerResource.java | Java | [
{
"context": ".mycompany.samplewebserviceapp;\n\n/**\n *\n * @author Vikas\n * \n */\n\n\n\n\nimport com.mycompany.model.Dealer;\nim",
"end": 252,
"score": 0.9997270107269287,
"start": 247,
"tag": "NAME",
"value": "Vikas"
},
{
"context": "the template in the editor.\n */\n\n/**\n *\n * @author Vikas\n */\n@Path(\"/dealerAdmin\")\npublic class dealerReso",
"end": 1127,
"score": 0.9996588826179504,
"start": 1122,
"tag": "NAME",
"value": "Vikas"
}
] | 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 com.mycompany.samplewebserviceapp;
/**
*
* @author Vikas
*
*/
import com.mycompany.model.Dealer;
import com.mycompany.model.Order;
import com.mycompany.model.OrderError;
import com.mycompany.model.OrderMessage;
import com.mycompany.service.DealerService;
import com.mycompany.service.OrderService;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/*
* 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.
*/
/**
*
* @author Vikas
*/
@Path("/dealerAdmin")
public class dealerResource {
//MessageService service= new MessageService();
OrderService orderService= new OrderService();
DealerService dsvc= new DealerService();
@GET
@Produces(value={MediaType.APPLICATION_XML,MediaType.TEXT_XML})
public List<Dealer> getMessages(){
return dsvc.getAllDealersList();
}
@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Dealer addDealer(Dealer dealer) throws URISyntaxException{
//OrderMessage orderMsg= orderService.processOrder(dealer);
Map<String,Dealer> dMap=dsvc.getAllDealersMap();
if(dMap.containsKey(dealer.getDealerId())){
return dMap.get(dealer.getDealerId());
}
//OrderError error= new OrderError("failure","not authorized", null);
dMap.put(dealer.getDealerId(),dealer);
return dealer;
}
// @DELETE
// @Consumes(MediaType.APPLICATION_XML)
// @Produces(MediaType.APPLICATION_XML)
// public Dealer removeDealer(Dealer dealer) throws URISyntaxException{
// //OrderMessage orderMsg= orderService.processOrder(dealer);
// Map<String,Dealer> dMap=dsvc.getAllDealersMap();
//
// if(dMap.containsKey(dealer.getDealerId())){
// return dMap.get(dealer.getDealerId());
//
// }
// //OrderError error= new OrderError("failure","not authorized", null);
// dMap.put(dealer.getDealerId(),dealer);
//
// return dealer;
// }
@PUT
@Path("{orderId}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Order updateOrder(@PathParam("orderId") long id,Order order){
order.setId(id);
return orderService.updateOrder(order);
}
@GET
@Path("{orderId}")
@Produces(MediaType.APPLICATION_JSON)
public Order getTestString(@PathParam("orderId") long id){
return orderService.getOrder(id);
}
}
| 3,195 | 0.676995 | 0.676995 | 125 | 24.559999 | 22.246042 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.456 | false | false | 2 |
352cbe6b4744c6849bec6cb614c3d92769ff0d75 | 25,778,393,733,869 | 3dca126c27f682077bc12bed1ada2faabb076fdb | /CurdOperationCompanyTest/src/main/java/com/app/service/UserService.java | 528818c24eed616939a23b26392b348ee331ae40 | [] | no_license | janardan904/Companytest | https://github.com/janardan904/Companytest | d37726cca248a474e9566ce4e4e20b51ccb9ee93 | 381fc5b0165efea5b2dc462592ac810e5b5f8997 | refs/heads/master | 2023-04-30T11:32:08.748000 | 2021-05-09T13:53:08 | 2021-05-09T13:53:08 | 365,762,200 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.app.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.app.model.User;
import com.app.repo.UserRepository;
@Service
public class UserService {
@Autowired
private UserRepository repository;
// fetch the record from db
public List<User> getAllUsers()
{
List<User> users= new ArrayList<User>();
repository.findAll().forEach(user1->users.add(user1));
return users;
}
//get the perticular record
public User getUserById(int userId)
{
return repository.findById(userId).get();
}
//save or update the record
public void saveOrUpdate(User user)
{
repository.save(user);
}
//delete the record
public void delete(int userId)
{
repository.deleteById(userId);
}
//update the record
public void update(User user, int userId)
{
repository.save(user);
}
}
| UTF-8 | Java | 1,013 | java | UserService.java | Java | [] | null | [] | package com.app.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.app.model.User;
import com.app.repo.UserRepository;
@Service
public class UserService {
@Autowired
private UserRepository repository;
// fetch the record from db
public List<User> getAllUsers()
{
List<User> users= new ArrayList<User>();
repository.findAll().forEach(user1->users.add(user1));
return users;
}
//get the perticular record
public User getUserById(int userId)
{
return repository.findById(userId).get();
}
//save or update the record
public void saveOrUpdate(User user)
{
repository.save(user);
}
//delete the record
public void delete(int userId)
{
repository.deleteById(userId);
}
//update the record
public void update(User user, int userId)
{
repository.save(user);
}
}
| 1,013 | 0.681145 | 0.679171 | 45 | 20.51111 | 17.079712 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.022222 | false | false | 2 |
9f8d634a1bf44c55cfda7363b06c12be55588596 | 2,568,390,482,731 | 71ef9f9f250766e782df7bcedbca327472c27e79 | /PROG-II/lesson02/exercise02/Vehicle.java | 98e8edc6c0239299ccf347a5c68b12a6328280ad | [] | no_license | lll101010lll/hsc.inf.sem2.prog2 | https://github.com/lll101010lll/hsc.inf.sem2.prog2 | 2426e43d41921d879639733238c74ed0f16a5d6e | eae38a38ecb2edf2a6fec8cb89b4c9cbb25879f5 | refs/heads/master | 2016-08-06T01:49:31.921000 | 2013-11-04T06:26:44 | 2013-11-04T06:26:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package exercise02;
public abstract class Vehicle {
protected double driveDistance;
protected double decelerationDistance;
protected double driveSpeed;
protected double maxSpeed;
protected double accelerationRate;
protected String vehicleName;
public Vehicle(String vehicleName) {
this.vehicleName = vehicleName;
}
/**
* Set specified acceleration rate for vehicles of the same type (car,
* lorry, etc.) -> allows to add new vehicles without editing the class
* structure
*
* @param accelerationRate
*/
public void setAccelerationRate(double accelerationRate) {
this.accelerationRate = accelerationRate;
}
/**
* Set specified max. speed for vehicles of the same type (car, lorry, etc.)
* -> allows to add new vehicles without editing the class structure
*
* @param maxSpeed
* in km/h -> m/s
*/
public void setMaxSpeed(double maxSpeed) {
this.maxSpeed = (maxSpeed / 3.6);
}
/**
* Set the driving distance of the current vehicle
*
* @param driveDistance
*/
public void setDriveDistance(double driveDistance) {
this.driveDistance = driveDistance;
}
/**
* Set the deceleration distance for the specified vehicle
*
* @param decelerationDistance
*/
public void setDecelerationDistance(double decelerationDistance) {
this.decelerationDistance = decelerationDistance;
}
/**
* Accelerate the specified vehicle for n seconds. If current speed = max.
* speed of the vehicle -> hold that speed If not -> store the attained
* speed and terminate action [wait for further actions], i.e.
* driveVehicle()
*
* Rounding up the driving distance with Math.rint(v * 100) / 100 [0.xx---]
*
* @param seconds
* @return
*/
public double accelerateVehicle(double seconds) {
this.driveSpeed = this.accelerationRate * seconds;
if (this.driveSpeed >= (this.maxSpeed)) {
this.driveSpeed = this.maxSpeed;
}
this.driveDistance += (Math
.rint((0.5 * (this.driveSpeed * seconds)) * 100.0) / 100);
return this.driveDistance;
}
/**
* Continue driving with constant speed: v = s * t; a = 0;
*
* @param minutes
* @return driving distance of the specified vehicle
*/
public double driveVehicle(double minutes) {
this.driveDistance += (this.driveSpeed) * (minutes * 60);
return this.driveDistance;
}
/**
* Deceleration distance strongly depends on the specified vehicle [car,
* lorry, etc.] -> @Override in the inherited classes
*
* @return decelerationDistance
*/
public abstract double decelerateVehicle();
public void testVehicle(double acc, double drive){
this.accelerateVehicle(acc);
this.driveVehicle(drive);
this.decelerateVehicle();
}
/**
* Override toString() method to put out the attributes of the class
*/
public String toString() {
StringBuffer tmpString = new StringBuffer();
return tmpString.append("ID = ").append(this.vehicleName)
.append(" \t v = ").append(this.driveSpeed * 3.6)
.append("km/h \t s = ").append((this.driveDistance / 1000))
.append("km \t s' = ").append(this.decelerationDistance)
.append("m").toString();
}
} | UTF-8 | Java | 3,126 | java | Vehicle.java | Java | [] | null | [] | package exercise02;
public abstract class Vehicle {
protected double driveDistance;
protected double decelerationDistance;
protected double driveSpeed;
protected double maxSpeed;
protected double accelerationRate;
protected String vehicleName;
public Vehicle(String vehicleName) {
this.vehicleName = vehicleName;
}
/**
* Set specified acceleration rate for vehicles of the same type (car,
* lorry, etc.) -> allows to add new vehicles without editing the class
* structure
*
* @param accelerationRate
*/
public void setAccelerationRate(double accelerationRate) {
this.accelerationRate = accelerationRate;
}
/**
* Set specified max. speed for vehicles of the same type (car, lorry, etc.)
* -> allows to add new vehicles without editing the class structure
*
* @param maxSpeed
* in km/h -> m/s
*/
public void setMaxSpeed(double maxSpeed) {
this.maxSpeed = (maxSpeed / 3.6);
}
/**
* Set the driving distance of the current vehicle
*
* @param driveDistance
*/
public void setDriveDistance(double driveDistance) {
this.driveDistance = driveDistance;
}
/**
* Set the deceleration distance for the specified vehicle
*
* @param decelerationDistance
*/
public void setDecelerationDistance(double decelerationDistance) {
this.decelerationDistance = decelerationDistance;
}
/**
* Accelerate the specified vehicle for n seconds. If current speed = max.
* speed of the vehicle -> hold that speed If not -> store the attained
* speed and terminate action [wait for further actions], i.e.
* driveVehicle()
*
* Rounding up the driving distance with Math.rint(v * 100) / 100 [0.xx---]
*
* @param seconds
* @return
*/
public double accelerateVehicle(double seconds) {
this.driveSpeed = this.accelerationRate * seconds;
if (this.driveSpeed >= (this.maxSpeed)) {
this.driveSpeed = this.maxSpeed;
}
this.driveDistance += (Math
.rint((0.5 * (this.driveSpeed * seconds)) * 100.0) / 100);
return this.driveDistance;
}
/**
* Continue driving with constant speed: v = s * t; a = 0;
*
* @param minutes
* @return driving distance of the specified vehicle
*/
public double driveVehicle(double minutes) {
this.driveDistance += (this.driveSpeed) * (minutes * 60);
return this.driveDistance;
}
/**
* Deceleration distance strongly depends on the specified vehicle [car,
* lorry, etc.] -> @Override in the inherited classes
*
* @return decelerationDistance
*/
public abstract double decelerateVehicle();
public void testVehicle(double acc, double drive){
this.accelerateVehicle(acc);
this.driveVehicle(drive);
this.decelerateVehicle();
}
/**
* Override toString() method to put out the attributes of the class
*/
public String toString() {
StringBuffer tmpString = new StringBuffer();
return tmpString.append("ID = ").append(this.vehicleName)
.append(" \t v = ").append(this.driveSpeed * 3.6)
.append("km/h \t s = ").append((this.driveDistance / 1000))
.append("km \t s' = ").append(this.decelerationDistance)
.append("m").toString();
}
} | 3,126 | 0.693218 | 0.683941 | 125 | 24.016001 | 24.504036 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.368 | false | false | 2 |
5276563256d8db1a5a74418f33798767bce5b05f | 7,112,465,871,540 | 75196819c910f3fd523f1a4d28e5d0fe12570ab1 | /src/bdb53/lang/java/src/com/sleepycat/db/ReplicationManagerSiteConfig.java | 93ebcef83d8dd97b6220f2b65502b966357068e6 | [
"BSD-3-Clause",
"Sleepycat",
"MIT"
] | permissive | gridcoin-community/Gridcoin-Research | https://github.com/gridcoin-community/Gridcoin-Research | 889967579b5b05bcc3ae836697a0f173b5ae91ea | 21414dd0f63c9a34060f7f762f08d1a52aeb9e87 | refs/heads/development | 2023-09-04T09:21:55.006000 | 2023-09-03T17:45:20 | 2023-09-03T17:45:20 | 23,332,350 | 292 | 117 | MIT | false | 2023-09-11T10:22:10 | 2014-08-25T23:41:04 | 2023-09-10T23:47:59 | 2023-09-11T10:22:09 | 314,893 | 571 | 181 | 40 | HTML | false | false | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2011, 2013 Oracle and/or its affiliates. All rights reserved.
*
* $Id$
*/
package com.sleepycat.db;
import com.sleepycat.db.internal.DbConstants;
import com.sleepycat.db.internal.DbSite;
/**
Specifies the attributes of a site in the replication group.
*/
public class ReplicationManagerSiteConfig implements Cloneable {
/* package */
private String host = null;
private long port = 0;
private boolean helper = false;
private boolean groupCreator = false;
private boolean legacy = false;
private boolean localSite = false;
private boolean peer = false;
/**
An instance created using the default constructor is initialized
with the system's default settings.
*/
public ReplicationManagerSiteConfig() {
}
/**
Configure the host and port for a site in replication group.
@param host
@param port
*/
public ReplicationManagerSiteConfig(String host, long port) {
this.host = host;
this.port = port;
}
/**
Configure the address for a site in replication group.
<p>
@param address
*/
public void setAddress(ReplicationHostAddress address) {
this.host = address.host;
this.port = address.port;
}
/**
Return the address of the site.
<p>
@return the address of the site.
*/
public ReplicationHostAddress getAddress() {
ReplicationHostAddress address = new ReplicationHostAddress();
if (this.host != null && this.port != 0) {
address.host = this.host;
address.port = (int)this.port;
}
return address;
}
/**
Configure the host of the site.
<p>
@param host
*/
public void setHost(String host) {
this.host = host;
}
/**
Return the host of the site.
<p>
@return the host of the site.
*/
public String getHost() {
return host;
}
/**
Configure the port of the site.
<p>
@param port
*/
public void setPort(long port) {
this.port = port;
}
/**
Return the port of the site.
<p>
@return the port of the site.
*/
public long getPort() {
return port;
}
/**
Set the site to be a helper site.
<p>
A remote site may be used as a helper when the local site first joins the
replication group. Once the local site has been established as a member of
the group, this config setting is ignored.
<p>
@param helper
If true, the site will be a helper.
*/
public void setBootstrapHelper(final boolean helper) {
this.helper = helper;
}
/**
Return if the site is a helper for the local site.
<p>
@return
If the site is a helper for the local site.
*/
public boolean getBootstrapHelper() {
return helper;
}
/**
Set the site to be a group creator.
<p>
Only the local site could be applied as a group creator. The group creator
would create the initial membership database, defining a replication group
of just the one site, rather than trying to join an existing group when it
starts for the first time.
<p>
@param groupCreator
If true, set the site a group creator.
*/
public void setGroupCreator(final boolean groupCreator) {
this.groupCreator = groupCreator;
}
/**
Return if the site is a group creator.
<p>
@return
If the the site is a group creator.
*/
public boolean getGroupCreator() {
return groupCreator;
}
/**
Specify the site in a legacy group. It would be considered as part of an
existing group, upgrading from a previous version of BDB. All sites in the
legacy group must specify this for themselves (the local site) and for all
other sites initially in the group.
<p>
@param legacy
If true, specify the site in a legacy group.
*/
public void setLegacy(final boolean legacy) {
this.legacy = legacy;
}
/**
Return if the site is in a legacy group.
<p>
@return
If the site is in a legacy group.
*/
public boolean getLegacy() {
return legacy;
}
/**
Set the site to be the local site.
<p>
@param localSite
If true, it is local site.
*/
public void setLocalSite(final boolean localSite) {
this.localSite = localSite;
}
/**
Return if the site is the local site.
<p>
@return
If the site is the local site.
*/
public boolean getLocalSite() {
return localSite;
}
/**
Set the site to be peer to local site.
<p>
A peer site may be used as a target for "client-to-client" synchronization
messages. It only makes sense to specify this for a remote site.
@param peer
If true, it is peer to loca site.
*/
public void setPeer(final boolean peer) {
this.peer = peer;
}
/**
Return if the site is peer.
<p>
@return
If the site is peer.
*/
public boolean getPeer() {
return peer;
}
/* package */
ReplicationManagerSiteConfig(final DbSite dbsite)
throws DatabaseException {
ReplicationHostAddress address = dbsite.get_address();
host = address.host;
port = address.port;
helper = dbsite.get_config(DbConstants.DB_BOOTSTRAP_HELPER);
groupCreator = dbsite.get_config(DbConstants.DB_GROUP_CREATOR);
legacy = dbsite.get_config(DbConstants.DB_LEGACY);
localSite = dbsite.get_config(DbConstants.DB_LOCAL_SITE);
peer = dbsite.get_config(DbConstants.DB_REPMGR_PEER);
}
}
| UTF-8 | Java | 5,725 | java | ReplicationManagerSiteConfig.java | Java | [] | null | [] | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2011, 2013 Oracle and/or its affiliates. All rights reserved.
*
* $Id$
*/
package com.sleepycat.db;
import com.sleepycat.db.internal.DbConstants;
import com.sleepycat.db.internal.DbSite;
/**
Specifies the attributes of a site in the replication group.
*/
public class ReplicationManagerSiteConfig implements Cloneable {
/* package */
private String host = null;
private long port = 0;
private boolean helper = false;
private boolean groupCreator = false;
private boolean legacy = false;
private boolean localSite = false;
private boolean peer = false;
/**
An instance created using the default constructor is initialized
with the system's default settings.
*/
public ReplicationManagerSiteConfig() {
}
/**
Configure the host and port for a site in replication group.
@param host
@param port
*/
public ReplicationManagerSiteConfig(String host, long port) {
this.host = host;
this.port = port;
}
/**
Configure the address for a site in replication group.
<p>
@param address
*/
public void setAddress(ReplicationHostAddress address) {
this.host = address.host;
this.port = address.port;
}
/**
Return the address of the site.
<p>
@return the address of the site.
*/
public ReplicationHostAddress getAddress() {
ReplicationHostAddress address = new ReplicationHostAddress();
if (this.host != null && this.port != 0) {
address.host = this.host;
address.port = (int)this.port;
}
return address;
}
/**
Configure the host of the site.
<p>
@param host
*/
public void setHost(String host) {
this.host = host;
}
/**
Return the host of the site.
<p>
@return the host of the site.
*/
public String getHost() {
return host;
}
/**
Configure the port of the site.
<p>
@param port
*/
public void setPort(long port) {
this.port = port;
}
/**
Return the port of the site.
<p>
@return the port of the site.
*/
public long getPort() {
return port;
}
/**
Set the site to be a helper site.
<p>
A remote site may be used as a helper when the local site first joins the
replication group. Once the local site has been established as a member of
the group, this config setting is ignored.
<p>
@param helper
If true, the site will be a helper.
*/
public void setBootstrapHelper(final boolean helper) {
this.helper = helper;
}
/**
Return if the site is a helper for the local site.
<p>
@return
If the site is a helper for the local site.
*/
public boolean getBootstrapHelper() {
return helper;
}
/**
Set the site to be a group creator.
<p>
Only the local site could be applied as a group creator. The group creator
would create the initial membership database, defining a replication group
of just the one site, rather than trying to join an existing group when it
starts for the first time.
<p>
@param groupCreator
If true, set the site a group creator.
*/
public void setGroupCreator(final boolean groupCreator) {
this.groupCreator = groupCreator;
}
/**
Return if the site is a group creator.
<p>
@return
If the the site is a group creator.
*/
public boolean getGroupCreator() {
return groupCreator;
}
/**
Specify the site in a legacy group. It would be considered as part of an
existing group, upgrading from a previous version of BDB. All sites in the
legacy group must specify this for themselves (the local site) and for all
other sites initially in the group.
<p>
@param legacy
If true, specify the site in a legacy group.
*/
public void setLegacy(final boolean legacy) {
this.legacy = legacy;
}
/**
Return if the site is in a legacy group.
<p>
@return
If the site is in a legacy group.
*/
public boolean getLegacy() {
return legacy;
}
/**
Set the site to be the local site.
<p>
@param localSite
If true, it is local site.
*/
public void setLocalSite(final boolean localSite) {
this.localSite = localSite;
}
/**
Return if the site is the local site.
<p>
@return
If the site is the local site.
*/
public boolean getLocalSite() {
return localSite;
}
/**
Set the site to be peer to local site.
<p>
A peer site may be used as a target for "client-to-client" synchronization
messages. It only makes sense to specify this for a remote site.
@param peer
If true, it is peer to loca site.
*/
public void setPeer(final boolean peer) {
this.peer = peer;
}
/**
Return if the site is peer.
<p>
@return
If the site is peer.
*/
public boolean getPeer() {
return peer;
}
/* package */
ReplicationManagerSiteConfig(final DbSite dbsite)
throws DatabaseException {
ReplicationHostAddress address = dbsite.get_address();
host = address.host;
port = address.port;
helper = dbsite.get_config(DbConstants.DB_BOOTSTRAP_HELPER);
groupCreator = dbsite.get_config(DbConstants.DB_GROUP_CREATOR);
legacy = dbsite.get_config(DbConstants.DB_LEGACY);
localSite = dbsite.get_config(DbConstants.DB_LOCAL_SITE);
peer = dbsite.get_config(DbConstants.DB_REPMGR_PEER);
}
}
| 5,725 | 0.622882 | 0.621135 | 232 | 23.676723 | 22.157621 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.228448 | false | false | 2 |
9e5c1e9803a44051d36aa866060827629a705cd8 | 19,086,834,685,960 | 24f090b8f7b8d4be1f204992f9dbafb9bfe31a25 | /Bucket.java | 148064473f7c3ce3940044e874752283cee0acd9 | [] | no_license | Chaitanya-Soni/alogorithms_data_structures | https://github.com/Chaitanya-Soni/alogorithms_data_structures | 6d4d856343209168ae1f719db12c63552b40b88e | 376538c65f5f131e6318c9d1051c450060b53a34 | refs/heads/main | 2023-08-29T06:50:45.908000 | 2021-10-01T16:41:39 | 2021-10-01T16:41:39 | 304,415,830 | 1 | 0 | null | true | 2020-10-15T18:31:41 | 2020-10-15T18:31:40 | 2020-10-15T18:23:57 | 2020-10-15T18:23:54 | 6 | 0 | 0 | 0 | null | false | false | import java.util.*;
import java.time.*;
public class Bucket
{
static void bucketsort (float A[], int n)
{
@SuppressWarnings("unchecked")
ArrayList<Float>[] bkt = new ArrayList[n];
for (int i=0;i<n;i++)
bkt[i] = new ArrayList<Float>();
for (int i=0;i<n;i++)
{
int bktInd = (int)A[i]*n;
bkt[bktInd].add(A[i]);
}
for (int i=0;i<n;i++)
Collections.sort((bkt[i]));
// Here you can use any other sorting algorithm also...
int j=0;
for (int i=0;i<n;i++)
{
for (int k=0, size=bkt[i].size();k<size;k++)
A[j++] = bkt[i].get(k);
}
public static void main (String args[])
{
int n=10000;
float A[] = new float[n];
Random rnd = new Random();
for (int i=0;i<n;i++)
A[i] = rnd.nextFloat(10001);
double time1 = System.nanoTime();
bucketsort(A, n);
double time2 = System.nanoTime();
double timediff = (time2-time1)/1000; // in microseconds
System.out.println("\nThe Execution time taken for bucket sort algorithm is - " + timediff + "\n\n");
}
} | UTF-8 | Java | 1,246 | java | Bucket.java | Java | [] | null | [] | import java.util.*;
import java.time.*;
public class Bucket
{
static void bucketsort (float A[], int n)
{
@SuppressWarnings("unchecked")
ArrayList<Float>[] bkt = new ArrayList[n];
for (int i=0;i<n;i++)
bkt[i] = new ArrayList<Float>();
for (int i=0;i<n;i++)
{
int bktInd = (int)A[i]*n;
bkt[bktInd].add(A[i]);
}
for (int i=0;i<n;i++)
Collections.sort((bkt[i]));
// Here you can use any other sorting algorithm also...
int j=0;
for (int i=0;i<n;i++)
{
for (int k=0, size=bkt[i].size();k<size;k++)
A[j++] = bkt[i].get(k);
}
public static void main (String args[])
{
int n=10000;
float A[] = new float[n];
Random rnd = new Random();
for (int i=0;i<n;i++)
A[i] = rnd.nextFloat(10001);
double time1 = System.nanoTime();
bucketsort(A, n);
double time2 = System.nanoTime();
double timediff = (time2-time1)/1000; // in microseconds
System.out.println("\nThe Execution time taken for bucket sort algorithm is - " + timediff + "\n\n");
}
} | 1,246 | 0.483949 | 0.463884 | 38 | 30.842106 | 21.422476 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.868421 | false | false | 2 |
e161eb0202720833381a2a43ab8d5f4b967a5cc3 | 24,739,011,646,947 | 3c30856e8f0e937fca678ef205c2bcafff36503c | /1SecondEveryday/src/com/googlecode/mp4parser/h264/read/BitstreamReader.java | 55a6d9bc581fabbe1e5b0d54812f122e5dc6a9bd | [] | no_license | sfault/AndroidApps | https://github.com/sfault/AndroidApps | d98fe115fac610e30794bd0bebacba7926cf82a7 | bb717b0ef781c102a4c0813391461551a588bb81 | refs/heads/master | 2020-04-09T14:56:22.402000 | 2014-08-10T02:34:50 | 2014-08-10T02:34:50 | 22,694,184 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.googlecode.mp4parser.h264.read;
import com.googlecode.mp4parser.h264.CharCache;
import java.io.IOException;
import java.io.InputStream;
public class BitstreamReader
{
protected static int bitsRead;
private int curByte;
protected CharCache debugBits = new CharCache(50);
private InputStream is;
int nBit;
private int nextByte;
public BitstreamReader(InputStream paramInputStream)
throws IOException
{
this.is = paramInputStream;
this.curByte = paramInputStream.read();
this.nextByte = paramInputStream.read();
}
private void advance()
throws IOException
{
this.curByte = this.nextByte;
this.nextByte = this.is.read();
this.nBit = 0;
}
public void close()
throws IOException
{}
public long getBitPosition()
{
return 8 * bitsRead + this.nBit % 8;
}
public int getCurBit()
{
return this.nBit;
}
public boolean isByteAligned()
{
return this.nBit % 8 == 0;
}
public boolean moreRBSPData()
throws IOException
{
int i = 1;
if (this.nBit == 8) {
advance();
}
int j = i << -1 + (8 - this.nBit);
if ((-1 + (j << 1) & this.curByte) == j) {}
int m;
for (int k = i;; m = 0)
{
if ((this.curByte == -1) || ((this.nextByte == -1) && (k != 0))) {
i = 0;
}
return i;
}
}
public int peakNextBits(int paramInt)
throws IOException
{
int i = -1;
if (paramInt > 8) {
throw new IllegalArgumentException("N should be less then 8");
}
if (this.nBit == 8)
{
advance();
if (this.curByte == i) {
return i;
}
}
int[] arrayOfInt = new int[16 - this.nBit];
int j = this.nBit;
int k = 0;
label60:
int n;
if (j >= 8) {
n = 0;
}
for (;;)
{
if (n >= 8)
{
i = 0;
for (int i2 = 0; i2 < paramInt; i2++) {
i = i << 1 | arrayOfInt[i2];
}
break;
int m = k + 1;
arrayOfInt[k] = (0x1 & this.curByte >> 7 - j);
j++;
k = m;
break label60;
}
int i1 = k + 1;
arrayOfInt[k] = (0x1 & this.nextByte >> 7 - n);
n++;
k = i1;
}
}
public int read1Bit()
throws IOException
{
if (this.nBit == 8)
{
advance();
if (this.curByte == -1) {
return -1;
}
}
int i = 0x1 & this.curByte >> 7 - this.nBit;
this.nBit = (1 + this.nBit);
CharCache localCharCache = this.debugBits;
if (i == 0) {}
for (char c = '0';; c = '1')
{
localCharCache.append(c);
bitsRead = 1 + bitsRead;
return i;
}
}
public int readByte()
throws IOException
{
if (this.nBit > 0) {
advance();
}
int i = this.curByte;
advance();
return i;
}
public long readNBit(int paramInt)
throws IOException
{
if (paramInt > 64) {
throw new IllegalArgumentException("Can not readByte more then 64 bit");
}
long l = 0L;
for (int i = 0;; i++)
{
if (i >= paramInt) {
return l;
}
l = l << 1 | read1Bit();
}
}
public long readRemainingByte()
throws IOException
{
return readNBit(8 - this.nBit);
}
}
/* Location: C:\Users\Ara\Desktop\dex2jar-0.0.9.15\classes_dex2jar.jar
* Qualified Name: com.googlecode.mp4parser.h264.read.BitstreamReader
* JD-Core Version: 0.7.0.1
*/ | UTF-8 | Java | 3,618 | java | BitstreamReader.java | Java | [] | null | [] | package com.googlecode.mp4parser.h264.read;
import com.googlecode.mp4parser.h264.CharCache;
import java.io.IOException;
import java.io.InputStream;
public class BitstreamReader
{
protected static int bitsRead;
private int curByte;
protected CharCache debugBits = new CharCache(50);
private InputStream is;
int nBit;
private int nextByte;
public BitstreamReader(InputStream paramInputStream)
throws IOException
{
this.is = paramInputStream;
this.curByte = paramInputStream.read();
this.nextByte = paramInputStream.read();
}
private void advance()
throws IOException
{
this.curByte = this.nextByte;
this.nextByte = this.is.read();
this.nBit = 0;
}
public void close()
throws IOException
{}
public long getBitPosition()
{
return 8 * bitsRead + this.nBit % 8;
}
public int getCurBit()
{
return this.nBit;
}
public boolean isByteAligned()
{
return this.nBit % 8 == 0;
}
public boolean moreRBSPData()
throws IOException
{
int i = 1;
if (this.nBit == 8) {
advance();
}
int j = i << -1 + (8 - this.nBit);
if ((-1 + (j << 1) & this.curByte) == j) {}
int m;
for (int k = i;; m = 0)
{
if ((this.curByte == -1) || ((this.nextByte == -1) && (k != 0))) {
i = 0;
}
return i;
}
}
public int peakNextBits(int paramInt)
throws IOException
{
int i = -1;
if (paramInt > 8) {
throw new IllegalArgumentException("N should be less then 8");
}
if (this.nBit == 8)
{
advance();
if (this.curByte == i) {
return i;
}
}
int[] arrayOfInt = new int[16 - this.nBit];
int j = this.nBit;
int k = 0;
label60:
int n;
if (j >= 8) {
n = 0;
}
for (;;)
{
if (n >= 8)
{
i = 0;
for (int i2 = 0; i2 < paramInt; i2++) {
i = i << 1 | arrayOfInt[i2];
}
break;
int m = k + 1;
arrayOfInt[k] = (0x1 & this.curByte >> 7 - j);
j++;
k = m;
break label60;
}
int i1 = k + 1;
arrayOfInt[k] = (0x1 & this.nextByte >> 7 - n);
n++;
k = i1;
}
}
public int read1Bit()
throws IOException
{
if (this.nBit == 8)
{
advance();
if (this.curByte == -1) {
return -1;
}
}
int i = 0x1 & this.curByte >> 7 - this.nBit;
this.nBit = (1 + this.nBit);
CharCache localCharCache = this.debugBits;
if (i == 0) {}
for (char c = '0';; c = '1')
{
localCharCache.append(c);
bitsRead = 1 + bitsRead;
return i;
}
}
public int readByte()
throws IOException
{
if (this.nBit > 0) {
advance();
}
int i = this.curByte;
advance();
return i;
}
public long readNBit(int paramInt)
throws IOException
{
if (paramInt > 64) {
throw new IllegalArgumentException("Can not readByte more then 64 bit");
}
long l = 0L;
for (int i = 0;; i++)
{
if (i >= paramInt) {
return l;
}
l = l << 1 | read1Bit();
}
}
public long readRemainingByte()
throws IOException
{
return readNBit(8 - this.nBit);
}
}
/* Location: C:\Users\Ara\Desktop\dex2jar-0.0.9.15\classes_dex2jar.jar
* Qualified Name: com.googlecode.mp4parser.h264.read.BitstreamReader
* JD-Core Version: 0.7.0.1
*/ | 3,618 | 0.504699 | 0.478718 | 178 | 18.35955 | 16.799042 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.432584 | false | false | 2 |
84b666de3d01b0ee1ab349dfefdfcee8fa74a7bd | 28,252,294,905,409 | 3a859a920abee10e28b833feda5734f71158ad87 | /src/main/java/com/ningpai/staff/service/StaffService.java | 60b1b50a6d77d4c0c1c42baefcf69ec29b334b14 | [] | no_license | okeeper/jietongda | https://github.com/okeeper/jietongda | 84aef7ee2223ee91efc77c76f5fe297b8a97f611 | 9eed9b0d87aa912b40e264bffdd8b5d6ae6a111f | refs/heads/master | 2019-08-29T18:33:04.443000 | 2014-12-12T09:58:43 | 2014-12-12T09:58:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2013 NINGPAI, Inc.All rights reserved.
* NINGPAI PROPRIETARY / CONFIDENTIAL.USE is subject to licence terms.
*/
package com.ningpai.staff.service;
import com.ningpai.common.util.JsonUtil;
import com.ningpai.staff.bean.Staff;
import com.ningpai.staff.dao.StaffMapper;
/**
* @version 创建时间:2014年3月5日 下午2:30:15
* @author zhangyue
*/
public class StaffService {
/**
* 根据主键删除
* 参数:主键
* 返回:删除个数
* @param staffId
* @return
*/
public int deleteByPrimaryKey(String staffId){
return staffMapper.deleteByPrimaryKey(staffId);
}
/**
* 插入,空属性不会插入
* @param jsonData json字符串
* @return int
*/
public int insertSelective(String jsonData){
Staff staff = (Staff) JsonUtil.getDTO(jsonData, Staff.class);
return staffMapper.insertSelective(staff);
}
/**
* 根据主键修改,空值条件不会修改成null
* 参数:1.要修改成的值
* @param jsonData json数据串
* @return int
*/
public int updateByPrimaryKeySelective(String jsonData){
Staff staff = (Staff) JsonUtil.getDTO(jsonData, Staff.class);
return staffMapper.updateByPrimaryKeySelective(staff);
}
private StaffMapper staffMapper;
public StaffMapper getStaffMapper() {
return staffMapper;
}
public void setStaffMapper(StaffMapper staffMapper) {
this.staffMapper = staffMapper;
}
}
| UTF-8 | Java | 1,576 | java | StaffService.java | Java | [
{
"context": "\r\n * @version 创建时间:2014年3月5日 下午2:30:15\r\n * @author zhangyue\r\n */\r\npublic class StaffService {\r\n /**\r\n ",
"end": 359,
"score": 0.9981641173362732,
"start": 351,
"tag": "USERNAME",
"value": "zhangyue"
}
] | null | [] | /*
* Copyright 2013 NINGPAI, Inc.All rights reserved.
* NINGPAI PROPRIETARY / CONFIDENTIAL.USE is subject to licence terms.
*/
package com.ningpai.staff.service;
import com.ningpai.common.util.JsonUtil;
import com.ningpai.staff.bean.Staff;
import com.ningpai.staff.dao.StaffMapper;
/**
* @version 创建时间:2014年3月5日 下午2:30:15
* @author zhangyue
*/
public class StaffService {
/**
* 根据主键删除
* 参数:主键
* 返回:删除个数
* @param staffId
* @return
*/
public int deleteByPrimaryKey(String staffId){
return staffMapper.deleteByPrimaryKey(staffId);
}
/**
* 插入,空属性不会插入
* @param jsonData json字符串
* @return int
*/
public int insertSelective(String jsonData){
Staff staff = (Staff) JsonUtil.getDTO(jsonData, Staff.class);
return staffMapper.insertSelective(staff);
}
/**
* 根据主键修改,空值条件不会修改成null
* 参数:1.要修改成的值
* @param jsonData json数据串
* @return int
*/
public int updateByPrimaryKeySelective(String jsonData){
Staff staff = (Staff) JsonUtil.getDTO(jsonData, Staff.class);
return staffMapper.updateByPrimaryKeySelective(staff);
}
private StaffMapper staffMapper;
public StaffMapper getStaffMapper() {
return staffMapper;
}
public void setStaffMapper(StaffMapper staffMapper) {
this.staffMapper = staffMapper;
}
}
| 1,576 | 0.634349 | 0.623269 | 55 | 24.254545 | 21.104259 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 2 |
6fd0a5fd9421bf5a90802a0748ee65ffd3b6fd2e | 19,490,561,625,754 | 3f464467b630a38e45b564757dc54afc3d34dacc | /src/test/java/ru/dserg/autotest/page/MediumTerm/LongModelElements/Create.java | 75097a1930ea95e8827cc263618a9c97a8a5524e | [] | no_license | darksergers/DcwebMVNSelenide | https://github.com/darksergers/DcwebMVNSelenide | 059eb389af156166e4407846565227b082bbb5f8 | daa435d065194b49c625f8ea1ce9b787b7ff3994 | refs/heads/master | 2020-09-23T13:24:47.945000 | 2017-01-20T16:31:27 | 2017-01-20T16:31:27 | 67,131,487 | 0 | 1 | null | false | 2017-01-18T10:12:16 | 2016-09-01T13:00:47 | 2016-09-01T13:21:20 | 2017-01-16T13:57:41 | 186 | 0 | 1 | 1 | Java | null | null | package ru.dserg.autotest.page.MediumTerm.LongModelElements;
import com.codeborne.selenide.Condition;
import com.codeborne.selenide.WebDriverRunner;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import ru.dserg.autotest.Utils.SelenideTable;
import ru.dserg.autotest.Utils.Util;
import ru.dserg.autotest.page.MediumTerm.LongScenario;
import ru.yandex.qatools.allure.annotations.Step;
import static com.codeborne.selenide.Selenide.$;
/**
* Created by Kalinin.S on 11.08.2016.
*
*
* класс ответсвенный за форму создания нового сценария
*
*/
public class Create {
/**
* вводит названия нового сценария
*/
@Step("Ввод названия сценария")
public void name(String s){
Util.typeText($("#scenarioName"),s);
}
/**
* дата начало расчета полезного притока
*/
@Step("Ввод даты начала расчета полезного притока")
public void beginDatePritok(String date){
Util.choiceDate("#params-begin-date",date);
}
/**
* дата начало имитационого расчета
*/
@Step("Ввод даты начала имитационого расчета")
public void beginDateCalculation(String date){
Util.choiceDate("#params-calc-date",date);
}
/**
* конечная дата расчета
*/
@Step("Ввод конечной даты расчета")
public void endDateCalculation(String date){
Util.choiceDate("#params-end-date",date);
}
/**
* чекбокс использованть нач. уровни из сценария
*/
public void useSenarioLevels(){
$("#use-scenario-levels").click();
}
/**
* чекбокс использовать приток
*/
public void usePritok(){
$("#use-inflow-for-vb-curve").click();
}
/**
* чекбокс использовать дг
*/
public void useDG(){
$("#use-dg-as-regime").click();
}
/**
* чекбокс сценарий доступен только для создателя
*/
public void privateScenario(){
$("#private-scenario").click();
}
/**
* кнопка создать
*/
@Step("Нажатие кнопки создать")
public LongScenario create() throws Exception {
$("#edit-scenario-button").click();
try {
$("#results-table").waitUntil(Condition.visible,60000);
}finally {
Util.findError();
}
return new LongScenario();
}
@Step("Выбор гранулярности {0}")
public void granularity(String granularity) throws Exception {//// TODO доделать
SelenideTable table= new SelenideTable($("#granularity-table").$(By.tagName("table")));
for (int i=0;i<12;i++) {
table.choiceTr(i, 1).doubleClick();
table.choiceTr(i, 1).click();
JavascriptExecutor js = (JavascriptExecutor) WebDriverRunner.getWebDriver();
js.executeScript(
"var textarea= document.querySelector('#granularity-table > div:nth-child(2) > textarea') ;" +
"textarea.value='"+granularity+"';");
$("#granularity-table > div:nth-child(2) > textarea").click();
$("#scenarioName").click();
}
}
}
| UTF-8 | Java | 3,555 | java | Create.java | Java | [
{
"context": ".codeborne.selenide.Selenide.$;\n\n/**\n * Created by Kalinin.S on 11.08.2016.\n *\n *\n * класс ответсвенный за фор",
"end": 494,
"score": 0.8658218383789062,
"start": 485,
"tag": "NAME",
"value": "Kalinin.S"
}
] | null | [] | package ru.dserg.autotest.page.MediumTerm.LongModelElements;
import com.codeborne.selenide.Condition;
import com.codeborne.selenide.WebDriverRunner;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import ru.dserg.autotest.Utils.SelenideTable;
import ru.dserg.autotest.Utils.Util;
import ru.dserg.autotest.page.MediumTerm.LongScenario;
import ru.yandex.qatools.allure.annotations.Step;
import static com.codeborne.selenide.Selenide.$;
/**
* Created by Kalinin.S on 11.08.2016.
*
*
* класс ответсвенный за форму создания нового сценария
*
*/
public class Create {
/**
* вводит названия нового сценария
*/
@Step("Ввод названия сценария")
public void name(String s){
Util.typeText($("#scenarioName"),s);
}
/**
* дата начало расчета полезного притока
*/
@Step("Ввод даты начала расчета полезного притока")
public void beginDatePritok(String date){
Util.choiceDate("#params-begin-date",date);
}
/**
* дата начало имитационого расчета
*/
@Step("Ввод даты начала имитационого расчета")
public void beginDateCalculation(String date){
Util.choiceDate("#params-calc-date",date);
}
/**
* конечная дата расчета
*/
@Step("Ввод конечной даты расчета")
public void endDateCalculation(String date){
Util.choiceDate("#params-end-date",date);
}
/**
* чекбокс использованть нач. уровни из сценария
*/
public void useSenarioLevels(){
$("#use-scenario-levels").click();
}
/**
* чекбокс использовать приток
*/
public void usePritok(){
$("#use-inflow-for-vb-curve").click();
}
/**
* чекбокс использовать дг
*/
public void useDG(){
$("#use-dg-as-regime").click();
}
/**
* чекбокс сценарий доступен только для создателя
*/
public void privateScenario(){
$("#private-scenario").click();
}
/**
* кнопка создать
*/
@Step("Нажатие кнопки создать")
public LongScenario create() throws Exception {
$("#edit-scenario-button").click();
try {
$("#results-table").waitUntil(Condition.visible,60000);
}finally {
Util.findError();
}
return new LongScenario();
}
@Step("Выбор гранулярности {0}")
public void granularity(String granularity) throws Exception {//// TODO доделать
SelenideTable table= new SelenideTable($("#granularity-table").$(By.tagName("table")));
for (int i=0;i<12;i++) {
table.choiceTr(i, 1).doubleClick();
table.choiceTr(i, 1).click();
JavascriptExecutor js = (JavascriptExecutor) WebDriverRunner.getWebDriver();
js.executeScript(
"var textarea= document.querySelector('#granularity-table > div:nth-child(2) > textarea') ;" +
"textarea.value='"+granularity+"';");
$("#granularity-table > div:nth-child(2) > textarea").click();
$("#scenarioName").click();
}
}
}
| 3,555 | 0.611219 | 0.604449 | 116 | 25.741379 | 24.314434 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.344828 | false | false | 2 |
17c40f7841e5e7a095970beb92fdc7da74787a76 | 9,887,014,739,561 | 8c8e43fe9982d2a64cee435222883b544fb2466a | /src/main/java/bit/lin/pointwise/Run.java | 2d17768db25f25d0faca38ae8e471596718ec3bb | [] | no_license | linshuang/learning2rank | https://github.com/linshuang/learning2rank | 47e86f977b54b47e34b6734f937e648c7095c9d5 | b0304eae5fcdee11397b11507deb1ac2ab9ba0c5 | refs/heads/master | 2021-01-01T06:27:27.177000 | 2012-04-10T02:04:17 | 2012-04-10T02:04:17 | 3,786,170 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bit.lin.pointwise;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Vector;
import org.joone.engine.Layer;
import org.joone.engine.Pattern;
import org.joone.io.FileInputSynapse;
import org.joone.io.MemoryInputSynapse;
import org.joone.io.MemoryOutputSynapse;
import org.joone.net.NeuralNet;
import bit.lin.nn.RankResult;
import bit.lin.utils.JUtils;
public class Run {
static String valiSrc = "/home/lins/data/learning to rank/10k4j/Fold1/vali.txt";
static String nnLocation = "src/main/resources/pointwise.nn";
static String serFile = "/home/lins/data/learning to rank/result";
public static void train() {
BasicPointwiseNN pnn = new BasicPointwiseNN(30);
pnn.setCicles(2000);
pnn.setPatternCount(50000);
pnn.setLearningRate(0.1);
pnn.train(true);
pnn.saveNeuralNet(nnLocation);
}
public static void validate() throws IOException {
BasicPointwiseNN pnn = BasicPointwiseNN.restoreNeuralNet(nnLocation);
NeuralNet nn = pnn.getNeuralNet().cloneNet();
// System.out.println(nn.getMonitor().isUseRMSE());
Layer input = nn.getInputLayer();
input.removeAllInputs();
FileInputSynapse inputData = new FileInputSynapse();
inputData.setAdvancedColumnSelector("3-138");
inputData.setBuffered(false);
inputData.setFirstRow(1);
inputData.setInputFile(new File(valiSrc));
input.addInputSynapse(inputData);
Layer output = nn.getOutputLayer();
output.removeAllOutputs();
MemoryOutputSynapse menOS = new MemoryOutputSynapse();
output.addOutputSynapse(menOS);
// menOS.
nn.getMonitor().setTotCicles(1);
nn.getMonitor().setValidation(true);
nn.getMonitor().setValidationPatterns(500);
nn.getMonitor().setLearning(false);
nn.go();
nn.stop();
RandomAccessFile raf = new RandomAccessFile(valiSrc, "r");
Vector v = menOS.getAllPatterns();
for (int i = 0; i < v.size(); i++) {
Pattern p = (Pattern) v.get(i);
double[] pattern = p.getArray();
String line = raf.readLine();
System.out.println("Output pattern#" + (i + 1) + " : " + pattern[0]
+ " - " + line.replaceAll(";*", " "));
}
}
public static void validate2f(int pCount) throws IOException {
BasicPointwiseNN pnn = BasicPointwiseNN.restoreNeuralNet(nnLocation);
NeuralNet nn = pnn.getNeuralNet().cloneNet();
// System.out.println(nn.getMonitor().isUseRMSE());
Layer input = nn.getInputLayer();
input.removeAllInputs();
FileInputSynapse inputData = new FileInputSynapse();
inputData.setAdvancedColumnSelector("3-138");
inputData.setBuffered(false);
inputData.setFirstRow(1);
inputData.setInputFile(new File(valiSrc));
input.addInputSynapse(inputData);
Layer output = nn.getOutputLayer();
output.removeAllOutputs();
MemoryOutputSynapse menOS = new MemoryOutputSynapse();
output.addOutputSynapse(menOS);
// menOS.
nn.getMonitor().setTotCicles(1);
nn.getMonitor().setValidation(true);
nn.getMonitor().setValidationPatterns(pCount);
nn.getMonitor().setLearning(false);
nn.go();
nn.stop();
RandomAccessFile raf = new RandomAccessFile(valiSrc, "r");
BufferedWriter bw = new BufferedWriter(
new FileWriter(new File(serFile)));
Vector v = menOS.getAllPatterns();
RankResult rRslt = new RankResult();
String rslt = "";
String q = "";
for (int i = 0; i < v.size(); i++) {
Pattern p = (Pattern) v.get(i);
double[] pattern = p.getArray();
String line = raf.readLine();
String[] tmp = line.split(";");
if (rRslt.getQ() == -1)
rRslt.reset(tmp[1]);
if (rRslt.getQ() != new Integer(line.split(";")[1])) {
rRslt.sort();
bw.write(rRslt.getTruthString());
rRslt.reset(tmp[1]);
}
rRslt.addS2T(pattern[0], tmp[0]);
}
bw.close();
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Run.validate2f(50000);
}
}
| UTF-8 | Java | 3,947 | java | Run.java | Java | [] | null | [] | package bit.lin.pointwise;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Vector;
import org.joone.engine.Layer;
import org.joone.engine.Pattern;
import org.joone.io.FileInputSynapse;
import org.joone.io.MemoryInputSynapse;
import org.joone.io.MemoryOutputSynapse;
import org.joone.net.NeuralNet;
import bit.lin.nn.RankResult;
import bit.lin.utils.JUtils;
public class Run {
static String valiSrc = "/home/lins/data/learning to rank/10k4j/Fold1/vali.txt";
static String nnLocation = "src/main/resources/pointwise.nn";
static String serFile = "/home/lins/data/learning to rank/result";
public static void train() {
BasicPointwiseNN pnn = new BasicPointwiseNN(30);
pnn.setCicles(2000);
pnn.setPatternCount(50000);
pnn.setLearningRate(0.1);
pnn.train(true);
pnn.saveNeuralNet(nnLocation);
}
public static void validate() throws IOException {
BasicPointwiseNN pnn = BasicPointwiseNN.restoreNeuralNet(nnLocation);
NeuralNet nn = pnn.getNeuralNet().cloneNet();
// System.out.println(nn.getMonitor().isUseRMSE());
Layer input = nn.getInputLayer();
input.removeAllInputs();
FileInputSynapse inputData = new FileInputSynapse();
inputData.setAdvancedColumnSelector("3-138");
inputData.setBuffered(false);
inputData.setFirstRow(1);
inputData.setInputFile(new File(valiSrc));
input.addInputSynapse(inputData);
Layer output = nn.getOutputLayer();
output.removeAllOutputs();
MemoryOutputSynapse menOS = new MemoryOutputSynapse();
output.addOutputSynapse(menOS);
// menOS.
nn.getMonitor().setTotCicles(1);
nn.getMonitor().setValidation(true);
nn.getMonitor().setValidationPatterns(500);
nn.getMonitor().setLearning(false);
nn.go();
nn.stop();
RandomAccessFile raf = new RandomAccessFile(valiSrc, "r");
Vector v = menOS.getAllPatterns();
for (int i = 0; i < v.size(); i++) {
Pattern p = (Pattern) v.get(i);
double[] pattern = p.getArray();
String line = raf.readLine();
System.out.println("Output pattern#" + (i + 1) + " : " + pattern[0]
+ " - " + line.replaceAll(";*", " "));
}
}
public static void validate2f(int pCount) throws IOException {
BasicPointwiseNN pnn = BasicPointwiseNN.restoreNeuralNet(nnLocation);
NeuralNet nn = pnn.getNeuralNet().cloneNet();
// System.out.println(nn.getMonitor().isUseRMSE());
Layer input = nn.getInputLayer();
input.removeAllInputs();
FileInputSynapse inputData = new FileInputSynapse();
inputData.setAdvancedColumnSelector("3-138");
inputData.setBuffered(false);
inputData.setFirstRow(1);
inputData.setInputFile(new File(valiSrc));
input.addInputSynapse(inputData);
Layer output = nn.getOutputLayer();
output.removeAllOutputs();
MemoryOutputSynapse menOS = new MemoryOutputSynapse();
output.addOutputSynapse(menOS);
// menOS.
nn.getMonitor().setTotCicles(1);
nn.getMonitor().setValidation(true);
nn.getMonitor().setValidationPatterns(pCount);
nn.getMonitor().setLearning(false);
nn.go();
nn.stop();
RandomAccessFile raf = new RandomAccessFile(valiSrc, "r");
BufferedWriter bw = new BufferedWriter(
new FileWriter(new File(serFile)));
Vector v = menOS.getAllPatterns();
RankResult rRslt = new RankResult();
String rslt = "";
String q = "";
for (int i = 0; i < v.size(); i++) {
Pattern p = (Pattern) v.get(i);
double[] pattern = p.getArray();
String line = raf.readLine();
String[] tmp = line.split(";");
if (rRslt.getQ() == -1)
rRslt.reset(tmp[1]);
if (rRslt.getQ() != new Integer(line.split(";")[1])) {
rRslt.sort();
bw.write(rRslt.getTruthString());
rRslt.reset(tmp[1]);
}
rRslt.addS2T(pattern[0], tmp[0]);
}
bw.close();
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Run.validate2f(50000);
}
}
| 3,947 | 0.70864 | 0.695972 | 132 | 28.901516 | 19.289995 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.310606 | false | false | 2 |
2209d9540ded867377c8a14b99342c05b439970b | 22,290,880,323,366 | 2466294c91d45da039562f440186306faa5340a3 | /Java/src/repeated_substring_pattern_1227/Solution.java | 7910a6d6dc751584b00687f682576c82081f1078 | [] | no_license | AiRanthem/Algorithm | https://github.com/AiRanthem/Algorithm | 2dfaac086a96a9d54bf6082faa361e42e4b01dab | 48a46333d6837105041389b6cfaa6c477d5b8940 | refs/heads/master | 2021-03-22T23:10:06.242000 | 2020-12-28T09:17:11 | 2020-12-28T09:17:11 | 247,404,779 | 2 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package src.repeated_substring_pattern_1227;
public class Solution {
/**
* @param s: a string
* @return return a boolean
*/
public boolean repeatedSubstringPattern(String s) {
int len = s.length() / 2;
while (len > 0){
if(s.length() % len == 0){
String pattern = s.substring(0, len);
boolean ok = true;
for (int i=len; i<s.length();i+=len){
String substring = s.substring(i, i + len);
if(!pattern.equals(substring)){
ok=false;
break;
}
}
if(ok) return true;
}
len--;
}
return false;
}
}
| UTF-8 | Java | 771 | java | Solution.java | Java | [] | null | [] | package src.repeated_substring_pattern_1227;
public class Solution {
/**
* @param s: a string
* @return return a boolean
*/
public boolean repeatedSubstringPattern(String s) {
int len = s.length() / 2;
while (len > 0){
if(s.length() % len == 0){
String pattern = s.substring(0, len);
boolean ok = true;
for (int i=len; i<s.length();i+=len){
String substring = s.substring(i, i + len);
if(!pattern.equals(substring)){
ok=false;
break;
}
}
if(ok) return true;
}
len--;
}
return false;
}
}
| 771 | 0.422827 | 0.412451 | 27 | 27.555555 | 17.331909 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.518519 | false | false | 2 |
6d818db3ec0a08038dfea2c043fbe388c541c982 | 28,698,971,525,840 | 429cf033b6acc4921daa158a2aaf305e97887435 | /trunk/baseball-yeah/src/main/java/com/rofour/baseball/controller/store/BusinessChlController.java | 6eb36f63d0ce3238b787cb120101e1ced411cc43 | [] | no_license | roronoafour/Baseball-Yeah | https://github.com/roronoafour/Baseball-Yeah | d797c074774cab73ed4b55ab870ddc43569ea846 | aed3da6cc1dead8d1c2edbd0b62651c730a8ae69 | refs/heads/master | 2021-01-13T08:21:16.413000 | 2016-11-16T08:10:03 | 2016-11-16T08:10:03 | 71,742,887 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.rofour.baseball.controller.store;
import com.rofour.baseball.common.JsonUtils;
import com.rofour.baseball.common.RandomHelper;
import com.rofour.baseball.controller.base.BaseController;
import com.rofour.baseball.controller.model.DataGrid;
import com.rofour.baseball.controller.model.ResultInfo;
import com.rofour.baseball.controller.model.store.BusinessChannelInfo;
import com.rofour.baseball.dao.user.bean.UserManagerLoginBean;
import com.rofour.baseball.service.store.BusinessChlService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* @ClassName: BusinessChlController
* @Description: 商户渠道控制层
* @author ZhangLei
* @date 2016年8月31日 下午5:12:35
*/
@Controller
@RequestMapping(value = "/business/chl")
public class BusinessChlController extends BaseController {
private static final Logger LOG = LoggerFactory.getLogger(BusinessChlController.class);
@Resource(name="businessChlService")
private BusinessChlService businessChlService;
/**
* @Description: 查询所有非系统商户渠道
* @param request
* @param response
* @param businessChannelInfo
*/
@RequestMapping(value = "/queryAll")
@ResponseBody
public void selectAllStoreChannel(HttpServletRequest request, HttpServletResponse response, BusinessChannelInfo businessChannelInfo) {
DataGrid<BusinessChannelInfo> grid=new DataGrid<BusinessChannelInfo>();
try {
if (StringUtils.isEmpty(businessChannelInfo.getSort())) {
businessChannelInfo.setSort("createDate");
}
LOG.error(JsonUtils.translateToJson(businessChannelInfo));
List<BusinessChannelInfo> list = businessChlService.selectAllBusinessChl(businessChannelInfo);
grid.setRows(list);
grid.setTotal(businessChlService.selectAllBusinessChlTotal(businessChannelInfo));
} catch (Exception e) {
LOG.error(e.getMessage(),e);
}
writeJson(grid, response);
}
/**
* @Description: 增加商户渠道
* @param businessChannelInfo
* @param request
* @return
*/
@RequestMapping(value = "/addBussinessChl",method=RequestMethod.POST)
@ResponseBody
public ResultInfo<BusinessChannelInfo> addBussinessChl(BusinessChannelInfo businessChannelInfo, HttpServletRequest request) {
try {
UserManagerLoginBean userInfo= (UserManagerLoginBean) request.getSession().getAttribute("user");
businessChannelInfo.setCreateUser(userInfo.getUserManagerId());
return businessChlService.addBussinessChl(businessChannelInfo);
} catch (Exception e) {
LOG.error(e.getMessage(),e);
return new ResultInfo<BusinessChannelInfo>(-1,"1060","增加商户渠道出错");
}
}
/**
* @Description: 逻辑删除商户渠道
* @param channelId
* @param request
* @return
*/
@RequestMapping(value = "/delBussinessChl",method=RequestMethod.POST)
@ResponseBody
public ResultInfo<BusinessChannelInfo> delBussinessChl(Long channelId, HttpServletRequest request) {
try {
return businessChlService.delBussinessChl(channelId);
} catch (Exception e) {
LOG.error(e.getMessage(),e);
return new ResultInfo<BusinessChannelInfo>(-1,"1060","删除商户渠道出错");
}
}
/**
* @Description: 禁用商户渠道
* @param channelId
* @param request
* @return
*/
@RequestMapping(value = "/cancleBussinessChl",method=RequestMethod.POST)
@ResponseBody
public ResultInfo<BusinessChannelInfo> cancleBussinessChl(Long channelId, HttpServletRequest request) {
try {
return businessChlService.cancleBussinessChl(channelId);
} catch (Exception e) {
LOG.error(e.getMessage(),e);
return new ResultInfo<BusinessChannelInfo>(-1,"1060","禁用商户渠道出错");
}
}
/**
* @Description: 启用商户渠道
* @param channelId
* @param request
* @return
*/
@RequestMapping(value = "/enabledBussinessChl",method=RequestMethod.POST)
@ResponseBody
public ResultInfo<BusinessChannelInfo> enabledBussinessChl(Long channelId, HttpServletRequest request) {
try {
return businessChlService.enabledBussinessChl(channelId);
} catch (Exception e) {
LOG.error(e.getMessage(),e);
return new ResultInfo<BusinessChannelInfo>(-1,"1060","启用商户渠道出错");
}
}
/**
* @Description: 验证商户渠道是否存在
* @param channelCode
* @param response
*/
@RequestMapping(value = "/ifExistChannelCode")
@ResponseBody
public void ifExistChannelCode(String channelCode, HttpServletResponse response) {
ResultInfo resultInfo=null;
try {
resultInfo=businessChlService.ifExistChannelCode(channelCode);
} catch (Exception e) {
LOG.error(e.getMessage(),e);
}
writeJson(resultInfo, response);
}
/**
* @Description: 获取6位商户渠道编码
* @param response
*/
@RequestMapping(value = "/getRandomChlCode")
@ResponseBody
public void getRandomChlCode(HttpServletResponse response) {
String channelCodeStr=null;
try {
channelCodeStr= RandomHelper.generateString(6);
while (businessChlService.ifExistChannelCode(channelCodeStr).getSuccess()!=0){
channelCodeStr=RandomHelper.generateString(6);
}
} catch (Exception e) {
LOG.error(e.getMessage(),e);
}
writeJson(channelCodeStr, response);
}
}
| UTF-8 | Java | 6,258 | java | BusinessChlController.java | Java | [
{
"context": "sChlController\n * @Description: 商户渠道控制层\n * @author ZhangLei\n * @date 2016年8月31日 下午5:12:35 \n */\n@Controller\n@R",
"end": 1079,
"score": 0.9996670484542847,
"start": 1071,
"tag": "NAME",
"value": "ZhangLei"
}
] | null | [] | package com.rofour.baseball.controller.store;
import com.rofour.baseball.common.JsonUtils;
import com.rofour.baseball.common.RandomHelper;
import com.rofour.baseball.controller.base.BaseController;
import com.rofour.baseball.controller.model.DataGrid;
import com.rofour.baseball.controller.model.ResultInfo;
import com.rofour.baseball.controller.model.store.BusinessChannelInfo;
import com.rofour.baseball.dao.user.bean.UserManagerLoginBean;
import com.rofour.baseball.service.store.BusinessChlService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* @ClassName: BusinessChlController
* @Description: 商户渠道控制层
* @author ZhangLei
* @date 2016年8月31日 下午5:12:35
*/
@Controller
@RequestMapping(value = "/business/chl")
public class BusinessChlController extends BaseController {
private static final Logger LOG = LoggerFactory.getLogger(BusinessChlController.class);
@Resource(name="businessChlService")
private BusinessChlService businessChlService;
/**
* @Description: 查询所有非系统商户渠道
* @param request
* @param response
* @param businessChannelInfo
*/
@RequestMapping(value = "/queryAll")
@ResponseBody
public void selectAllStoreChannel(HttpServletRequest request, HttpServletResponse response, BusinessChannelInfo businessChannelInfo) {
DataGrid<BusinessChannelInfo> grid=new DataGrid<BusinessChannelInfo>();
try {
if (StringUtils.isEmpty(businessChannelInfo.getSort())) {
businessChannelInfo.setSort("createDate");
}
LOG.error(JsonUtils.translateToJson(businessChannelInfo));
List<BusinessChannelInfo> list = businessChlService.selectAllBusinessChl(businessChannelInfo);
grid.setRows(list);
grid.setTotal(businessChlService.selectAllBusinessChlTotal(businessChannelInfo));
} catch (Exception e) {
LOG.error(e.getMessage(),e);
}
writeJson(grid, response);
}
/**
* @Description: 增加商户渠道
* @param businessChannelInfo
* @param request
* @return
*/
@RequestMapping(value = "/addBussinessChl",method=RequestMethod.POST)
@ResponseBody
public ResultInfo<BusinessChannelInfo> addBussinessChl(BusinessChannelInfo businessChannelInfo, HttpServletRequest request) {
try {
UserManagerLoginBean userInfo= (UserManagerLoginBean) request.getSession().getAttribute("user");
businessChannelInfo.setCreateUser(userInfo.getUserManagerId());
return businessChlService.addBussinessChl(businessChannelInfo);
} catch (Exception e) {
LOG.error(e.getMessage(),e);
return new ResultInfo<BusinessChannelInfo>(-1,"1060","增加商户渠道出错");
}
}
/**
* @Description: 逻辑删除商户渠道
* @param channelId
* @param request
* @return
*/
@RequestMapping(value = "/delBussinessChl",method=RequestMethod.POST)
@ResponseBody
public ResultInfo<BusinessChannelInfo> delBussinessChl(Long channelId, HttpServletRequest request) {
try {
return businessChlService.delBussinessChl(channelId);
} catch (Exception e) {
LOG.error(e.getMessage(),e);
return new ResultInfo<BusinessChannelInfo>(-1,"1060","删除商户渠道出错");
}
}
/**
* @Description: 禁用商户渠道
* @param channelId
* @param request
* @return
*/
@RequestMapping(value = "/cancleBussinessChl",method=RequestMethod.POST)
@ResponseBody
public ResultInfo<BusinessChannelInfo> cancleBussinessChl(Long channelId, HttpServletRequest request) {
try {
return businessChlService.cancleBussinessChl(channelId);
} catch (Exception e) {
LOG.error(e.getMessage(),e);
return new ResultInfo<BusinessChannelInfo>(-1,"1060","禁用商户渠道出错");
}
}
/**
* @Description: 启用商户渠道
* @param channelId
* @param request
* @return
*/
@RequestMapping(value = "/enabledBussinessChl",method=RequestMethod.POST)
@ResponseBody
public ResultInfo<BusinessChannelInfo> enabledBussinessChl(Long channelId, HttpServletRequest request) {
try {
return businessChlService.enabledBussinessChl(channelId);
} catch (Exception e) {
LOG.error(e.getMessage(),e);
return new ResultInfo<BusinessChannelInfo>(-1,"1060","启用商户渠道出错");
}
}
/**
* @Description: 验证商户渠道是否存在
* @param channelCode
* @param response
*/
@RequestMapping(value = "/ifExistChannelCode")
@ResponseBody
public void ifExistChannelCode(String channelCode, HttpServletResponse response) {
ResultInfo resultInfo=null;
try {
resultInfo=businessChlService.ifExistChannelCode(channelCode);
} catch (Exception e) {
LOG.error(e.getMessage(),e);
}
writeJson(resultInfo, response);
}
/**
* @Description: 获取6位商户渠道编码
* @param response
*/
@RequestMapping(value = "/getRandomChlCode")
@ResponseBody
public void getRandomChlCode(HttpServletResponse response) {
String channelCodeStr=null;
try {
channelCodeStr= RandomHelper.generateString(6);
while (businessChlService.ifExistChannelCode(channelCodeStr).getSuccess()!=0){
channelCodeStr=RandomHelper.generateString(6);
}
} catch (Exception e) {
LOG.error(e.getMessage(),e);
}
writeJson(channelCodeStr, response);
}
}
| 6,258 | 0.677121 | 0.670848 | 175 | 33.617142 | 29.322966 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.468571 | false | false | 2 |
1a6bf1741c0320c857847c9cfb127d99714a1d7b | 11,725,260,726,389 | ef58f7bf31e575f069d1d5e1200cc62509cb06cb | /ProjectAdlez/core/src/com/mygdx/game/model/core/WorldObjectObserver.java | 22054ee3c6830852be38b08f3c0e11a26f61945e | [] | no_license | pontusthome/Adlez | https://github.com/pontusthome/Adlez | 8ef4dd9846e0b922bc8c385cfeb6d0e8893e636e | 720d10991f29bee03191b6d7d0aef6a39ed66b70 | refs/heads/master | 2021-01-21T13:33:29.650000 | 2016-05-29T12:26:47 | 2016-05-29T12:26:47 | 54,380,885 | 1 | 0 | null | false | 2016-04-25T05:16:37 | 2016-03-21T10:45:33 | 2016-04-13T13:35:33 | 2016-04-25T05:16:37 | 2,531 | 1 | 0 | 0 | Java | null | null | package com.mygdx.game.model.core;
import com.mygdx.game.model.core.IWorldObject;
/**
* Created by Michel on 2016-05-24.
*/
public interface WorldObjectObserver{
void update(IWorldObject worldObject, String action);
}
| UTF-8 | Java | 223 | java | WorldObjectObserver.java | Java | [
{
"context": "x.game.model.core.IWorldObject;\n\n/**\n * Created by Michel on 2016-05-24.\n */\npublic interface WorldObjectOb",
"end": 108,
"score": 0.9984993934631348,
"start": 102,
"tag": "NAME",
"value": "Michel"
}
] | null | [] | package com.mygdx.game.model.core;
import com.mygdx.game.model.core.IWorldObject;
/**
* Created by Michel on 2016-05-24.
*/
public interface WorldObjectObserver{
void update(IWorldObject worldObject, String action);
}
| 223 | 0.766816 | 0.730942 | 10 | 21.299999 | 20.649698 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
e732bc94009403e7f558042b6ed80fbcaf3316d4 | 481,036,376,283 | 6ca3e7178fa98025b49820bdbbf5f8ef207acf94 | /src/main/java/Facility/Facility.java | e204418f762a005c0d143326d9f363bc88199201 | [] | no_license | johare1/OFPProject2 | https://github.com/johare1/OFPProject2 | 2c3735f2ace402f4561f6d7655116ad9138f52b7 | 16e4e093e87ccb2c44311f1942a6144a2b24a49f | refs/heads/master | 2020-04-29T05:15:12.661000 | 2019-02-23T22:14:56 | 2019-02-23T22:14:56 | 175,875,967 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Facility {
int capacity;
boolean isvacated;
info information;
} | UTF-8 | Java | 97 | java | Facility.java | Java | [] | null | [] |
public class Facility {
int capacity;
boolean isvacated;
info information;
} | 97 | 0.628866 | 0.628866 | 5 | 18.4 | 5.122499 | 23 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 9 |
1541447d70faca3479627eb0e109494255f47157 | 4,690,104,333,508 | 4d7002b091f6638ff8e2b1c88a686e1242c799a7 | /citamedica/src/main/java/citamedica/model/service/UsuarioService.java | e3490b517c65b26037a705a078135b651e64c7fe | [] | no_license | jlgarciasanchez/citamedica | https://github.com/jlgarciasanchez/citamedica | 609ddd60f89913577d2402bb5e62cc0b4f2e8333 | 7f79aa19a294c96de0f47e02652cbbd3cf27304d | refs/heads/master | 2022-12-24T05:24:08.279000 | 2019-12-27T12:16:29 | 2019-12-27T12:16:29 | 228,245,246 | 0 | 0 | null | false | 2022-12-16T05:46:46 | 2019-12-15T20:12:10 | 2019-12-27T12:16:56 | 2022-12-16T05:46:45 | 42,010 | 0 | 0 | 6 | TSQL | false | false | package citamedica.model.service;
import citamedica.model.entities.Usuario;
public interface UsuarioService {
public Usuario login(String user, String pass);
}
| UTF-8 | Java | 166 | java | UsuarioService.java | Java | [] | null | [] | package citamedica.model.service;
import citamedica.model.entities.Usuario;
public interface UsuarioService {
public Usuario login(String user, String pass);
}
| 166 | 0.795181 | 0.795181 | 7 | 22.714285 | 20.175758 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 9 |
e17aad7cd741a8d5fc56dc0fef0be73426fd0657 | 28,836,410,470,604 | be96712b1567e2e9021ab5b8f3ed8410dc72546a | /MainClass.java | 70735d5d3b08c0fec3fabe81f0af5a0c0d8c587a | [] | no_license | korybilak/Server-Program | https://github.com/korybilak/Server-Program | c478ccaa6627657df6b79a9b54bc93dde3db755b | 747cd2e9785fe3fee3bd75bc0d55841b0e751614 | refs/heads/master | 2020-03-19T14:31:26.462000 | 2018-06-08T14:08:28 | 2018-06-08T14:08:28 | 136,626,871 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* Program Created Spring 2018
* CSC 492: Senior Project II
* By: Kory Bilak
* Version .1 created 2/02/2018: dummy program sends data to Server class, and Client class
* displays data on screen
* Version .5 created 2/16/2018: can connect to thingworx using restAPI
* Version 1.0 created 3/3/2018: can accept data from sensors by reading lines of data
* and converting the strings into floats and ints
* it then sends the values to thingworx
* Version 1.1 created 3/5/2018: can accept data from sensors by reading ints sent by the
* sensors via a packet
* Version 1.2 created 4/9/2018: code cleanup, removed alot of test code to make program
* smaller
*/
import java.io.IOException;
import org.json.JSONException;
//Our main class begins the program and calls the Server.Recieve() function
public class MainClass
{
//Calls the Server.Recieve function
public static void main(String[] args) throws ClassNotFoundException, IOException, InterruptedException, JSONException
{
Server.Receive(); //runs the Receive() function
}
}
//End of MainClass
| UTF-8 | Java | 1,069 | java | MainClass.java | Java | [
{
"context": "d Spring 2018\n * CSC 492: Senior Project II\n * By: Kory Bilak\n * Version .1 created 2/02/2018: dummy program se",
"end": 78,
"score": 0.999813437461853,
"start": 68,
"tag": "NAME",
"value": "Kory Bilak"
}
] | null | [] | /* Program Created Spring 2018
* CSC 492: Senior Project II
* By: <NAME>
* Version .1 created 2/02/2018: dummy program sends data to Server class, and Client class
* displays data on screen
* Version .5 created 2/16/2018: can connect to thingworx using restAPI
* Version 1.0 created 3/3/2018: can accept data from sensors by reading lines of data
* and converting the strings into floats and ints
* it then sends the values to thingworx
* Version 1.1 created 3/5/2018: can accept data from sensors by reading ints sent by the
* sensors via a packet
* Version 1.2 created 4/9/2018: code cleanup, removed alot of test code to make program
* smaller
*/
import java.io.IOException;
import org.json.JSONException;
//Our main class begins the program and calls the Server.Recieve() function
public class MainClass
{
//Calls the Server.Recieve function
public static void main(String[] args) throws ClassNotFoundException, IOException, InterruptedException, JSONException
{
Server.Receive(); //runs the Receive() function
}
}
//End of MainClass
| 1,065 | 0.753976 | 0.710009 | 29 | 35.862068 | 33.769733 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.551724 | false | false | 9 |
61f6120622d6d49b7d2eff81744b01c6951370d2 | 6,279,242,244,719 | 1fd2472f8bfca5681b7be276f9706c8b76402822 | /Android/Demo/app/src/main/java/com/tencent/qcloud/tim/demo/component/interfaces/IUnreadWatcher.java | 4212b23d34a7fb8732ace237223a0ef065251882 | [] | no_license | wangxueiOS/TIMSDK | https://github.com/wangxueiOS/TIMSDK | 250e0b1464b7f1dfbb957854db30ab8cc498c1a4 | 2b6c17f49430f7f8a1710d32e18856908883195a | refs/heads/master | 2023-09-02T19:17:17.488000 | 2021-11-23T04:57:30 | 2021-11-23T04:57:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tencent.qcloud.tim.demo.component.interfaces;
public interface IUnreadWatcher {
void updateUnread(int count);
}
| UTF-8 | Java | 129 | java | IUnreadWatcher.java | Java | [] | null | [] | package com.tencent.qcloud.tim.demo.component.interfaces;
public interface IUnreadWatcher {
void updateUnread(int count);
}
| 129 | 0.790698 | 0.790698 | 5 | 24.799999 | 21.692394 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 9 |
c54dbd4e89d77f6702157e42add3e6e17bea1d66 | 6,279,242,246,479 | e5c77608a8e0c9621b6b0cd431b7b20a72f025a3 | /Java/Misc/Student.java | 8ac2ef513b955d608ff23996b793a7290339dd5f | [] | no_license | cloud-hybrid/Open-Source | https://github.com/cloud-hybrid/Open-Source | 8dcf731068f7172bcaafdffdabb38d4c597a3211 | 0434bce0688239d22f5076be5fccf9523d6b8010 | refs/heads/master | 2020-05-04T19:01:44.255000 | 2019-05-25T05:10:29 | 2019-05-25T05:10:29 | 179,376,595 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Student{
private String name;
private String major;
private Double gpa;
public Student(){
}
public Student(String iName, String iMajor, Double iGPA){
name = iName;
major = iMajor;
setGPA(iGPA);
}
public void setName(String setName){
name = setName;
}
public String getName(){
return name;
}
public void setMajor(String setMajor){
major = setMajor;
}
public String getMajor(){
return major;
}
public void setGPA(Double setGPA){
try{
if (0.0 <= setGPA && setGPA <= 4.0){
gpa = setGPA;
}
else {
throw new GPAOutOfBoundsException("Invalid input for GPA." + "\n" + "Double-type input != 0.0 <= GPA && GPA <= 4.0");
}
}
catch(GPAOutOfBoundsException gpaException){
System.out.println(name + " " + gpaException);
System.exit(0);
}
}
public Double getGPA(){
return gpa;
}
public boolean equals(Student inputObject){
if (inputObject.name.equals(name) && inputObject.major.equals(major) && inputObject.gpa.equals(gpa)){
return true;
}
else{
return false;
}
}
public String toString(){
String gpaString = Double.toString(gpa);
return "Name: " + name + "\n" + "Major: " + major + "\n" + "GPA: " + gpaString;
}
protected static class GPAOutOfBoundsException extends Exception {
private static final long serialVersionUID = 000001;
public GPAOutOfBoundsException () {
}
public GPAOutOfBoundsException (String message) {
super ("Invalid input for GPA." + "\n" + "Double-type input != 0.0 <= GPA <= 4.0");
}
public GPAOutOfBoundsException (Throwable cause) {
super (cause);
}
public GPAOutOfBoundsException (String message, Throwable cause) {
super (message, cause);
}
}
public static void main(String[] args){
Student Jacob = new Student("Jacob Sanders", "Computer Science", 3.9);
Student Jess = new Student("Jessica Sanders", "Art", 3.1);
Student Ryan = new Student("Jacob Sanders", "Computer Science", 2.9);
Student Bill = Jacob;
System.out.println(Jacob.toString());
System.out.println(Jacob.equals(Bill));
}
}
| UTF-8 | Java | 2,464 | java | Student.java | Java | [
{
"context": "static void main(String[] args){\n Student Jacob = new Student(\"Jacob Sanders\", \"Computer Science\"",
"end": 2129,
"score": 0.9997115731239319,
"start": 2125,
"tag": "NAME",
"value": "acob"
},
{
"context": "ing[] args){\n Student Jacob = new Student(\"Jacob Sanders\", \"Computer Science\", 3.9);\n Student Jess ",
"end": 2158,
"score": 0.9998834133148193,
"start": 2145,
"tag": "NAME",
"value": "Jacob Sanders"
},
{
"context": "anders\", \"Computer Science\", 3.9);\n Student Jess = new Student(\"Jessica Sanders\", \"Art\", 3.1);\n ",
"end": 2207,
"score": 0.9790869355201721,
"start": 2203,
"tag": "NAME",
"value": "Jess"
},
{
"context": "ience\", 3.9);\n Student Jess = new Student(\"Jessica Sanders\", \"Art\", 3.1);\n Student Ryan = new Student",
"end": 2238,
"score": 0.9998778104782104,
"start": 2223,
"tag": "NAME",
"value": "Jessica Sanders"
},
{
"context": "nt(\"Jessica Sanders\", \"Art\", 3.1);\n Student Ryan = new Student(\"Jacob Sanders\", \"Computer Science\"",
"end": 2274,
"score": 0.8893700242042542,
"start": 2270,
"tag": "NAME",
"value": "Ryan"
},
{
"context": " \"Art\", 3.1);\n Student Ryan = new Student(\"Jacob Sanders\", \"Computer Science\", 2.9);\n Student Bill ",
"end": 2303,
"score": 0.9998636841773987,
"start": 2290,
"tag": "NAME",
"value": "Jacob Sanders"
},
{
"context": "anders\", \"Computer Science\", 2.9);\n Student Bill = Jacob;\n System.out.println(Jacob.toStrin",
"end": 2352,
"score": 0.8646540641784668,
"start": 2348,
"tag": "NAME",
"value": "Bill"
},
{
"context": ", \"Computer Science\", 2.9);\n Student Bill = Jacob;\n System.out.println(Jacob.toString());\n ",
"end": 2360,
"score": 0.9428548812866211,
"start": 2355,
"tag": "NAME",
"value": "Jacob"
},
{
"context": "tring());\n System.out.println(Jacob.equals(Bill));\n }\n}\n",
"end": 2452,
"score": 0.9478909969329834,
"start": 2448,
"tag": "NAME",
"value": "Bill"
}
] | null | [] | public class Student{
private String name;
private String major;
private Double gpa;
public Student(){
}
public Student(String iName, String iMajor, Double iGPA){
name = iName;
major = iMajor;
setGPA(iGPA);
}
public void setName(String setName){
name = setName;
}
public String getName(){
return name;
}
public void setMajor(String setMajor){
major = setMajor;
}
public String getMajor(){
return major;
}
public void setGPA(Double setGPA){
try{
if (0.0 <= setGPA && setGPA <= 4.0){
gpa = setGPA;
}
else {
throw new GPAOutOfBoundsException("Invalid input for GPA." + "\n" + "Double-type input != 0.0 <= GPA && GPA <= 4.0");
}
}
catch(GPAOutOfBoundsException gpaException){
System.out.println(name + " " + gpaException);
System.exit(0);
}
}
public Double getGPA(){
return gpa;
}
public boolean equals(Student inputObject){
if (inputObject.name.equals(name) && inputObject.major.equals(major) && inputObject.gpa.equals(gpa)){
return true;
}
else{
return false;
}
}
public String toString(){
String gpaString = Double.toString(gpa);
return "Name: " + name + "\n" + "Major: " + major + "\n" + "GPA: " + gpaString;
}
protected static class GPAOutOfBoundsException extends Exception {
private static final long serialVersionUID = 000001;
public GPAOutOfBoundsException () {
}
public GPAOutOfBoundsException (String message) {
super ("Invalid input for GPA." + "\n" + "Double-type input != 0.0 <= GPA <= 4.0");
}
public GPAOutOfBoundsException (Throwable cause) {
super (cause);
}
public GPAOutOfBoundsException (String message, Throwable cause) {
super (message, cause);
}
}
public static void main(String[] args){
Student Jacob = new Student("<NAME>", "Computer Science", 3.9);
Student Jess = new Student("<NAME>", "Art", 3.1);
Student Ryan = new Student("<NAME>", "Computer Science", 2.9);
Student Bill = Jacob;
System.out.println(Jacob.toString());
System.out.println(Jacob.equals(Bill));
}
}
| 2,441 | 0.557224 | 0.547078 | 91 | 26.076923 | 27.255096 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 9 |
6734e99c311c59451d87ccf73413a661f000eb6d | 23,725,399,394,961 | 7df880a749dfc34f5ba589f7c484500371107097 | /src/main/java/training/tasks/unit2/task3/NoviceSuite.java | a4d7fcc255273e09c15e6a13b5799c790b5f3cee | [] | no_license | vld-evseev/epam-training-javase | https://github.com/vld-evseev/epam-training-javase | f337cab8c9eb9772632ca5c3660d087cb38729f0 | 18efa8150b6307f88513fdf66cefd47704c52528 | refs/heads/master | 2021-01-12T12:39:23.526000 | 2016-12-07T15:06:39 | 2016-12-07T15:06:39 | 69,895,615 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package training.tasks.unit2.task3;
import training.tasks.unit2.task2.stationery.Stationery;
import java.util.ArrayList;
import java.util.List;
public class NoviceSuite {
private List<Stationery> stationeryList = new ArrayList<>();
public void addTool(Stationery tool) {
stationeryList.add(tool);
}
public void removeTool(Stationery tool) {
stationeryList.remove(tool);
}
public List<Stationery> getAllTools() {
return stationeryList;
}
}
| UTF-8 | Java | 499 | java | NoviceSuite.java | Java | [] | null | [] | package training.tasks.unit2.task3;
import training.tasks.unit2.task2.stationery.Stationery;
import java.util.ArrayList;
import java.util.List;
public class NoviceSuite {
private List<Stationery> stationeryList = new ArrayList<>();
public void addTool(Stationery tool) {
stationeryList.add(tool);
}
public void removeTool(Stationery tool) {
stationeryList.remove(tool);
}
public List<Stationery> getAllTools() {
return stationeryList;
}
}
| 499 | 0.701403 | 0.693387 | 24 | 19.791666 | 20.355137 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 9 |
80a8f36b7078c9c5084585d345c6a983060b91eb | 2,946,347,627,290 | 9bbe9591476a64e3df37b5eadee68cd1f81b39a8 | /dto/ReportDTO.java | 5a632c601790e9880c9710ba55e723a21dc57733 | [] | no_license | liqiangq/ezEMS | https://github.com/liqiangq/ezEMS | 4f8a1995aaa27dc17c4276fc8f52d59baba3cd5e | 59a176c7ab06870e7f49612c26dd0911ff803466 | refs/heads/master | 2020-07-24T03:10:15.743000 | 2019-09-11T10:28:27 | 2019-09-11T10:28:27 | 207,783,972 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.thtf.dto;
import java.util.Date;
import java.util.List;
import com.thtf.entity.BasicObject;
public class ReportDTO extends BasicObject {
private static final long serialVersionUID = 1L;
private Long id;//主键
private String name;//名称
private Date date;//创建时间
private String dateType;//时间类型:year\month\day
private String reportType;//统计类型:pdf,xls
private String remark;//描述
private Long userId;//用户id
private String email;
private Long unitId;//单位id
private String dataType;//数据类型:energy、rate、rule
private List<String> itemIds;
private String itemType;//设备类型:subitem、subitemfloor、item、cur、vol
private String sendType;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public void setName(String name) {
this.name = name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getDateType() {
return dateType;
}
public void setDateType(String dateType) {
this.dateType = dateType;
}
public String getReportType() {
return reportType;
}
public void setReportType(String reportType) {
this.reportType = reportType;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<String> getItemIds() {
return itemIds;
}
public void setItemIds(List<String> itemIds) {
this.itemIds = itemIds;
}
public String getItemType() {
return itemType;
}
public void setItemType(String itemType) {
this.itemType = itemType;
}
public String getSendType() {
return sendType;
}
public void setSendType(String sendType) {
this.sendType = sendType;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Long getUnitId() {
return unitId;
}
public void setUnitId(Long unitId) {
this.unitId = unitId;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
}
| UTF-8 | Java | 2,370 | java | ReportDTO.java | Java | [] | null | [] | package com.thtf.dto;
import java.util.Date;
import java.util.List;
import com.thtf.entity.BasicObject;
public class ReportDTO extends BasicObject {
private static final long serialVersionUID = 1L;
private Long id;//主键
private String name;//名称
private Date date;//创建时间
private String dateType;//时间类型:year\month\day
private String reportType;//统计类型:pdf,xls
private String remark;//描述
private Long userId;//用户id
private String email;
private Long unitId;//单位id
private String dataType;//数据类型:energy、rate、rule
private List<String> itemIds;
private String itemType;//设备类型:subitem、subitemfloor、item、cur、vol
private String sendType;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public void setName(String name) {
this.name = name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getDateType() {
return dateType;
}
public void setDateType(String dateType) {
this.dateType = dateType;
}
public String getReportType() {
return reportType;
}
public void setReportType(String reportType) {
this.reportType = reportType;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<String> getItemIds() {
return itemIds;
}
public void setItemIds(List<String> itemIds) {
this.itemIds = itemIds;
}
public String getItemType() {
return itemType;
}
public void setItemType(String itemType) {
this.itemType = itemType;
}
public String getSendType() {
return sendType;
}
public void setSendType(String sendType) {
this.sendType = sendType;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Long getUnitId() {
return unitId;
}
public void setUnitId(Long unitId) {
this.unitId = unitId;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
}
| 2,370 | 0.680786 | 0.680349 | 106 | 19.603773 | 15.251155 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.575472 | false | false | 9 |
4ef118ed235ee438c847f4a60f55b99054d5af73 | 19,851,338,887,547 | 4f0c68a455465949d6c71c91b7bc3777911d6989 | /workspace/src/test/java/unitTest/dao/TestResearchAttachmentDAO.java | b114b7e66d26d906b5aa0a6793ac175c7c380085 | [] | no_license | yang4851/gdkm | https://github.com/yang4851/gdkm | 01215e79ce18c6eb7d68d86dfc38ad2460e47707 | 45738f5b3d8f561ef135231d77002d2203163cb4 | refs/heads/master | 2022-12-21T13:34:39.769000 | 2019-11-14T08:19:00 | 2019-11-14T08:19:00 | 221,623,094 | 2 | 0 | null | false | 2022-12-16T09:42:47 | 2019-11-14T05:58:32 | 2021-07-01T13:41:39 | 2022-12-16T09:42:46 | 64,646 | 2 | 0 | 11 | Perl | false | false | package unitTest.dao;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.insilicogen.gdkm.dao.ResearchAttachmentDAO;
import com.insilicogen.gdkm.model.Research;
import com.insilicogen.gdkm.model.ResearchAttachment;
import com.insilicogen.gdkm.model.User;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath:/egovframework/spring/context-*.xml"})
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestResearchAttachmentDAO {
@Resource(name="ResearchAttachmentDAO")
ResearchAttachmentDAO dao;
private User owner;
private String[] types = new String[] {
"type1", "type2", "type3", "other"
};
private Research[] researches;
@Before
public void setup() {
owner = new User();
owner.setUserId("administrator");
researches = new Research[3];
researches[0] = new Research(1);
researches[0].setRegistNo("GDKM-R-0001");
researches[1] = new Research(2);
researches[1].setRegistNo("GDKM-R-0002");
researches[2] = new Research(3);
researches[2].setRegistNo("GDKM-R-0003");
}
@Test
public void test1InsertAttachment() throws Exception {
for(int i=0; i < 10 ; i++) {
ResearchAttachment attachment = new ResearchAttachment();
attachment.setResearch(researches[i%researches.length]);
attachment.setName("attachment-file-name" + i);
attachment.setSize(123456789L+i);
attachment.setType(types[i%types.length]);
attachment.setDescription("description" + i);
attachment.setRegistUser(owner);
assertEquals(1, dao.insertAttachment(attachment));
assertEquals(i+1, attachment.getId());
}
}
@Test
public void test2GetAttachment() throws Exception {
for(int i=0; i < 10 ; i++) {
assertNotNull(dao.selectAttachment(i+1));
assertEquals(i+1, dao.selectAttachment(i+1).getId());
assertNotNull(dao.selectAttachment(i+1).getRegistNo());
assertEquals(researches[i%researches.length], dao.selectAttachment(i+1).getResearch());
assertEquals("attachment-file-name"+i, dao.selectAttachment(i+1).getName());
assertEquals(new Long(123456789+i), dao.selectAttachment(i+1).getSize());
assertEquals(types[i%types.length], dao.selectAttachment(i+1).getType());
assertEquals("description"+i, dao.selectAttachment(i+1).getDescription());
assertEquals(owner, dao.selectAttachment(i+1).getRegistUser());
assertNotNull(dao.selectAttachment(i+1).getRegistDate());
}
}
@Test
public void test3UpdateAttachment() throws Exception {
for(int i=0; i < 10 ; i++) {
ResearchAttachment attachment = new ResearchAttachment(i+1);
attachment.setName("attachment-file-name-modified" + i);
attachment.setSize(123456789L+(i+1));
attachment.setType(types[(i+1)%types.length]);
attachment.setDescription("description-modified" + i);
assertEquals(1, dao.updateAttachment(attachment));
assertEquals(i+1, dao.selectAttachment(i+1).getId());
assertNotNull(dao.selectAttachment(i+1).getRegistNo());
assertEquals(researches[i%researches.length], dao.selectAttachment(i+1).getResearch());
assertEquals("attachment-file-name-modified"+i, dao.selectAttachment(i+1).getName());
assertEquals(new Long(123456789+(i+1)), dao.selectAttachment(i+1).getSize());
assertEquals(types[(i+1)%types.length], dao.selectAttachment(i+1).getType());
assertEquals("description-modified"+i, dao.selectAttachment(i+1).getDescription());
assertEquals(owner, dao.selectAttachment(i+1).getRegistUser());
assertNotNull(dao.selectAttachment(i+1).getRegistDate());
}
}
@Test
public void test4GetAttachmentList() throws Exception {
Map<String, Object> params = new HashMap<String, Object>();
assertEquals(10, dao.selectAttachmentList(params).size());
params.put("keyword", "description-modified");
assertEquals(10, dao.selectAttachmentList(params).size());
params.put("keyword", "description-modified5");
assertEquals(1, dao.selectAttachmentList(params).size());
params.put("fields", new String[] {"description"});
assertEquals(1, dao.selectAttachmentList(params).size());
params.put("fields", new String[] {"registNo"});
assertEquals(0, dao.selectAttachmentList(params).size());
params.put("fields", new String[] {"registNo", "description"});
assertEquals(1, dao.selectAttachmentList(params).size());
params = new HashMap<String, Object>();
params.put("fileType", types[0]);
assertEquals(2, dao.selectAttachmentList(params).size());
assertEquals(4, dao.selectAttachmentList(researches[0]).size());
params = new HashMap<String, Object>();
params.put("firstIndex", 0);
params.put("rowSize", 5);
assertEquals(5, dao.selectAttachmentList(params).size());
params.put("registFrom", "2019-08-27");
params.put("registTo", "2019-08-27");
assertEquals(5, dao.selectAttachmentList(params).size());
params.put("registUser", owner);
assertEquals(5, dao.selectAttachmentList(params).size());
}
@Test
public void test5GetAttachmentCount() throws Exception {
Map<String, Object> params = new HashMap<String, Object>();
assertEquals(10, dao.selectAttachmentCount(params));
params.put("keyword", "description-modified");
assertEquals(10, dao.selectAttachmentCount(params));
params.put("keyword", "description-modified5");
assertEquals(1, dao.selectAttachmentCount(params));
params.put("fields", new String[] {"description"});
assertEquals(1, dao.selectAttachmentCount(params));
params.put("fields", new String[] {"registNo"});
assertEquals(0, dao.selectAttachmentCount(params));
params.put("fields", new String[] {"registNo", "description"});
assertEquals(1, dao.selectAttachmentCount(params));
params = new HashMap<String, Object>();
params.put("fileType", types[0]);
assertEquals(2, dao.selectAttachmentCount(params));
assertEquals(4, dao.selectAttachmentCount(researches[0]));
params = new HashMap<String, Object>();
params.put("registFrom", "2019-08-27");
params.put("registTo", "2019-08-27");
assertEquals(10, dao.selectAttachmentCount(params));
params.put("registUser", owner);
assertEquals(10, dao.selectAttachmentCount(params));
}
@Test
public void test6DeleteAttachment() throws Exception {
assertEquals(1, dao.deleteAttachment(new ResearchAttachment(1)));
assertEquals(1, dao.deleteAttachment(new ResearchAttachment(2)));
assertEquals(1, dao.deleteAttachment(new ResearchAttachment(3)));
assertEquals(3, dao.deleteAttachment(researches[0]));
assertEquals(2, dao.deleteAttachment(researches[1]));
assertEquals(2, dao.deleteAttachment(researches[2]));
}
}
| UTF-8 | Java | 7,003 | java | TestResearchAttachmentDAO.java | Java | [
{
"context": "etup() {\n\t\towner = new User();\n\t\towner.setUserId(\"administrator\");\n\t\t\n\t\tresearches = new Research[3];\n\t\tresearche",
"end": 1223,
"score": 0.7107357978820801,
"start": 1210,
"tag": "USERNAME",
"value": "administrator"
}
] | null | [] | package unitTest.dao;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.insilicogen.gdkm.dao.ResearchAttachmentDAO;
import com.insilicogen.gdkm.model.Research;
import com.insilicogen.gdkm.model.ResearchAttachment;
import com.insilicogen.gdkm.model.User;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath:/egovframework/spring/context-*.xml"})
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestResearchAttachmentDAO {
@Resource(name="ResearchAttachmentDAO")
ResearchAttachmentDAO dao;
private User owner;
private String[] types = new String[] {
"type1", "type2", "type3", "other"
};
private Research[] researches;
@Before
public void setup() {
owner = new User();
owner.setUserId("administrator");
researches = new Research[3];
researches[0] = new Research(1);
researches[0].setRegistNo("GDKM-R-0001");
researches[1] = new Research(2);
researches[1].setRegistNo("GDKM-R-0002");
researches[2] = new Research(3);
researches[2].setRegistNo("GDKM-R-0003");
}
@Test
public void test1InsertAttachment() throws Exception {
for(int i=0; i < 10 ; i++) {
ResearchAttachment attachment = new ResearchAttachment();
attachment.setResearch(researches[i%researches.length]);
attachment.setName("attachment-file-name" + i);
attachment.setSize(123456789L+i);
attachment.setType(types[i%types.length]);
attachment.setDescription("description" + i);
attachment.setRegistUser(owner);
assertEquals(1, dao.insertAttachment(attachment));
assertEquals(i+1, attachment.getId());
}
}
@Test
public void test2GetAttachment() throws Exception {
for(int i=0; i < 10 ; i++) {
assertNotNull(dao.selectAttachment(i+1));
assertEquals(i+1, dao.selectAttachment(i+1).getId());
assertNotNull(dao.selectAttachment(i+1).getRegistNo());
assertEquals(researches[i%researches.length], dao.selectAttachment(i+1).getResearch());
assertEquals("attachment-file-name"+i, dao.selectAttachment(i+1).getName());
assertEquals(new Long(123456789+i), dao.selectAttachment(i+1).getSize());
assertEquals(types[i%types.length], dao.selectAttachment(i+1).getType());
assertEquals("description"+i, dao.selectAttachment(i+1).getDescription());
assertEquals(owner, dao.selectAttachment(i+1).getRegistUser());
assertNotNull(dao.selectAttachment(i+1).getRegistDate());
}
}
@Test
public void test3UpdateAttachment() throws Exception {
for(int i=0; i < 10 ; i++) {
ResearchAttachment attachment = new ResearchAttachment(i+1);
attachment.setName("attachment-file-name-modified" + i);
attachment.setSize(123456789L+(i+1));
attachment.setType(types[(i+1)%types.length]);
attachment.setDescription("description-modified" + i);
assertEquals(1, dao.updateAttachment(attachment));
assertEquals(i+1, dao.selectAttachment(i+1).getId());
assertNotNull(dao.selectAttachment(i+1).getRegistNo());
assertEquals(researches[i%researches.length], dao.selectAttachment(i+1).getResearch());
assertEquals("attachment-file-name-modified"+i, dao.selectAttachment(i+1).getName());
assertEquals(new Long(123456789+(i+1)), dao.selectAttachment(i+1).getSize());
assertEquals(types[(i+1)%types.length], dao.selectAttachment(i+1).getType());
assertEquals("description-modified"+i, dao.selectAttachment(i+1).getDescription());
assertEquals(owner, dao.selectAttachment(i+1).getRegistUser());
assertNotNull(dao.selectAttachment(i+1).getRegistDate());
}
}
@Test
public void test4GetAttachmentList() throws Exception {
Map<String, Object> params = new HashMap<String, Object>();
assertEquals(10, dao.selectAttachmentList(params).size());
params.put("keyword", "description-modified");
assertEquals(10, dao.selectAttachmentList(params).size());
params.put("keyword", "description-modified5");
assertEquals(1, dao.selectAttachmentList(params).size());
params.put("fields", new String[] {"description"});
assertEquals(1, dao.selectAttachmentList(params).size());
params.put("fields", new String[] {"registNo"});
assertEquals(0, dao.selectAttachmentList(params).size());
params.put("fields", new String[] {"registNo", "description"});
assertEquals(1, dao.selectAttachmentList(params).size());
params = new HashMap<String, Object>();
params.put("fileType", types[0]);
assertEquals(2, dao.selectAttachmentList(params).size());
assertEquals(4, dao.selectAttachmentList(researches[0]).size());
params = new HashMap<String, Object>();
params.put("firstIndex", 0);
params.put("rowSize", 5);
assertEquals(5, dao.selectAttachmentList(params).size());
params.put("registFrom", "2019-08-27");
params.put("registTo", "2019-08-27");
assertEquals(5, dao.selectAttachmentList(params).size());
params.put("registUser", owner);
assertEquals(5, dao.selectAttachmentList(params).size());
}
@Test
public void test5GetAttachmentCount() throws Exception {
Map<String, Object> params = new HashMap<String, Object>();
assertEquals(10, dao.selectAttachmentCount(params));
params.put("keyword", "description-modified");
assertEquals(10, dao.selectAttachmentCount(params));
params.put("keyword", "description-modified5");
assertEquals(1, dao.selectAttachmentCount(params));
params.put("fields", new String[] {"description"});
assertEquals(1, dao.selectAttachmentCount(params));
params.put("fields", new String[] {"registNo"});
assertEquals(0, dao.selectAttachmentCount(params));
params.put("fields", new String[] {"registNo", "description"});
assertEquals(1, dao.selectAttachmentCount(params));
params = new HashMap<String, Object>();
params.put("fileType", types[0]);
assertEquals(2, dao.selectAttachmentCount(params));
assertEquals(4, dao.selectAttachmentCount(researches[0]));
params = new HashMap<String, Object>();
params.put("registFrom", "2019-08-27");
params.put("registTo", "2019-08-27");
assertEquals(10, dao.selectAttachmentCount(params));
params.put("registUser", owner);
assertEquals(10, dao.selectAttachmentCount(params));
}
@Test
public void test6DeleteAttachment() throws Exception {
assertEquals(1, dao.deleteAttachment(new ResearchAttachment(1)));
assertEquals(1, dao.deleteAttachment(new ResearchAttachment(2)));
assertEquals(1, dao.deleteAttachment(new ResearchAttachment(3)));
assertEquals(3, dao.deleteAttachment(researches[0]));
assertEquals(2, dao.deleteAttachment(researches[1]));
assertEquals(2, dao.deleteAttachment(researches[2]));
}
}
| 7,003 | 0.733686 | 0.706983 | 193 | 35.284973 | 25.584902 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.73057 | false | false | 9 |
5d7bdacc032c3813f7fd9c027dcb2867f1c11eeb | 8,040,178,828,486 | 69922a6a63720461ff6865579581b5d57e7b4d90 | /src/main/java/com/planeta/pfum/domain/Filiere.java | 6f74f740e127d8ef6b3f20f5605b13b27ebd6253 | [] | no_license | chbitar/PFUMLOT1 | https://github.com/chbitar/PFUMLOT1 | ffc1b4c78c2920ac9b77005d934b5a8abfebe4d7 | 8bee9447ff4cdbf9da87cf87272b3dedc42991f6 | refs/heads/main | 2023-01-30T05:39:36.188000 | 2020-11-11T21:59:41 | 2020-11-11T21:59:41 | 303,221,506 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.planeta.pfum.domain;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.planeta.pfum.domain.enumeration.Programme;
/**
* A Filiere.
*/
@Entity
@Table(name = "filiere")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Filiere implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "nomfiliere")
private String nomfiliere;
@Column(name = "responsable")
private String responsable;
@Column(name = "accreditaion")
private String accreditaion;
@Enumerated(EnumType.STRING)
@Column(name = "programme")
private Programme programme;
@OneToMany(mappedBy = "filiere")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<EtudiantsExecutif> etudiantsExecutifs = new HashSet<>();
@OneToMany(mappedBy = "filiere")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<EtudiantsLicence> etudiantsLicences = new HashSet<>();
@OneToMany(mappedBy = "filiere")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<EtudiantsMaster> etudiantsMasters = new HashSet<>();
@OneToMany(mappedBy = "filiere")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Module> modules = new HashSet<>();
@ManyToOne
@JsonIgnoreProperties("filieres")
private Etablissement etablissement;
@ManyToOne
@JsonIgnoreProperties("filieres")
private AnneeInscription anneeInscription;
@ManyToMany(mappedBy = "filiers")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@JsonIgnore
private Set<TableauDeBoard> boards = new HashSet<>();
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNomfiliere() {
return nomfiliere;
}
public Filiere nomfiliere(String nomfiliere) {
this.nomfiliere = nomfiliere;
return this;
}
public void setNomfiliere(String nomfiliere) {
this.nomfiliere = nomfiliere;
}
public String getResponsable() {
return responsable;
}
public Filiere responsable(String responsable) {
this.responsable = responsable;
return this;
}
public void setResponsable(String responsable) {
this.responsable = responsable;
}
public String getAccreditaion() {
return accreditaion;
}
public Filiere accreditaion(String accreditaion) {
this.accreditaion = accreditaion;
return this;
}
public void setAccreditaion(String accreditaion) {
this.accreditaion = accreditaion;
}
public Programme getProgramme() {
return programme;
}
public Filiere programme(Programme programme) {
this.programme = programme;
return this;
}
public void setProgramme(Programme programme) {
this.programme = programme;
}
public Set<EtudiantsExecutif> getEtudiantsExecutifs() {
return etudiantsExecutifs;
}
public Filiere etudiantsExecutifs(Set<EtudiantsExecutif> etudiantsExecutifs) {
this.etudiantsExecutifs = etudiantsExecutifs;
return this;
}
public Filiere addEtudiantsExecutif(EtudiantsExecutif etudiantsExecutif) {
this.etudiantsExecutifs.add(etudiantsExecutif);
etudiantsExecutif.setFiliere(this);
return this;
}
public Filiere removeEtudiantsExecutif(EtudiantsExecutif etudiantsExecutif) {
this.etudiantsExecutifs.remove(etudiantsExecutif);
etudiantsExecutif.setFiliere(null);
return this;
}
public void setEtudiantsExecutifs(Set<EtudiantsExecutif> etudiantsExecutifs) {
this.etudiantsExecutifs = etudiantsExecutifs;
}
public Set<EtudiantsLicence> getEtudiantsLicences() {
return etudiantsLicences;
}
public Filiere etudiantsLicences(Set<EtudiantsLicence> etudiantsLicences) {
this.etudiantsLicences = etudiantsLicences;
return this;
}
public Filiere addEtudiantsLicence(EtudiantsLicence etudiantsLicence) {
this.etudiantsLicences.add(etudiantsLicence);
etudiantsLicence.setFiliere(this);
return this;
}
public Filiere removeEtudiantsLicence(EtudiantsLicence etudiantsLicence) {
this.etudiantsLicences.remove(etudiantsLicence);
etudiantsLicence.setFiliere(null);
return this;
}
public void setEtudiantsLicences(Set<EtudiantsLicence> etudiantsLicences) {
this.etudiantsLicences = etudiantsLicences;
}
public Set<EtudiantsMaster> getEtudiantsMasters() {
return etudiantsMasters;
}
public Filiere etudiantsMasters(Set<EtudiantsMaster> etudiantsMasters) {
this.etudiantsMasters = etudiantsMasters;
return this;
}
public Filiere addEtudiantsMaster(EtudiantsMaster etudiantsMaster) {
this.etudiantsMasters.add(etudiantsMaster);
etudiantsMaster.setFiliere(this);
return this;
}
public Filiere removeEtudiantsMaster(EtudiantsMaster etudiantsMaster) {
this.etudiantsMasters.remove(etudiantsMaster);
etudiantsMaster.setFiliere(null);
return this;
}
public void setEtudiantsMasters(Set<EtudiantsMaster> etudiantsMasters) {
this.etudiantsMasters = etudiantsMasters;
}
public Set<Module> getModules() {
return modules;
}
public Filiere modules(Set<Module> modules) {
this.modules = modules;
return this;
}
public Filiere addModule(Module module) {
this.modules.add(module);
module.setFiliere(this);
return this;
}
public Filiere removeModule(Module module) {
this.modules.remove(module);
module.setFiliere(null);
return this;
}
public void setModules(Set<Module> modules) {
this.modules = modules;
}
public Etablissement getEtablissement() {
return etablissement;
}
public Filiere etablissement(Etablissement etablissement) {
this.etablissement = etablissement;
return this;
}
public void setEtablissement(Etablissement etablissement) {
this.etablissement = etablissement;
}
public AnneeInscription getAnneeInscription() {
return anneeInscription;
}
public Filiere anneeInscription(AnneeInscription anneeInscription) {
this.anneeInscription = anneeInscription;
return this;
}
public void setAnneeInscription(AnneeInscription anneeInscription) {
this.anneeInscription = anneeInscription;
}
public Set<TableauDeBoard> getBoards() {
return boards;
}
public Filiere boards(Set<TableauDeBoard> tableauDeBoards) {
this.boards = tableauDeBoards;
return this;
}
public Filiere addBoard(TableauDeBoard tableauDeBoard) {
this.boards.add(tableauDeBoard);
tableauDeBoard.getFiliers().add(this);
return this;
}
public Filiere removeBoard(TableauDeBoard tableauDeBoard) {
this.boards.remove(tableauDeBoard);
tableauDeBoard.getFiliers().remove(this);
return this;
}
public void setBoards(Set<TableauDeBoard> tableauDeBoards) {
this.boards = tableauDeBoards;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Filiere)) {
return false;
}
return id != null && id.equals(((Filiere) o).id);
}
@Override
public int hashCode() {
return 31;
}
@Override
public String toString() {
return "Filiere{" +
"id=" + getId() +
", nomfiliere='" + getNomfiliere() + "'" +
", responsable='" + getResponsable() + "'" +
", accreditaion='" + getAccreditaion() + "'" +
", programme='" + getProgramme() + "'" +
"}";
}
}
| UTF-8 | Java | 8,937 | java | Filiere.java | Java | [] | null | [] | package com.planeta.pfum.domain;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.planeta.pfum.domain.enumeration.Programme;
/**
* A Filiere.
*/
@Entity
@Table(name = "filiere")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Filiere implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "nomfiliere")
private String nomfiliere;
@Column(name = "responsable")
private String responsable;
@Column(name = "accreditaion")
private String accreditaion;
@Enumerated(EnumType.STRING)
@Column(name = "programme")
private Programme programme;
@OneToMany(mappedBy = "filiere")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<EtudiantsExecutif> etudiantsExecutifs = new HashSet<>();
@OneToMany(mappedBy = "filiere")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<EtudiantsLicence> etudiantsLicences = new HashSet<>();
@OneToMany(mappedBy = "filiere")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<EtudiantsMaster> etudiantsMasters = new HashSet<>();
@OneToMany(mappedBy = "filiere")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Module> modules = new HashSet<>();
@ManyToOne
@JsonIgnoreProperties("filieres")
private Etablissement etablissement;
@ManyToOne
@JsonIgnoreProperties("filieres")
private AnneeInscription anneeInscription;
@ManyToMany(mappedBy = "filiers")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@JsonIgnore
private Set<TableauDeBoard> boards = new HashSet<>();
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNomfiliere() {
return nomfiliere;
}
public Filiere nomfiliere(String nomfiliere) {
this.nomfiliere = nomfiliere;
return this;
}
public void setNomfiliere(String nomfiliere) {
this.nomfiliere = nomfiliere;
}
public String getResponsable() {
return responsable;
}
public Filiere responsable(String responsable) {
this.responsable = responsable;
return this;
}
public void setResponsable(String responsable) {
this.responsable = responsable;
}
public String getAccreditaion() {
return accreditaion;
}
public Filiere accreditaion(String accreditaion) {
this.accreditaion = accreditaion;
return this;
}
public void setAccreditaion(String accreditaion) {
this.accreditaion = accreditaion;
}
public Programme getProgramme() {
return programme;
}
public Filiere programme(Programme programme) {
this.programme = programme;
return this;
}
public void setProgramme(Programme programme) {
this.programme = programme;
}
public Set<EtudiantsExecutif> getEtudiantsExecutifs() {
return etudiantsExecutifs;
}
public Filiere etudiantsExecutifs(Set<EtudiantsExecutif> etudiantsExecutifs) {
this.etudiantsExecutifs = etudiantsExecutifs;
return this;
}
public Filiere addEtudiantsExecutif(EtudiantsExecutif etudiantsExecutif) {
this.etudiantsExecutifs.add(etudiantsExecutif);
etudiantsExecutif.setFiliere(this);
return this;
}
public Filiere removeEtudiantsExecutif(EtudiantsExecutif etudiantsExecutif) {
this.etudiantsExecutifs.remove(etudiantsExecutif);
etudiantsExecutif.setFiliere(null);
return this;
}
public void setEtudiantsExecutifs(Set<EtudiantsExecutif> etudiantsExecutifs) {
this.etudiantsExecutifs = etudiantsExecutifs;
}
public Set<EtudiantsLicence> getEtudiantsLicences() {
return etudiantsLicences;
}
public Filiere etudiantsLicences(Set<EtudiantsLicence> etudiantsLicences) {
this.etudiantsLicences = etudiantsLicences;
return this;
}
public Filiere addEtudiantsLicence(EtudiantsLicence etudiantsLicence) {
this.etudiantsLicences.add(etudiantsLicence);
etudiantsLicence.setFiliere(this);
return this;
}
public Filiere removeEtudiantsLicence(EtudiantsLicence etudiantsLicence) {
this.etudiantsLicences.remove(etudiantsLicence);
etudiantsLicence.setFiliere(null);
return this;
}
public void setEtudiantsLicences(Set<EtudiantsLicence> etudiantsLicences) {
this.etudiantsLicences = etudiantsLicences;
}
public Set<EtudiantsMaster> getEtudiantsMasters() {
return etudiantsMasters;
}
public Filiere etudiantsMasters(Set<EtudiantsMaster> etudiantsMasters) {
this.etudiantsMasters = etudiantsMasters;
return this;
}
public Filiere addEtudiantsMaster(EtudiantsMaster etudiantsMaster) {
this.etudiantsMasters.add(etudiantsMaster);
etudiantsMaster.setFiliere(this);
return this;
}
public Filiere removeEtudiantsMaster(EtudiantsMaster etudiantsMaster) {
this.etudiantsMasters.remove(etudiantsMaster);
etudiantsMaster.setFiliere(null);
return this;
}
public void setEtudiantsMasters(Set<EtudiantsMaster> etudiantsMasters) {
this.etudiantsMasters = etudiantsMasters;
}
public Set<Module> getModules() {
return modules;
}
public Filiere modules(Set<Module> modules) {
this.modules = modules;
return this;
}
public Filiere addModule(Module module) {
this.modules.add(module);
module.setFiliere(this);
return this;
}
public Filiere removeModule(Module module) {
this.modules.remove(module);
module.setFiliere(null);
return this;
}
public void setModules(Set<Module> modules) {
this.modules = modules;
}
public Etablissement getEtablissement() {
return etablissement;
}
public Filiere etablissement(Etablissement etablissement) {
this.etablissement = etablissement;
return this;
}
public void setEtablissement(Etablissement etablissement) {
this.etablissement = etablissement;
}
public AnneeInscription getAnneeInscription() {
return anneeInscription;
}
public Filiere anneeInscription(AnneeInscription anneeInscription) {
this.anneeInscription = anneeInscription;
return this;
}
public void setAnneeInscription(AnneeInscription anneeInscription) {
this.anneeInscription = anneeInscription;
}
public Set<TableauDeBoard> getBoards() {
return boards;
}
public Filiere boards(Set<TableauDeBoard> tableauDeBoards) {
this.boards = tableauDeBoards;
return this;
}
public Filiere addBoard(TableauDeBoard tableauDeBoard) {
this.boards.add(tableauDeBoard);
tableauDeBoard.getFiliers().add(this);
return this;
}
public Filiere removeBoard(TableauDeBoard tableauDeBoard) {
this.boards.remove(tableauDeBoard);
tableauDeBoard.getFiliers().remove(this);
return this;
}
public void setBoards(Set<TableauDeBoard> tableauDeBoards) {
this.boards = tableauDeBoards;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Filiere)) {
return false;
}
return id != null && id.equals(((Filiere) o).id);
}
@Override
public int hashCode() {
return 31;
}
@Override
public String toString() {
return "Filiere{" +
"id=" + getId() +
", nomfiliere='" + getNomfiliere() + "'" +
", responsable='" + getResponsable() + "'" +
", accreditaion='" + getAccreditaion() + "'" +
", programme='" + getProgramme() + "'" +
"}";
}
}
| 8,937 | 0.681437 | 0.681101 | 320 | 26.928125 | 23.815001 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 9 |
a8bece41a2a0deadd41c507bbe2979d2d37ab066 | 31,447,750,551,013 | 0c5e0a58e2805bd8d21ac39347845e9acdad6338 | /librarymanagement/src/main/java/com/nagarro/librarymanagement/entities/UserData.java | 989bb22048a39477839c2d3d6a1d30c22fc91346 | [] | no_license | kamini-shrivastava/SpringBoot | https://github.com/kamini-shrivastava/SpringBoot | 7729a89f5bbb885a83c2070430be456af86ed0c0 | 2748c4d1e0098a5f82edff73a2adc43b8490b08b | refs/heads/master | 2023-08-25T22:25:14.892000 | 2021-10-31T12:24:05 | 2021-10-31T12:24:05 | 422,576,072 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nagarro.librarymanagement.entities;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "userdata")
public class UserData {
@Id
String userid;
String password;
public String getUserId() {
return userid;
}
public void setUserId(String userid) {
this.userid = userid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "UserData [userid=" + userid + ", password=" + password + "]";
}
}
| UTF-8 | Java | 607 | java | UserData.java | Java | [
{
"context": "urn \"UserData [userid=\" + userid + \", password=\" + password + \"]\";\n\t}\n\n}\n",
"end": 593,
"score": 0.7846581935882568,
"start": 585,
"tag": "PASSWORD",
"value": "password"
}
] | null | [] | package com.nagarro.librarymanagement.entities;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "userdata")
public class UserData {
@Id
String userid;
String password;
public String getUserId() {
return userid;
}
public void setUserId(String userid) {
this.userid = userid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "UserData [userid=" + userid + ", password=" + <PASSWORD> + "]";
}
}
| 609 | 0.713344 | 0.713344 | 35 | 16.342857 | 17.025934 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.028571 | false | false | 9 |
003f1854ed8fecb2aab2f1e3805574f405c86477 | 755,914,246,539 | 4dca3f552a2b1df1857bb55b4b0708c3be43679c | /stack/src/test/java/com/bobocode/StackTest.java | 34f2a62e688d956b6ece13348a804df2beaef4ad | [] | no_license | bobocode-projects/tdd-exercises | https://github.com/bobocode-projects/tdd-exercises | b8a27f331872f06402e76741259ed2d6d202a437 | 729a0246807da5338073fe89865cd6546edf4885 | refs/heads/master | 2021-06-02T00:21:28.884000 | 2021-02-10T07:38:48 | 2021-02-10T07:38:48 | 108,302,933 | 11 | 13 | null | false | 2019-08-30T09:41:29 | 2017-10-25T17:31:15 | 2019-08-30T09:39:18 | 2019-08-30T09:41:28 | 84 | 3 | 5 | 6 | Java | false | false | package com.bobocode;
import org.junit.jupiter.api.Test;
public class StackTest {
}
| UTF-8 | Java | 86 | java | StackTest.java | Java | [] | null | [] | package com.bobocode;
import org.junit.jupiter.api.Test;
public class StackTest {
}
| 86 | 0.767442 | 0.767442 | 6 | 13.333333 | 13.585122 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 9 |
573ba4a95a989425ebcb65cf705198226ba2f698 | 6,081,673,707,364 | 33694540ae4a4094922d802e0ba8e74eb5071163 | /doc/hepterminal/src/com/hep/terminalhep/config/ActivityContext.java | 6514d90036dc10b2b727a2999db7295672e39cca | [] | no_license | fangzi11/FQYLibs | https://github.com/fangzi11/FQYLibs | aa01c46ad91da7d6abd71b40afe233a152a2b8de | ba3347a3365fd11c9a14414086304ec28f3dbe8d | refs/heads/master | 2021-01-25T08:37:24.469000 | 2015-09-12T06:46:37 | 2015-09-12T06:46:37 | 36,916,202 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hep.terminalhep.config;
import android.app.Application;
/**
*
* @ClassName: ActivityContext
* @Description: TODO
* @author zhangj
* @date 2015年4月28日
*/
public class ActivityContext extends Application {
private static ActivityContext Instance = null;
public static final ActivityContext getCurrent() {
return Instance;
}
@Override
public void onCreate() {
super.onCreate();
Instance = this;
}
@Override
public void onTerminate() {
super.onTerminate();
try {
this.exit();
} catch (Exception e) {
}
}
public void exit() {
ActivityManager.finishAll();
System.exit(0);
}
}
| UTF-8 | Java | 640 | java | ActivityContext.java | Java | [
{
"context": "me: ActivityContext\n* @Description: TODO\n* @author zhangj\n* @date 2015年4月28日\n */\npublic class ActivityConte",
"end": 147,
"score": 0.9994909763336182,
"start": 141,
"tag": "USERNAME",
"value": "zhangj"
}
] | null | [] |
package com.hep.terminalhep.config;
import android.app.Application;
/**
*
* @ClassName: ActivityContext
* @Description: TODO
* @author zhangj
* @date 2015年4月28日
*/
public class ActivityContext extends Application {
private static ActivityContext Instance = null;
public static final ActivityContext getCurrent() {
return Instance;
}
@Override
public void onCreate() {
super.onCreate();
Instance = this;
}
@Override
public void onTerminate() {
super.onTerminate();
try {
this.exit();
} catch (Exception e) {
}
}
public void exit() {
ActivityManager.finishAll();
System.exit(0);
}
}
| 640 | 0.682965 | 0.670347 | 39 | 15.205129 | 14.592199 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.307692 | false | false | 9 |
23277db6b8234d6131b24a8bd4dbf0a0ab4fff18 | 22,308,060,136,370 | 3c43ca05f4a3104b73a4c8d17d12535007f71d10 | /core/src/main/java/com/srhub/dicecup/core/Group.java | adbd980a1653df1e579e748435a999dfd8c4626c | [] | no_license | srhub/dicecup | https://github.com/srhub/dicecup | c4d54f6c549ed131e36615b4816e7402a22169a4 | 3583709d405ae948a80c8044484ab3df2c7dee07 | refs/heads/master | 2021-01-01T19:50:34.119000 | 2012-11-21T14:57:47 | 2012-11-21T14:57:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2012 Oliver Schrenk
*
* 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.srhub.dicecup.core;
import java.util.Arrays;
import com.srhub.dicecup.api.Dice;
import com.srhub.dicecup.api.Feature;
/**
* A group of dice.
*
* @author Oliver Schrenk <oliver.schrenk@gmail.com>
*/
public class Group {
/** The id. */
private final String id;
/** The dice. */
private final Dice dice;
/** The features. */
private final Feature[] features;
/**
* Instantiates a new group.
*
* @param id
* the id
* @param dice
* the dice
* @param features
* the features
*/
Group(final String id, final Dice dice, final Feature[] features) {
this.id = id;
this.dice = dice;
this.features = features;
}
/**
* Gets the id.
*
* @return the id
*/
public String getId() {
return id;
}
/**
* Gets the dice.
*
* @return the dice
*/
public Dice getDice() {
return dice;
}
/**
* Gets the features.
*
* @return the features
*/
public Feature[] getFeatures() {
return features;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dice == null) ? 0 : dice.hashCode());
result = prime * result + Arrays.hashCode(features);
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Group other = (Group) obj;
if (dice == null) {
if (other.dice != null) {
return false;
}
} else if (!dice.equals(other.dice)) {
return false;
}
if (!Arrays.equals(features, other.features)) {
return false;
}
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Group ["
+ (id != null ? "id=" + id + ", " : "")
+ (dice != null ? "dice=" + dice + ", " : "")
+ (features != null ? "features=" + Arrays.toString(features)
: "") + "]";
}
}
| UTF-8 | Java | 2,707 | java | Group.java | Java | [
{
"context": "/*\n * Copyright 2012 Oliver Schrenk\n *\n * Licensed under the Apache License, Version ",
"end": 35,
"score": 0.999786376953125,
"start": 21,
"tag": "NAME",
"value": "Oliver Schrenk"
},
{
"context": "pi.Feature;\n\n/**\n * A group of dice.\n *\n * @author Oliver Schrenk <oliver.schrenk@gmail.com>\n */\npublic class Group",
"end": 779,
"score": 0.9997475743293762,
"start": 765,
"tag": "NAME",
"value": "Oliver Schrenk"
},
{
"context": " * A group of dice.\n *\n * @author Oliver Schrenk <oliver.schrenk@gmail.com>\n */\npublic class Group {\n\n\t/** The id. */\n\tpriva",
"end": 805,
"score": 0.9999319911003113,
"start": 781,
"tag": "EMAIL",
"value": "oliver.schrenk@gmail.com"
}
] | null | [] | /*
* Copyright 2012 <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 com.srhub.dicecup.core;
import java.util.Arrays;
import com.srhub.dicecup.api.Dice;
import com.srhub.dicecup.api.Feature;
/**
* A group of dice.
*
* @author <NAME> <<EMAIL>>
*/
public class Group {
/** The id. */
private final String id;
/** The dice. */
private final Dice dice;
/** The features. */
private final Feature[] features;
/**
* Instantiates a new group.
*
* @param id
* the id
* @param dice
* the dice
* @param features
* the features
*/
Group(final String id, final Dice dice, final Feature[] features) {
this.id = id;
this.dice = dice;
this.features = features;
}
/**
* Gets the id.
*
* @return the id
*/
public String getId() {
return id;
}
/**
* Gets the dice.
*
* @return the dice
*/
public Dice getDice() {
return dice;
}
/**
* Gets the features.
*
* @return the features
*/
public Feature[] getFeatures() {
return features;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dice == null) ? 0 : dice.hashCode());
result = prime * result + Arrays.hashCode(features);
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Group other = (Group) obj;
if (dice == null) {
if (other.dice != null) {
return false;
}
} else if (!dice.equals(other.dice)) {
return false;
}
if (!Arrays.equals(features, other.features)) {
return false;
}
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Group ["
+ (id != null ? "id=" + id + ", " : "")
+ (dice != null ? "dice=" + dice + ", " : "")
+ (features != null ? "features=" + Arrays.toString(features)
: "") + "]";
}
}
| 2,674 | 0.606576 | 0.601773 | 133 | 19.353384 | 19.155163 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.518797 | false | false | 9 |
cbd281d661b5973e2e43d381212b6644ad725148 | 24,807,731,161,308 | 087bf328663b3c8fb8c42b91e0b7dfbffcfb1d2c | /TriviaCore/src/main/java/com/trivia/core/service/QuestionService.java | 06a3d3722641e633afd0ca6cbe4e996a48b4f838 | [
"MIT"
] | permissive | Internecivus/TriviaServer | https://github.com/Internecivus/TriviaServer | c743d3666d59716b6c3d9014ae6ed536d349a161 | 15dd8e3864ec55100a1880c9d496f10bf8f53f7e | refs/heads/master | 2020-03-18T10:33:43.650000 | 2018-06-08T12:57:06 | 2018-06-08T12:57:06 | 134,619,676 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.trivia.core.service;
import com.trivia.core.exception.InvalidInputException;
import com.trivia.core.utility.Generator;
import com.trivia.core.utility.ImageUtil;
import com.trivia.persistence.dto.client.ImageData;
import com.trivia.persistence.dto.client.QuestionClient;
import com.trivia.persistence.entity.*;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import org.slf4j.Logger;
import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Root;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
// TODO: Lots of confusing trouble with imagePath...
@Stateless
@RolesAllowed(RoleType.Name.PRINCIPAL)
public class QuestionService extends Service<Question> {
@PersistenceContext(unitName = "TriviaDB")
private EntityManager em;
private @Inject UserService userService;
private @Inject Logger logger;
private @Resource SessionContext sessionContext;
private final static Integer PAGE_SIZE_RANDOM_DEFAULT = 10;
private final static Integer PAGE_SIZE_RANDOM_MAX = 50;
public QuestionService() {
super.DEFAULT_SORT_COLUMN = Question_.dateCreated;
super.SEARCHABLE_COLUMNS = SORTABLE_COLUMNS = new HashSet<>(Arrays.asList(
Question_.id, Question_.answerFirst, Question_.question, Question_.dateLastModified,
Question_.answerSecond, Question_.answerThird, Question_.answerFourth,
Question_.answerCorrect, Question_.comment, Question_.dateCreated
));
}
@RolesAllowed(RoleType.Name.CLIENT)
public List<Question> getRandomFromCategory(int size, String category) {
if (category == null || category.trim().length() < 1) throw new InvalidInputException("No category specified.");
if (size == 0) size = PAGE_SIZE_RANDOM_DEFAULT;
if (size < 0) throw new InvalidInputException(String.format("Size must be a positive number (is %d).", size));
if (size > PAGE_SIZE_RANDOM_MAX) throw new InvalidInputException(String.format(
"Size is over the maximum allowed size of %d (is %d).", PAGE_SIZE_RANDOM_MAX, size));
List<Question> questions = new ArrayList<>();
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Question> query = builder.createQuery(Question.class);
Root<Question> root = query.from(Question.class);
query.select(root);
Join join = root.join(Question_.categories);
query.where(builder.equal(join.get(Category_.name), category));
TypedQuery<Question> typedQuery = em.createQuery(query);
int count = typedQuery.getResultList().size();
if (size > count) throw new InvalidInputException(String.format(
"Not enough questions matching category '%s' found (found only %d out of %d).", category, count, size));
// Would this be faster with RAND()?
int[] randomUniqueArray = Generator.generateRandomUniqueArray(size, count);
for (int i = 0; i < randomUniqueArray.length; i++) {
typedQuery.setFirstResult(randomUniqueArray[i]).setMaxResults(1);
questions.addAll(typedQuery.getResultList()); // This logic is unfortunate.
}
return questions;
}
@RolesAllowed({RoleType.Name.CONTRIBUTOR})
public void update(Question updatedQuestion, InputStream imageStream) {
Question oldQuestion = findById(updatedQuestion.getId());
ImageUtil.validateImagePath(oldQuestion.getImage(), updatedQuestion.getImage());
// There is already an image present, and since we are adding a new one we need to delete it.
if (oldQuestion.getImage() != null) {
ImageUtil.deleteImage(oldQuestion.getImage());
}
// Create and set the new image.
updatedQuestion.setImage(ImageUtil.saveImage(imageStream));
em.merge(updatedQuestion);
em.flush();
logger.info("Question id: {} was UPDATED by user: {}", updatedQuestion.getId(), sessionContext.getCallerPrincipal().getName());
}
@Override
@RolesAllowed({RoleType.Name.CONTRIBUTOR})
public Question update(Question updatedQuestion) {
Question oldQuestion = findById(updatedQuestion.getId());
ImageUtil.validateImagePath(oldQuestion.getImage(), updatedQuestion.getImage());
// The image was previously present and was just now removed.
if (updatedQuestion.getImage() == null && oldQuestion.getImage() != null) {
ImageUtil.deleteImage(oldQuestion.getImage());
}
em.merge(updatedQuestion);
em.flush();
logger.info("Question id: {} was UPDATED by user: {}", updatedQuestion.getId(), sessionContext.getCallerPrincipal().getName());
return updatedQuestion;
}
@Override
@RolesAllowed(RoleType.Name.MODERATOR)
public void deleteById(Object id) {
Question question = findById(id);
if (question.getImage() != null) {
ImageUtil.deleteImage(question.getImage());
}
em.remove(question);
em.flush();
logger.info("Question id: {} was DELETED by user: {}", id, sessionContext.getCallerPrincipal().getName());
}
@RolesAllowed(RoleType.Name.CONTRIBUTOR)
public Question create(Question newQuestion, InputStream imageStream) {
String imagePath = ImageUtil.saveImage(imageStream);
newQuestion.setImage(imagePath);
User user = userService.findByField(User_.name, sessionContext.getCallerPrincipal().getName());
newQuestion.setUser(user);
Question createdQuestion = super.create(newQuestion);
logger.info("Question id: {} was CREATED by user id: {}", newQuestion.getId(), sessionContext.getCallerPrincipal().getName());
return createdQuestion;
}
@Override
@RolesAllowed(RoleType.Name.CONTRIBUTOR)
public Question create(Question newQuestion) {
User user = userService.findByField(User_.name, sessionContext.getCallerPrincipal().getName());
newQuestion.setUser(user);
newQuestion.setImage(null);
Question createdQuestion = super.create(newQuestion);
logger.info("Question id: {} was CREATED by user id: {}", newQuestion.getId(), sessionContext.getCallerPrincipal().getName());
return createdQuestion;
}
@PermitAll
public List<QuestionClient> toDto(List<Question> questions) {
ModelMapper mapper = new ModelMapper();
List<QuestionClient> questionsDto = mapper.map(questions, new TypeToken<List<QuestionClient>>() {
}.getType());
for (int i = 0; i < questionsDto.size(); i++) {
String imagePath = new ArrayList<>(questions).get(i).getImage();
if (imagePath != null) {
questionsDto.get(i).setImageData(new ImageData(imagePath, ImageUtil.getDateCreated(imagePath)));
}
}
return questionsDto;
}
} | UTF-8 | Java | 7,419 | java | QuestionService.java | Java | [] | null | [] | package com.trivia.core.service;
import com.trivia.core.exception.InvalidInputException;
import com.trivia.core.utility.Generator;
import com.trivia.core.utility.ImageUtil;
import com.trivia.persistence.dto.client.ImageData;
import com.trivia.persistence.dto.client.QuestionClient;
import com.trivia.persistence.entity.*;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import org.slf4j.Logger;
import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Root;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
// TODO: Lots of confusing trouble with imagePath...
@Stateless
@RolesAllowed(RoleType.Name.PRINCIPAL)
public class QuestionService extends Service<Question> {
@PersistenceContext(unitName = "TriviaDB")
private EntityManager em;
private @Inject UserService userService;
private @Inject Logger logger;
private @Resource SessionContext sessionContext;
private final static Integer PAGE_SIZE_RANDOM_DEFAULT = 10;
private final static Integer PAGE_SIZE_RANDOM_MAX = 50;
public QuestionService() {
super.DEFAULT_SORT_COLUMN = Question_.dateCreated;
super.SEARCHABLE_COLUMNS = SORTABLE_COLUMNS = new HashSet<>(Arrays.asList(
Question_.id, Question_.answerFirst, Question_.question, Question_.dateLastModified,
Question_.answerSecond, Question_.answerThird, Question_.answerFourth,
Question_.answerCorrect, Question_.comment, Question_.dateCreated
));
}
@RolesAllowed(RoleType.Name.CLIENT)
public List<Question> getRandomFromCategory(int size, String category) {
if (category == null || category.trim().length() < 1) throw new InvalidInputException("No category specified.");
if (size == 0) size = PAGE_SIZE_RANDOM_DEFAULT;
if (size < 0) throw new InvalidInputException(String.format("Size must be a positive number (is %d).", size));
if (size > PAGE_SIZE_RANDOM_MAX) throw new InvalidInputException(String.format(
"Size is over the maximum allowed size of %d (is %d).", PAGE_SIZE_RANDOM_MAX, size));
List<Question> questions = new ArrayList<>();
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Question> query = builder.createQuery(Question.class);
Root<Question> root = query.from(Question.class);
query.select(root);
Join join = root.join(Question_.categories);
query.where(builder.equal(join.get(Category_.name), category));
TypedQuery<Question> typedQuery = em.createQuery(query);
int count = typedQuery.getResultList().size();
if (size > count) throw new InvalidInputException(String.format(
"Not enough questions matching category '%s' found (found only %d out of %d).", category, count, size));
// Would this be faster with RAND()?
int[] randomUniqueArray = Generator.generateRandomUniqueArray(size, count);
for (int i = 0; i < randomUniqueArray.length; i++) {
typedQuery.setFirstResult(randomUniqueArray[i]).setMaxResults(1);
questions.addAll(typedQuery.getResultList()); // This logic is unfortunate.
}
return questions;
}
@RolesAllowed({RoleType.Name.CONTRIBUTOR})
public void update(Question updatedQuestion, InputStream imageStream) {
Question oldQuestion = findById(updatedQuestion.getId());
ImageUtil.validateImagePath(oldQuestion.getImage(), updatedQuestion.getImage());
// There is already an image present, and since we are adding a new one we need to delete it.
if (oldQuestion.getImage() != null) {
ImageUtil.deleteImage(oldQuestion.getImage());
}
// Create and set the new image.
updatedQuestion.setImage(ImageUtil.saveImage(imageStream));
em.merge(updatedQuestion);
em.flush();
logger.info("Question id: {} was UPDATED by user: {}", updatedQuestion.getId(), sessionContext.getCallerPrincipal().getName());
}
@Override
@RolesAllowed({RoleType.Name.CONTRIBUTOR})
public Question update(Question updatedQuestion) {
Question oldQuestion = findById(updatedQuestion.getId());
ImageUtil.validateImagePath(oldQuestion.getImage(), updatedQuestion.getImage());
// The image was previously present and was just now removed.
if (updatedQuestion.getImage() == null && oldQuestion.getImage() != null) {
ImageUtil.deleteImage(oldQuestion.getImage());
}
em.merge(updatedQuestion);
em.flush();
logger.info("Question id: {} was UPDATED by user: {}", updatedQuestion.getId(), sessionContext.getCallerPrincipal().getName());
return updatedQuestion;
}
@Override
@RolesAllowed(RoleType.Name.MODERATOR)
public void deleteById(Object id) {
Question question = findById(id);
if (question.getImage() != null) {
ImageUtil.deleteImage(question.getImage());
}
em.remove(question);
em.flush();
logger.info("Question id: {} was DELETED by user: {}", id, sessionContext.getCallerPrincipal().getName());
}
@RolesAllowed(RoleType.Name.CONTRIBUTOR)
public Question create(Question newQuestion, InputStream imageStream) {
String imagePath = ImageUtil.saveImage(imageStream);
newQuestion.setImage(imagePath);
User user = userService.findByField(User_.name, sessionContext.getCallerPrincipal().getName());
newQuestion.setUser(user);
Question createdQuestion = super.create(newQuestion);
logger.info("Question id: {} was CREATED by user id: {}", newQuestion.getId(), sessionContext.getCallerPrincipal().getName());
return createdQuestion;
}
@Override
@RolesAllowed(RoleType.Name.CONTRIBUTOR)
public Question create(Question newQuestion) {
User user = userService.findByField(User_.name, sessionContext.getCallerPrincipal().getName());
newQuestion.setUser(user);
newQuestion.setImage(null);
Question createdQuestion = super.create(newQuestion);
logger.info("Question id: {} was CREATED by user id: {}", newQuestion.getId(), sessionContext.getCallerPrincipal().getName());
return createdQuestion;
}
@PermitAll
public List<QuestionClient> toDto(List<Question> questions) {
ModelMapper mapper = new ModelMapper();
List<QuestionClient> questionsDto = mapper.map(questions, new TypeToken<List<QuestionClient>>() {
}.getType());
for (int i = 0; i < questionsDto.size(); i++) {
String imagePath = new ArrayList<>(questions).get(i).getImage();
if (imagePath != null) {
questionsDto.get(i).setImageData(new ImageData(imagePath, ImageUtil.getDateCreated(imagePath)));
}
}
return questionsDto;
}
} | 7,419 | 0.694164 | 0.692681 | 176 | 41.159092 | 33.882614 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.761364 | false | false | 9 |
cf52dd388255188a3f0e068fc1f3b3c391856dad | 33,243,046,874,169 | afb3ed4144ec83b8c5908a8cb105f8bd9a0875fe | /SmartCityHub/src/bg/sofia/uni/fmi/mjt/smartcity/device/SmartTrafficLight.java | cebd1f1cf39e6303201eb095e8daf09b9e8ee237 | [] | no_license | msbaleva/Modern-Java-Technologies-FMI | https://github.com/msbaleva/Modern-Java-Technologies-FMI | dbdcc39062e51dfd19253f85c26c95e404d2a335 | 669d7be00d3f44f5b4c4960bfa50940170b85109 | refs/heads/main | 2023-01-03T09:22:14.965000 | 2020-10-28T12:11:04 | 2020-10-28T12:11:04 | 308,004,493 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bg.sofia.uni.fmi.mjt.smartcity.device;
import java.time.LocalDateTime;
import bg.sofia.uni.fmi.mjt.smartcity.enums.DeviceType;
public class SmartTrafficLight implements SmartDevice{
private String id;
private String name;
private double powerConsumption;
private LocalDateTime installationDateTime;
private DeviceType type;
private static int numberOfLights;
public SmartTrafficLight(String name, double powerConsumption, LocalDateTime installationDateTime) {
this.name=name;
this.powerConsumption=powerConsumption;
this.installationDateTime=installationDateTime;
type=DeviceType.TRAFFIC_LIGHT;
id=type.getShortName() + "-" + name + "-" + numberOfLights++;
}
/**
* Returns the ID of the device.
*/
public String getId() {
return id;
}
/**
* Returns the name of the device.
*/
public String getName() {
return name;
}
/**
* Returns the power consumption of the device.
* For example, a lamp may consume 1kW/hour.
*/
public double getPowerConsumption() {
return powerConsumption;
}
/**
* Returns the date and time of device installation.
* This is a time in the past when the device was 'physically' installed.
* It is not related to the time when the device is registered in the Hub.
*/
public LocalDateTime getInstallationDateTime() {
return installationDateTime;
}
/**
* Returns the type of the device.
*/
public DeviceType getType() {
return type;
}
public static int getNumberOfLights() {
return numberOfLights;
}
@Override
public boolean equals(Object obj) {
SmartTrafficLight other = (SmartTrafficLight) obj;
return id.equals(other.id);
}
}
| UTF-8 | Java | 1,769 | java | SmartTrafficLight.java | Java | [] | null | [] | package bg.sofia.uni.fmi.mjt.smartcity.device;
import java.time.LocalDateTime;
import bg.sofia.uni.fmi.mjt.smartcity.enums.DeviceType;
public class SmartTrafficLight implements SmartDevice{
private String id;
private String name;
private double powerConsumption;
private LocalDateTime installationDateTime;
private DeviceType type;
private static int numberOfLights;
public SmartTrafficLight(String name, double powerConsumption, LocalDateTime installationDateTime) {
this.name=name;
this.powerConsumption=powerConsumption;
this.installationDateTime=installationDateTime;
type=DeviceType.TRAFFIC_LIGHT;
id=type.getShortName() + "-" + name + "-" + numberOfLights++;
}
/**
* Returns the ID of the device.
*/
public String getId() {
return id;
}
/**
* Returns the name of the device.
*/
public String getName() {
return name;
}
/**
* Returns the power consumption of the device.
* For example, a lamp may consume 1kW/hour.
*/
public double getPowerConsumption() {
return powerConsumption;
}
/**
* Returns the date and time of device installation.
* This is a time in the past when the device was 'physically' installed.
* It is not related to the time when the device is registered in the Hub.
*/
public LocalDateTime getInstallationDateTime() {
return installationDateTime;
}
/**
* Returns the type of the device.
*/
public DeviceType getType() {
return type;
}
public static int getNumberOfLights() {
return numberOfLights;
}
@Override
public boolean equals(Object obj) {
SmartTrafficLight other = (SmartTrafficLight) obj;
return id.equals(other.id);
}
}
| 1,769 | 0.682306 | 0.681741 | 72 | 23.569445 | 22.563383 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.