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
unknown
revision_date
unknown
committer_date
unknown
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
unknown
gha_created_at
unknown
gha_updated_at
unknown
gha_pushed_at
unknown
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
fad8cc23ea1d4fdfe73fda7d6db052d44243892e
37,469,294,707,943
116ca15c6834dab1eb706203334d65abfdbcab74
/src/gui/ExitKontrolldialog.java
a47179610d70f8cfda637583a6d10a20bedfdd47
[]
no_license
felixkopf/tltv
https://github.com/felixkopf/tltv
00393b30d8f41bf1a007293916333bd5f8976c1d
fd6e67cb0aa9b11bd589ecb6d4e895c29d7c016f
refs/heads/master
"2018-12-20T17:35:29.831000"
"2018-12-06T19:58:07"
"2018-12-06T19:58:07"
144,627,951
0
0
null
false
"2018-12-06T19:58:08"
"2018-08-13T20:03:27"
"2018-12-05T13:50:37"
"2018-12-06T19:58:08"
62
0
0
0
Java
false
null
package gui; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; public class ExitKontrolldialog extends JDialog implements ActionListener { private static final long serialVersionUID = 1L; private TurnierverwaltungGUI parent; private ObserverFenster observerFenster; private JDialog backgroundDialog; public ExitKontrolldialog(TurnierverwaltungGUI parent, ObserverFenster of, JDialog backgroundDialog, String msg) { super(parent, "Achtung", true); this.parent = parent; this.observerFenster = of; this.backgroundDialog = backgroundDialog; JButton jaButton = new JButton("Ja"); jaButton.addActionListener(this); JButton neinButton = new JButton("Nein"); neinButton.addActionListener(this); this.setLayout(new FlowLayout()); this.add(new JLabel(msg)); this.add(neinButton); this.add(jaButton); this.getContentPane().setBackground(TurnierApp.warnColor); jaButton.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyChar() == KeyEvent.VK_ESCAPE) dispose(); else if (e.getKeyChar() == KeyEvent.VK_ENTER) onJa(); else if (e.getKeyCode() == 37) { neinButton.requestFocus(); } } }); neinButton.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyChar() == KeyEvent.VK_ESCAPE) dispose(); else if (e.getKeyChar() == KeyEvent.VK_ENTER) dispose(); else if (e.getKeyCode() == 39) { jaButton.requestFocus(); } } }); pack(); this.setResizable(false); this.setLocation(parent.getLocation().x + parent.getSize().width/2 - this.getSize().width/2, parent.getLocation().y + parent.getSize().height/2 - this.getSize().height/2); setVisible(true); } private void onJa() { parent.dispose(); observerFenster.dispose(); backgroundDialog.dispose(); } @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Ja")) { onJa(); } else if (e.getActionCommand().equals("Nein")) { dispose(); } } }
UTF-8
Java
2,326
java
ExitKontrolldialog.java
Java
[]
null
[]
package gui; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; public class ExitKontrolldialog extends JDialog implements ActionListener { private static final long serialVersionUID = 1L; private TurnierverwaltungGUI parent; private ObserverFenster observerFenster; private JDialog backgroundDialog; public ExitKontrolldialog(TurnierverwaltungGUI parent, ObserverFenster of, JDialog backgroundDialog, String msg) { super(parent, "Achtung", true); this.parent = parent; this.observerFenster = of; this.backgroundDialog = backgroundDialog; JButton jaButton = new JButton("Ja"); jaButton.addActionListener(this); JButton neinButton = new JButton("Nein"); neinButton.addActionListener(this); this.setLayout(new FlowLayout()); this.add(new JLabel(msg)); this.add(neinButton); this.add(jaButton); this.getContentPane().setBackground(TurnierApp.warnColor); jaButton.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyChar() == KeyEvent.VK_ESCAPE) dispose(); else if (e.getKeyChar() == KeyEvent.VK_ENTER) onJa(); else if (e.getKeyCode() == 37) { neinButton.requestFocus(); } } }); neinButton.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyChar() == KeyEvent.VK_ESCAPE) dispose(); else if (e.getKeyChar() == KeyEvent.VK_ENTER) dispose(); else if (e.getKeyCode() == 39) { jaButton.requestFocus(); } } }); pack(); this.setResizable(false); this.setLocation(parent.getLocation().x + parent.getSize().width/2 - this.getSize().width/2, parent.getLocation().y + parent.getSize().height/2 - this.getSize().height/2); setVisible(true); } private void onJa() { parent.dispose(); observerFenster.dispose(); backgroundDialog.dispose(); } @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Ja")) { onJa(); } else if (e.getActionCommand().equals("Nein")) { dispose(); } } }
2,326
0.675838
0.671969
87
24.735632
25.881897
173
false
false
0
0
0
0
0
0
2.448276
false
false
5
36c4e21b2d06c9123b169cda7dae83622a43c623
38,560,216,389,679
e88ba3282238a46e136e66328a1b610572ae531c
/app/src/main/java/com/dianjiake/android/base/BaseActivity.java
557408eaf8e57d7bd49c4fbef60357816a2732ab
[]
no_license
1210733518/sugartea-dev
https://github.com/1210733518/sugartea-dev
d3873b8ad37e775982bbbbe84edece3f4495709c
aa94f74212f9083347963d33d8637fef92e9728d
refs/heads/master
"2021-06-24T06:34:39.722000"
"2017-09-08T08:02:31"
"2017-09-08T08:02:31"
102,835,351
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dianjiake.android.base; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import com.dianjiake.android.service.InitPushService; import com.dianjiake.android.service.ReceivePushService; import com.igexin.sdk.PushManager; import butterknife.ButterKnife; import butterknife.Unbinder; /** * Created by lfs on 2017/5/11. */ public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity { private Unbinder unbinder; protected P presenter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(provideContentView()); unbinder = ButterKnife.bind(this); presenter = getPresenter(); if (presenter != null) { presenter.start(); } create(savedInstanceState); PushManager.getInstance().initialize(this.getApplicationContext(), InitPushService.class); PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), ReceivePushService.class); } @LayoutRes public abstract int provideContentView(); public abstract void create(@Nullable Bundle savedInstanceState); public abstract P getPresenter(); @Override protected void onDestroy() { if (presenter != null) { presenter.onDestroy(); } super.onDestroy(); unbinder.unbind(); } }
UTF-8
Java
1,541
java
BaseActivity.java
Java
[ { "context": "e;\nimport butterknife.Unbinder;\n\n/**\n * Created by lfs on 2017/5/11.\n */\n\npublic abstract class BaseActi", "end": 432, "score": 0.9995789527893066, "start": 429, "tag": "USERNAME", "value": "lfs" } ]
null
[]
package com.dianjiake.android.base; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import com.dianjiake.android.service.InitPushService; import com.dianjiake.android.service.ReceivePushService; import com.igexin.sdk.PushManager; import butterknife.ButterKnife; import butterknife.Unbinder; /** * Created by lfs on 2017/5/11. */ public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity { private Unbinder unbinder; protected P presenter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(provideContentView()); unbinder = ButterKnife.bind(this); presenter = getPresenter(); if (presenter != null) { presenter.start(); } create(savedInstanceState); PushManager.getInstance().initialize(this.getApplicationContext(), InitPushService.class); PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), ReceivePushService.class); } @LayoutRes public abstract int provideContentView(); public abstract void create(@Nullable Bundle savedInstanceState); public abstract P getPresenter(); @Override protected void onDestroy() { if (presenter != null) { presenter.onDestroy(); } super.onDestroy(); unbinder.unbind(); } }
1,541
0.715769
0.710578
52
28.634615
26.002239
116
false
false
0
0
0
0
0
0
0.538462
false
false
5
8c22f1296099fa120ec453dd137d22ad0b4494e2
39,256,001,085,939
3bc473de685b08b56bdf949b60ba6c9929aa8ac2
/src/main/java/kdjsystem/mllink/domain/UserSmsChargeMst.java
72ff057b6e83f7eaee35313f64da7b3e81cb826d
[]
no_license
Anhosik/restapi2
https://github.com/Anhosik/restapi2
ebed7b20cdaf80f7efd4cad55ad00d57af526722
47bff3f1c91733974ec7dcb22a57a28dc26b3094
refs/heads/master
"2023-03-01T18:01:16.057000"
"2021-02-02T11:19:07"
"2021-02-02T11:19:07"
335,262,979
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kdjsystem.mllink.domain; import kdjsystem.mllink.domain.composit_pk.SMSCharageDtl_ID; import kdjsystem.mllink.domain.composit_pk.UserId; import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; import javax.persistence.*; import javax.persistence.criteria.CriteriaBuilder; import java.util.ArrayList; import java.util.List; @Entity @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @Table(name = "user_smschargemst") public class UserSmsChargeMst { @EmbeddedId private UserId id; @Column(name = "smsaliase") private String smsaliase; @Column(name = "smsno") private String smsno; @Column(name = "smschgamt") private Integer smschgamt; @Column(name = "smsuseamt") private Integer smsuseamt; @Column(name = "smsbalance") private Integer smsbalance; @Column(name = "contprice") private Integer contprice; @Column(name = "serialno") private Integer serialno; @Column(name = "smsprice") private Integer smsprice; @Column(name = "lmsprice") private Integer lmsprice; }
UTF-8
Java
1,091
java
UserSmsChargeMst.java
Java
[]
null
[]
package kdjsystem.mllink.domain; import kdjsystem.mllink.domain.composit_pk.SMSCharageDtl_ID; import kdjsystem.mllink.domain.composit_pk.UserId; import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; import javax.persistence.*; import javax.persistence.criteria.CriteriaBuilder; import java.util.ArrayList; import java.util.List; @Entity @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @Table(name = "user_smschargemst") public class UserSmsChargeMst { @EmbeddedId private UserId id; @Column(name = "smsaliase") private String smsaliase; @Column(name = "smsno") private String smsno; @Column(name = "smschgamt") private Integer smschgamt; @Column(name = "smsuseamt") private Integer smsuseamt; @Column(name = "smsbalance") private Integer smsbalance; @Column(name = "contprice") private Integer contprice; @Column(name = "serialno") private Integer serialno; @Column(name = "smsprice") private Integer smsprice; @Column(name = "lmsprice") private Integer lmsprice; }
1,091
0.730522
0.730522
42
24.976191
14.539745
60
false
false
0
0
0
0
0
0
0.47619
false
false
5
e8aedb9c28565b3955ea3dea80ac2eeed494271b
2,336,462,213,195
5669a7567f0f53f8593ce1935d4ba2b46deeacb9
/src/com/changeme/ringbuffer/RingBufferTest.java
1e22d94ce25242a3297621b4afa123036304229f
[]
no_license
dudehook/RingBuffer
https://github.com/dudehook/RingBuffer
bf1cbeb8fff9c4f0a182b3a97c4bb83a62974df1
8895bbb170ffbcaaf0c16b42dc5f6769bbf047da
refs/heads/master
"2016-09-06T12:25:23.221000"
"2010-03-14T04:22:34"
"2010-03-14T04:22:34"
561,509
6
8
null
null
null
null
null
null
null
null
null
null
null
null
null
// // // // // package com.changeme.ringbuffer; import java.util.Iterator; import junit.framework.TestCase; public class RingBufferTest extends TestCase { public void testAddRemove() throws Exception { RingBuffer<Integer> buffer = new RingBuffer<Integer>(10, new RBDiscardPolicy<Integer>()); buffer.add(1); assertTrue(buffer.count() == 1); buffer.add(2); assertTrue(buffer.count() == 2); buffer.add(3); assertTrue(buffer.count() == 3); buffer.add(4); assertTrue(buffer.count() == 4); buffer.add(5); assertTrue(buffer.count() == 5); buffer.add(6); assertTrue(buffer.count() == 6); buffer.add(7); assertTrue(buffer.count() == 7); buffer.add(8); assertTrue(buffer.count() == 8); buffer.add(9); assertTrue(buffer.count() == 9); buffer.add(10); assertTrue(buffer.count() == 10); buffer.add(11); assertTrue(buffer.count() == 10); // buffer should contain 2-11 Integer remove = buffer.remove(); assertTrue(remove == 2); assertTrue(buffer.count() == 9); remove = buffer.remove(); assertTrue(remove == 3); assertTrue(buffer.count() == 8); remove = buffer.remove(); assertTrue(remove == 4); assertTrue(buffer.count() == 7); remove = buffer.remove(); assertTrue(remove == 5); assertTrue(buffer.count() == 6); remove = buffer.remove(); assertTrue(remove == 6); assertTrue(buffer.count() == 5); remove = buffer.remove(); assertTrue(remove == 7); assertTrue(buffer.count() == 4); remove = buffer.remove(); assertTrue(remove == 8); assertTrue(buffer.count() == 3); remove = buffer.remove(); assertTrue(remove == 9); assertTrue(buffer.count() == 2); remove = buffer.remove(); assertTrue(remove == 10); assertTrue(buffer.count() == 1); remove = buffer.remove(); assertTrue(remove == 11); assertTrue(buffer.count() == 0); assertTrue(buffer.isEmpty()); } public void testWrapping() throws Exception { RingBuffer<Integer> buffer = new RingBuffer<Integer>(10, new RBDiscardPolicy<Integer>()); for (int i = 0; i < 10; i++) { buffer.add(i); } assertTrue(buffer.count() == 10); assertTrue(buffer.tail() == 0); assertTrue(buffer.head() == 10); buffer.remove(); buffer.remove(); buffer.remove(); buffer.remove(); buffer.remove(); assertTrue(buffer.tail() == 5); assertTrue(buffer.head() == 10); assertTrue(buffer.count() == 5); buffer.add(666); buffer.add(666); buffer.add(666); assertTrue(buffer.tail() == 5); assertTrue(buffer.head() == 3); assertTrue(buffer.count() == 8); buffer.remove(); buffer.remove(); buffer.remove(); buffer.remove(); buffer.remove(); assertTrue(buffer.tail() == 0); assertTrue(buffer.head() == 3); assertTrue(buffer.count() == 3); assertTrue(buffer.remove() == 666); assertTrue(buffer.remove() == 666); assertTrue(buffer.remove() == 666); assertTrue(buffer.tail() == 3); assertTrue(buffer.head() == 3); assertTrue(buffer.isEmpty()); } public void testSimpleIteration() throws Exception { RingBuffer<Integer> buffer = setupBuffer(8); Iterator<Integer> iterator = buffer.iterator(); for (int i = 0; i < 8; i++) { assertTrue(iterator.hasNext()); assertTrue(iterator.next() == i); System.out.print("" + i + "... "); } System.out.println(); assertFalse(iterator.hasNext()); } public void testWrappingIteration() throws Exception { RingBuffer<Integer> buffer = setupBuffer(8); buffer.remove(); buffer.remove(); buffer.remove(); buffer.remove(); buffer.add(8); buffer.add(9); buffer.add(10); assertTrue(buffer.count() == 7); assertTrue(buffer.tail() == 4); assertTrue(buffer.head() == 3); Iterator<Integer> iterator = buffer.iterator(); for (int i = 0; i < 7; i++) { assertTrue(iterator.hasNext()); assertTrue(iterator.next() == i + 4); System.out.print("" + (i + 4) + "... "); } System.out.println(); assertFalse(iterator.hasNext()); buffer.add(11); assertTrue(buffer.count() == 8); assertTrue(buffer.tail() == 4); assertTrue(buffer.head() == 4); iterator = buffer.iterator(); for (int i = 0; i < 8; i++) { assertTrue(iterator.hasNext()); assertTrue(iterator.next() == i + 4); System.out.print("" + (i + 4) + "... "); } System.out.println(); assertFalse(iterator.hasNext()); } private RingBuffer<Integer> setupBuffer(int size) { RingBuffer<Integer> buffer = new RingBuffer<Integer>(size, new RBDiscardPolicy<Integer>()); for (int i = 0; i < size; i++) { buffer.add(i); } assertTrue(buffer.count() == size); assertTrue(buffer.tail() == 0); assertTrue(buffer.head() == size); return buffer; } public void testHasNext() throws Exception { RingBuffer<Integer> buffer = setupBuffer(10); Iterator<Integer> iterator = buffer.iterator(); assertTrue(iterator.hasNext()); for (int i = 0; i < 10; i++) { assertTrue(iterator.next() == i); if (i % 2 == 0) { assertTrue(iterator.hasNext()); } } assertFalse(iterator.hasNext()); } public void testAllIterations() throws Exception { RingBuffer<Integer> buffer = setupBuffer(10); Iterator<Integer> iterator = buffer.iterator(); // ** M1 ** iterator.next(); // 0 iterator.next(); // 1 iterator.next(); // 2 iterator.next(); // 3 iterator.next(); // 4 iterator.next(); // 5 iterator.next(); // 6 // iterator points at 7th element // now change the mode from M1 to M2L buffer.remove(); // 0 buffer.remove(); // 1 buffer.remove(); // 2 buffer.remove(); // 3 buffer.remove(); // 4 buffer.add(10); buffer.add(11); buffer.add(12); // Now M2R assertTrue(buffer.count() == 8); assertTrue(buffer.tail() == 5); assertTrue(buffer.head() == 3); assertTrue(iterator.hasNext()); assertTrue(iterator.next() == 7); assertTrue(iterator.next() == 8); assertTrue(iterator.next() == 9); // Now M2L assertTrue(iterator.next() == 10); assertTrue(iterator.next() == 11); assertTrue(iterator.next() == 12); // Now at the end assertFalse(iterator.hasNext()); // Adding to the end buffer.add(13); assertTrue(iterator.hasNext()); assertTrue(iterator.next() == 13); assertFalse(iterator.hasNext()); buffer.add(14); assertTrue(iterator.hasNext()); buffer.remove(); buffer.remove(); buffer.remove(); buffer.remove(); buffer.remove(); // M1 now, next is at index 4 buffer.remove(); assertTrue(buffer.count() == 4); assertTrue(buffer.tail() == 1); assertTrue(buffer.head() == 5); buffer.add(15); buffer.add(16); buffer.add(17); buffer.add(18); assertTrue(iterator.next() == 14); assertTrue(iterator.next() == 15); assertTrue(iterator.next() == 16); assertTrue(iterator.next() == 17); assertTrue(iterator.next() == 18); assertNull(iterator.next()); } public void testOverflowIteration() throws Exception { RingBuffer<Integer> buffer = setupBuffer(8); buffer.remove(); buffer.remove(); buffer.remove(); buffer.remove(); assertTrue(buffer.count() == 4); assertTrue(buffer.tail() == 4); assertTrue("head = " + buffer.head(), buffer.head() == 8); Iterator<Integer> iterator = buffer.iterator(); iterator.next(); iterator.next(); // next is now at slot 6 buffer.add(8); // 0 buffer.add(9); // 1 buffer.add(10); buffer.add(11); buffer.add(12); buffer.add(13); buffer.add(14); assertTrue(buffer.count() == 8); assertTrue(buffer.tail() == 7); assertTrue("head = " + buffer.head(), buffer.head() == 7); Integer next = iterator.next(); assertTrue("next = " + next, next == 14); } }
UTF-8
Java
9,088
java
RingBufferTest.java
Java
[]
null
[]
// // // // // package com.changeme.ringbuffer; import java.util.Iterator; import junit.framework.TestCase; public class RingBufferTest extends TestCase { public void testAddRemove() throws Exception { RingBuffer<Integer> buffer = new RingBuffer<Integer>(10, new RBDiscardPolicy<Integer>()); buffer.add(1); assertTrue(buffer.count() == 1); buffer.add(2); assertTrue(buffer.count() == 2); buffer.add(3); assertTrue(buffer.count() == 3); buffer.add(4); assertTrue(buffer.count() == 4); buffer.add(5); assertTrue(buffer.count() == 5); buffer.add(6); assertTrue(buffer.count() == 6); buffer.add(7); assertTrue(buffer.count() == 7); buffer.add(8); assertTrue(buffer.count() == 8); buffer.add(9); assertTrue(buffer.count() == 9); buffer.add(10); assertTrue(buffer.count() == 10); buffer.add(11); assertTrue(buffer.count() == 10); // buffer should contain 2-11 Integer remove = buffer.remove(); assertTrue(remove == 2); assertTrue(buffer.count() == 9); remove = buffer.remove(); assertTrue(remove == 3); assertTrue(buffer.count() == 8); remove = buffer.remove(); assertTrue(remove == 4); assertTrue(buffer.count() == 7); remove = buffer.remove(); assertTrue(remove == 5); assertTrue(buffer.count() == 6); remove = buffer.remove(); assertTrue(remove == 6); assertTrue(buffer.count() == 5); remove = buffer.remove(); assertTrue(remove == 7); assertTrue(buffer.count() == 4); remove = buffer.remove(); assertTrue(remove == 8); assertTrue(buffer.count() == 3); remove = buffer.remove(); assertTrue(remove == 9); assertTrue(buffer.count() == 2); remove = buffer.remove(); assertTrue(remove == 10); assertTrue(buffer.count() == 1); remove = buffer.remove(); assertTrue(remove == 11); assertTrue(buffer.count() == 0); assertTrue(buffer.isEmpty()); } public void testWrapping() throws Exception { RingBuffer<Integer> buffer = new RingBuffer<Integer>(10, new RBDiscardPolicy<Integer>()); for (int i = 0; i < 10; i++) { buffer.add(i); } assertTrue(buffer.count() == 10); assertTrue(buffer.tail() == 0); assertTrue(buffer.head() == 10); buffer.remove(); buffer.remove(); buffer.remove(); buffer.remove(); buffer.remove(); assertTrue(buffer.tail() == 5); assertTrue(buffer.head() == 10); assertTrue(buffer.count() == 5); buffer.add(666); buffer.add(666); buffer.add(666); assertTrue(buffer.tail() == 5); assertTrue(buffer.head() == 3); assertTrue(buffer.count() == 8); buffer.remove(); buffer.remove(); buffer.remove(); buffer.remove(); buffer.remove(); assertTrue(buffer.tail() == 0); assertTrue(buffer.head() == 3); assertTrue(buffer.count() == 3); assertTrue(buffer.remove() == 666); assertTrue(buffer.remove() == 666); assertTrue(buffer.remove() == 666); assertTrue(buffer.tail() == 3); assertTrue(buffer.head() == 3); assertTrue(buffer.isEmpty()); } public void testSimpleIteration() throws Exception { RingBuffer<Integer> buffer = setupBuffer(8); Iterator<Integer> iterator = buffer.iterator(); for (int i = 0; i < 8; i++) { assertTrue(iterator.hasNext()); assertTrue(iterator.next() == i); System.out.print("" + i + "... "); } System.out.println(); assertFalse(iterator.hasNext()); } public void testWrappingIteration() throws Exception { RingBuffer<Integer> buffer = setupBuffer(8); buffer.remove(); buffer.remove(); buffer.remove(); buffer.remove(); buffer.add(8); buffer.add(9); buffer.add(10); assertTrue(buffer.count() == 7); assertTrue(buffer.tail() == 4); assertTrue(buffer.head() == 3); Iterator<Integer> iterator = buffer.iterator(); for (int i = 0; i < 7; i++) { assertTrue(iterator.hasNext()); assertTrue(iterator.next() == i + 4); System.out.print("" + (i + 4) + "... "); } System.out.println(); assertFalse(iterator.hasNext()); buffer.add(11); assertTrue(buffer.count() == 8); assertTrue(buffer.tail() == 4); assertTrue(buffer.head() == 4); iterator = buffer.iterator(); for (int i = 0; i < 8; i++) { assertTrue(iterator.hasNext()); assertTrue(iterator.next() == i + 4); System.out.print("" + (i + 4) + "... "); } System.out.println(); assertFalse(iterator.hasNext()); } private RingBuffer<Integer> setupBuffer(int size) { RingBuffer<Integer> buffer = new RingBuffer<Integer>(size, new RBDiscardPolicy<Integer>()); for (int i = 0; i < size; i++) { buffer.add(i); } assertTrue(buffer.count() == size); assertTrue(buffer.tail() == 0); assertTrue(buffer.head() == size); return buffer; } public void testHasNext() throws Exception { RingBuffer<Integer> buffer = setupBuffer(10); Iterator<Integer> iterator = buffer.iterator(); assertTrue(iterator.hasNext()); for (int i = 0; i < 10; i++) { assertTrue(iterator.next() == i); if (i % 2 == 0) { assertTrue(iterator.hasNext()); } } assertFalse(iterator.hasNext()); } public void testAllIterations() throws Exception { RingBuffer<Integer> buffer = setupBuffer(10); Iterator<Integer> iterator = buffer.iterator(); // ** M1 ** iterator.next(); // 0 iterator.next(); // 1 iterator.next(); // 2 iterator.next(); // 3 iterator.next(); // 4 iterator.next(); // 5 iterator.next(); // 6 // iterator points at 7th element // now change the mode from M1 to M2L buffer.remove(); // 0 buffer.remove(); // 1 buffer.remove(); // 2 buffer.remove(); // 3 buffer.remove(); // 4 buffer.add(10); buffer.add(11); buffer.add(12); // Now M2R assertTrue(buffer.count() == 8); assertTrue(buffer.tail() == 5); assertTrue(buffer.head() == 3); assertTrue(iterator.hasNext()); assertTrue(iterator.next() == 7); assertTrue(iterator.next() == 8); assertTrue(iterator.next() == 9); // Now M2L assertTrue(iterator.next() == 10); assertTrue(iterator.next() == 11); assertTrue(iterator.next() == 12); // Now at the end assertFalse(iterator.hasNext()); // Adding to the end buffer.add(13); assertTrue(iterator.hasNext()); assertTrue(iterator.next() == 13); assertFalse(iterator.hasNext()); buffer.add(14); assertTrue(iterator.hasNext()); buffer.remove(); buffer.remove(); buffer.remove(); buffer.remove(); buffer.remove(); // M1 now, next is at index 4 buffer.remove(); assertTrue(buffer.count() == 4); assertTrue(buffer.tail() == 1); assertTrue(buffer.head() == 5); buffer.add(15); buffer.add(16); buffer.add(17); buffer.add(18); assertTrue(iterator.next() == 14); assertTrue(iterator.next() == 15); assertTrue(iterator.next() == 16); assertTrue(iterator.next() == 17); assertTrue(iterator.next() == 18); assertNull(iterator.next()); } public void testOverflowIteration() throws Exception { RingBuffer<Integer> buffer = setupBuffer(8); buffer.remove(); buffer.remove(); buffer.remove(); buffer.remove(); assertTrue(buffer.count() == 4); assertTrue(buffer.tail() == 4); assertTrue("head = " + buffer.head(), buffer.head() == 8); Iterator<Integer> iterator = buffer.iterator(); iterator.next(); iterator.next(); // next is now at slot 6 buffer.add(8); // 0 buffer.add(9); // 1 buffer.add(10); buffer.add(11); buffer.add(12); buffer.add(13); buffer.add(14); assertTrue(buffer.count() == 8); assertTrue(buffer.tail() == 7); assertTrue("head = " + buffer.head(), buffer.head() == 7); Integer next = iterator.next(); assertTrue("next = " + next, next == 14); } }
9,088
0.523988
0.50011
320
27.4
17.963923
99
false
false
0
0
0
0
0
0
0.721875
false
false
5
6ebdadd088089241f190ab2458e170969fdf9ecf
36,180,804,533,656
4c288a298771677036a8da57354d2213ef52872b
/shack-core/src/main/java/com/gaming/shack/core/resource/ShackJacksonObjectMapperProvider.java
4039101e99a398ac5a05173c1f828ce3b433dab0
[]
no_license
andybajaj/shack
https://github.com/andybajaj/shack
4e074f47c7941ffdd395282be996a8e65ddb7c41
7f1d1fbbf0639f9e2a65d11a2c6909db98dc660b
refs/heads/master
"2021-01-21T06:38:22.639000"
"2017-03-07T03:00:36"
"2017-03-07T03:00:36"
83,259,701
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * */ package com.gaming.shack.core.resource; import javax.ws.rs.ext.ContextResolver; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; // TODO: Auto-generated Javadoc /** * The Class ObjectMapperProvider. */ public class ShackJacksonObjectMapperProvider implements ContextResolver<ObjectMapper> { /** The default object mapper. */ final ObjectMapper defaultObjectMapper; /** * Instantiates a new object mapper provider. */ public ShackJacksonObjectMapperProvider() { defaultObjectMapper = createDefaultMapper(); } /* * (non-Javadoc) * * @see javax.ws.rs.ext.ContextResolver#getContext(java.lang.Class) */ @Override public ObjectMapper getContext(final Class<?> type) { return defaultObjectMapper; } /** * Creates the default mapper. * * @return the object mapper */ private static ObjectMapper createDefaultMapper() { final ObjectMapper result = new ObjectMapper(); result.setAnnotationIntrospector(new JacksonAnnotationIntrospector()); result.enable(SerializationFeature.INDENT_OUTPUT); result.setSerializationInclusion(JsonInclude.Include.NON_NULL); return result; } }
UTF-8
Java
1,334
java
ShackJacksonObjectMapperProvider.java
Java
[]
null
[]
/* * */ package com.gaming.shack.core.resource; import javax.ws.rs.ext.ContextResolver; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; // TODO: Auto-generated Javadoc /** * The Class ObjectMapperProvider. */ public class ShackJacksonObjectMapperProvider implements ContextResolver<ObjectMapper> { /** The default object mapper. */ final ObjectMapper defaultObjectMapper; /** * Instantiates a new object mapper provider. */ public ShackJacksonObjectMapperProvider() { defaultObjectMapper = createDefaultMapper(); } /* * (non-Javadoc) * * @see javax.ws.rs.ext.ContextResolver#getContext(java.lang.Class) */ @Override public ObjectMapper getContext(final Class<?> type) { return defaultObjectMapper; } /** * Creates the default mapper. * * @return the object mapper */ private static ObjectMapper createDefaultMapper() { final ObjectMapper result = new ObjectMapper(); result.setAnnotationIntrospector(new JacksonAnnotationIntrospector()); result.enable(SerializationFeature.INDENT_OUTPUT); result.setSerializationInclusion(JsonInclude.Include.NON_NULL); return result; } }
1,334
0.766867
0.766867
57
22.403509
25.290495
88
false
false
0
0
0
0
0
0
0.877193
false
false
5
96ecfa68f354c1c259c2a55cd4561c99c88e2508
11,553,462,084,883
2dd1a6811fa36b3d9ab90586a7fb633da04f93f8
/src/main/java/org/akhq/utils/AvroToJsonSerializer.java
3cf487b2983e8028925feb76ec284e6b3c054d9f
[ "Apache-2.0" ]
permissive
AnatomicJC/akhq
https://github.com/AnatomicJC/akhq
db5f010f6547c25535497f964c07c6d48dbdc460
008935c385554ae5e2e07427da5c5f347988bea0
refs/heads/dev
"2023-06-15T13:23:42.260000"
"2021-07-01T13:11:21"
"2021-07-01T13:11:21"
381,422,207
0
0
Apache-2.0
true
"2021-06-29T15:59:17"
"2021-06-29T15:59:16"
"2021-06-27T18:13:16"
"2021-06-22T16:19:20"
12,538
0
0
0
null
false
false
package org.akhq.utils; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.apache.avro.generic.GenericRecord; import java.io.IOException; import java.util.Map; import java.util.TimeZone; public class AvroToJsonSerializer { private static final ObjectMapper MAPPER = new ObjectMapper() .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .setSerializationInclusion(JsonInclude.Include.NON_EMPTY) .registerModule(new JavaTimeModule()) .registerModule(new Jdk8Module()) .setTimeZone(TimeZone.getDefault()); public static String toJson(GenericRecord record) throws IOException { Map<String, Object> map = AvroDeserializer.recordDeserializer(record); return MAPPER.writeValueAsString(map); } }
UTF-8
Java
1,082
java
AvroToJsonSerializer.java
Java
[]
null
[]
package org.akhq.utils; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.apache.avro.generic.GenericRecord; import java.io.IOException; import java.util.Map; import java.util.TimeZone; public class AvroToJsonSerializer { private static final ObjectMapper MAPPER = new ObjectMapper() .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .setSerializationInclusion(JsonInclude.Include.NON_EMPTY) .registerModule(new JavaTimeModule()) .registerModule(new Jdk8Module()) .setTimeZone(TimeZone.getDefault()); public static String toJson(GenericRecord record) throws IOException { Map<String, Object> map = AvroDeserializer.recordDeserializer(record); return MAPPER.writeValueAsString(map); } }
1,082
0.777264
0.771719
28
37.642857
25.683811
78
false
false
0
0
0
0
0
0
0.535714
false
false
5
7eb5cb9c0c07ee5b5d680d618dde032ec567b2e6
12,352,325,945,692
7d516051c88244a408032a37f57e48f600e2ea58
/edusoho_v3/src/main/java/com/edusoho/kuozhi/clean/module/classroom/review/ClassDiscussContract.java
f58d96fbbd74810fd888af40cc2f44b5ec4d5de2
[]
no_license
sdmengchen12580/tanggang
https://github.com/sdmengchen12580/tanggang
58b69cf7a413fb06595f4691951a2f0d742f704c
3bb7ab608c2485f41335bc667bce34ca7929135a
refs/heads/main
"2023-06-03T21:00:44.834000"
"2021-06-18T03:19:41"
"2021-06-18T03:19:41"
370,194,843
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.edusoho.kuozhi.clean.module.classroom.review; import com.edusoho.kuozhi.clean.module.base.BasePresenter; import com.edusoho.kuozhi.clean.module.base.BaseView; import com.edusoho.kuozhi.v3.entity.course.DiscussDetail; import java.util.List; /** * Created by DF on 2017/5/23. */ public interface ClassDiscussContract { interface View extends BaseView<Presenter>{ void initDiscuss(final DiscussDetail discussDetail); void setLoadViewVisibleible(int isVis); void setEmptyViewVis(int isVis); void showCompanies(DiscussDetail discussDetail); void setRecyclerViewStatus(int status); void setSwipeStatus(boolean status); void adapterRefresh(List<DiscussDetail.ResourcesBean> list); } interface Presenter extends BasePresenter{ void loadMore(int start); void refresh(); } }
UTF-8
Java
884
java
ClassDiscussContract.java
Java
[ { "context": "Detail;\n\nimport java.util.List;\n\n/**\n * Created by DF on 2017/5/23.\n */\n\npublic interface ClassDiscussC", "end": 275, "score": 0.9935150146484375, "start": 273, "tag": "USERNAME", "value": "DF" } ]
null
[]
package com.edusoho.kuozhi.clean.module.classroom.review; import com.edusoho.kuozhi.clean.module.base.BasePresenter; import com.edusoho.kuozhi.clean.module.base.BaseView; import com.edusoho.kuozhi.v3.entity.course.DiscussDetail; import java.util.List; /** * Created by DF on 2017/5/23. */ public interface ClassDiscussContract { interface View extends BaseView<Presenter>{ void initDiscuss(final DiscussDetail discussDetail); void setLoadViewVisibleible(int isVis); void setEmptyViewVis(int isVis); void showCompanies(DiscussDetail discussDetail); void setRecyclerViewStatus(int status); void setSwipeStatus(boolean status); void adapterRefresh(List<DiscussDetail.ResourcesBean> list); } interface Presenter extends BasePresenter{ void loadMore(int start); void refresh(); } }
884
0.722851
0.713801
40
21.1
24.027901
68
false
false
0
0
0
0
0
0
0.35
false
false
5
e6dbb5e097c112c7030b489e4fcb3edf7a5c5add
33,767,032,929,446
b6950c84a66a6fc1d7d88bd48ff48b0e651d896e
/src/medrex/client/census/countAudit/PanelCountAuditFloors.java
7016887fe285c9d77be7bf7274fc1b080cbc5ea0
[]
no_license
technolabshq/medrex
https://github.com/technolabshq/medrex
e80f147ba7ee60003b6c04fe8bc8c9c1499d3a0b
ed5a7f7643da6c72c64a24f31dae128fd1ea063b
refs/heads/master
"2021-01-21T12:58:18.186000"
"2017-05-20T05:30:27"
"2017-05-20T05:30:27"
91,803,960
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package medrex.client.census.countAudit; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.border.LineBorder; import medrex.client.constants.Global; import medrex.client.utils.controls.ChooseResidentList; import medrex.commons.enums.GuiModes; import com.sX.swing.JxButton; public class PanelCountAuditFloors extends JPanel { private JPanel countAuditControls; private ChooseResidentList lstFloors; private JxButton btnHistory; private JLabel lblChooseFloor; private static final long serialVersionUID = 1L; public PanelCountAuditFloors() { super(); setLayout(null); addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName() == "DISPLAY_TAB") { doUpdate(); } } }); setPreferredSize(new Dimension(868, 592)); countAuditControls = new JPanel(); countAuditControls.setOpaque(false); countAuditControls.setBounds(288, 66, 356, 372); countAuditControls.setLayout(null); add(countAuditControls); lblChooseFloor = new JLabel(); lblChooseFloor.setHorizontalAlignment(SwingConstants.CENTER); lblChooseFloor.setForeground(GuiModes.DESIGNER_SCREEN .getControlForegroundColor()); lblChooseFloor.setFont(new Font("", Font.BOLD, 28)); lblChooseFloor.setText("CHOOSE FLOOR"); lblChooseFloor.setBounds(0, 0, 294, 52); countAuditControls.add(lblChooseFloor); lstFloors = new ChooseResidentList(); // lstFloors.setBorder(new // LineBorder(GuiModes.DESIGNER_SCREEN.getControlForegroundColor(), 2, // false)); lstFloors.setFont(GuiModes.DESIGNER_SCREEN.getControlFont().deriveFont( 16f)); lstFloors.setForeground(GuiModes.DESIGNER_SCREEN .getControlForegroundColor()); lstFloors.setBackground(Color.WHITE); lstFloors.setFixedCellHeight(52); lstFloors.setFixedCellMargin(10); lstFloors.setBounds(0, 58, 356, 248); lstFloors.getJListComponent().setForeground( GuiModes.DESIGNER_SCREEN.getControlForegroundColor()); lstFloors.getJListComponent().setBackground(Color.WHITE); lstFloors.getJListComponent().setFont( GuiModes.DESIGNER_SCREEN.getControlFont().deriveFont(16f)); // lstFloors.getJListComponent().setForeground(new Color(5, 65, 94)); // lstFloors.getJListComponent().setBackground(new Color(206, 221, 224, // 250)); // lstFloors.getJListComponent().setFont(new Font("Dialog", Font.BOLD, // 16)); lstFloors.setPreferredSize(lstFloors.getBounds().getSize()); lstFloors.setCellRenderer(lstFloors.new JxListCellRenderer() { @Override protected String getText(Object value) { return super.getText(value); } }); lstFloors.getJListComponent().addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 1) { String str = (String) lstFloors.getJListComponent() .getSelectedValue(); Global.panelCountAuditMain.setFloorType(str); Global.panelCountAuditMain .changeCard(PanelCountAuditMain.FLOOR_WISE); } } }); countAuditControls.add(lstFloors); btnHistory = new JxButton(); btnHistory.setArc(0.2f); btnHistory.setText("VIEW REPORTS"); btnHistory.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { if (btnHistory.isEnabled()) { Global.panelCountAuditMain.setFloorType(null); Global.panelCountAuditMain .changeCard(PanelCountAuditMain.REPORTS); } } }); btnHistory.setBorder(new LineBorder(GuiModes.DESIGNER_SCREEN .getControlForegroundColor(), 2, false)); btnHistory.setFont(GuiModes.DESIGNER_SCREEN.getControlFont() .deriveFont(16f)); btnHistory.setForeground(GuiModes.DESIGNER_SCREEN .getControlForegroundColor()); btnHistory.setBackground(Color.WHITE); btnHistory.setBorder(new LineBorder(GuiModes.DESIGNER_SCREEN .getControlForegroundColor(), 2, false)); btnHistory.setLayout(null); btnHistory.setBounds(0, 316, 294, 52); countAuditControls.add(btnHistory); updateList(); } protected void doUpdate() { int w = getWidth(); int h = getHeight(); float wF = ((float) w / 868); float hF = ((float) h / 592); // 288, 66, 356, 372 countAuditControls.setLocation((int) (288 * wF), (int) (66 * hF)); if (getTopLevelAncestor() != null) { getTopLevelAncestor().repaint(); } else { this.repaint(); } } private void updateList() { List<String> floorList = new ArrayList<String>(); floorList.add("1st floor"); floorList.add("2nd floor"); lstFloors.setListData(floorList.toArray()); } }
UTF-8
Java
5,032
java
PanelCountAuditFloors.java
Java
[]
null
[]
package medrex.client.census.countAudit; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.border.LineBorder; import medrex.client.constants.Global; import medrex.client.utils.controls.ChooseResidentList; import medrex.commons.enums.GuiModes; import com.sX.swing.JxButton; public class PanelCountAuditFloors extends JPanel { private JPanel countAuditControls; private ChooseResidentList lstFloors; private JxButton btnHistory; private JLabel lblChooseFloor; private static final long serialVersionUID = 1L; public PanelCountAuditFloors() { super(); setLayout(null); addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName() == "DISPLAY_TAB") { doUpdate(); } } }); setPreferredSize(new Dimension(868, 592)); countAuditControls = new JPanel(); countAuditControls.setOpaque(false); countAuditControls.setBounds(288, 66, 356, 372); countAuditControls.setLayout(null); add(countAuditControls); lblChooseFloor = new JLabel(); lblChooseFloor.setHorizontalAlignment(SwingConstants.CENTER); lblChooseFloor.setForeground(GuiModes.DESIGNER_SCREEN .getControlForegroundColor()); lblChooseFloor.setFont(new Font("", Font.BOLD, 28)); lblChooseFloor.setText("CHOOSE FLOOR"); lblChooseFloor.setBounds(0, 0, 294, 52); countAuditControls.add(lblChooseFloor); lstFloors = new ChooseResidentList(); // lstFloors.setBorder(new // LineBorder(GuiModes.DESIGNER_SCREEN.getControlForegroundColor(), 2, // false)); lstFloors.setFont(GuiModes.DESIGNER_SCREEN.getControlFont().deriveFont( 16f)); lstFloors.setForeground(GuiModes.DESIGNER_SCREEN .getControlForegroundColor()); lstFloors.setBackground(Color.WHITE); lstFloors.setFixedCellHeight(52); lstFloors.setFixedCellMargin(10); lstFloors.setBounds(0, 58, 356, 248); lstFloors.getJListComponent().setForeground( GuiModes.DESIGNER_SCREEN.getControlForegroundColor()); lstFloors.getJListComponent().setBackground(Color.WHITE); lstFloors.getJListComponent().setFont( GuiModes.DESIGNER_SCREEN.getControlFont().deriveFont(16f)); // lstFloors.getJListComponent().setForeground(new Color(5, 65, 94)); // lstFloors.getJListComponent().setBackground(new Color(206, 221, 224, // 250)); // lstFloors.getJListComponent().setFont(new Font("Dialog", Font.BOLD, // 16)); lstFloors.setPreferredSize(lstFloors.getBounds().getSize()); lstFloors.setCellRenderer(lstFloors.new JxListCellRenderer() { @Override protected String getText(Object value) { return super.getText(value); } }); lstFloors.getJListComponent().addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 1) { String str = (String) lstFloors.getJListComponent() .getSelectedValue(); Global.panelCountAuditMain.setFloorType(str); Global.panelCountAuditMain .changeCard(PanelCountAuditMain.FLOOR_WISE); } } }); countAuditControls.add(lstFloors); btnHistory = new JxButton(); btnHistory.setArc(0.2f); btnHistory.setText("VIEW REPORTS"); btnHistory.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { if (btnHistory.isEnabled()) { Global.panelCountAuditMain.setFloorType(null); Global.panelCountAuditMain .changeCard(PanelCountAuditMain.REPORTS); } } }); btnHistory.setBorder(new LineBorder(GuiModes.DESIGNER_SCREEN .getControlForegroundColor(), 2, false)); btnHistory.setFont(GuiModes.DESIGNER_SCREEN.getControlFont() .deriveFont(16f)); btnHistory.setForeground(GuiModes.DESIGNER_SCREEN .getControlForegroundColor()); btnHistory.setBackground(Color.WHITE); btnHistory.setBorder(new LineBorder(GuiModes.DESIGNER_SCREEN .getControlForegroundColor(), 2, false)); btnHistory.setLayout(null); btnHistory.setBounds(0, 316, 294, 52); countAuditControls.add(btnHistory); updateList(); } protected void doUpdate() { int w = getWidth(); int h = getHeight(); float wF = ((float) w / 868); float hF = ((float) h / 592); // 288, 66, 356, 372 countAuditControls.setLocation((int) (288 * wF), (int) (66 * hF)); if (getTopLevelAncestor() != null) { getTopLevelAncestor().repaint(); } else { this.repaint(); } } private void updateList() { List<String> floorList = new ArrayList<String>(); floorList.add("1st floor"); floorList.add("2nd floor"); lstFloors.setListData(floorList.toArray()); } }
5,032
0.719793
0.699126
156
30.26923
20.601328
73
false
false
0
0
0
0
0
0
2.698718
false
false
5
f96e9996d6ec1a95bbd0f21b6fe1d551516a95e8
38,216,619,016,397
c01269662b0950b092f579ad84dbd5d2ee14105c
/GUI/HotKeyApp-GUI-src/src/HotKeyApp/model/HotkeyServerListener.java
34aca552397e0c7de562ccc1c50bf10b205db959
[]
no_license
nicenoize/HotkeyApp_Android
https://github.com/nicenoize/HotkeyApp_Android
e7f1a3a06afc58daaec29440aceb0d4671cfe27e
69616deaa12d23fb92657e6dc214c5d8c2c9bfc4
refs/heads/master
"2020-03-28T14:15:25.587000"
"2019-02-20T10:14:04"
"2019-02-20T10:14:04"
148,472,009
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package HotKeyApp.model; import com.esotericsoftware.kryonet.Connection; import com.esotericsoftware.kryonet.Listener; import HotKeyApp.model.Hotkey; import HotKeyApp.model.HotkeyMap; import HotKeyApp.model.Keypresses; import HotKeyApp.model.MapRequest; /** * HotKeyApp_GUI v0.5 * * @author Alexander Stahl * @version 0.5 */ public class HotkeyServerListener extends Listener { /** The user selected Map*/ private HotkeyMap map; /** * Constructor: Creates the Listener with the user selected HotkeyMap * @param map map of selected program */ public HotkeyServerListener(HotkeyMap map){ this.map = map; } /** * Client has established a connection * @param connection the established connection */ @Override public void connected(Connection connection){} /** * Client has disconnected * @param connection the connection that has closed */ @Override public void disconnected(Connection connection){} /** * Listens for a incomming message from the client. * @param connection the connetion that has send a object to this server * @param object the object itself */ @Override public void received(Connection connection, Object object){ System.out.println("Objekt erhalten: " + object); if(object instanceof Hotkey){ new Keypresses().executeKeys((Hotkey) object); } else if(object instanceof MapRequest){ connection.sendTCP(map); } } }
UTF-8
Java
1,539
java
HotkeyServerListener.java
Java
[ { "context": "pRequest;\n\n/**\n * HotKeyApp_GUI v0.5\n *\n * @author Alexander Stahl\n * @version 0.5\n */\npublic class HotkeyServerList", "end": 311, "score": 0.9997650384902954, "start": 296, "tag": "NAME", "value": "Alexander Stahl" } ]
null
[]
package HotKeyApp.model; import com.esotericsoftware.kryonet.Connection; import com.esotericsoftware.kryonet.Listener; import HotKeyApp.model.Hotkey; import HotKeyApp.model.HotkeyMap; import HotKeyApp.model.Keypresses; import HotKeyApp.model.MapRequest; /** * HotKeyApp_GUI v0.5 * * @author <NAME> * @version 0.5 */ public class HotkeyServerListener extends Listener { /** The user selected Map*/ private HotkeyMap map; /** * Constructor: Creates the Listener with the user selected HotkeyMap * @param map map of selected program */ public HotkeyServerListener(HotkeyMap map){ this.map = map; } /** * Client has established a connection * @param connection the established connection */ @Override public void connected(Connection connection){} /** * Client has disconnected * @param connection the connection that has closed */ @Override public void disconnected(Connection connection){} /** * Listens for a incomming message from the client. * @param connection the connetion that has send a object to this server * @param object the object itself */ @Override public void received(Connection connection, Object object){ System.out.println("Objekt erhalten: " + object); if(object instanceof Hotkey){ new Keypresses().executeKeys((Hotkey) object); } else if(object instanceof MapRequest){ connection.sendTCP(map); } } }
1,530
0.673164
0.670565
59
25.101694
21.670643
76
false
false
0
0
0
0
0
0
0.220339
false
false
5
6914f5821b31cc13596269185d9ee01156e4c09b
38,860,864,135,102
ca3ed6d2be395cf161557a4b91022d01809ff79f
/CIS-217/AssignmentSession2/src/Six/Twenty/TotalSalesForADay.java
cf0a06806cdbcd80e44f9d3d34a5dba94bbf7f1d
[]
no_license
danecodder/Introductory-Java
https://github.com/danecodder/Introductory-Java
cf31532dca817997dca47e319de61cc0181d345d
d350758d340730d965fa16ebc809c68b2b566290
refs/heads/master
"2020-06-18T23:11:39.662000"
"2016-11-28T04:00:30"
"2016-11-28T04:00:30"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Six.Twenty; public class TotalSalesForADay { public static void main( String[] args ) { // two-dimensional array of salesperson sales for a day!!! int[][] totalSales = { { 50, 50, 50,50}, { 50, 50, 50,50}, { 50, 50, 50,50}, { 50, 50, 50,50}, { 50, 50, 50,50}, }; // output grades array outputTotalSales( totalSales ); } // end main // output the contents of the grades array public static void outputTotalSales( int totalSales[][] ) { System.out.println( "The total sales for the day are:\n" ); System.out.print( " " ); // align column heads // create a column heading for each of the products for ( int salesPerson = 0; salesPerson < totalSales[ 0 ].length; salesPerson++ ) System.out.printf( "Sales Person %d ", salesPerson + 1 ); System.out.println( "Total Product Sold in $$$$" ); // total amount sold per salesperson // create rows/columns of text representing arrayTotalSales //creates the rows of products for ( int product = 0; product < totalSales.length; product++ ) { System.out.printf( "Product %4d", product + 1); for ( int itemSold : totalSales[ product ] ) // output total sale System.out.printf( "%15d", itemSold ); double totalSold = getTotalSold( totalSales[ product ] ); System.out.printf( "%24.2f\n", totalSold ); } // end outer for System.out.println("Total Amount Sold"); } // end method outputTotalSales private static double getTotalSold(int[] setOfSales) { int total = 0; // initialize total // sum total for each salesperson for ( int productSold : setOfSales ) total += productSold; // return total amount sold return (double) total;//Casting total to double } }
UTF-8
Java
1,809
java
TotalSalesForADay.java
Java
[]
null
[]
package Six.Twenty; public class TotalSalesForADay { public static void main( String[] args ) { // two-dimensional array of salesperson sales for a day!!! int[][] totalSales = { { 50, 50, 50,50}, { 50, 50, 50,50}, { 50, 50, 50,50}, { 50, 50, 50,50}, { 50, 50, 50,50}, }; // output grades array outputTotalSales( totalSales ); } // end main // output the contents of the grades array public static void outputTotalSales( int totalSales[][] ) { System.out.println( "The total sales for the day are:\n" ); System.out.print( " " ); // align column heads // create a column heading for each of the products for ( int salesPerson = 0; salesPerson < totalSales[ 0 ].length; salesPerson++ ) System.out.printf( "Sales Person %d ", salesPerson + 1 ); System.out.println( "Total Product Sold in $$$$" ); // total amount sold per salesperson // create rows/columns of text representing arrayTotalSales //creates the rows of products for ( int product = 0; product < totalSales.length; product++ ) { System.out.printf( "Product %4d", product + 1); for ( int itemSold : totalSales[ product ] ) // output total sale System.out.printf( "%15d", itemSold ); double totalSold = getTotalSold( totalSales[ product ] ); System.out.printf( "%24.2f\n", totalSold ); } // end outer for System.out.println("Total Amount Sold"); } // end method outputTotalSales private static double getTotalSold(int[] setOfSales) { int total = 0; // initialize total // sum total for each salesperson for ( int productSold : setOfSales ) total += productSold; // return total amount sold return (double) total;//Casting total to double } }
1,809
0.622996
0.594251
63
26.698412
24.860649
90
false
false
0
0
0
0
0
0
2.349206
false
false
5
208426ff5afe6b19d8869155819795e50198fe8a
23,828,478,619,190
b3310896e61b0a3e47cf27d1bb7c25739dfa544f
/src/main/java/com/metin/heroku/spring/boot/jar/deploy/herokuspringbootjardeploy/controller/HelloWorld.java
cd74364c62a8451835f049d5ef3d2bd6cc29bf81
[]
no_license
Muhammederendemir/heroku-jar-deploy
https://github.com/Muhammederendemir/heroku-jar-deploy
a6b2fd0c14d34ae8c09915c727e4fad9c9ce906a
944280046ef365a62785911bec1211b054c29f23
refs/heads/master
"2023-03-28T22:07:21.149000"
"2021-04-05T06:40:49"
"2021-04-05T06:40:49"
354,023,481
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.metin.heroku.spring.boot.jar.deploy.herokuspringbootjardeploy.controller; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; /** * Created by Metin on 18.05.2019. */ @RestController() @RequestMapping("/api") public class HelloWorld { String last = ""; @GetMapping("/v2/test") @ResponseStatus(value = HttpStatus.OK) public String sayHello(){ last = "test Get"; return last; } @PostMapping("/v2/test") @ResponseStatus(value = HttpStatus.OK) public void sayHelloPost(){ last = "test Post"; } @GetMapping("/v2/test1") @ResponseStatus(value = HttpStatus.OK) public void sayHello1(String token){ last = token; System.out.printf(token); } @PostMapping("/v2/test1") @ResponseStatus(value = HttpStatus.OK) public void sayHelloPost1(String token){ last = token; System.out.printf(token); } @GetMapping("/v2/test2") @ResponseStatus(value = HttpStatus.OK) public void sayHello2(Object object){ last = object.toString(); System.out.printf(object.toString()); } @PostMapping("/v2/test2") @ResponseStatus(value = HttpStatus.OK) public void sayHelloPost2(Object object){ last = object.toString(); System.out.printf(object.toString()); } @GetMapping("/v2/test3") @ResponseStatus(value = HttpStatus.OK) public void sayHello3(String code, String state, String error){ last = code+state+error; } @PostMapping("/v2/test3") @ResponseStatus(value = HttpStatus.OK) public void sayHelloPost3(String code, String state, String error) { last = code + state + error; } @GetMapping("/v2/test4") @ResponseStatus(value = HttpStatus.OK) public String sayHello4() { return last; } @PostMapping("/v2/test5") @ResponseStatus(value = HttpStatus.OK) public void sayHelloPost5(@RequestBody String token) { last = token; System.out.printf(token); } @GetMapping("/v2/test6") @ResponseStatus(value = HttpStatus.OK) public void sayHello6(@RequestBody Object object) { last = object.toString(); System.out.printf(object.toString()); } @PostMapping("/v2/test7") @ResponseStatus(value = HttpStatus.OK) public void sayHelloPost7(@RequestBody Object object) { last = object.toString(); System.out.printf(object.toString()); } @GetMapping("/v2/test8") @ResponseStatus(value = HttpStatus.OK) public void sayHello8(@RequestBody String code, @RequestBody String state, @RequestBody String error) { last = code + state + error; } @PostMapping("/v2/test9") @ResponseStatus(value = HttpStatus.OK) public void sayHelloPost9(@RequestBody String code, @RequestBody String state, @RequestBody String error) { last = code + state + error; } }
UTF-8
Java
2,967
java
HelloWorld.java
Java
[ { "context": "ramework.web.bind.annotation.*;\n\n/**\n * Created by Metin on 18.05.2019.\n */\n@RestController()\n@RequestMapp", "end": 205, "score": 0.9661794900894165, "start": 200, "tag": "NAME", "value": "Metin" } ]
null
[]
package com.metin.heroku.spring.boot.jar.deploy.herokuspringbootjardeploy.controller; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; /** * Created by Metin on 18.05.2019. */ @RestController() @RequestMapping("/api") public class HelloWorld { String last = ""; @GetMapping("/v2/test") @ResponseStatus(value = HttpStatus.OK) public String sayHello(){ last = "test Get"; return last; } @PostMapping("/v2/test") @ResponseStatus(value = HttpStatus.OK) public void sayHelloPost(){ last = "test Post"; } @GetMapping("/v2/test1") @ResponseStatus(value = HttpStatus.OK) public void sayHello1(String token){ last = token; System.out.printf(token); } @PostMapping("/v2/test1") @ResponseStatus(value = HttpStatus.OK) public void sayHelloPost1(String token){ last = token; System.out.printf(token); } @GetMapping("/v2/test2") @ResponseStatus(value = HttpStatus.OK) public void sayHello2(Object object){ last = object.toString(); System.out.printf(object.toString()); } @PostMapping("/v2/test2") @ResponseStatus(value = HttpStatus.OK) public void sayHelloPost2(Object object){ last = object.toString(); System.out.printf(object.toString()); } @GetMapping("/v2/test3") @ResponseStatus(value = HttpStatus.OK) public void sayHello3(String code, String state, String error){ last = code+state+error; } @PostMapping("/v2/test3") @ResponseStatus(value = HttpStatus.OK) public void sayHelloPost3(String code, String state, String error) { last = code + state + error; } @GetMapping("/v2/test4") @ResponseStatus(value = HttpStatus.OK) public String sayHello4() { return last; } @PostMapping("/v2/test5") @ResponseStatus(value = HttpStatus.OK) public void sayHelloPost5(@RequestBody String token) { last = token; System.out.printf(token); } @GetMapping("/v2/test6") @ResponseStatus(value = HttpStatus.OK) public void sayHello6(@RequestBody Object object) { last = object.toString(); System.out.printf(object.toString()); } @PostMapping("/v2/test7") @ResponseStatus(value = HttpStatus.OK) public void sayHelloPost7(@RequestBody Object object) { last = object.toString(); System.out.printf(object.toString()); } @GetMapping("/v2/test8") @ResponseStatus(value = HttpStatus.OK) public void sayHello8(@RequestBody String code, @RequestBody String state, @RequestBody String error) { last = code + state + error; } @PostMapping("/v2/test9") @ResponseStatus(value = HttpStatus.OK) public void sayHelloPost9(@RequestBody String code, @RequestBody String state, @RequestBody String error) { last = code + state + error; } }
2,967
0.644085
0.628581
111
25.729731
22.227304
111
false
false
0
0
0
0
0
0
0.306306
false
false
5
41e0b825ec8f9343730cb9381de8f69fcba199d1
36,833,639,559,613
07be3ed849c578bc43ec1d9d5adfcaed858d320c
/src/main/java/com/example/demo/controller/UserController.java
52fb6bdc47dabd297700a8d6a7aebf6413b140a1
[]
no_license
xiens/InvoicesManager
https://github.com/xiens/InvoicesManager
dd050a3661d3fa70768002ca37ff67af1ecd0a1e
beb5940a95ce86c4cc7efdd227c09123ee94a6b3
refs/heads/master
"2020-04-07T18:25:01.984000"
"2018-12-12T17:31:02"
"2018-12-12T17:31:02"
158,609,149
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.example.demo.controller; import com.example.demo.model.User; import com.example.demo.repo.UserRepository; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; /** * * @author xiens */ @Controller public class UserController { @Autowired UserRepository userRepository; @GetMapping("/users") public String userForm(Model model) { model.addAttribute("userlist", userRepository.findAll()); model.addAttribute("user", new User()); return "users"; } @PostMapping("/users") public String userSubmit(@ModelAttribute User user, Model model) { userRepository.save(user); model.addAttribute("userlist", userRepository.findAll()); return "users"; } @PostMapping("/saveUser") public String saveUser(User user) { userRepository.save(user); return "redirect:/"; } @GetMapping("/deleteUser") public String deleteUser(Long userId) { userRepository.deleteById(userId); return "redirect:/"; } @GetMapping("/findByUserId") public Optional<User> findByUserId(Long userId) { return userRepository.findById(userId); } @RequestMapping("/save") public String process() { userRepository.save(new User("Jack", "Smith")); userRepository.save(new User("Adam", "Johnson")); userRepository.save(new User("Bro", "Johnson")); userRepository.save(new User("OO Long", "Johnson")); userRepository.save(new User("Evan", "Smith")); return "Done"; } @RequestMapping("/findbyid") public String findById(@RequestParam("id") long id) { String result = ""; result = userRepository.findById(id).toString(); return result; } }
UTF-8
Java
2,377
java
UserController.java
Java
[ { "context": "b.bind.annotation.RequestParam;\n\n/**\n *\n * @author xiens\n */\n@Controller\npublic class UserController {\n\n ", "end": 811, "score": 0.999008059501648, "start": 806, "tag": "USERNAME", "value": "xiens" }, { "context": "rocess() {\n\n userRepository.save(new User(\"Jack\", \"Smith\"));\n userRepository.save(new User", "end": 1892, "score": 0.9998348355293274, "start": 1888, "tag": "NAME", "value": "Jack" }, { "context": " {\n\n userRepository.save(new User(\"Jack\", \"Smith\"));\n userRepository.save(new User(\"Adam\", ", "end": 1901, "score": 0.999721109867096, "start": 1896, "tag": "NAME", "value": "Smith" }, { "context": " \"Smith\"));\n userRepository.save(new User(\"Adam\", \"Johnson\"));\n userRepository.save(new Us", "end": 1948, "score": 0.9998528361320496, "start": 1944, "tag": "NAME", "value": "Adam" }, { "context": "));\n userRepository.save(new User(\"Adam\", \"Johnson\"));\n userRepository.save(new User(\"Bro\", \"", "end": 1959, "score": 0.9996988773345947, "start": 1952, "tag": "NAME", "value": "Johnson" }, { "context": "Johnson\"));\n userRepository.save(new User(\"Bro\", \"Johnson\"));\n userRepository.save(new Us", "end": 2005, "score": 0.9994495511054993, "start": 2002, "tag": "NAME", "value": "Bro" }, { "context": "\"));\n userRepository.save(new User(\"Bro\", \"Johnson\"));\n userRepository.save(new User(\"OO Long", "end": 2016, "score": 0.9997137784957886, "start": 2009, "tag": "NAME", "value": "Johnson" }, { "context": "Johnson\"));\n userRepository.save(new User(\"OO Long\", \"Johnson\"));\n userRepository.save(new Us", "end": 2066, "score": 0.7429631352424622, "start": 2059, "tag": "NAME", "value": "OO Long" }, { "context": "\n userRepository.save(new User(\"OO Long\", \"Johnson\"));\n userRepository.save(new User(\"Evan\", ", "end": 2077, "score": 0.9996172785758972, "start": 2070, "tag": "NAME", "value": "Johnson" }, { "context": "Johnson\"));\n userRepository.save(new User(\"Evan\", \"Smith\"));\n\n return \"Done\";\n }\n\n @", "end": 2124, "score": 0.9998043775558472, "start": 2120, "tag": "NAME", "value": "Evan" }, { "context": "));\n userRepository.save(new User(\"Evan\", \"Smith\"));\n\n return \"Done\";\n }\n\n @RequestMa", "end": 2133, "score": 0.9997881650924683, "start": 2128, "tag": "NAME", "value": "Smith" } ]
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.example.demo.controller; import com.example.demo.model.User; import com.example.demo.repo.UserRepository; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; /** * * @author xiens */ @Controller public class UserController { @Autowired UserRepository userRepository; @GetMapping("/users") public String userForm(Model model) { model.addAttribute("userlist", userRepository.findAll()); model.addAttribute("user", new User()); return "users"; } @PostMapping("/users") public String userSubmit(@ModelAttribute User user, Model model) { userRepository.save(user); model.addAttribute("userlist", userRepository.findAll()); return "users"; } @PostMapping("/saveUser") public String saveUser(User user) { userRepository.save(user); return "redirect:/"; } @GetMapping("/deleteUser") public String deleteUser(Long userId) { userRepository.deleteById(userId); return "redirect:/"; } @GetMapping("/findByUserId") public Optional<User> findByUserId(Long userId) { return userRepository.findById(userId); } @RequestMapping("/save") public String process() { userRepository.save(new User("Jack", "Smith")); userRepository.save(new User("Adam", "Johnson")); userRepository.save(new User("Bro", "Johnson")); userRepository.save(new User("<NAME>", "Johnson")); userRepository.save(new User("Evan", "Smith")); return "Done"; } @RequestMapping("/findbyid") public String findById(@RequestParam("id") long id) { String result = ""; result = userRepository.findById(id).toString(); return result; } }
2,376
0.689104
0.689104
80
28.7125
22.860552
79
false
false
0
0
0
0
0
0
0.5625
false
false
5
41658ef8a890568aeabc076d87e4a951c799d3a4
36,833,639,559,602
1cffda97c6ef5bf857bc1341a1dcc68ed5d36937
/src/main/java/traypass/syntax/Interpreter.java
04d3c1bc8500e26edeb7d9f5e569119ca3b8f114
[]
no_license
jlaloi/TrayPass
https://github.com/jlaloi/TrayPass
1328d615b36c5e782dcf08d869767f12ad9a3124
61debe59e6670ca0ac78059448cc05fd50269ae0
refs/heads/master
"2021-01-01T16:25:06.365000"
"2013-05-14T16:48:05"
"2013-05-14T16:48:05"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package traypass.syntax; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import traypass.ressources.Factory; import traypass.syntax.plugin.Plugin; public class Interpreter extends Thread { private static final Logger logger = LoggerFactory.getLogger(Interpreter.class); private String line; private boolean stop = false; private boolean invisible = false; public Interpreter(String line) { this.line = line; } public void run() { stop = false; if (!invisible && Factory.get().getTrayPass() != null) { Factory.get().getTrayPass().setWorking(true); } computeFunctions(line); if (!invisible && Factory.get().getTrayPass() != null) { Factory.get().getTrayPass().setWorking(false); } stop = true; } public String computeFunctions(String line) { String result = ""; try { for (String function : splitFunctions(line)) { if (stop) { if (function != null && function.trim().length() > 0) { Factory.get().getTrayPass().showError("Stopped before executing: " + function); } break; } if (function != null && function.length() > 0) { result = computeFunction(function); } if (result == null && !stop) { showError("Error while executing: " + function); break; } } } catch (Exception e) { showError("Exception while computeFunctions:" + line + ":\n" + e); logger.error("Error", e); } return result; } private String computeFunction(String function) { logger.debug("Executing " + function); String result = function; try { if (stop || !checkSyntax(function)) { return function; } int indexOfParam = function.indexOf(Function.functionParamStart); String methodName = function.substring(0, indexOfParam); String paramsS = function.substring(indexOfParam + 1); List<String> params = new ArrayList<String>(); StringBuilder paramBuilder = new StringBuilder(); int i = 0; int numberOfBracket = 1; while (numberOfBracket > 0 && i < paramsS.length()) { if (isSpecialChar(paramsS, i, Function.functionParamEnd)) { numberOfBracket--; if (numberOfBracket == 0) { String p = paramBuilder.toString(); if (null != p && (!"".equals(p) || isEmptyParam(paramsS, i))) { params.add(paramBuilder.toString()); } } else { paramBuilder.append(paramsS.charAt(i)); } } else if (isSpecialChar(paramsS, i, Function.functionStart)) { numberOfBracket++; paramBuilder.append(paramsS.charAt(i)); } else if (isSpecialChar(paramsS, i, Function.functionParamSeparator) && numberOfBracket == 1) { params.add(paramBuilder.toString()); paramBuilder = new StringBuilder(); } else { paramBuilder.append(paramsS.charAt(i)); } i++; } Action action = getAction(methodName, params.size()); if (!stop && action != null) { logger.info("Executing " + methodName); result = action.execute(this, params); } } catch (Exception e) { showError("Exception while executing:" + function + ":\n" + e); logger.error("Error", e); } return result; } public static Action getAction(String functionName, int nbParameters) { Action result = null; // Default action for (Syntax syntax : Syntax.values()) { if (syntax.getPattern().toLowerCase().equals(functionName.toLowerCase())) { result = syntax.getAction(); break; } } // Plugin action if (result == null) { for (Plugin plugin : Factory.get().getPluginManager().getPluginList()) { if ((plugin.getPattern()).toLowerCase().equals(functionName.toLowerCase())) { result = plugin; break; } } } return result; } public static boolean isSpecialChar(String str, int pos, char c) { boolean result = str != null && pos >= 0 && pos < str.length() && str.charAt(pos) == c; if (result) { int i = pos - 1; while (i >= 0 && str.charAt(i) == Function.escapeChar) { i--; } int mod = (pos - 1 - i) % 2; if (mod != 0) { result = false; } } return result; } public static boolean isEmptyParam(String str, int pos) { boolean result = pos > 0 && (isSpecialChar(str, pos - 1, Function.functionParamSeparator)) || isSpecialChar(str, pos - 1, Function.functionParamStart); return result; } public static boolean isSyntaxChar(char c) { boolean result = false; if (c == Function.functionParamEnd) { result = true; } else if (c == Function.functionParamStart) { result = true; } else if (c == Function.functionParamSeparator) { result = true; } else if (c == Function.functionStart) { result = true; } else if (c == Function.escapeChar) { result = true; } return result; } private static boolean checkSyntax(String function) { Matcher matcher = Function.functionPattern.matcher(function); return matcher.find() && matcher.group().equals(function); } public static List<String> splitFunctions(String functions) { List<String> result = new ArrayList<String>(); int nbIn = 0; int startPos = getNext(functions, 0, Function.functionStart); if (startPos > 0) { result.add(functions.substring(0, startPos)); } else if (startPos == -1) { result.add(functions); } int pos = getNext(functions, startPos, Function.functionParamStart); while (pos < functions.length() && startPos > -1 && pos > 0) { if (isSpecialChar(functions, pos, Function.functionParamStart)) { nbIn++; } else if (isSpecialChar(functions, pos, Function.functionParamEnd)) { nbIn--; } if (nbIn == 0) { result.add(functions.substring(startPos, pos + 1)); startPos = getNext(functions, pos, Function.functionStart); if (startPos > 0 && pos + 1 < functions.length() && pos + 1 != startPos) { result.add(functions.substring(pos + 1, startPos)); } else if (startPos == -1 && pos + 1 != functions.length()) { result.add(functions.substring(pos + 1, functions.length())); } if (getNext(functions, startPos, Function.functionParamStart) == -1 && pos + 1 != functions.length()) { result.add(functions.substring(pos + 1, functions.length())); } pos = getNext(functions, startPos, Function.functionParamStart); } else { pos++; } } return result; } private static int getNext(String str, int start, char c) { int result = -1; for (int pos = start; str != null && pos < str.length(); pos++) { if (isSpecialChar(str, pos, c)) { result = pos; break; } } return result; } public static String clearEscapeChar(String str) { String result = ""; for (int i = 0; str != null && i < str.length(); i++) { char c = str.charAt(i); if (c == Function.escapeChar && i + 1 < str.length() && isSyntaxChar(str.charAt(i + 1))) { result += str.charAt(i + 1); i++; } else { result += c; } } return result; } public static void showError(String text) { if (Factory.get().getTrayPass() != null) { Factory.get().getTrayPass().showError(text); } else { System.out.println("ERROR " + text); } } public static boolean isTrue(String bool) { boolean result = false; if (bool != null && bool.trim().toLowerCase().equals(Function.boolTrue)) { result = true; } return result; } public boolean isStop() { return stop; } public void setStop(boolean stop) { this.stop = stop; } public String getLine() { return line; } public void setLine(String line) { this.line = line; } public boolean isInvisible() { return invisible; } public void setInvisible(boolean invisible) { this.invisible = invisible; } }
UTF-8
Java
7,622
java
Interpreter.java
Java
[]
null
[]
package traypass.syntax; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import traypass.ressources.Factory; import traypass.syntax.plugin.Plugin; public class Interpreter extends Thread { private static final Logger logger = LoggerFactory.getLogger(Interpreter.class); private String line; private boolean stop = false; private boolean invisible = false; public Interpreter(String line) { this.line = line; } public void run() { stop = false; if (!invisible && Factory.get().getTrayPass() != null) { Factory.get().getTrayPass().setWorking(true); } computeFunctions(line); if (!invisible && Factory.get().getTrayPass() != null) { Factory.get().getTrayPass().setWorking(false); } stop = true; } public String computeFunctions(String line) { String result = ""; try { for (String function : splitFunctions(line)) { if (stop) { if (function != null && function.trim().length() > 0) { Factory.get().getTrayPass().showError("Stopped before executing: " + function); } break; } if (function != null && function.length() > 0) { result = computeFunction(function); } if (result == null && !stop) { showError("Error while executing: " + function); break; } } } catch (Exception e) { showError("Exception while computeFunctions:" + line + ":\n" + e); logger.error("Error", e); } return result; } private String computeFunction(String function) { logger.debug("Executing " + function); String result = function; try { if (stop || !checkSyntax(function)) { return function; } int indexOfParam = function.indexOf(Function.functionParamStart); String methodName = function.substring(0, indexOfParam); String paramsS = function.substring(indexOfParam + 1); List<String> params = new ArrayList<String>(); StringBuilder paramBuilder = new StringBuilder(); int i = 0; int numberOfBracket = 1; while (numberOfBracket > 0 && i < paramsS.length()) { if (isSpecialChar(paramsS, i, Function.functionParamEnd)) { numberOfBracket--; if (numberOfBracket == 0) { String p = paramBuilder.toString(); if (null != p && (!"".equals(p) || isEmptyParam(paramsS, i))) { params.add(paramBuilder.toString()); } } else { paramBuilder.append(paramsS.charAt(i)); } } else if (isSpecialChar(paramsS, i, Function.functionStart)) { numberOfBracket++; paramBuilder.append(paramsS.charAt(i)); } else if (isSpecialChar(paramsS, i, Function.functionParamSeparator) && numberOfBracket == 1) { params.add(paramBuilder.toString()); paramBuilder = new StringBuilder(); } else { paramBuilder.append(paramsS.charAt(i)); } i++; } Action action = getAction(methodName, params.size()); if (!stop && action != null) { logger.info("Executing " + methodName); result = action.execute(this, params); } } catch (Exception e) { showError("Exception while executing:" + function + ":\n" + e); logger.error("Error", e); } return result; } public static Action getAction(String functionName, int nbParameters) { Action result = null; // Default action for (Syntax syntax : Syntax.values()) { if (syntax.getPattern().toLowerCase().equals(functionName.toLowerCase())) { result = syntax.getAction(); break; } } // Plugin action if (result == null) { for (Plugin plugin : Factory.get().getPluginManager().getPluginList()) { if ((plugin.getPattern()).toLowerCase().equals(functionName.toLowerCase())) { result = plugin; break; } } } return result; } public static boolean isSpecialChar(String str, int pos, char c) { boolean result = str != null && pos >= 0 && pos < str.length() && str.charAt(pos) == c; if (result) { int i = pos - 1; while (i >= 0 && str.charAt(i) == Function.escapeChar) { i--; } int mod = (pos - 1 - i) % 2; if (mod != 0) { result = false; } } return result; } public static boolean isEmptyParam(String str, int pos) { boolean result = pos > 0 && (isSpecialChar(str, pos - 1, Function.functionParamSeparator)) || isSpecialChar(str, pos - 1, Function.functionParamStart); return result; } public static boolean isSyntaxChar(char c) { boolean result = false; if (c == Function.functionParamEnd) { result = true; } else if (c == Function.functionParamStart) { result = true; } else if (c == Function.functionParamSeparator) { result = true; } else if (c == Function.functionStart) { result = true; } else if (c == Function.escapeChar) { result = true; } return result; } private static boolean checkSyntax(String function) { Matcher matcher = Function.functionPattern.matcher(function); return matcher.find() && matcher.group().equals(function); } public static List<String> splitFunctions(String functions) { List<String> result = new ArrayList<String>(); int nbIn = 0; int startPos = getNext(functions, 0, Function.functionStart); if (startPos > 0) { result.add(functions.substring(0, startPos)); } else if (startPos == -1) { result.add(functions); } int pos = getNext(functions, startPos, Function.functionParamStart); while (pos < functions.length() && startPos > -1 && pos > 0) { if (isSpecialChar(functions, pos, Function.functionParamStart)) { nbIn++; } else if (isSpecialChar(functions, pos, Function.functionParamEnd)) { nbIn--; } if (nbIn == 0) { result.add(functions.substring(startPos, pos + 1)); startPos = getNext(functions, pos, Function.functionStart); if (startPos > 0 && pos + 1 < functions.length() && pos + 1 != startPos) { result.add(functions.substring(pos + 1, startPos)); } else if (startPos == -1 && pos + 1 != functions.length()) { result.add(functions.substring(pos + 1, functions.length())); } if (getNext(functions, startPos, Function.functionParamStart) == -1 && pos + 1 != functions.length()) { result.add(functions.substring(pos + 1, functions.length())); } pos = getNext(functions, startPos, Function.functionParamStart); } else { pos++; } } return result; } private static int getNext(String str, int start, char c) { int result = -1; for (int pos = start; str != null && pos < str.length(); pos++) { if (isSpecialChar(str, pos, c)) { result = pos; break; } } return result; } public static String clearEscapeChar(String str) { String result = ""; for (int i = 0; str != null && i < str.length(); i++) { char c = str.charAt(i); if (c == Function.escapeChar && i + 1 < str.length() && isSyntaxChar(str.charAt(i + 1))) { result += str.charAt(i + 1); i++; } else { result += c; } } return result; } public static void showError(String text) { if (Factory.get().getTrayPass() != null) { Factory.get().getTrayPass().showError(text); } else { System.out.println("ERROR " + text); } } public static boolean isTrue(String bool) { boolean result = false; if (bool != null && bool.trim().toLowerCase().equals(Function.boolTrue)) { result = true; } return result; } public boolean isStop() { return stop; } public void setStop(boolean stop) { this.stop = stop; } public String getLine() { return line; } public void setLine(String line) { this.line = line; } public boolean isInvisible() { return invisible; } public void setInvisible(boolean invisible) { this.invisible = invisible; } }
7,622
0.643532
0.637759
277
26.519855
25.568422
153
false
false
0
0
0
0
0
0
2.906137
false
false
5
fa014067b58d5ad8757b7c4f853014bd0482734f
10,771,778,045,078
6c3349a1874aef201635495c60dfe7920be374e5
/src/main/java/org/travelplan/dao/impl/UserDAOImpl.java
c843aae6d3ba509e3463b182f5ad84d2d3212cc0
[]
no_license
InnaKrasnitskaya/TravelPlanning
https://github.com/InnaKrasnitskaya/TravelPlanning
9c57b63a704e80c22be82afc775cf78b753d3a68
b50ed25d4ff98ae2e66d93ed0727d8d541f72d24
refs/heads/master
"2016-09-05T14:11:01.063000"
"2013-05-27T14:00:10"
"2013-05-27T14:00:10"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.travelplan.dao.impl; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import org.travelplan.dao.UserDAO; import org.travelplan.entity.User; @Repository("userDAO") @Transactional public class UserDAOImpl extends CommonDAOImpl<User> implements UserDAO { public UserDAOImpl() { super(User.class); } public User findByName(String name) { return (User) getSession(). createCriteria(User.class). add(Restrictions.eq("name", name)). uniqueResult(); } }
UTF-8
Java
621
java
UserDAOImpl.java
Java
[]
null
[]
package org.travelplan.dao.impl; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import org.travelplan.dao.UserDAO; import org.travelplan.entity.User; @Repository("userDAO") @Transactional public class UserDAOImpl extends CommonDAOImpl<User> implements UserDAO { public UserDAOImpl() { super(User.class); } public User findByName(String name) { return (User) getSession(). createCriteria(User.class). add(Restrictions.eq("name", name)). uniqueResult(); } }
621
0.740741
0.740741
23
26
20.474798
73
false
false
0
0
0
0
0
0
0.869565
false
false
5
c556dbc6904df1507513c1c930f961f5132adb9e
32,117,765,498,256
135583d1678bdd9e258ab16605b6ce836a5106a7
/modules/VowedAPI/src/main/java/net/vowed/api/bases/IBase.java
a9a50f6736da4aaa2f76bfb2f97ca1034e81f025
[]
no_license
jared-paul/Vowed
https://github.com/jared-paul/Vowed
1fce41dbf7f07a08651397f534a3ad344af0823c
15476c5e6c7ba615a18af58b53932b4e265664be
refs/heads/master
"2020-05-24T06:33:57.615000"
"2019-05-17T03:31:06"
"2019-05-17T03:31:06"
187,140,477
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.vowed.api.bases; import net.vowed.api.clans.IClan; import org.bukkit.Location; import java.util.List; /** * Created by JPaul on 8/12/2016. */ public interface IBase { String getName(); String getFormattedName(); Location getLocation(); IClan getOwner(); List<IBaseComponent> getComponents(); }
UTF-8
Java
335
java
IBase.java
Java
[ { "context": "cation;\n\nimport java.util.List;\n\n/**\n * Created by JPaul on 8/12/2016.\n */\npublic interface IBase\n{\n St", "end": 140, "score": 0.9713795781135559, "start": 135, "tag": "USERNAME", "value": "JPaul" } ]
null
[]
package net.vowed.api.bases; import net.vowed.api.clans.IClan; import org.bukkit.Location; import java.util.List; /** * Created by JPaul on 8/12/2016. */ public interface IBase { String getName(); String getFormattedName(); Location getLocation(); IClan getOwner(); List<IBaseComponent> getComponents(); }
335
0.692537
0.671642
22
14.227273
14.170815
41
false
false
0
0
0
0
0
0
0.409091
false
false
5
4797bddbc3d30a0588399d7f7cddd69ef501ab27
24,275,155,186,383
267c320a1991a120b8a1d5e69644bdafeab55f1d
/task1/model/Elf.java
8e813baa663e8a04a44106799071ebae03d0539a
[]
no_license
CODERS-BAY/java-christmas-exercise-deutschha
https://github.com/CODERS-BAY/java-christmas-exercise-deutschha
c0b98b02008ac71a96169a4b2d69597f1cded18e
348183ac592464c23958281b2a4aebffbf047a85
refs/heads/main
"2023-02-18T05:33:24.498000"
"2021-01-17T21:31:26"
"2021-01-17T21:31:26"
322,944,050
0
0
null
false
"2020-12-19T21:50:04"
"2020-12-19T21:49:56"
"2020-12-19T21:50:03"
"2020-12-19T21:50:03"
0
0
0
1
Java
false
false
package model; public class Elf { public String name; public Elf(String name) { // Sortierfunktion ?? // TODO Auto-generated constructor stub this.name = name; } public Elf() { } }
UTF-8
Java
203
java
Elf.java
Java
[]
null
[]
package model; public class Elf { public String name; public Elf(String name) { // Sortierfunktion ?? // TODO Auto-generated constructor stub this.name = name; } public Elf() { } }
203
0.635468
0.635468
17
10.941176
11.8146
41
false
false
0
0
0
0
0
0
1.117647
false
false
5
d89d02cb75c7f6909e0a5bfebe157d0fcd0867ce
34,402,688,060,407
6ca050758d847e56ae3631aa0ae90848daaad8fc
/src/main/java/limestone/interfaces/TaskRepository.java
0693a0f019756e04d1be96ace18d9e5c3d4e399b
[]
no_license
NickAndreew/Limestone
https://github.com/NickAndreew/Limestone
96e9b791b6818e0345938a38aa3bdd75077d02f8
0001ef381f5868ea010367587061cee27a6dd90a
refs/heads/master
"2020-03-26T15:23:20.566000"
"2018-08-18T20:50:25"
"2018-08-18T20:50:25"
145,040,090
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package limestone.interfaces; import limestone.instances.Task; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface TaskRepository extends MongoRepository<Task, String> { Optional<Task> findById(String id); List<Task> getByStatus(String status); }
UTF-8
Java
405
java
TaskRepository.java
Java
[]
null
[]
package limestone.interfaces; import limestone.instances.Task; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface TaskRepository extends MongoRepository<Task, String> { Optional<Task> findById(String id); List<Task> getByStatus(String status); }
405
0.809877
0.809877
16
24.3125
23.592155
71
false
false
0
0
0
0
0
0
0.5625
false
false
5
2bcd95a07427cf51e08a58d092356a3f35650b15
2,585,570,374,055
5ca15beacc3d6e4f1deb96d930e8744466caf735
/src/analysis/RouteAnalyser.java
6610182c67038aafbee158e55bc4bf521ea558da
[]
no_license
MarcoKe/VerologChallenge
https://github.com/MarcoKe/VerologChallenge
9a068e05027ffbc953ae0af7c4879bb7a6150168
8d48e7c2d84596369e636903e4ff3ac9cf3f24b8
refs/heads/master
"2021-03-27T10:17:07.648000"
"2017-06-26T16:03:19"
"2017-06-26T16:03:19"
82,057,264
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package analysis; import java.util.List; import data.DataController; import data.DayInformation; import data.Global; import data.Location; import data.StrategyController; import data.Tool; import data.VehicleAction; import data.VehicleAction.Action; import data.VehicleInformation; public class RouteAnalyser { private DataController data; public RouteAnalyser(DataController data) { this.data = data; } public int getConstraintViolations(StrategyController solution) { return getDistanceViolations(solution) + getMaxToolViolations(solution); } public int getDistanceViolations(StrategyController solution) { int maxDistance = data.getVehicle().getMaxDistance(); int violations = 0; for (DayInformation day : solution.getDays()) { for (VehicleInformation vehicle : day.getVehicleInformationList()) { int vehicleDistance = routeDistance(vehicle.getRoute()); if (vehicleDistance > maxDistance) { violations += vehicleDistance - maxDistance; } } } return violations; } public int routeDistance(List<VehicleAction> actions) { Global g = data.getGlobal(); Location depot = data.getLocationList().get(0); int distance = 0; for (int i = 1; i < actions.size(); i++) { Location loc1 = actions.get(i-1).getVehicleAction() == Action.TO_DEPOT ? depot : actions.get(i-1).getRequest().getLocation(); Location loc2 = actions.get(i).getVehicleAction() == Action.TO_DEPOT ? depot : actions.get(i).getRequest().getLocation(); distance += g.computeDistance(loc1, loc2); } return distance; } public int getMaxToolViolations(StrategyController solution) { int violations = 0; int numTools = data.getToolList().size(); int[] maxTools = new int[numTools]; for (Tool tool : data.getToolList()) { maxTools[tool.getId()-1] = tool.getMaxAvailable(); } // calculate tool usage int[][] used = new int[numTools][solution.getDays().size()]; for (DayInformation day : solution.getDays()) { for (VehicleInformation vehicle : day.getVehicleInformationList()) { int[] vehicleToolUsage = getVehicleToolUsage(vehicle); for (int i = 0; i < vehicleToolUsage.length; i++) { used[i][day.getDay()-1] += vehicleToolUsage[i]; } } } //calculate in between days (in between delivery & pickup) for (DayInformation day : solution.getDays()) { for (VehicleInformation vehicle : day.getVehicleInformationList()) { for (VehicleAction action : vehicle.getRoute()) { if (action.getVehicleAction() == Action.LOAD_AND_DELIVER) { int start = day.getDay(); int finish = start + action.getRequest().getUsageTime(); for (int i = start+1; i < finish; i++) { used[action.getRequest().getTool().getId()-1][i-1] += action.getRequest().getAmountOfTools(); } } } } } for (int day = 0; day < solution.getDays().size(); day++) { for (int i = 0; i < used.length; i++) { if(used[i][day] > maxTools[i]) { violations += used[i][day] - maxTools[i]; } } } return violations; } public int[] getVehicleToolUsage(VehicleInformation vehicle) { int numTools = data.getToolList().size(); int[] toolsInVehicle = new int[numTools]; int[] needed = new int[numTools]; for (VehicleAction action : vehicle.getRoute()) { if (action.getVehicleAction() == Action.PICK_UP) { Tool tool = action.getRequest().getTool(); toolsInVehicle[tool.getId()-1] += action.getRequest().getAmountOfTools(); needed[tool.getId()-1] += action.getRequest().getAmountOfTools(); } else if (action.getVehicleAction() == Action.LOAD_AND_DELIVER) { Tool tool = action.getRequest().getTool(); int common = Math.min(action.getRequest().getAmountOfTools(), toolsInVehicle[tool.getId()-1]); toolsInVehicle[tool.getId()-1] -= common; needed[tool.getId()-1] += action.getRequest().getAmountOfTools() - common; } } return needed; } }
UTF-8
Java
3,979
java
RouteAnalyser.java
Java
[]
null
[]
package analysis; import java.util.List; import data.DataController; import data.DayInformation; import data.Global; import data.Location; import data.StrategyController; import data.Tool; import data.VehicleAction; import data.VehicleAction.Action; import data.VehicleInformation; public class RouteAnalyser { private DataController data; public RouteAnalyser(DataController data) { this.data = data; } public int getConstraintViolations(StrategyController solution) { return getDistanceViolations(solution) + getMaxToolViolations(solution); } public int getDistanceViolations(StrategyController solution) { int maxDistance = data.getVehicle().getMaxDistance(); int violations = 0; for (DayInformation day : solution.getDays()) { for (VehicleInformation vehicle : day.getVehicleInformationList()) { int vehicleDistance = routeDistance(vehicle.getRoute()); if (vehicleDistance > maxDistance) { violations += vehicleDistance - maxDistance; } } } return violations; } public int routeDistance(List<VehicleAction> actions) { Global g = data.getGlobal(); Location depot = data.getLocationList().get(0); int distance = 0; for (int i = 1; i < actions.size(); i++) { Location loc1 = actions.get(i-1).getVehicleAction() == Action.TO_DEPOT ? depot : actions.get(i-1).getRequest().getLocation(); Location loc2 = actions.get(i).getVehicleAction() == Action.TO_DEPOT ? depot : actions.get(i).getRequest().getLocation(); distance += g.computeDistance(loc1, loc2); } return distance; } public int getMaxToolViolations(StrategyController solution) { int violations = 0; int numTools = data.getToolList().size(); int[] maxTools = new int[numTools]; for (Tool tool : data.getToolList()) { maxTools[tool.getId()-1] = tool.getMaxAvailable(); } // calculate tool usage int[][] used = new int[numTools][solution.getDays().size()]; for (DayInformation day : solution.getDays()) { for (VehicleInformation vehicle : day.getVehicleInformationList()) { int[] vehicleToolUsage = getVehicleToolUsage(vehicle); for (int i = 0; i < vehicleToolUsage.length; i++) { used[i][day.getDay()-1] += vehicleToolUsage[i]; } } } //calculate in between days (in between delivery & pickup) for (DayInformation day : solution.getDays()) { for (VehicleInformation vehicle : day.getVehicleInformationList()) { for (VehicleAction action : vehicle.getRoute()) { if (action.getVehicleAction() == Action.LOAD_AND_DELIVER) { int start = day.getDay(); int finish = start + action.getRequest().getUsageTime(); for (int i = start+1; i < finish; i++) { used[action.getRequest().getTool().getId()-1][i-1] += action.getRequest().getAmountOfTools(); } } } } } for (int day = 0; day < solution.getDays().size(); day++) { for (int i = 0; i < used.length; i++) { if(used[i][day] > maxTools[i]) { violations += used[i][day] - maxTools[i]; } } } return violations; } public int[] getVehicleToolUsage(VehicleInformation vehicle) { int numTools = data.getToolList().size(); int[] toolsInVehicle = new int[numTools]; int[] needed = new int[numTools]; for (VehicleAction action : vehicle.getRoute()) { if (action.getVehicleAction() == Action.PICK_UP) { Tool tool = action.getRequest().getTool(); toolsInVehicle[tool.getId()-1] += action.getRequest().getAmountOfTools(); needed[tool.getId()-1] += action.getRequest().getAmountOfTools(); } else if (action.getVehicleAction() == Action.LOAD_AND_DELIVER) { Tool tool = action.getRequest().getTool(); int common = Math.min(action.getRequest().getAmountOfTools(), toolsInVehicle[tool.getId()-1]); toolsInVehicle[tool.getId()-1] -= common; needed[tool.getId()-1] += action.getRequest().getAmountOfTools() - common; } } return needed; } }
3,979
0.669515
0.663483
129
29.844961
28.517763
128
false
false
0
0
0
0
0
0
2.914729
false
false
5
4fa60c78b12680865fe209a1c45204087330e1db
32,839,319,972,638
b938e8b8117eb3ba37e116b4510aa3a8fb79d4a2
/src/test/java/com/tribesbackend/tribes/TribesKingdomTest.java
513208974849fdc15cbffd29f65596aedea0a42e
[]
no_license
green-fox-academy/vulpes-tribes-backend
https://github.com/green-fox-academy/vulpes-tribes-backend
acca72d8ae54a3a2a2615f411712ca02f4795186
21154d4c0d4fcb2c8e2a1ac1f442b8075dcc8337
refs/heads/master
"2020-04-10T17:30:03.797000"
"2019-01-24T14:39:17"
"2019-01-24T14:39:17"
161,176,136
1
1
null
false
"2019-02-07T13:06:53"
"2018-12-10T13:04:20"
"2019-01-24T14:39:19"
"2019-02-07T13:06:53"
849
1
1
0
Java
false
null
package com.tribesbackend.tribes; import com.tribesbackend.tribes.tribeskingdom.model.Kingdom; import com.tribesbackend.tribes.tribeskingdom.model.KingdomModelHelpersMethods; import com.tribesbackend.tribes.tribesuser.model.TribesUser; import org.junit.Test; import static org.junit.Assert.assertEquals; public class TribesKingdomTest { TribesUser testUser; @Test public void kingdomNameIsValid(){ Kingdom kingdom = new Kingdom( "kingdom", testUser ); assertEquals(true, KingdomModelHelpersMethods.isValid(kingdom)); } @Test public void kingdomNameIsNotValid(){ Kingdom kingdom = new Kingdom( null, testUser ); assertEquals( false, KingdomModelHelpersMethods.isValid(kingdom) ); } }
UTF-8
Java
749
java
TribesKingdomTest.java
Java
[]
null
[]
package com.tribesbackend.tribes; import com.tribesbackend.tribes.tribeskingdom.model.Kingdom; import com.tribesbackend.tribes.tribeskingdom.model.KingdomModelHelpersMethods; import com.tribesbackend.tribes.tribesuser.model.TribesUser; import org.junit.Test; import static org.junit.Assert.assertEquals; public class TribesKingdomTest { TribesUser testUser; @Test public void kingdomNameIsValid(){ Kingdom kingdom = new Kingdom( "kingdom", testUser ); assertEquals(true, KingdomModelHelpersMethods.isValid(kingdom)); } @Test public void kingdomNameIsNotValid(){ Kingdom kingdom = new Kingdom( null, testUser ); assertEquals( false, KingdomModelHelpersMethods.isValid(kingdom) ); } }
749
0.753004
0.753004
25
28.959999
27.152134
79
false
false
0
0
0
0
0
0
0.6
false
false
5
ca815dc50860050c4d7409e504b39409b93d2308
35,201,551,971,501
28248cb38a36ffe877f49aceb2e3be93f34dbe22
/src/main/java/Bot/User.java
be570a4aee8167ab641902a121924ed883c7f4cd
[ "MIT" ]
permissive
TemirkhanN/twitch-chat-bot
https://github.com/TemirkhanN/twitch-chat-bot
1f904f239de13a4c507b847cc3933cee8a21f4d2
b40be97053216e434346ec71fa89a52f82824dbf
refs/heads/master
"2021-04-14T06:40:41.560000"
"2020-11-30T01:47:05"
"2020-11-30T01:47:05"
249,213,952
1
3
MIT
false
"2020-05-04T10:09:33"
"2020-03-22T15:34:50"
"2020-04-27T17:23:23"
"2020-05-02T15:33:13"
29,449
1
3
0
Java
false
false
package Bot; public class User { private String name; private boolean isAdmin; public User(String name) { this.name = name; this.isAdmin = false; } public User(String name, boolean isAdmin) { this.name = name; this.isAdmin = isAdmin; } public String getName() { return name; } public boolean isAdmin() { return isAdmin; } }
UTF-8
Java
444
java
User.java
Java
[]
null
[]
package Bot; public class User { private String name; private boolean isAdmin; public User(String name) { this.name = name; this.isAdmin = false; } public User(String name, boolean isAdmin) { this.name = name; this.isAdmin = isAdmin; } public String getName() { return name; } public boolean isAdmin() { return isAdmin; } }
444
0.533784
0.533784
24
16.5
13.573872
47
false
false
0
0
0
0
0
0
0.416667
false
false
5
133e240cd212a863ef3ae5aab7bc4b3a69a30e8d
16,381,005,325,843
855413ecb28940ffcff43315e526855d1b714ec4
/2017/Server/ServerLearn/src/main/java/com/senzer/serverlearn/bean/po/Location.java
f412128ffd133dd465af492eb7a89136f5673734
[]
no_license
SenzerZheng/Plains
https://github.com/SenzerZheng/Plains
a3c3cd0814da18cf5fea02fa6e730e6b420b5418
e07749fc420c84e5b7ec514df267457627b0058a
refs/heads/master
"2021-01-17T23:42:12.778000"
"2021-01-07T07:44:09"
"2021-01-07T07:44:09"
56,959,702
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.senzer.serverlearn.bean.po; import lombok.Data; /** * Created by spider on 2017/7/12. */ @Data public class Location { private String id; private String locationInfo; }
UTF-8
Java
193
java
Location.java
Java
[ { "context": "n.bean.po;\n\nimport lombok.Data;\n\n/**\n * Created by spider on 2017/7/12.\n */\n@Data\npublic class Location {\n ", "end": 86, "score": 0.9993008971214294, "start": 80, "tag": "USERNAME", "value": "spider" } ]
null
[]
package com.senzer.serverlearn.bean.po; import lombok.Data; /** * Created by spider on 2017/7/12. */ @Data public class Location { private String id; private String locationInfo; }
193
0.704663
0.668394
12
15.083333
14.109444
39
false
false
0
0
0
0
0
0
0.333333
false
false
5
9f7fa418774ae4135cb09709dc8eb30681a5fde8
29,128,468,256,757
e75c33b64928d4d86439ae35dc950f4902bf7b67
/app/src/main/java/com/example/mpaiproject/CustomPackageActivity.java
78a5a8418634d9ad2e7788419bacaa5c32babe05
[]
no_license
IrinaDobre/android-mdas
https://github.com/IrinaDobre/android-mdas
cfc3b98cee06c6e0d917830984e758f929d71d4e
80e836534ef2518685f4fffc16a8db126153f011
refs/heads/master
"2023-02-10T17:22:31.251000"
"2021-01-10T10:13:35"
"2021-01-10T10:13:35"
311,775,998
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.mpaiproject; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import com.example.mpaiproject.models.designpatterns.bridge.Box; import com.example.mpaiproject.models.designpatterns.bridge.LoggedUser; import com.example.mpaiproject.models.designpatterns.bridge.OtherRecipient; import com.example.mpaiproject.models.designpatterns.bridge.PackageRecipient; import com.example.mpaiproject.models.designpatterns.bridge.WrappingPaper; public class CustomPackageActivity extends AppCompatActivity { private RadioGroup radioGroupRecipient; private RadioGroup radioGroupPackage; String recipient = ""; String pack = ""; RadioButton rbRecipient; RadioButton rbPackage; Button buttonAddToOrder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custom_package); radioGroupRecipient = findViewById(R.id.radioGroupRecipient); radioGroupPackage = findViewById(R.id.radioGroupPackage); buttonAddToOrder = findViewById(R.id.buttonAddOrder); radioGroupRecipient.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { RadioButton rb = radioGroupRecipient.findViewById(i); recipient = rb.getText().toString(); } }); radioGroupPackage.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { RadioButton rb = radioGroupPackage.findViewById(i); pack = rb.getText().toString(); if(!recipient.equals("") && !pack.equals("")){ buttonAddToOrder.setEnabled(true); } } }); } public void applyPackage(View view){ PackageRecipient packageRecipient; if(recipient.equals("Myself")){ if(pack.equals("Box")){ packageRecipient = new LoggedUser(new Box()); CartDetailsActivity.SELECTED_TYPE_OF_PACKAGE = "Box"; } else { packageRecipient = new LoggedUser(new WrappingPaper()); CartDetailsActivity.SELECTED_TYPE_OF_PACKAGE = "Wrapping paper"; } CartDetailsActivity.result = packageRecipient.set(); Log.d("DESIGN_PATTERN_BRIDGE", CartDetailsActivity.result); } else { if(pack.equals("Box")){ packageRecipient = new OtherRecipient(new Box()); CartDetailsActivity.SELECTED_TYPE_OF_PACKAGE = "Box"; } else { packageRecipient = new OtherRecipient(new WrappingPaper()); CartDetailsActivity.SELECTED_TYPE_OF_PACKAGE = "Wrapping paper"; } CartDetailsActivity.result = packageRecipient.set(); Log.d("DESIGN_PATTERN_BRIDGE", CartDetailsActivity.result); } if(!CartDetailsActivity.result.equals("")){ finish(); } } }
UTF-8
Java
3,380
java
CustomPackageActivity.java
Java
[]
null
[]
package com.example.mpaiproject; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import com.example.mpaiproject.models.designpatterns.bridge.Box; import com.example.mpaiproject.models.designpatterns.bridge.LoggedUser; import com.example.mpaiproject.models.designpatterns.bridge.OtherRecipient; import com.example.mpaiproject.models.designpatterns.bridge.PackageRecipient; import com.example.mpaiproject.models.designpatterns.bridge.WrappingPaper; public class CustomPackageActivity extends AppCompatActivity { private RadioGroup radioGroupRecipient; private RadioGroup radioGroupPackage; String recipient = ""; String pack = ""; RadioButton rbRecipient; RadioButton rbPackage; Button buttonAddToOrder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custom_package); radioGroupRecipient = findViewById(R.id.radioGroupRecipient); radioGroupPackage = findViewById(R.id.radioGroupPackage); buttonAddToOrder = findViewById(R.id.buttonAddOrder); radioGroupRecipient.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { RadioButton rb = radioGroupRecipient.findViewById(i); recipient = rb.getText().toString(); } }); radioGroupPackage.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { RadioButton rb = radioGroupPackage.findViewById(i); pack = rb.getText().toString(); if(!recipient.equals("") && !pack.equals("")){ buttonAddToOrder.setEnabled(true); } } }); } public void applyPackage(View view){ PackageRecipient packageRecipient; if(recipient.equals("Myself")){ if(pack.equals("Box")){ packageRecipient = new LoggedUser(new Box()); CartDetailsActivity.SELECTED_TYPE_OF_PACKAGE = "Box"; } else { packageRecipient = new LoggedUser(new WrappingPaper()); CartDetailsActivity.SELECTED_TYPE_OF_PACKAGE = "Wrapping paper"; } CartDetailsActivity.result = packageRecipient.set(); Log.d("DESIGN_PATTERN_BRIDGE", CartDetailsActivity.result); } else { if(pack.equals("Box")){ packageRecipient = new OtherRecipient(new Box()); CartDetailsActivity.SELECTED_TYPE_OF_PACKAGE = "Box"; } else { packageRecipient = new OtherRecipient(new WrappingPaper()); CartDetailsActivity.SELECTED_TYPE_OF_PACKAGE = "Wrapping paper"; } CartDetailsActivity.result = packageRecipient.set(); Log.d("DESIGN_PATTERN_BRIDGE", CartDetailsActivity.result); } if(!CartDetailsActivity.result.equals("")){ finish(); } } }
3,380
0.652071
0.652071
91
36.153847
27.861874
97
false
false
0
0
0
0
0
0
0.549451
false
false
5
22e5ff2b93bd684d6ba46964c0c9b7471c8ddb22
34,694,745,849,507
bfb29dee8abb61aad91c31b0c90a675a0631ed62
/app/src/main/java/project/fiesta/padraoCadastro.java
b83312300b2c250150dbed3da62db526f841b797
[]
no_license
fernando1910/Fiesta
https://github.com/fernando1910/Fiesta
276a758c6e22079f247395b38d9f0fbb48a50c71
6b1bed10c2aa1ec945ae033e5b1d49b19a31a589
refs/heads/master
"2015-08-21T02:48:39.515000"
"2015-03-03T02:33:33"
"2015-03-03T02:33:33"
31,575,429
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package project.fiesta; /** * Created by Fernando on 02/03/2015. */ public class padraoCadastro { }
UTF-8
Java
103
java
padraoCadastro.java
Java
[ { "context": "package project.fiesta;\n\n/**\n * Created by Fernando on 02/03/2015.\n */\npublic class padraoCadastro {\n", "end": 51, "score": 0.9998248219490051, "start": 43, "tag": "NAME", "value": "Fernando" } ]
null
[]
package project.fiesta; /** * Created by Fernando on 02/03/2015. */ public class padraoCadastro { }
103
0.699029
0.621359
7
13.714286
14.349856
37
false
false
0
0
0
0
0
0
0.142857
false
false
7
ea22ae05f2295e9b1055d1e63070e6d805ef3faa
11,690,901,033,706
d94d3df17d228bfec22557ac3d0f6bf1599aa2a9
/src/me/yamas/tools/commands/utils/Executor.java
89b3ffcda521b21d32637597501189bcf843fd32
[]
no_license
Yamaskyy/YamasTools
https://github.com/Yamaskyy/YamasTools
af359b8d735547594b29f888cb024aa8b6ff98a9
a1bdd3234df8945ee8cbaeb31015840989ccb40b
refs/heads/master
"2021-05-06T23:15:05.425000"
"2017-12-04T17:35:32"
"2017-12-04T17:35:32"
112,958,971
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.yamas.tools.commands.utils; import org.bukkit.command.CommandSender; public interface Executor { public void execute(CommandSender sender, String[] args); }
UTF-8
Java
172
java
Executor.java
Java
[]
null
[]
package me.yamas.tools.commands.utils; import org.bukkit.command.CommandSender; public interface Executor { public void execute(CommandSender sender, String[] args); }
172
0.790698
0.790698
8
20.5
21.725561
58
false
false
0
0
0
0
0
0
0.625
false
false
7
4325daefc8dfe229c4d738b3e34236381b7fc476
34,823,594,854,054
6c795945a1615ab1ee8dd2df72d228448816827d
/src/main/java/com/mmt/lib/models/Library.java
1c41d1cf752c1a2bd975189a8e7f3b4e5b012efb
[]
no_license
aishwat/mmtSpring
https://github.com/aishwat/mmtSpring
7eafc5f7ca6f5cd2d02def850ef8730cb9e070d2
8ff2856362f0752b872aacaf5e8339c83ff0a7ae
refs/heads/master
"2020-09-11T12:20:09.291000"
"2019-11-16T07:13:19"
"2019-11-16T07:13:19"
222,061,747
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mmt.lib.models; import java.util.HashMap; import java.util.Map; public class Library { public Map<Integer, Book> getBooks() { return books; } public void setBooks(Map<Integer, Book> books) { this.books = books; } public Map<Integer, Account> getAccounts() { return accounts; } public void setAccounts(Map<Integer, Account> accounts) { this.accounts = accounts; } // account, book private Map<Integer, Book> books; private Map<Integer, Account> accounts; public Library() { books = new HashMap<Integer, Book>(); accounts = new HashMap<Integer, Account>(); } }
UTF-8
Java
681
java
Library.java
Java
[]
null
[]
package com.mmt.lib.models; import java.util.HashMap; import java.util.Map; public class Library { public Map<Integer, Book> getBooks() { return books; } public void setBooks(Map<Integer, Book> books) { this.books = books; } public Map<Integer, Account> getAccounts() { return accounts; } public void setAccounts(Map<Integer, Account> accounts) { this.accounts = accounts; } // account, book private Map<Integer, Book> books; private Map<Integer, Account> accounts; public Library() { books = new HashMap<Integer, Book>(); accounts = new HashMap<Integer, Account>(); } }
681
0.619677
0.619677
32
20.3125
18.863718
61
false
false
0
0
0
0
0
0
0.625
false
false
7
da6ed72603a8b6c7f02ab0dfe30f1d5016052dae
11,149,735,104,379
573e0f07b3b76043f82a91d987a4cffe66784d54
/Week2/LaurAlejandraC/spring-rest/src/main/java/bootcamp/springrest/studentFilter/controller/StudentFilter.java
efebdd7d24b05fe9d0e8201f5ecbb45de08b9c4c
[ "Apache-2.0" ]
permissive
globant-scalable-platforms/bootcamp-java-spring-may-2019
https://github.com/globant-scalable-platforms/bootcamp-java-spring-may-2019
0570928af7b5628e8ca8dd7165f06fef40561276
cdbbc8a5fcb62e704848cf3c4c153d849968c9f6
refs/heads/master
"2020-05-21T11:00:47.009000"
"2019-06-20T22:26:57"
"2019-06-20T22:26:57"
186,023,330
0
4
Apache-2.0
false
"2019-07-19T19:45:40"
"2019-05-10T16:51:44"
"2019-06-20T22:27:03"
"2019-07-19T19:42:55"
5,088
0
3
9
Java
false
false
package bootcamp.springrest.studentFilter.controller; import bootcamp.springrest.studentFilter.data.StudentRepository; import bootcamp.springrest.studentFilter.domain.Student; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; @RestController @RequestMapping("/students") public class StudentFilter { private StudentRepository studentRepository; Logger logger = LoggerFactory.getLogger(StudentFilter.class); public StudentFilter(){ this.studentRepository = new StudentRepository(); } @GetMapping public ResponseEntity<List<Student>> getFilteredStudents(@RequestParam Map<String, String> filters){ Stream<Student> stream = studentRepository.getStudents().stream(); if(filters.containsKey("name")){ stream = stream.filter(s -> s.getName().equals(filters.get("name"))); } if(filters.containsKey("age")){ try{ Integer age = Integer.parseInt(filters.get("age")); stream = stream.filter(s -> s.getAge().equals(age)); }catch (Exception ex){ logger.error("Age filter not applied due to: " + ex.toString()); } } if(filters.containsKey("identification")){ stream = stream.filter(s -> s.getIdentification().equals(filters.get("identification"))); } return new ResponseEntity<>(stream.collect(Collectors.toList()), HttpStatus.OK); } }
UTF-8
Java
1,896
java
StudentFilter.java
Java
[]
null
[]
package bootcamp.springrest.studentFilter.controller; import bootcamp.springrest.studentFilter.data.StudentRepository; import bootcamp.springrest.studentFilter.domain.Student; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; @RestController @RequestMapping("/students") public class StudentFilter { private StudentRepository studentRepository; Logger logger = LoggerFactory.getLogger(StudentFilter.class); public StudentFilter(){ this.studentRepository = new StudentRepository(); } @GetMapping public ResponseEntity<List<Student>> getFilteredStudents(@RequestParam Map<String, String> filters){ Stream<Student> stream = studentRepository.getStudents().stream(); if(filters.containsKey("name")){ stream = stream.filter(s -> s.getName().equals(filters.get("name"))); } if(filters.containsKey("age")){ try{ Integer age = Integer.parseInt(filters.get("age")); stream = stream.filter(s -> s.getAge().equals(age)); }catch (Exception ex){ logger.error("Age filter not applied due to: " + ex.toString()); } } if(filters.containsKey("identification")){ stream = stream.filter(s -> s.getIdentification().equals(filters.get("identification"))); } return new ResponseEntity<>(stream.collect(Collectors.toList()), HttpStatus.OK); } }
1,896
0.708861
0.707806
51
36.176472
29.0319
104
false
false
0
0
0
0
0
0
0.529412
false
false
7
a67d27b58db90c16f9872903a45a8e837d0f753f
34,230,889,390,368
5e0dbc3f9066a39280123b44ca51abcbf7387871
/Android/app/src/main/java/com/srm/srmhack/LiveActivity.java
2fc78a4baefbb57a800923d766c1dfec8f141d03
[]
no_license
SRM-Hackathon/Team-Gen-Y
https://github.com/SRM-Hackathon/Team-Gen-Y
c15063fc00d9b7f6ea24eba89d25c520fc5def19
a5f7244a199a14f649bc8a4c79558916c6a491b5
refs/heads/Android
"2022-12-14T20:58:59.172000"
"2019-10-13T07:23:45"
"2019-10-13T07:23:45"
214,111,062
0
0
null
false
"2022-12-11T09:02:46"
"2019-10-10T07:03:32"
"2019-10-13T07:23:47"
"2022-12-11T09:02:46"
3,056
0
0
5
Jupyter Notebook
false
false
package com.srm.srmhack; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import org.w3c.dom.Text; import java.util.ArrayList; public class LiveActivity extends AppCompatActivity { ArrayList arrayList; Toolbar toolbar; ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_live); toolbar = findViewById(R.id.toolbarTrip); toolbar.setTitle(""); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); arrayList = new ArrayList(); arrayList.add("Day"); arrayList.add("Loc"); arrayList.add("link"); arrayList.add("Stay"); arrayList.add("link"); arrayList.add("Stay"); arrayList.add("link"); arrayList.add("Stay"); arrayList.add("Day"); arrayList.add("Loc"); arrayList.add("link"); arrayList.add("Stay"); arrayList.add("link"); arrayList.add("Stay"); listView = findViewById(R.id.listMyTrips); listView.setAdapter(new CustomAdapter()); } public class CustomAdapter extends BaseAdapter { @Override public int getCount() { return arrayList.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (arrayList.get(position).equals("Day")) { convertView = getLayoutInflater().inflate(R.layout.day_list, null); } else if (arrayList.get(position).equals("Loc")) { convertView = getLayoutInflater().inflate(R.layout.location_trip_list, null); TextView imageView = convertView.findViewById(R.id.editImage); } else if (arrayList.get(position).equals("link")) { convertView = getLayoutInflater().inflate(R.layout.time_list, null); RelativeLayout relativeLayout = convertView.findViewById(R.id.plusButton); relativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(LiveActivity.this); View view = getLayoutInflater().inflate(R.layout.details_dialog, null); builder.setView(view); builder.create(); builder.show(); } }); } else if (arrayList.get(position).equals("Stay")) { convertView = getLayoutInflater().inflate(R.layout.stay_trip_list, null); ImageView imageView = convertView.findViewById(R.id.stayImage); Glide.with(LiveActivity.this).load("https://upload.wikimedia.org/wikipedia/commons/b/b3/Everest_North_Face_toward_Base_Camp_Tibet_Luca_Galuzzi_2006_%28square%29.jpg").into(imageView); TextView editImage = convertView.findViewById(R.id.editImage); } return convertView; } } }
UTF-8
Java
3,720
java
LiveActivity.java
Java
[]
null
[]
package com.srm.srmhack; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import org.w3c.dom.Text; import java.util.ArrayList; public class LiveActivity extends AppCompatActivity { ArrayList arrayList; Toolbar toolbar; ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_live); toolbar = findViewById(R.id.toolbarTrip); toolbar.setTitle(""); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); arrayList = new ArrayList(); arrayList.add("Day"); arrayList.add("Loc"); arrayList.add("link"); arrayList.add("Stay"); arrayList.add("link"); arrayList.add("Stay"); arrayList.add("link"); arrayList.add("Stay"); arrayList.add("Day"); arrayList.add("Loc"); arrayList.add("link"); arrayList.add("Stay"); arrayList.add("link"); arrayList.add("Stay"); listView = findViewById(R.id.listMyTrips); listView.setAdapter(new CustomAdapter()); } public class CustomAdapter extends BaseAdapter { @Override public int getCount() { return arrayList.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (arrayList.get(position).equals("Day")) { convertView = getLayoutInflater().inflate(R.layout.day_list, null); } else if (arrayList.get(position).equals("Loc")) { convertView = getLayoutInflater().inflate(R.layout.location_trip_list, null); TextView imageView = convertView.findViewById(R.id.editImage); } else if (arrayList.get(position).equals("link")) { convertView = getLayoutInflater().inflate(R.layout.time_list, null); RelativeLayout relativeLayout = convertView.findViewById(R.id.plusButton); relativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(LiveActivity.this); View view = getLayoutInflater().inflate(R.layout.details_dialog, null); builder.setView(view); builder.create(); builder.show(); } }); } else if (arrayList.get(position).equals("Stay")) { convertView = getLayoutInflater().inflate(R.layout.stay_trip_list, null); ImageView imageView = convertView.findViewById(R.id.stayImage); Glide.with(LiveActivity.this).load("https://upload.wikimedia.org/wikipedia/commons/b/b3/Everest_North_Face_toward_Base_Camp_Tibet_Luca_Galuzzi_2006_%28square%29.jpg").into(imageView); TextView editImage = convertView.findViewById(R.id.editImage); } return convertView; } } }
3,720
0.61828
0.615323
105
34.42857
30.110228
199
false
false
0
0
0
0
0
0
0.638095
false
false
7
69809db87cee0c29cbd50330de71c2a18bbcef1b
29,807,073,102,130
373956b2e928eca674018f3329146c983d6e873b
/app/src/main/java/me/org/kudagotest/activity/fragment/CommentFragment.java
7742d87b94dac2d0b4047e1ecbf0ba6e4bf187a0
[]
no_license
smbduknow/KudaGoTest
https://github.com/smbduknow/KudaGoTest
053a81f6486a7e9582a88a7bd7b7a6d10a663bbe
297f9709020946dc546e6db8f2e2ece887dd6597
refs/heads/master
"2016-08-07T14:00:12.983000"
"2015-07-10T19:07:01"
"2015-07-10T19:07:01"
38,781,817
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.org.kudagotest.activity.fragment; import android.graphics.Point; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import java.util.List; import me.org.kudagotest.R; import me.org.kudagotest.activity.adapter.CommentRecyclerAdapter; import me.org.kudagotest.activity.loader.CommentListLoader; import me.org.kudagotest.model.Comment; import me.org.kudagotest.view.WrapperLinearLayoutManager; public class CommentFragment extends RecyclerViewFragment implements LoaderManager.LoaderCallbacks<List<Comment>> { private static final String ARG_loaderId = "loaderId"; private static final String ARG_categoryId = "categoryId"; private int screenHeight = 0; public static CommentFragment newInstance( Integer loaderId, Long categoryId ) { CommentFragment fragment = new CommentFragment(); Bundle args = new Bundle(); args.putInt(ARG_loaderId, loaderId); args.putLong(ARG_categoryId, categoryId); fragment.setArguments(args); return fragment; } private int getLoaderId(){ return getArguments().getInt(ARG_loaderId, 0); } private Long getCategoryId(){ return getArguments().getLong(ARG_categoryId); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_comment, null); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setLayoutManager(new WrapperLinearLayoutManager(getActivity())); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getLoaderManager().initLoader(getLoaderId(), null, this).forceLoad(); Point size = new Point(); getActivity().getWindowManager().getDefaultDisplay().getSize(size); screenHeight = size.y; } @Override public Loader<List<Comment>> onCreateLoader(int id, Bundle args) { return new CommentListLoader(getActivity(), getCategoryId()); } @Override public void onLoadFinished(Loader<List<Comment>> loader, List<Comment> data) { setAdapter(new CommentRecyclerAdapter(getActivity(), data)); setListShown(true); final CategoryFragment parentFragment = (CategoryFragment)getParentFragment(); parentFragment.getScrollView().getViewTreeObserver() .addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { if(getView() != null) { int[] location = new int[2]; getView().getLocationOnScreen(location); parentFragment.setEditCommentViewVisible(screenHeight>0 && location[1] < screenHeight-parentFragment.getEditCommentView().getHeight()); } } }); } @Override public void onLoaderReset(Loader<List<Comment>> loader) {} }
UTF-8
Java
3,381
java
CommentFragment.java
Java
[]
null
[]
package me.org.kudagotest.activity.fragment; import android.graphics.Point; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import java.util.List; import me.org.kudagotest.R; import me.org.kudagotest.activity.adapter.CommentRecyclerAdapter; import me.org.kudagotest.activity.loader.CommentListLoader; import me.org.kudagotest.model.Comment; import me.org.kudagotest.view.WrapperLinearLayoutManager; public class CommentFragment extends RecyclerViewFragment implements LoaderManager.LoaderCallbacks<List<Comment>> { private static final String ARG_loaderId = "loaderId"; private static final String ARG_categoryId = "categoryId"; private int screenHeight = 0; public static CommentFragment newInstance( Integer loaderId, Long categoryId ) { CommentFragment fragment = new CommentFragment(); Bundle args = new Bundle(); args.putInt(ARG_loaderId, loaderId); args.putLong(ARG_categoryId, categoryId); fragment.setArguments(args); return fragment; } private int getLoaderId(){ return getArguments().getInt(ARG_loaderId, 0); } private Long getCategoryId(){ return getArguments().getLong(ARG_categoryId); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_comment, null); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setLayoutManager(new WrapperLinearLayoutManager(getActivity())); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getLoaderManager().initLoader(getLoaderId(), null, this).forceLoad(); Point size = new Point(); getActivity().getWindowManager().getDefaultDisplay().getSize(size); screenHeight = size.y; } @Override public Loader<List<Comment>> onCreateLoader(int id, Bundle args) { return new CommentListLoader(getActivity(), getCategoryId()); } @Override public void onLoadFinished(Loader<List<Comment>> loader, List<Comment> data) { setAdapter(new CommentRecyclerAdapter(getActivity(), data)); setListShown(true); final CategoryFragment parentFragment = (CategoryFragment)getParentFragment(); parentFragment.getScrollView().getViewTreeObserver() .addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { if(getView() != null) { int[] location = new int[2]; getView().getLocationOnScreen(location); parentFragment.setEditCommentViewVisible(screenHeight>0 && location[1] < screenHeight-parentFragment.getEditCommentView().getHeight()); } } }); } @Override public void onLoaderReset(Loader<List<Comment>> loader) {} }
3,381
0.680568
0.678497
88
37.420456
30.154421
115
false
false
0
0
0
0
0
0
0.647727
false
false
7
fc051b8bfe8793de5f01c419a598af4cae057ee0
39,109,972,216,929
204729351a46bc8d18342e131a49a8f0a059d583
/src/main/java/com/codecool/jokerchildspring/repository/GameSessionRepository.java
e53670f0010382763dfc14f9b39d123a64ca0768
[]
no_license
barnaholl/joker-child-spring
https://github.com/barnaholl/joker-child-spring
414e1846abbf1b2fc31f8a920e3622c326e029f2
14e7d426757522c98733a1372eabc5537a89cdbf
refs/heads/main
"2023-03-31T03:45:24.428000"
"2021-04-07T10:17:05"
"2021-04-07T10:17:05"
334,893,249
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.codecool.jokerchildspring.repository; import com.codecool.jokerchildspring.entity.GameSession; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; public interface GameSessionRepository extends JpaRepository<GameSession,Long> { Optional<GameSession> findByUserId(Long userId); void deleteByUserId(Long userId); GameSession getByUserId(Long userId); }
UTF-8
Java
417
java
GameSessionRepository.java
Java
[]
null
[]
package com.codecool.jokerchildspring.repository; import com.codecool.jokerchildspring.entity.GameSession; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; public interface GameSessionRepository extends JpaRepository<GameSession,Long> { Optional<GameSession> findByUserId(Long userId); void deleteByUserId(Long userId); GameSession getByUserId(Long userId); }
417
0.820144
0.820144
14
28.785715
27.370939
80
false
false
0
0
0
0
0
0
0.571429
false
false
7
282afc43d6fcab3753cf422ca4bf93b042653af8
29,807,073,100,969
bd0e9daa768b5332942b59686b9d9dcee7a668ec
/src/main/java/it/polimi/deib/provaFinale/cantiniDignani/controller/gestionePartita/GiocatoreDisconnessoException.java
4b4096727ca3ace5b05538bea486db9ee809c5a8
[]
no_license
aecant/Sheepland
https://github.com/aecant/Sheepland
f977903420843153c3d9b6c91c0640bdbf4d429c
caaa8b03eb0b4b2f8660cc46c12c38d1c558b1f8
refs/heads/master
"2020-04-08T23:36:09.540000"
"2018-12-03T16:26:02"
"2018-12-03T16:26:02"
159,832,029
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package it.polimi.deib.provaFinale.cantiniDignani.controller.gestionePartita; public class GiocatoreDisconnessoException extends Exception { private static final long serialVersionUID = 3267147905296599488L; public GiocatoreDisconnessoException() { super(); } public GiocatoreDisconnessoException(String message, Throwable cause) { super(message, cause); } public GiocatoreDisconnessoException(String message) { super(message); } public GiocatoreDisconnessoException(Throwable cause) { super(cause); } }
UTF-8
Java
528
java
GiocatoreDisconnessoException.java
Java
[]
null
[]
package it.polimi.deib.provaFinale.cantiniDignani.controller.gestionePartita; public class GiocatoreDisconnessoException extends Exception { private static final long serialVersionUID = 3267147905296599488L; public GiocatoreDisconnessoException() { super(); } public GiocatoreDisconnessoException(String message, Throwable cause) { super(message, cause); } public GiocatoreDisconnessoException(String message) { super(message); } public GiocatoreDisconnessoException(Throwable cause) { super(cause); } }
528
0.797348
0.761364
23
21.956522
27.510437
77
false
false
0
0
0
0
0
0
1.086957
false
false
7
a09325667b9dea12cf2e84551fd944243aed6536
27,049,704,080,522
b157a3f73bf10aa46cbfe29a6aa77c66c31cd5f4
/user_center/src/main/java/com/meirengu/uc/dao/CheckCodeDao.java
ef678b8c32d4915714d06ba9d9381547095d79a4
[]
no_license
JasonZhangSx/meirengu
https://github.com/JasonZhangSx/meirengu
dd53faa9e5a06f03e561c23b5806d9104e9e0bab
bf06289a1f3b3645db320b7b68dd6299e3a391ab
refs/heads/master
"2021-01-19T18:46:43.082000"
"2017-08-21T04:22:04"
"2017-08-21T04:22:04"
101,160,314
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.meirengu.uc.dao; import com.meirengu.uc.model.CheckCode; import java.util.Map; /** * 验证码数据访问对象类 * * @author Marvin * @create 2017-01-12 下午7:30 */ public interface CheckCodeDao { /** * 新增验证码 * * @param checkCode * @return */ int create(CheckCode checkCode); /** * 修改验证码 * @param checkCode * @return */ int update(CheckCode checkCode); /** * 获取验证码 * @param params * @return */ CheckCode retrieve(Map params); }
UTF-8
Java
576
java
CheckCodeDao.java
Java
[ { "context": "rt java.util.Map;\n\n/**\n * 验证码数据访问对象类\n *\n * @author Marvin\n * @create 2017-01-12 下午7:30\n */\npublic interface", "end": 132, "score": 0.9074785709381104, "start": 126, "tag": "NAME", "value": "Marvin" } ]
null
[]
package com.meirengu.uc.dao; import com.meirengu.uc.model.CheckCode; import java.util.Map; /** * 验证码数据访问对象类 * * @author Marvin * @create 2017-01-12 下午7:30 */ public interface CheckCodeDao { /** * 新增验证码 * * @param checkCode * @return */ int create(CheckCode checkCode); /** * 修改验证码 * @param checkCode * @return */ int update(CheckCode checkCode); /** * 获取验证码 * @param params * @return */ CheckCode retrieve(Map params); }
576
0.561303
0.54023
37
13.108109
11.899998
39
false
false
0
0
0
0
0
0
0.162162
false
false
7
d67365e7c0ca488f2c43aae02c94643f44d6138c
25,898,652,823,482
608b9a40a7c4c2034a7a7c5b8ab267e4e668cfec
/应用架构设计/src/main/java/xl/gcs/com/myapplication/net/NetTask.java
5ad6f5d32dd4b51f05ef358fae8111014420118e
[ "Apache-2.0" ]
permissive
xivanglei/view
https://github.com/xivanglei/view
89ed0858d2a3b8cc681c17e5db62a5e0e618f1a6
b8fb6e932aa387667cc38456212eba709542e56f
refs/heads/master
"2020-03-12T09:49:30.910000"
"2018-06-02T03:05:49"
"2018-06-02T03:05:49"
130,560,183
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package xl.gcs.com.myapplication.net; /** * Created by Administrator on 2016/12/29 0029. */ public interface NetTask<T> { void execute(T data, LoadTasksCallBack callBack); }
UTF-8
Java
182
java
NetTask.java
Java
[ { "context": "e xl.gcs.com.myapplication.net;\n\n/**\n * Created by Administrator on 2016/12/29 0029.\n */\n\npublic interface NetTask", "end": 70, "score": 0.43781569600105286, "start": 57, "tag": "NAME", "value": "Administrator" } ]
null
[]
package xl.gcs.com.myapplication.net; /** * Created by Administrator on 2016/12/29 0029. */ public interface NetTask<T> { void execute(T data, LoadTasksCallBack callBack); }
182
0.71978
0.653846
9
19.222221
20.874107
53
false
false
0
0
0
0
0
0
0.333333
false
false
7
62d17f3a275dff1c46ba71eb691d8be4bb05b7ca
34,308,198,763,796
353c42d919fdc6c0c389e911fce9181c018e253e
/ss.core/src/ss/common/path/FolderFinder.java
ce591fbdd6f10da98b86f6da93114d14e1590eaa
[]
no_license
djat/suprabrowser
https://github.com/djat/suprabrowser
ca5decc6fc27a66d7acd6068060285e6c6ac7659
110d84094e3ac6abda2af09f4f20368683103f80
refs/heads/master
"2023-05-11T06:34:57.322000"
"2014-02-08T01:31:07"
"2014-02-08T01:31:07"
10,919,796
1
2
null
false
"2014-02-08T01:31:08"
"2013-06-24T20:45:03"
"2014-02-08T01:31:07"
"2014-02-08T01:31:07"
96,344
1
1
0
Java
null
null
/** * */ package ss.common.path; import java.io.File; import java.util.ArrayList; import java.util.List; import ss.common.ListUtils; import ss.common.PathUtils; import ss.common.path.application.SupraJarApplicationFolderCondition; /** * */ public final class FolderFinder { @SuppressWarnings("unused") private static org.apache.log4j.Logger logger = ss.global.SSLogger .getLogger(FolderFinder.class); private final List<AbstractFolderCondition> conditions = new ArrayList<AbstractFolderCondition>(); private List<File> lookUpsFolders = new ArrayList<File>(); /** * */ public FolderFinder() { super(); final SupraJarApplicationFolderCondition surpaJarApplicationFolderCondition = new SupraJarApplicationFolderCondition(); addCondition(surpaJarApplicationFolderCondition); } /** * @param condition */ public void addCondition(AbstractFolderCondition condition) { this.conditions.add( condition ); } public void addLookUp( String lookUpPath ) { if ( lookUpPath != null ) { for( String path : PathUtils.splitMultiplePathes(lookUpPath ) ) { if ( !path.equals( PathUtils.SAME_FOLDER_DOT ) ) { addSingleLookUp( path ); } } } } private void addSingleLookUp( String lookUpPath ) { if ( lookUpPath == null ) { return; } File file = new File( lookUpPath ).getAbsoluteFile(); file = file.isFile() ? file.getParentFile() : file; if ( !file.exists() ) { return; } this.lookUpsFolders.add( file ); } public String find() { if (logger.isDebugEnabled()) { logger.debug( "Look ups " + ListUtils.valuesToString( this.lookUpsFolders ) ); } for( AbstractFolderCondition condition : this.conditions ) { for( File folder : this.lookUpsFolders ) { if ( condition.match(folder) ) { return folder.getAbsolutePath(); } } } return null; } /** * */ public void addLookUpClassPath( String classPath ) { } }
UTF-8
Java
1,931
java
FolderFinder.java
Java
[]
null
[]
/** * */ package ss.common.path; import java.io.File; import java.util.ArrayList; import java.util.List; import ss.common.ListUtils; import ss.common.PathUtils; import ss.common.path.application.SupraJarApplicationFolderCondition; /** * */ public final class FolderFinder { @SuppressWarnings("unused") private static org.apache.log4j.Logger logger = ss.global.SSLogger .getLogger(FolderFinder.class); private final List<AbstractFolderCondition> conditions = new ArrayList<AbstractFolderCondition>(); private List<File> lookUpsFolders = new ArrayList<File>(); /** * */ public FolderFinder() { super(); final SupraJarApplicationFolderCondition surpaJarApplicationFolderCondition = new SupraJarApplicationFolderCondition(); addCondition(surpaJarApplicationFolderCondition); } /** * @param condition */ public void addCondition(AbstractFolderCondition condition) { this.conditions.add( condition ); } public void addLookUp( String lookUpPath ) { if ( lookUpPath != null ) { for( String path : PathUtils.splitMultiplePathes(lookUpPath ) ) { if ( !path.equals( PathUtils.SAME_FOLDER_DOT ) ) { addSingleLookUp( path ); } } } } private void addSingleLookUp( String lookUpPath ) { if ( lookUpPath == null ) { return; } File file = new File( lookUpPath ).getAbsoluteFile(); file = file.isFile() ? file.getParentFile() : file; if ( !file.exists() ) { return; } this.lookUpsFolders.add( file ); } public String find() { if (logger.isDebugEnabled()) { logger.debug( "Look ups " + ListUtils.valuesToString( this.lookUpsFolders ) ); } for( AbstractFolderCondition condition : this.conditions ) { for( File folder : this.lookUpsFolders ) { if ( condition.match(folder) ) { return folder.getAbsolutePath(); } } } return null; } /** * */ public void addLookUpClassPath( String classPath ) { } }
1,931
0.690834
0.690316
88
20.931818
25.388704
121
false
false
0
0
0
0
0
0
1.647727
false
false
7
0b53e9e3daea4f2bba28b8bf0be1ada2387480e7
34,308,198,762,197
7a74f3ca59b5c19453c8ab78fdab162db5013fb2
/app/src/main/java/com/firstems/erp/data/DataConvertProvider.java
566f278a9593e38b0f0563ae01a9b8a1d96be148
[]
no_license
quoccuong15111997/1EMSERP
https://github.com/quoccuong15111997/1EMSERP
d6c7babfece6de58b3bc1bd6e1bf2dd453b05139
60b7084bb9baf8908fcf96fed09468ec8d2c5aaa
refs/heads/master
"2022-12-28T16:13:33.737000"
"2020-10-16T11:18:08"
"2020-10-16T11:18:08"
298,209,460
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.firstems.erp.data; import com.firstems.erp.callback.data.ConvertJsonCallback; import com.google.gson.Gson; /** * Created by Nguyen Quoc Cuong on 8/11/2020. */ public class DataConvertProvider { private static DataConvertProvider instance; private DataConvertProvider(){ } public static DataConvertProvider getInstance(){ if (instance==null){ instance= new DataConvertProvider(); } return instance; } public void convertJsonToObject(String json, Object object, ConvertJsonCallback convertJsonCallback){ try{ //System.out.println("Convert "+json); Gson gson= new Gson(); Object objReturn = gson.fromJson(json,object.getClass()); convertJsonCallback.onConvertSuccess(objReturn); } catch (Exception ex){ ex.printStackTrace(); } } }
UTF-8
Java
874
java
DataConvertProvider.java
Java
[ { "context": "k;\nimport com.google.gson.Gson;\n\n/**\n * Created by Nguyen Quoc Cuong on 8/11/2020.\n */\npublic class DataConvertProvide", "end": 156, "score": 0.9998658895492554, "start": 139, "tag": "NAME", "value": "Nguyen Quoc Cuong" } ]
null
[]
package com.firstems.erp.data; import com.firstems.erp.callback.data.ConvertJsonCallback; import com.google.gson.Gson; /** * Created by <NAME> on 8/11/2020. */ public class DataConvertProvider { private static DataConvertProvider instance; private DataConvertProvider(){ } public static DataConvertProvider getInstance(){ if (instance==null){ instance= new DataConvertProvider(); } return instance; } public void convertJsonToObject(String json, Object object, ConvertJsonCallback convertJsonCallback){ try{ //System.out.println("Convert "+json); Gson gson= new Gson(); Object objReturn = gson.fromJson(json,object.getClass()); convertJsonCallback.onConvertSuccess(objReturn); } catch (Exception ex){ ex.printStackTrace(); } } }
863
0.668192
0.660183
31
27.193548
24.650354
105
false
false
0
0
0
0
0
0
0.451613
false
false
7
36c773cd1dddaf4ecf9d9c7f9264217902f64753
1,967,095,058,096
1d2ee44eaa0edeedf9dcf70ea351913c1acf14ed
/src/test/java/com/rmbcorp/securitiesdemo/remoteservices/QuandlTestData.java
ebff9a4b0f9d7d53c03385ca8d5e6e3930727145
[]
no_license
robertbrako/securitiesdemo
https://github.com/robertbrako/securitiesdemo
b0f25b3ba3784bb548f88fbdf5ca021d2ba71e9a
9d03a6b29be7f931eb0dac916ae427e3a585dcd7
refs/heads/master
"2021-07-03T20:59:08.789000"
"2017-09-25T20:03:14"
"2017-09-25T20:14:20"
104,797,151
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rmbcorp.securitiesdemo.remoteservices; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; class QuandleTestData { private static final String TEST_DATE = "2017-06"; private static final String FIRST_DAY = "2017-06-21"; private static final String SECOND_DAY = "2017-06-22"; private static final String THIRD_DAY = "2017-06-23"; static Map<String, Map<String, List<SecuritiesInfo>>> testData() { Map<String, Map<String, List<SecuritiesInfo>>> result = new HashMap<>(); result.put("COF", QuandleTestData.getCOF()); result.put("MSFT", QuandleTestData.getMSFT()); result.put("GOOGL", QuandleTestData.getGOOGL()); return result; } private static Map<String, List<SecuritiesInfo>> getMSFT() { Map<String, List<SecuritiesInfo>> msftGroups = new HashMap<>(); String ticker = "MSFT"; msftGroups.put(TEST_DATE, Arrays.asList( getStockData(ticker, 70.21, 70.27, FIRST_DAY),//up getStockData(ticker, 70.54, 70.26, SECOND_DAY),//dn getStockData(ticker, 70.09, 71.21, THIRD_DAY)));//up return msftGroups; } private static Map<String, List<SecuritiesInfo>> getCOF() { Map<String, List<SecuritiesInfo>> msftGroups = new HashMap<>(); String ticker = "COF"; msftGroups.put(TEST_DATE, Arrays.asList( getStockData(ticker, 81.3,80.88, FIRST_DAY), getStockData(ticker, 80.73,80.39, SECOND_DAY), getStockData(ticker, 80.75,79.52, THIRD_DAY))); return msftGroups; } private static Map<String, List<SecuritiesInfo>> getGOOGL() { Map<String, List<SecuritiesInfo>> msftGroups = new HashMap<>(); String ticker = "GOOGL"; msftGroups.put(TEST_DATE, Arrays.asList( getStockData(ticker, 970.79,978.59, FIRST_DAY), getStockData(ticker, 976.87, 976.62, SECOND_DAY), getStockData(ticker, 975.5, 986.09, THIRD_DAY))); return msftGroups; } private static SecuritiesInfo getStockData(String ticker, double open, double close, String testDate) { SecuritiesInfo securitiesInfo = new SecuritiesInfo(); securitiesInfo.setTicker(ticker); securitiesInfo.setDate(LocalDate.parse(testDate)); securitiesInfo.setOpen(BigDecimal.valueOf(open)); securitiesInfo.setClose(BigDecimal.valueOf(close)); return securitiesInfo; } }
UTF-8
Java
2,581
java
QuandlTestData.java
Java
[]
null
[]
package com.rmbcorp.securitiesdemo.remoteservices; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; class QuandleTestData { private static final String TEST_DATE = "2017-06"; private static final String FIRST_DAY = "2017-06-21"; private static final String SECOND_DAY = "2017-06-22"; private static final String THIRD_DAY = "2017-06-23"; static Map<String, Map<String, List<SecuritiesInfo>>> testData() { Map<String, Map<String, List<SecuritiesInfo>>> result = new HashMap<>(); result.put("COF", QuandleTestData.getCOF()); result.put("MSFT", QuandleTestData.getMSFT()); result.put("GOOGL", QuandleTestData.getGOOGL()); return result; } private static Map<String, List<SecuritiesInfo>> getMSFT() { Map<String, List<SecuritiesInfo>> msftGroups = new HashMap<>(); String ticker = "MSFT"; msftGroups.put(TEST_DATE, Arrays.asList( getStockData(ticker, 70.21, 70.27, FIRST_DAY),//up getStockData(ticker, 70.54, 70.26, SECOND_DAY),//dn getStockData(ticker, 70.09, 71.21, THIRD_DAY)));//up return msftGroups; } private static Map<String, List<SecuritiesInfo>> getCOF() { Map<String, List<SecuritiesInfo>> msftGroups = new HashMap<>(); String ticker = "COF"; msftGroups.put(TEST_DATE, Arrays.asList( getStockData(ticker, 81.3,80.88, FIRST_DAY), getStockData(ticker, 80.73,80.39, SECOND_DAY), getStockData(ticker, 80.75,79.52, THIRD_DAY))); return msftGroups; } private static Map<String, List<SecuritiesInfo>> getGOOGL() { Map<String, List<SecuritiesInfo>> msftGroups = new HashMap<>(); String ticker = "GOOGL"; msftGroups.put(TEST_DATE, Arrays.asList( getStockData(ticker, 970.79,978.59, FIRST_DAY), getStockData(ticker, 976.87, 976.62, SECOND_DAY), getStockData(ticker, 975.5, 986.09, THIRD_DAY))); return msftGroups; } private static SecuritiesInfo getStockData(String ticker, double open, double close, String testDate) { SecuritiesInfo securitiesInfo = new SecuritiesInfo(); securitiesInfo.setTicker(ticker); securitiesInfo.setDate(LocalDate.parse(testDate)); securitiesInfo.setOpen(BigDecimal.valueOf(open)); securitiesInfo.setClose(BigDecimal.valueOf(close)); return securitiesInfo; } }
2,581
0.647424
0.606354
63
39.968254
26.384199
107
false
false
0
0
0
0
0
0
1.365079
false
false
7
61107b225285eb384f9cd75a15592fccf7d6b987
16,140,487,160,842
64721dc67143a85306aa6efdcdc1ee008408275a
/java/src/ch06/ex11/OptimusPrime.java
4d08e92dc3ec35261831b94b298b59276861f3c4
[]
no_license
imdangun/java-17
https://github.com/imdangun/java-17
fbf363d21ba4e4b8c4945d398ac146236036c057
d57510e25ebfd669f24e2da7c72b4f0929b285b3
refs/heads/master
"2017-11-11T16:39:08.911000"
"2017-10-11T09:18:16"
"2017-10-11T09:18:16"
84,036,558
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ch06.ex11; public class OptimusPrime implements AutoBot{ public void drive(){ System.out.println("프라임 달리다."); } public void fight(){ System.out.println("프라임 싸우다."); } public void command(){ System.out.println("프라임 지휘하다."); } }
UTF-8
Java
305
java
OptimusPrime.java
Java
[]
null
[]
package ch06.ex11; public class OptimusPrime implements AutoBot{ public void drive(){ System.out.println("프라임 달리다."); } public void fight(){ System.out.println("프라임 싸우다."); } public void command(){ System.out.println("프라임 지휘하다."); } }
305
0.632959
0.617977
15
15.8
14.976426
45
false
false
0
0
0
0
0
0
1.2
false
false
7
55dcbc6114e3a4ab57eb91d3899271349a837e89
21,466,246,577,383
07d2448c7b4397467fd72ee7a1bfd6fa5bcd1298
/src/test/java/com/jvalenc/stock/util/SMADataPointTest.java
693cce36dc91ddd8d59f46df78d72623e8fecac5
[]
no_license
jvalenci/stock_filter
https://github.com/jvalenci/stock_filter
c4bb97e53395cbc9549a24fc79eeeaa3a9ec498d
289a3cd2dc88c25bb80353de0bec74a653ea5d08
refs/heads/master
"2021-07-18T04:02:11.749000"
"2020-08-25T19:48:27"
"2020-08-25T19:48:27"
117,911,993
0
0
null
false
"2021-04-26T16:45:08"
"2018-01-18T00:57:12"
"2020-08-25T19:48:54"
"2021-04-26T16:45:08"
121
0
0
2
Java
false
false
package com.jvalenc.stock.util; import com.jvalenc.stock.models.SMADataPoint; import java.util.Date; import static org.junit.Assert.*; /** * Created by jonat on 11/13/2017. */ public class SMADataPointTest { @org.junit.Test public void getAndSetTimeStamp() throws Exception { //arrange SMADataPoint smaDataPoint = new SMADataPoint(12, "2017-11-10"); //act Date actual = smaDataPoint.getTimeStamp(); //assert assertNotNull(actual); assertTrue("This is not of a Date type", actual instanceof Date); } @org.junit.Test public void getAndSetSimpleMovingAverage() throws Exception { //arrange double expected = 12.2432; SMADataPoint smaDataPoint = new SMADataPoint(12.2432, "2017-11-10"); //act smaDataPoint.setValue(expected); double actual = smaDataPoint.getValue(); //assert assertNotNull(actual); assertTrue("Values are not the same", actual == expected); } }
UTF-8
Java
1,019
java
SMADataPointTest.java
Java
[ { "context": "port static org.junit.Assert.*;\n\n/**\n * Created by jonat on 11/13/2017.\n */\npublic class SMADataPointTest ", "end": 162, "score": 0.9996464848518372, "start": 157, "tag": "USERNAME", "value": "jonat" } ]
null
[]
package com.jvalenc.stock.util; import com.jvalenc.stock.models.SMADataPoint; import java.util.Date; import static org.junit.Assert.*; /** * Created by jonat on 11/13/2017. */ public class SMADataPointTest { @org.junit.Test public void getAndSetTimeStamp() throws Exception { //arrange SMADataPoint smaDataPoint = new SMADataPoint(12, "2017-11-10"); //act Date actual = smaDataPoint.getTimeStamp(); //assert assertNotNull(actual); assertTrue("This is not of a Date type", actual instanceof Date); } @org.junit.Test public void getAndSetSimpleMovingAverage() throws Exception { //arrange double expected = 12.2432; SMADataPoint smaDataPoint = new SMADataPoint(12.2432, "2017-11-10"); //act smaDataPoint.setValue(expected); double actual = smaDataPoint.getValue(); //assert assertNotNull(actual); assertTrue("Values are not the same", actual == expected); } }
1,019
0.646712
0.609421
39
25.153847
23.386976
76
false
false
0
0
0
0
0
0
0.461538
false
false
7
81acd27001a0dbeb2a98c726b6f9121d263f8474
23,407,571,778,404
05219905bcc301604ba6e85337db2d666e7d7218
/Client/src/tests/UserUtilTest.java
50993b09cc3b1aa1322a84306586bfc97b308606
[]
no_license
Gruppe-08/Fellesprosjekt
https://github.com/Gruppe-08/Fellesprosjekt
1f93252a67c3c79a2a6357723c7750ccc73ca48c
13bf0e388b45f18afbfc2f6f9edd7ad166fe8dd2
refs/heads/master
"2021-01-21T11:08:25.424000"
"2015-03-22T16:30:53"
"2015-03-22T16:30:53"
31,769,971
0
0
null
false
"2015-03-20T16:14:49"
"2015-03-06T13:16:12"
"2015-03-20T15:54:22"
"2015-03-20T16:14:49"
2,188
0
0
1
Java
null
null
package tests; import static org.junit.Assert.*; import models.User; import org.junit.Test; import util.UserUtil; public class UserUtilTest { @Test public void testIsValidUser() { User user = new User("kristian", "Kristian", "Aurlien", true); Boolean result = UserUtil.isValidUser(user); assertTrue(result); user = new User(); result = UserUtil.isValidUser(user); assertFalse(result); } @Test public void testIsValidPassword() { assertTrue(UserUtil.isValidPassword("123456")); assertFalse(UserUtil.isValidPassword("12345")); } @Test public void testIsMatchingPasswords(){ assertTrue(UserUtil.isMatchingPasswords("kebab1","kebab1")); assertFalse(UserUtil.isMatchingPasswords("kebab1","burger1")); } }
UTF-8
Java
747
java
UserUtilTest.java
Java
[ { "context": " void testIsValidUser() {\n\t\tUser user = new User(\"kristian\", \"Kristian\", \"Aurlien\", true);\n\t\tBoolean result ", "end": 219, "score": 0.9990759491920471, "start": 211, "tag": "USERNAME", "value": "kristian" }, { "context": "ValidUser() {\n\t\tUser user = new User(\"kristian\", \"Kristian\", \"Aurlien\", true);\n\t\tBoolean result = UserUtil.i", "end": 231, "score": 0.9997100234031677, "start": 223, "tag": "NAME", "value": "Kristian" }, { "context": "{\n\t\tUser user = new User(\"kristian\", \"Kristian\", \"Aurlien\", true);\n\t\tBoolean result = UserUtil.isValidUser(", "end": 242, "score": 0.9994311332702637, "start": 235, "tag": "NAME", "value": "Aurlien" }, { "context": "ssword() {\n\t\tassertTrue(UserUtil.isValidPassword(\"123456\"));\n\t\tassertFalse(UserUtil.isValidPassword(\"12345", "end": 501, "score": 0.9989182353019714, "start": 495, "tag": "PASSWORD", "value": "123456" }, { "context": "23456\"));\n\t\tassertFalse(UserUtil.isValidPassword(\"12345\"));\n\t}\n\t\n\t@Test\n\tpublic void testIsMatchingPasswo", "end": 551, "score": 0.9990021586418152, "start": 546, "tag": "PASSWORD", "value": "12345" }, { "context": "ssertFalse(UserUtil.isMatchingPasswords(\"kebab1\",\"burger1\"));\n\n\t}\n\t\n\t\n\n}\n", "end": 731, "score": 0.8282597661018372, "start": 724, "tag": "PASSWORD", "value": "burger1" } ]
null
[]
package tests; import static org.junit.Assert.*; import models.User; import org.junit.Test; import util.UserUtil; public class UserUtilTest { @Test public void testIsValidUser() { User user = new User("kristian", "Kristian", "Aurlien", true); Boolean result = UserUtil.isValidUser(user); assertTrue(result); user = new User(); result = UserUtil.isValidUser(user); assertFalse(result); } @Test public void testIsValidPassword() { assertTrue(UserUtil.isValidPassword("<PASSWORD>")); assertFalse(UserUtil.isValidPassword("<PASSWORD>")); } @Test public void testIsMatchingPasswords(){ assertTrue(UserUtil.isMatchingPasswords("kebab1","kebab1")); assertFalse(UserUtil.isMatchingPasswords("kebab1","<PASSWORD>")); } }
759
0.72423
0.70415
38
18.657894
20.368031
64
false
false
0
0
0
0
0
0
1.447368
false
false
7
3e7091800833b31ccd611a3bbfc2ead66c51f9a3
11,854,109,758,064
31b550b3a6b0dd5ce420d1e4b7746aeb813ba775
/src/main/java/com/terabits/service/AccessTokenService.java
72e12a694dbd0df1327ddd817154171471dbe2ff
[]
no_license
MasterXuBoya/platform
https://github.com/MasterXuBoya/platform
10f25dad63381b8f3122a6c84c29506dea95f964
c94576b87b79458cc39a55d50d7735c744df7ef3
refs/heads/master
"2021-07-15T04:09:10.015000"
"2017-10-21T05:26:00"
"2017-10-21T05:26:00"
107,754,095
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.terabits.service; import com.terabits.meta.po.AccessTokenPO; /** * Created by Administrator on 2017/6/15. */ public interface AccessTokenService { public void insertToken(AccessTokenPO accessTokenPO); public AccessTokenPO getLatestToken(); }
UTF-8
Java
266
java
AccessTokenService.java
Java
[]
null
[]
package com.terabits.service; import com.terabits.meta.po.AccessTokenPO; /** * Created by Administrator on 2017/6/15. */ public interface AccessTokenService { public void insertToken(AccessTokenPO accessTokenPO); public AccessTokenPO getLatestToken(); }
266
0.770677
0.744361
11
23.181818
20.836237
57
false
false
0
0
0
0
0
0
0.363636
false
false
7
c57da46dc50e38cea976623f8d35c6841c637f08
12,403,865,588,738
f5630ded174f2a01d84228a93213068ad9800142
/java8newfeature/src/main/java/com/sto/csv/Advice.java
54fb7b40cec7e52856a419b24713f499c2c9aeff
[]
no_license
thebigdipperbdx/SpringBootList
https://github.com/thebigdipperbdx/SpringBootList
0e20709f73e3226e6e4b5a46df482fb711524691
4b51d81e0355e433ffba78bf99b8bcbfbe7db3bf
refs/heads/master
"2022-07-07T14:31:45.496000"
"2020-06-04T02:44:17"
"2020-06-04T02:44:17"
206,746,443
0
0
null
false
"2022-06-17T02:36:27"
"2019-09-06T08:13:29"
"2020-06-04T02:44:20"
"2022-06-17T02:36:26"
87,113
0
0
9
Java
false
false
package com.sto.csv; import java.lang.reflect.InvocationHandler; /** * @author yanyugang * @description * @date 2019-09-21 14:38 */ public interface Advice extends InvocationHandler { }
UTF-8
Java
192
java
Advice.java
Java
[ { "context": "va.lang.reflect.InvocationHandler;\n\n/**\n * @author yanyugang\n * @description\n * @date 2019-09-21 14:38\n */\npub", "end": 91, "score": 0.9993024468421936, "start": 82, "tag": "USERNAME", "value": "yanyugang" } ]
null
[]
package com.sto.csv; import java.lang.reflect.InvocationHandler; /** * @author yanyugang * @description * @date 2019-09-21 14:38 */ public interface Advice extends InvocationHandler { }
192
0.734375
0.671875
11
16.454546
16.897356
51
false
false
0
0
0
0
0
0
0.181818
false
false
7
326f4447b251b218f865b45c0e58f14560765334
35,708,358,107,912
1da7f65b13c49f3bd40d3b54de008ab843338144
/src/main/java/dcdmod/Card/Special/Kabuto_PutOn.java
e08af30e323ce922de304ad91bb91b23a28c079e
[]
no_license
q541257877/KR-DCD
https://github.com/q541257877/KR-DCD
dac71e21d0b600b556b4778e338e59162db9f6f6
5299af610f484d878687baef0d5343f99d153223
refs/heads/master
"2022-02-14T15:22:19.731000"
"2019-08-13T13:27:25"
"2019-08-13T13:27:25"
197,047,158
0
2
null
false
"2019-07-23T14:37:34"
"2019-07-15T17:56:24"
"2019-07-22T03:06:55"
"2019-07-22T03:06:53"
274,553
0
1
1
Java
false
false
package dcdmod.Card.Special; import java.util.ArrayList; import java.util.List; import com.megacrit.cardcrawl.actions.animations.VFXAction; import com.megacrit.cardcrawl.actions.common.ApplyPowerAction; import com.megacrit.cardcrawl.actions.common.MakeTempCardInHandAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.cards.DamageInfo.DamageType; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.localization.CardStrings; import com.megacrit.cardcrawl.monsters.AbstractMonster; import basemod.helpers.TooltipInfo; import dcdmod.DCDmod; import dcdmod.Patches.AbstractCardEnum; import dcdmod.Patches.AbstractCustomCardWithType; import dcdmod.Power.KabutoMaskedPower; import dcdmod.Vfx.Kabuto_RiderToMasked; public class Kabuto_PutOn extends AbstractCustomCardWithType{ public static final String ID = "Kabuto_PutOn"; private static final CardStrings cardStrings; public static final String NAME; public static final String DESCRIPTION; public static final String[] EXTENDED_DESCRIPTION; public static final String IMG_PATH = "img/cards/Kabuto_PutOn.png"; private static final int COST = 0; private List<TooltipInfo> tips; public Kabuto_PutOn() { super(ID, NAME, IMG_PATH, COST, DESCRIPTION, AbstractCard.CardType.SKILL, AbstractCardEnum.DCD, AbstractCard.CardRarity.SPECIAL, AbstractCard.CardTarget.SELF,CardColorType.Kabuto); this.tags.add(DCDmod.RiderCard); this.tags.add(DCDmod.KamenRide); this.exhaust = true; this.tips = new ArrayList<>(); this.tips.add(new TooltipInfo(EXTENDED_DESCRIPTION[1], EXTENDED_DESCRIPTION[2])); } @Override public void use(AbstractPlayer p, AbstractMonster m) { AbstractDungeon.actionManager.addToTop(new VFXAction(new Kabuto_RiderToMasked(), 1.2F)); AbstractDungeon.actionManager.addToBottom(new ApplyPowerAction(p, p, new KabutoMaskedPower(p,1),1)); AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(new Kabuto_CastOff(), 1)); } @Override public AbstractCard makeCopy() { return new Kabuto_PutOn(); } @Override public List<TooltipInfo> getCustomTooltips() { return this.tips; } public boolean canUse(AbstractPlayer p, AbstractMonster m) { boolean canUse = super.canUse(p, m); if(!canUse) return false; if(p.hasPower("KabutoMaskedPower")) { canUse = false; this.cantUseMessage = EXTENDED_DESCRIPTION[0]; } if(!p.hasPower("KamenRideKabutoPower")) { canUse = false; this.cantUseMessage = EXTENDED_DESCRIPTION[3]; } return canUse; } @Override public void optionDecade() { this.damageType = DamageType.NORMAL; } @Override public void optionKuuga() { } @Override public void optionAgito() { // TODO 自动生成的方法存根 } @Override public void optionRyuki() { // TODO 自动生成的方法存根 } @Override public void optionFaiz() { // TODO 自动生成的方法存根 } @Override public void optionBlade() { // TODO 自动生成的方法存根 } @Override public void optionHibiki() { // TODO 自动生成的方法存根 } @Override public void optionKabuto() { // TODO 自动生成的方法存根 } @Override public void optionDenO() { // TODO 自动生成的方法存根 } @Override public void optionKiva() { // TODO 自动生成的方法存根 } @Override public void optionNeutral() { this.damageType = DamageType.NORMAL; } @Override public void upgrade() { } static { cardStrings = CardCrawlGame.languagePack.getCardStrings("Kabuto_PutOn"); NAME = Kabuto_PutOn.cardStrings.NAME; DESCRIPTION = Kabuto_PutOn.cardStrings.DESCRIPTION; EXTENDED_DESCRIPTION = Kabuto_PutOn.cardStrings.EXTENDED_DESCRIPTION; } @Override public void energychange() { if(this.freeToPlayOnce){ setBannerTexture(DCDmod.SPECIAL[0], DCDmod.SPECIAL_P[0]); } else if(this.costForTurn == -1 || this.costForTurn > 5) { setBannerTexture(DCDmod.SPECIAL[6], DCDmod.SPECIAL_P[6]); } else { int cost = this.costForTurn; setBannerTexture(DCDmod.SPECIAL[cost], DCDmod.SPECIAL_P[cost]); } } }
UTF-8
Java
4,301
java
Kabuto_PutOn.java
Java
[]
null
[]
package dcdmod.Card.Special; import java.util.ArrayList; import java.util.List; import com.megacrit.cardcrawl.actions.animations.VFXAction; import com.megacrit.cardcrawl.actions.common.ApplyPowerAction; import com.megacrit.cardcrawl.actions.common.MakeTempCardInHandAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.cards.DamageInfo.DamageType; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.localization.CardStrings; import com.megacrit.cardcrawl.monsters.AbstractMonster; import basemod.helpers.TooltipInfo; import dcdmod.DCDmod; import dcdmod.Patches.AbstractCardEnum; import dcdmod.Patches.AbstractCustomCardWithType; import dcdmod.Power.KabutoMaskedPower; import dcdmod.Vfx.Kabuto_RiderToMasked; public class Kabuto_PutOn extends AbstractCustomCardWithType{ public static final String ID = "Kabuto_PutOn"; private static final CardStrings cardStrings; public static final String NAME; public static final String DESCRIPTION; public static final String[] EXTENDED_DESCRIPTION; public static final String IMG_PATH = "img/cards/Kabuto_PutOn.png"; private static final int COST = 0; private List<TooltipInfo> tips; public Kabuto_PutOn() { super(ID, NAME, IMG_PATH, COST, DESCRIPTION, AbstractCard.CardType.SKILL, AbstractCardEnum.DCD, AbstractCard.CardRarity.SPECIAL, AbstractCard.CardTarget.SELF,CardColorType.Kabuto); this.tags.add(DCDmod.RiderCard); this.tags.add(DCDmod.KamenRide); this.exhaust = true; this.tips = new ArrayList<>(); this.tips.add(new TooltipInfo(EXTENDED_DESCRIPTION[1], EXTENDED_DESCRIPTION[2])); } @Override public void use(AbstractPlayer p, AbstractMonster m) { AbstractDungeon.actionManager.addToTop(new VFXAction(new Kabuto_RiderToMasked(), 1.2F)); AbstractDungeon.actionManager.addToBottom(new ApplyPowerAction(p, p, new KabutoMaskedPower(p,1),1)); AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(new Kabuto_CastOff(), 1)); } @Override public AbstractCard makeCopy() { return new Kabuto_PutOn(); } @Override public List<TooltipInfo> getCustomTooltips() { return this.tips; } public boolean canUse(AbstractPlayer p, AbstractMonster m) { boolean canUse = super.canUse(p, m); if(!canUse) return false; if(p.hasPower("KabutoMaskedPower")) { canUse = false; this.cantUseMessage = EXTENDED_DESCRIPTION[0]; } if(!p.hasPower("KamenRideKabutoPower")) { canUse = false; this.cantUseMessage = EXTENDED_DESCRIPTION[3]; } return canUse; } @Override public void optionDecade() { this.damageType = DamageType.NORMAL; } @Override public void optionKuuga() { } @Override public void optionAgito() { // TODO 自动生成的方法存根 } @Override public void optionRyuki() { // TODO 自动生成的方法存根 } @Override public void optionFaiz() { // TODO 自动生成的方法存根 } @Override public void optionBlade() { // TODO 自动生成的方法存根 } @Override public void optionHibiki() { // TODO 自动生成的方法存根 } @Override public void optionKabuto() { // TODO 自动生成的方法存根 } @Override public void optionDenO() { // TODO 自动生成的方法存根 } @Override public void optionKiva() { // TODO 自动生成的方法存根 } @Override public void optionNeutral() { this.damageType = DamageType.NORMAL; } @Override public void upgrade() { } static { cardStrings = CardCrawlGame.languagePack.getCardStrings("Kabuto_PutOn"); NAME = Kabuto_PutOn.cardStrings.NAME; DESCRIPTION = Kabuto_PutOn.cardStrings.DESCRIPTION; EXTENDED_DESCRIPTION = Kabuto_PutOn.cardStrings.EXTENDED_DESCRIPTION; } @Override public void energychange() { if(this.freeToPlayOnce){ setBannerTexture(DCDmod.SPECIAL[0], DCDmod.SPECIAL_P[0]); } else if(this.costForTurn == -1 || this.costForTurn > 5) { setBannerTexture(DCDmod.SPECIAL[6], DCDmod.SPECIAL_P[6]); } else { int cost = this.costForTurn; setBannerTexture(DCDmod.SPECIAL[cost], DCDmod.SPECIAL_P[cost]); } } }
4,301
0.735867
0.732018
171
23.309942
24.211855
102
false
false
0
0
0
0
0
0
1.51462
false
false
7
eff51df0167aae31c8b9dfb15a8ea222156c7612
33,002,528,735,313
bacd99275ac7f5c313736355fde8234a83b38bc5
/iaudience/src/main/java/com/iclick/symphony/iaudience/service/impl/AudiencePlanServiceImpl.java
accf9757da3788d5bf3ce719345d1d5a78842d07
[]
no_license
sunwenjie/iaudience_pro
https://github.com/sunwenjie/iaudience_pro
5a97c8ba38b26f84b4bcd9cab2c747c8d5e2c1b6
3cf86b537c92c6c24e262fb60745f12cc4c5e8d8
refs/heads/master
"2020-12-03T01:52:00.893000"
"2017-06-30T10:39:59"
"2017-06-30T10:39:59"
95,874,898
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.iclick.symphony.iaudience.service.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.iclick.symphony.iaudience.dao.*; import com.iclick.symphony.iaudience.entity.*; import com.iclick.symphony.iaudience.model.Interest; import com.iclick.symphony.iaudience.model.remote.Advertiser; import com.iclick.symphony.iaudience.model.remote.AudienceRightRetMsg; import com.iclick.symphony.iaudience.model.remote.AudienceRights; import com.iclick.symphony.iaudience.model.remote.ClientAttributes; import com.iclick.symphony.iaudience.model.view.*; import com.iclick.symphony.iaudience.service.AudiencePlanService; import com.iclick.symphony.iaudience.service.BaseService; import com.iclick.symphony.iaudience.service.UserSerivce; import org.apache.commons.lang3.StringUtils; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.*; /** * Created by wenjie.sun on 2017/5/17. */ @Service public class AudiencePlanServiceImpl extends BaseService implements AudiencePlanService { @Resource private AudiencePlanRepository audiencePlanRepository; @Resource private LocationRepository locationRepository; @Resource private LocationCityRepository locationCityRepository; @Resource private InterestStructureRepository interestRepository; @Resource private BrandRepository brandRepository; @Resource private ProductRepository productRepository; @Resource private AdvancedSettingRepository advancedSettingRepository; @Resource private UserSerivce userSerivce; @Override public void save(AudiencePlan audiencePlan) { audiencePlanRepository.save(audiencePlan); } @Transactional(propagation = Propagation.REQUIRED) public boolean saveOrUpdate(AudiencePlanModel audiencePlanModel) { AudiencePlan audiencePlan = null; try { //新增 if (audiencePlanModel.getPlanId() == null){ audiencePlan = new AudiencePlan(); // audiencePlan.setCreateBy(UserUtil.getLoginUserId()); // audiencePlan.setUpdateBy(UserUtil.getLoginUserId()); audiencePlan.setCreateBy(1206); audiencePlan.setCreateTime(new Date()); audiencePlan.setUpdateBy(1206); audiencePlan.setUpdateTime(new Date()); }else { //修改之前先删除 this.deleteBrands(audiencePlanModel.getDeleteBrandIds()); this.deleteProducts(audiencePlanModel.getDeleteProductIds()); //修改 audiencePlan = this.getAudiencePlanById(audiencePlanModel.getPlanId()); //audiencePlan.setUpdateBy(UserUtil.getLoginUserId()); audiencePlan.setUpdateBy(1208); audiencePlan.setUpdateTime(new Date()); } audiencePlan.setClientId(audiencePlanModel.getClientId()); audiencePlan.setCategoryId(audiencePlanModel.getCategoryId()); audiencePlan.setName(audiencePlanModel.getName()); //新增或修改高级设置 AdvancedSettingModel advancedSettingModel = audiencePlanModel.getAdvancedSettingModel(); AdvancedSetting advancedSetting = new AdvancedSetting(); if ( advancedSettingModel.getAdvancedSettingId() != null ){ advancedSetting = advancedSettingRepository.findOne(advancedSettingModel.getAdvancedSettingId()); } setAdvancedSettingProperty(advancedSetting,advancedSettingModel); audiencePlan.setAdvancedSetting(advancedSetting); //新增或修改品牌 List<BrandModel> brandModelList = audiencePlanModel.getBrandModelList(); removeNullBrandAndProduct(brandModelList); for (BrandModel brandModel : brandModelList) { Brand brand = null; if (brandModel.getBrandId() == null){ brand = new Brand(); setBrandProperty(brand,brandModel); List<ProductModel> productModelList = brandModel.getProductModelList(); for (ProductModel productModel : productModelList) { Product product = new Product(); setProductProperty(product,productModel); brand.addProduct(product); } audiencePlan.addBrand(brand); }else { brand = brandRepository.findOne(brandModel.getBrandId()); setBrandProperty(brand,brandModel); List<ProductModel> productModelList = brandModel.getProductModelList(); //新增或修改产品 for (ProductModel productModel : productModelList) { Product product = null; if (productModel.getProductId() == null){ product = new Product(); }else { product = productRepository.findOne(productModel.getProductId()); } setProductProperty(product,productModel); brand.addProduct(product); } } } } catch (Exception e) { e.printStackTrace(); return false; } this.save(audiencePlan); return true; } private void removeNullBrandAndProduct(List<BrandModel> brandModelList){ //先去除空brand List<BrandModel> removeBrandModelList = new ArrayList<>(); for (BrandModel brandModel : brandModelList){ if (brandModel.getBrandId() == null && StringUtils.isBlank(brandModel.getName()) && StringUtils.isBlank(brandModel.getKeyWords())) removeBrandModelList.add(brandModel); } brandModelList.removeAll(removeBrandModelList); //再去除空product for (BrandModel brandModel : brandModelList){ List<ProductModel> productModelList = brandModel.getProductModelList(); List<ProductModel> removeProductModelList = new ArrayList<>(); for (ProductModel productModel : productModelList){ if (productModel.getProductId() == null && StringUtils.isBlank(productModel.getName()) && StringUtils.isBlank(productModel.getCategory()) && StringUtils.isBlank(productModel.getKeyWords())){ removeProductModelList.add(productModel); } } productModelList.removeAll(removeProductModelList); brandModel.setProductModelList(productModelList); } } private void setAdvancedSettingProperty(AdvancedSetting advancedSetting,AdvancedSettingModel advancedSettingModel){ advancedSetting.setCity(advancedSettingModel.getCity()); advancedSetting.setLocation(advancedSettingModel.getLocation()); advancedSetting.setKeyWords(advancedSettingModel.getKeyWords()); } private void setBrandProperty(Brand brand,BrandModel brandModel){ brand.setName(brandModel.getName()); brand.setKeyWords(brandModel.getKeyWords()); brand.setCompetitor(brandModel.getCompetitor().equals("true") ? true :false); } private void setProductProperty(Product product,ProductModel productModel){ product.setCategory(productModel.getCategory()); product.setName(productModel.getName()); product.setKeyWords(productModel.getKeyWords()); } @Transactional(propagation = Propagation.REQUIRED) public void deleteBrands(String[] deleteBrandIds){ if (deleteBrandIds != null && deleteBrandIds.length > 0) { List<Brand> brandList = new ArrayList<>(); for (String brandId : deleteBrandIds) { if (StringUtils.isNotBlank(brandId)) { Brand brand = brandRepository.findOne(Integer.parseInt(brandId)); List<Product> productList = brand.getProducts(); productRepository.deleteInBatch(productList); brand.setAudiencePlan(null); brandList.add(brand); } } brandRepository.deleteInBatch(brandList); } } @Transactional(propagation = Propagation.REQUIRED) public void deleteProducts(String[] deleteProductIds){ if (deleteProductIds != null && deleteProductIds.length >0){ List<Product> productList = new ArrayList<>(); for (String productId : deleteProductIds){ if (StringUtils.isNotBlank(productId)) { Product product = productRepository.findOne(Integer.parseInt(productId)); if (product != null) { product.setBrand(null); productList.add(product); } } } if (productList.size() > 0) productRepository.deleteInBatch(productList); } } @Transactional(propagation = Propagation.REQUIRED) public void deleteAudiencePlan(Integer id){ AudiencePlan audiencePlan = this.getAudiencePlanById(id); if (audiencePlan != null){ audiencePlan.setDeleted(true); audiencePlanRepository.save(audiencePlan); } } @Transactional(readOnly = true) public List<String> getSelectCategoryNames(Integer id,Locale locale) { String interestLab = this.getInterestList(locale); List<Interest> interestList = JSON.parseArray(interestLab,Interest.class); Interest interest = new Interest(); for (Interest temp : interestList){ if (temp.getAudienceId().equals(id)){ interest = temp; break; } } List<String> initList = new ArrayList<>(); initList.add(interest.getName()); return this.getChildrenInterestList(interest,initList); } @Transactional(readOnly = true) // 递归方法查询字interest public List<String> getChildrenInterestList(Interest interest,List<String> interestNameList) { List<Interest> interestListChildren = interest.getChildren(); if (interest == null && interestListChildren.size() == 0){ return interestNameList; }else { for (Interest tmp : interestListChildren){ interestNameList.add(tmp.getName()); getChildrenInterestList(tmp,interestNameList); } } return interestNameList; } @Transactional(propagation = Propagation.REQUIRED) public List<Province> getProvinceNameCnList() { List<Province> provinceList = new ArrayList<Province>(); List<LocationProvince> rows = locationRepository.findProvinceList(); for (LocationProvince row : rows) { Province pro = new Province(); pro.setProvinceId(row.getProvinceId() + ""); pro.setProvinceName(row.getProvinceNameCn()); provinceList.add(pro); } return provinceList; } @Transactional(propagation = Propagation.REQUIRED) public List<Province> getProvinceNameEnList() { List<Province> provinceList = new ArrayList<Province>(); List<LocationProvince> rows = locationRepository.findProvinceList(); for (LocationProvince row : rows) { Province pro = new Province(); pro.setProvinceId(row.getProvinceId() + ""); pro.setProvinceName(row.getProvinceNameEn()); provinceList.add(pro); } return provinceList; } private Interest coverToInterest(InterestStructure row, Locale locale) { Interest interest = new Interest(); if (Locale.CHINESE.toString().equals(locale.getLanguage())) { interest.setName(row.getNameCn()); } else { interest.setName(row.getNameEn()); } String id = String.valueOf(row.getId()); interest.setAudienceId(id); if (StringUtils.isNotBlank(id) && id.length() > 2) { interest.setParentId(id.substring(0, id.length() - 2)); } else { interest.setParentId("0"); } return interest; } @Transactional(propagation = Propagation.REQUIRED) public List<City> getCityNameCnList() { List<City> cityList = new ArrayList<City>(); List<LocationCity> rows = locationCityRepository.findCityList(); for (LocationCity row : rows) { City city = new City(); city.setCityId(row.getCityId()+""); city.setCityName(row.getCityNameCn()); cityList.add(city); } return cityList; } @Transactional(propagation = Propagation.REQUIRED) public List<City> getCityNameEnList() { List<City> cityList = new ArrayList<City>(); List<LocationCity> rows = locationCityRepository.findCityList(); for (LocationCity row : rows) { City city = new City(); city.setCityId(row.getCityId()+""); city.setCityName(row.getCityNameEn()); cityList.add(city); } return cityList; } @Override public String getInterestName(Integer id, Locale locale) { InterestStructure interest = interestRepository.findOne(id); String name = ""; if (Locale.ENGLISH.toString().equals(locale.getLanguage())) { name = interest.getNameEn(); } else { name = interest.getNameCn(); } return name; } @Transactional(propagation = Propagation.REQUIRED) @Override public String getInterestList(Locale locale) { List<Interest> resultList = new ArrayList<Interest>(); List<Interest> tempList = null; try { List<InterestStructure> interestList = interestRepository.findInterestList(); Interest interest = null; Map<String, List<Interest>> subMap = new HashMap<>(); String parentId = null; for (InterestStructure row : interestList) { interest = coverToInterest(row, locale); parentId = interest.getParentId(); interest.setChildren(subMap.get(interest.getAudienceId())); // 顶级节点 if ("0".equals(parentId)) { resultList.add(interest); } else { if (subMap.containsKey(parentId)) { subMap.get(parentId).add(interest); } else { tempList = new ArrayList<Interest>(); tempList.add(interest); subMap.put(parentId, tempList); } } interest = null; } } catch (Exception e) { } return JSONObject.toJSONString(resultList); } @Override public AudiencePlanModel getAudiencePlanModel(Integer id) { AudiencePlanModel audiencePlanModel = new AudiencePlanModel(); AudiencePlan audiencePlan = this.getAudiencePlanById(id); if (audiencePlan == null) { return null; } audiencePlanModel.setPlanId(audiencePlan.getId()); audiencePlanModel.setName(audiencePlan.getName()); audiencePlanModel.setCategoryId(audiencePlan.getCategoryId()); audiencePlanModel.setClientId(audiencePlan.getClientId()); // audiencePlanModel.setUserId( UserUtil.getLoginUserId()); //brandModel集合 List<BrandModel> brandModelList = new ArrayList<>(); List<Brand> brandList = new ArrayList<>(audiencePlan.getBrands()); Collections.sort(brandList, Comparator.comparingInt(Brand::getId)); for (Brand brand : brandList){ BrandModel brandModel = new BrandModel(); brandModel.setName(brand.getName()); brandModel.setBrandId(brand.getId()); brandModel.setCompetitor(brand.isCompetitor()? "true" : "false"); brandModel.setKeyWords(brand.getKeyWords()); //producModel集合 List<ProductModel> productModelList = new ArrayList<>(); for (Product product : brand.getProducts()){ ProductModel productModel = new ProductModel(); productModel.setProductId(product.getId()); productModel.setCategory(product.getCategory()); productModel.setName(product.getName()); productModel.setKeyWords(product.getKeyWords()); productModelList.add(productModel); } brandModel.setProductModelList(productModelList); brandModelList.add(brandModel); } audiencePlanModel.setBrandModelList(brandModelList); AdvancedSettingModel advancedSettingModel = new AdvancedSettingModel(); AdvancedSetting advancedSetting = audiencePlan.getAdvancedSetting(); advancedSettingModel.setAdvancedSettingId(advancedSetting.getId()); advancedSettingModel.setCity(advancedSetting.getCity()); advancedSettingModel.setLocation(advancedSetting.getLocation()); advancedSettingModel.setKeyWords(advancedSetting.getKeyWords()); audiencePlanModel.setAdvancedSettingModel(advancedSettingModel); return audiencePlanModel; } @Override public List<Product> getProductList(Integer id, String type) { List<Product> productList = new ArrayList<>(); if (type.equals("brand")){ productList = productRepository.findByBrandId(id); } if (type.equals("product")){ Product product = productRepository.findOne(id); productList.add(product); } return productList; } @Transactional(propagation = Propagation.REQUIRED) public Map<String, String> getInterestMaping(Locale locale) { List<InterestStructure> interestList = interestRepository.findInterestList(); Map<String, String> interestMapping = new HashMap<>(); String name = null; for (InterestStructure interest : interestList) { if (Locale.ENGLISH.toString().equals(locale.getLanguage())) { name = interest.getNameEn(); } else { name = interest.getNameCn(); } interestMapping.put(interest.getId() + "", name); } return interestMapping; } @Transactional(readOnly = true) public List<AudiencePlan> getAudiencePlanList(List<Integer> clientIds) { Sort sort = new Sort(Direction.DESC, "updateTime"); return audiencePlanRepository.findByIsDeletedFalseAndClientIdIn(clientIds,sort); } @Transactional(readOnly = true) public List<AudiencePlan> getAudiencePlanList(int clientId) { Sort sort = new Sort(Direction.DESC, "updateTime"); return audiencePlanRepository.findByIsDeletedFalseAndClientId(clientId,sort); } @Transactional(readOnly = true) public List<AudiencePlan> getAudiencePlanList() { Sort sort = new Sort(Direction.DESC, "updateTime"); return audiencePlanRepository.findByIsDeletedFalse(sort); } @Override public List<AudiencePlanModel> getAudienceModelList(int clientId) { List<AudiencePlan> audiencePlanList = this.getAudiencePlanList(clientId); List<AudiencePlanModel> audiencePlanModelList = new ArrayList<>(); if (audiencePlanList.size() > 0) { for (AudiencePlan audiencePlan : audiencePlanList) { audiencePlanModelList.add(this.getAudiencePlanModel(audiencePlan.getId())); } } return audiencePlanModelList; } @Transactional(readOnly = true) public AudiencePlan getAudiencePlanById(Integer id) { if (id == null){ return null; } return audiencePlanRepository.findOne(id); } @Transactional(readOnly = true) public Map<String, Object> getClientsShow(Integer userId,Integer currentClientId) { List<ClientModel> recentClients = new ArrayList<>(); ClientModel currentClient = new ClientModel(); List<AgentModel> allAgents = new ArrayList<>(); List<Integer> userIds = new ArrayList<>(); userIds.add(userId); AudienceRights audienceRights = userSerivce.getClients(userIds); AudienceRightRetMsg audienceRightRetMsg = audienceRights.getRet_msg(); if (audienceRightRetMsg != null && audienceRightRetMsg.getList() != null){ ClientAttributes clientAttributes = audienceRightRetMsg.getList().get(0); List<Advertiser> advertiserList = clientAttributes.getAdvids(); if (!advertiserList.isEmpty()){ for (Advertiser advertiser : advertiserList) { AgentModel agentModel = new AgentModel(); agentModel.setAgentId(advertiser.getAgent().getId()); if (advertiser.getId() == currentClientId){ currentClient.setClientId(currentClientId); currentClient.setClientName(advertiser.getName()); } } } } System.out.println(audienceRights); Map<String,Object> map = new HashMap(); map.put("currentClient",""); map.put("recentClient",""); map.put("all",""); return map; } @Transactional(readOnly = true) public Page<AudiencePlan> getAllByPage(int pageNumber, int pageSize) { Sort sort = new Sort(Direction.DESC, "createTime"); PageRequest request = buildPageRequest(pageNumber,pageSize, sort); Page<AudiencePlan> audiencePlans = audiencePlanRepository.findAllPlans(false, request); return audiencePlans; } @Override public List<Product> getProductsByBrandId(int id) { return productRepository.findByBrandId(id); } }
UTF-8
Java
22,361
java
AudiencePlanServiceImpl.java
Java
[ { "context": "n.Resource;\nimport java.util.*;\n\n/**\n * Created by wenjie.sun on 2017/5/17.\n */\n@Service\npublic class AudienceP", "end": 1272, "score": 0.9995561242103577, "start": 1262, "tag": "USERNAME", "value": "wenjie.sun" } ]
null
[]
package com.iclick.symphony.iaudience.service.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.iclick.symphony.iaudience.dao.*; import com.iclick.symphony.iaudience.entity.*; import com.iclick.symphony.iaudience.model.Interest; import com.iclick.symphony.iaudience.model.remote.Advertiser; import com.iclick.symphony.iaudience.model.remote.AudienceRightRetMsg; import com.iclick.symphony.iaudience.model.remote.AudienceRights; import com.iclick.symphony.iaudience.model.remote.ClientAttributes; import com.iclick.symphony.iaudience.model.view.*; import com.iclick.symphony.iaudience.service.AudiencePlanService; import com.iclick.symphony.iaudience.service.BaseService; import com.iclick.symphony.iaudience.service.UserSerivce; import org.apache.commons.lang3.StringUtils; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.*; /** * Created by wenjie.sun on 2017/5/17. */ @Service public class AudiencePlanServiceImpl extends BaseService implements AudiencePlanService { @Resource private AudiencePlanRepository audiencePlanRepository; @Resource private LocationRepository locationRepository; @Resource private LocationCityRepository locationCityRepository; @Resource private InterestStructureRepository interestRepository; @Resource private BrandRepository brandRepository; @Resource private ProductRepository productRepository; @Resource private AdvancedSettingRepository advancedSettingRepository; @Resource private UserSerivce userSerivce; @Override public void save(AudiencePlan audiencePlan) { audiencePlanRepository.save(audiencePlan); } @Transactional(propagation = Propagation.REQUIRED) public boolean saveOrUpdate(AudiencePlanModel audiencePlanModel) { AudiencePlan audiencePlan = null; try { //新增 if (audiencePlanModel.getPlanId() == null){ audiencePlan = new AudiencePlan(); // audiencePlan.setCreateBy(UserUtil.getLoginUserId()); // audiencePlan.setUpdateBy(UserUtil.getLoginUserId()); audiencePlan.setCreateBy(1206); audiencePlan.setCreateTime(new Date()); audiencePlan.setUpdateBy(1206); audiencePlan.setUpdateTime(new Date()); }else { //修改之前先删除 this.deleteBrands(audiencePlanModel.getDeleteBrandIds()); this.deleteProducts(audiencePlanModel.getDeleteProductIds()); //修改 audiencePlan = this.getAudiencePlanById(audiencePlanModel.getPlanId()); //audiencePlan.setUpdateBy(UserUtil.getLoginUserId()); audiencePlan.setUpdateBy(1208); audiencePlan.setUpdateTime(new Date()); } audiencePlan.setClientId(audiencePlanModel.getClientId()); audiencePlan.setCategoryId(audiencePlanModel.getCategoryId()); audiencePlan.setName(audiencePlanModel.getName()); //新增或修改高级设置 AdvancedSettingModel advancedSettingModel = audiencePlanModel.getAdvancedSettingModel(); AdvancedSetting advancedSetting = new AdvancedSetting(); if ( advancedSettingModel.getAdvancedSettingId() != null ){ advancedSetting = advancedSettingRepository.findOne(advancedSettingModel.getAdvancedSettingId()); } setAdvancedSettingProperty(advancedSetting,advancedSettingModel); audiencePlan.setAdvancedSetting(advancedSetting); //新增或修改品牌 List<BrandModel> brandModelList = audiencePlanModel.getBrandModelList(); removeNullBrandAndProduct(brandModelList); for (BrandModel brandModel : brandModelList) { Brand brand = null; if (brandModel.getBrandId() == null){ brand = new Brand(); setBrandProperty(brand,brandModel); List<ProductModel> productModelList = brandModel.getProductModelList(); for (ProductModel productModel : productModelList) { Product product = new Product(); setProductProperty(product,productModel); brand.addProduct(product); } audiencePlan.addBrand(brand); }else { brand = brandRepository.findOne(brandModel.getBrandId()); setBrandProperty(brand,brandModel); List<ProductModel> productModelList = brandModel.getProductModelList(); //新增或修改产品 for (ProductModel productModel : productModelList) { Product product = null; if (productModel.getProductId() == null){ product = new Product(); }else { product = productRepository.findOne(productModel.getProductId()); } setProductProperty(product,productModel); brand.addProduct(product); } } } } catch (Exception e) { e.printStackTrace(); return false; } this.save(audiencePlan); return true; } private void removeNullBrandAndProduct(List<BrandModel> brandModelList){ //先去除空brand List<BrandModel> removeBrandModelList = new ArrayList<>(); for (BrandModel brandModel : brandModelList){ if (brandModel.getBrandId() == null && StringUtils.isBlank(brandModel.getName()) && StringUtils.isBlank(brandModel.getKeyWords())) removeBrandModelList.add(brandModel); } brandModelList.removeAll(removeBrandModelList); //再去除空product for (BrandModel brandModel : brandModelList){ List<ProductModel> productModelList = brandModel.getProductModelList(); List<ProductModel> removeProductModelList = new ArrayList<>(); for (ProductModel productModel : productModelList){ if (productModel.getProductId() == null && StringUtils.isBlank(productModel.getName()) && StringUtils.isBlank(productModel.getCategory()) && StringUtils.isBlank(productModel.getKeyWords())){ removeProductModelList.add(productModel); } } productModelList.removeAll(removeProductModelList); brandModel.setProductModelList(productModelList); } } private void setAdvancedSettingProperty(AdvancedSetting advancedSetting,AdvancedSettingModel advancedSettingModel){ advancedSetting.setCity(advancedSettingModel.getCity()); advancedSetting.setLocation(advancedSettingModel.getLocation()); advancedSetting.setKeyWords(advancedSettingModel.getKeyWords()); } private void setBrandProperty(Brand brand,BrandModel brandModel){ brand.setName(brandModel.getName()); brand.setKeyWords(brandModel.getKeyWords()); brand.setCompetitor(brandModel.getCompetitor().equals("true") ? true :false); } private void setProductProperty(Product product,ProductModel productModel){ product.setCategory(productModel.getCategory()); product.setName(productModel.getName()); product.setKeyWords(productModel.getKeyWords()); } @Transactional(propagation = Propagation.REQUIRED) public void deleteBrands(String[] deleteBrandIds){ if (deleteBrandIds != null && deleteBrandIds.length > 0) { List<Brand> brandList = new ArrayList<>(); for (String brandId : deleteBrandIds) { if (StringUtils.isNotBlank(brandId)) { Brand brand = brandRepository.findOne(Integer.parseInt(brandId)); List<Product> productList = brand.getProducts(); productRepository.deleteInBatch(productList); brand.setAudiencePlan(null); brandList.add(brand); } } brandRepository.deleteInBatch(brandList); } } @Transactional(propagation = Propagation.REQUIRED) public void deleteProducts(String[] deleteProductIds){ if (deleteProductIds != null && deleteProductIds.length >0){ List<Product> productList = new ArrayList<>(); for (String productId : deleteProductIds){ if (StringUtils.isNotBlank(productId)) { Product product = productRepository.findOne(Integer.parseInt(productId)); if (product != null) { product.setBrand(null); productList.add(product); } } } if (productList.size() > 0) productRepository.deleteInBatch(productList); } } @Transactional(propagation = Propagation.REQUIRED) public void deleteAudiencePlan(Integer id){ AudiencePlan audiencePlan = this.getAudiencePlanById(id); if (audiencePlan != null){ audiencePlan.setDeleted(true); audiencePlanRepository.save(audiencePlan); } } @Transactional(readOnly = true) public List<String> getSelectCategoryNames(Integer id,Locale locale) { String interestLab = this.getInterestList(locale); List<Interest> interestList = JSON.parseArray(interestLab,Interest.class); Interest interest = new Interest(); for (Interest temp : interestList){ if (temp.getAudienceId().equals(id)){ interest = temp; break; } } List<String> initList = new ArrayList<>(); initList.add(interest.getName()); return this.getChildrenInterestList(interest,initList); } @Transactional(readOnly = true) // 递归方法查询字interest public List<String> getChildrenInterestList(Interest interest,List<String> interestNameList) { List<Interest> interestListChildren = interest.getChildren(); if (interest == null && interestListChildren.size() == 0){ return interestNameList; }else { for (Interest tmp : interestListChildren){ interestNameList.add(tmp.getName()); getChildrenInterestList(tmp,interestNameList); } } return interestNameList; } @Transactional(propagation = Propagation.REQUIRED) public List<Province> getProvinceNameCnList() { List<Province> provinceList = new ArrayList<Province>(); List<LocationProvince> rows = locationRepository.findProvinceList(); for (LocationProvince row : rows) { Province pro = new Province(); pro.setProvinceId(row.getProvinceId() + ""); pro.setProvinceName(row.getProvinceNameCn()); provinceList.add(pro); } return provinceList; } @Transactional(propagation = Propagation.REQUIRED) public List<Province> getProvinceNameEnList() { List<Province> provinceList = new ArrayList<Province>(); List<LocationProvince> rows = locationRepository.findProvinceList(); for (LocationProvince row : rows) { Province pro = new Province(); pro.setProvinceId(row.getProvinceId() + ""); pro.setProvinceName(row.getProvinceNameEn()); provinceList.add(pro); } return provinceList; } private Interest coverToInterest(InterestStructure row, Locale locale) { Interest interest = new Interest(); if (Locale.CHINESE.toString().equals(locale.getLanguage())) { interest.setName(row.getNameCn()); } else { interest.setName(row.getNameEn()); } String id = String.valueOf(row.getId()); interest.setAudienceId(id); if (StringUtils.isNotBlank(id) && id.length() > 2) { interest.setParentId(id.substring(0, id.length() - 2)); } else { interest.setParentId("0"); } return interest; } @Transactional(propagation = Propagation.REQUIRED) public List<City> getCityNameCnList() { List<City> cityList = new ArrayList<City>(); List<LocationCity> rows = locationCityRepository.findCityList(); for (LocationCity row : rows) { City city = new City(); city.setCityId(row.getCityId()+""); city.setCityName(row.getCityNameCn()); cityList.add(city); } return cityList; } @Transactional(propagation = Propagation.REQUIRED) public List<City> getCityNameEnList() { List<City> cityList = new ArrayList<City>(); List<LocationCity> rows = locationCityRepository.findCityList(); for (LocationCity row : rows) { City city = new City(); city.setCityId(row.getCityId()+""); city.setCityName(row.getCityNameEn()); cityList.add(city); } return cityList; } @Override public String getInterestName(Integer id, Locale locale) { InterestStructure interest = interestRepository.findOne(id); String name = ""; if (Locale.ENGLISH.toString().equals(locale.getLanguage())) { name = interest.getNameEn(); } else { name = interest.getNameCn(); } return name; } @Transactional(propagation = Propagation.REQUIRED) @Override public String getInterestList(Locale locale) { List<Interest> resultList = new ArrayList<Interest>(); List<Interest> tempList = null; try { List<InterestStructure> interestList = interestRepository.findInterestList(); Interest interest = null; Map<String, List<Interest>> subMap = new HashMap<>(); String parentId = null; for (InterestStructure row : interestList) { interest = coverToInterest(row, locale); parentId = interest.getParentId(); interest.setChildren(subMap.get(interest.getAudienceId())); // 顶级节点 if ("0".equals(parentId)) { resultList.add(interest); } else { if (subMap.containsKey(parentId)) { subMap.get(parentId).add(interest); } else { tempList = new ArrayList<Interest>(); tempList.add(interest); subMap.put(parentId, tempList); } } interest = null; } } catch (Exception e) { } return JSONObject.toJSONString(resultList); } @Override public AudiencePlanModel getAudiencePlanModel(Integer id) { AudiencePlanModel audiencePlanModel = new AudiencePlanModel(); AudiencePlan audiencePlan = this.getAudiencePlanById(id); if (audiencePlan == null) { return null; } audiencePlanModel.setPlanId(audiencePlan.getId()); audiencePlanModel.setName(audiencePlan.getName()); audiencePlanModel.setCategoryId(audiencePlan.getCategoryId()); audiencePlanModel.setClientId(audiencePlan.getClientId()); // audiencePlanModel.setUserId( UserUtil.getLoginUserId()); //brandModel集合 List<BrandModel> brandModelList = new ArrayList<>(); List<Brand> brandList = new ArrayList<>(audiencePlan.getBrands()); Collections.sort(brandList, Comparator.comparingInt(Brand::getId)); for (Brand brand : brandList){ BrandModel brandModel = new BrandModel(); brandModel.setName(brand.getName()); brandModel.setBrandId(brand.getId()); brandModel.setCompetitor(brand.isCompetitor()? "true" : "false"); brandModel.setKeyWords(brand.getKeyWords()); //producModel集合 List<ProductModel> productModelList = new ArrayList<>(); for (Product product : brand.getProducts()){ ProductModel productModel = new ProductModel(); productModel.setProductId(product.getId()); productModel.setCategory(product.getCategory()); productModel.setName(product.getName()); productModel.setKeyWords(product.getKeyWords()); productModelList.add(productModel); } brandModel.setProductModelList(productModelList); brandModelList.add(brandModel); } audiencePlanModel.setBrandModelList(brandModelList); AdvancedSettingModel advancedSettingModel = new AdvancedSettingModel(); AdvancedSetting advancedSetting = audiencePlan.getAdvancedSetting(); advancedSettingModel.setAdvancedSettingId(advancedSetting.getId()); advancedSettingModel.setCity(advancedSetting.getCity()); advancedSettingModel.setLocation(advancedSetting.getLocation()); advancedSettingModel.setKeyWords(advancedSetting.getKeyWords()); audiencePlanModel.setAdvancedSettingModel(advancedSettingModel); return audiencePlanModel; } @Override public List<Product> getProductList(Integer id, String type) { List<Product> productList = new ArrayList<>(); if (type.equals("brand")){ productList = productRepository.findByBrandId(id); } if (type.equals("product")){ Product product = productRepository.findOne(id); productList.add(product); } return productList; } @Transactional(propagation = Propagation.REQUIRED) public Map<String, String> getInterestMaping(Locale locale) { List<InterestStructure> interestList = interestRepository.findInterestList(); Map<String, String> interestMapping = new HashMap<>(); String name = null; for (InterestStructure interest : interestList) { if (Locale.ENGLISH.toString().equals(locale.getLanguage())) { name = interest.getNameEn(); } else { name = interest.getNameCn(); } interestMapping.put(interest.getId() + "", name); } return interestMapping; } @Transactional(readOnly = true) public List<AudiencePlan> getAudiencePlanList(List<Integer> clientIds) { Sort sort = new Sort(Direction.DESC, "updateTime"); return audiencePlanRepository.findByIsDeletedFalseAndClientIdIn(clientIds,sort); } @Transactional(readOnly = true) public List<AudiencePlan> getAudiencePlanList(int clientId) { Sort sort = new Sort(Direction.DESC, "updateTime"); return audiencePlanRepository.findByIsDeletedFalseAndClientId(clientId,sort); } @Transactional(readOnly = true) public List<AudiencePlan> getAudiencePlanList() { Sort sort = new Sort(Direction.DESC, "updateTime"); return audiencePlanRepository.findByIsDeletedFalse(sort); } @Override public List<AudiencePlanModel> getAudienceModelList(int clientId) { List<AudiencePlan> audiencePlanList = this.getAudiencePlanList(clientId); List<AudiencePlanModel> audiencePlanModelList = new ArrayList<>(); if (audiencePlanList.size() > 0) { for (AudiencePlan audiencePlan : audiencePlanList) { audiencePlanModelList.add(this.getAudiencePlanModel(audiencePlan.getId())); } } return audiencePlanModelList; } @Transactional(readOnly = true) public AudiencePlan getAudiencePlanById(Integer id) { if (id == null){ return null; } return audiencePlanRepository.findOne(id); } @Transactional(readOnly = true) public Map<String, Object> getClientsShow(Integer userId,Integer currentClientId) { List<ClientModel> recentClients = new ArrayList<>(); ClientModel currentClient = new ClientModel(); List<AgentModel> allAgents = new ArrayList<>(); List<Integer> userIds = new ArrayList<>(); userIds.add(userId); AudienceRights audienceRights = userSerivce.getClients(userIds); AudienceRightRetMsg audienceRightRetMsg = audienceRights.getRet_msg(); if (audienceRightRetMsg != null && audienceRightRetMsg.getList() != null){ ClientAttributes clientAttributes = audienceRightRetMsg.getList().get(0); List<Advertiser> advertiserList = clientAttributes.getAdvids(); if (!advertiserList.isEmpty()){ for (Advertiser advertiser : advertiserList) { AgentModel agentModel = new AgentModel(); agentModel.setAgentId(advertiser.getAgent().getId()); if (advertiser.getId() == currentClientId){ currentClient.setClientId(currentClientId); currentClient.setClientName(advertiser.getName()); } } } } System.out.println(audienceRights); Map<String,Object> map = new HashMap(); map.put("currentClient",""); map.put("recentClient",""); map.put("all",""); return map; } @Transactional(readOnly = true) public Page<AudiencePlan> getAllByPage(int pageNumber, int pageSize) { Sort sort = new Sort(Direction.DESC, "createTime"); PageRequest request = buildPageRequest(pageNumber,pageSize, sort); Page<AudiencePlan> audiencePlans = audiencePlanRepository.findAllPlans(false, request); return audiencePlans; } @Override public List<Product> getProductsByBrandId(int id) { return productRepository.findByBrandId(id); } }
22,361
0.633883
0.63249
553
39.229656
28.162659
207
false
false
0
0
0
0
0
0
0.564195
false
false
7
e5fb512f368b67106eded8c44750dfc15734441a
11,587,821,806,520
411da3bc03a68746067a1d6f7c34b0b084f462bc
/commons-web/src/main/java/com/shengpay/commons/web/protocol/ProtocolSignTOForTest.java
0bb2e56c8b2e76edb4bd1824cf46cd23899a93c3
[]
no_license
wulliam/commons
https://github.com/wulliam/commons
82d0da7d0835dc54ad7363edf84f9fb161b62b8a
c9e903b915eeb55d27b07252e49e67320212ed86
refs/heads/master
"2021-01-15T11:13:44.312000"
"2014-07-02T02:40:19"
"2014-07-02T02:40:19"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.shengpay.commons.web.protocol; import java.util.Date; import java.util.List; import com.shengpay.commons.core.base.BaseObject; public class ProtocolSignTOForTest extends BaseObject { private String merchantId; private String merchantName; private String merchantSeqNO; @ProtocolFieldAnn(paramName="goods_num") private Integer goodsNUM; @ProtocolFieldAnn(paramName="item") private List<ProtocolSignTOClientForTest> goods; @ProtocolFieldAnn(dateFormat="yyyyMMddHHmmss",paramName="mer_date") private Date merchantDate; public String getMerchantSeqNO() { return merchantSeqNO; } public void setMerchantSeqNO(String itemName) { this.merchantSeqNO = itemName; } public Integer getGoodsNUM() { return goodsNUM; } public void setGoodsNUM(Integer itemCount) { this.goodsNUM = itemCount; } public String getMerchantName() { return merchantName; } public void setMerchantName(String merchantName) { this.merchantName = merchantName; } public List<ProtocolSignTOClientForTest> getGoods() { return goods; } public void setGoods(List<ProtocolSignTOClientForTest> clientList) { this.goods = clientList; } public String getMerchantId() { return merchantId; } public void setMerchantId(String merchantId) { this.merchantId = merchantId; } public Date getMerchantDate() { return merchantDate; } public void setMerchantDate(Date merchantDate) { this.merchantDate = merchantDate; } }
UTF-8
Java
1,456
java
ProtocolSignTOForTest.java
Java
[]
null
[]
package com.shengpay.commons.web.protocol; import java.util.Date; import java.util.List; import com.shengpay.commons.core.base.BaseObject; public class ProtocolSignTOForTest extends BaseObject { private String merchantId; private String merchantName; private String merchantSeqNO; @ProtocolFieldAnn(paramName="goods_num") private Integer goodsNUM; @ProtocolFieldAnn(paramName="item") private List<ProtocolSignTOClientForTest> goods; @ProtocolFieldAnn(dateFormat="yyyyMMddHHmmss",paramName="mer_date") private Date merchantDate; public String getMerchantSeqNO() { return merchantSeqNO; } public void setMerchantSeqNO(String itemName) { this.merchantSeqNO = itemName; } public Integer getGoodsNUM() { return goodsNUM; } public void setGoodsNUM(Integer itemCount) { this.goodsNUM = itemCount; } public String getMerchantName() { return merchantName; } public void setMerchantName(String merchantName) { this.merchantName = merchantName; } public List<ProtocolSignTOClientForTest> getGoods() { return goods; } public void setGoods(List<ProtocolSignTOClientForTest> clientList) { this.goods = clientList; } public String getMerchantId() { return merchantId; } public void setMerchantId(String merchantId) { this.merchantId = merchantId; } public Date getMerchantDate() { return merchantDate; } public void setMerchantDate(Date merchantDate) { this.merchantDate = merchantDate; } }
1,456
0.76717
0.76717
72
19.222221
19.871267
69
false
false
0
0
0
0
0
0
1.138889
false
false
7
74a54d3846d737c7c8e43c93c50a812506d24af2
17,386,027,677,440
7186708f851211518d579e32c0b574ee75aa7043
/myappconverter_library/src/main/java/com/myappconverter/uikit/myappclasses/MyAppNumberPicker.java
06c1add19fb43b02419271267e7ea2b7ecdf96f5
[]
no_license
MyAppConverter/Touches-android
https://github.com/MyAppConverter/Touches-android
4336fd0a266aabc9ce67c8b58857ef71dfde2680
6fb6e25e50d99ec53e272f08897fc252c865be96
refs/heads/master
"2021-01-10T15:48:17.034000"
"2016-01-20T15:14:21"
"2016-01-20T15:14:21"
50,038,111
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.myappconverter.uikit.myappclasses; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.NumberPicker; public class MyAppNumberPicker extends NumberPicker { // private NumberPicker numberPicker; // private LayoutInflater inflater; private int stepValue; private boolean wraps; public MyAppNumberPicker(Context ctx) { super(ctx); stepValue = 1; // inflater = LayoutInflater.from(ctx); // View v = inflater.inflate(R.layout.datepicker_layout, null); } public int getStepValue() { return stepValue; } public void setStepValue(int stepValue) { this.stepValue = stepValue; this.setValue(this.getValue() + this.stepValue); } public boolean getWraps() { return wraps; } public void setWraps(boolean wraps) { this.wraps = wraps; if (wraps == true) { this.setMaxValue(this.getMinValue()); } else { this.setMinValue(this.getMaxValue()); } } }
UTF-8
Java
1,097
java
MyAppNumberPicker.java
Java
[]
null
[]
package com.myappconverter.uikit.myappclasses; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.NumberPicker; public class MyAppNumberPicker extends NumberPicker { // private NumberPicker numberPicker; // private LayoutInflater inflater; private int stepValue; private boolean wraps; public MyAppNumberPicker(Context ctx) { super(ctx); stepValue = 1; // inflater = LayoutInflater.from(ctx); // View v = inflater.inflate(R.layout.datepicker_layout, null); } public int getStepValue() { return stepValue; } public void setStepValue(int stepValue) { this.stepValue = stepValue; this.setValue(this.getValue() + this.stepValue); } public boolean getWraps() { return wraps; } public void setWraps(boolean wraps) { this.wraps = wraps; if (wraps == true) { this.setMaxValue(this.getMinValue()); } else { this.setMinValue(this.getMaxValue()); } } }
1,097
0.640839
0.639927
47
22.340425
19.609243
72
false
false
0
0
0
0
0
0
0.574468
false
false
7
cbfb800efd6be7464d6ccd09cfe41f7da9f45e04
32,598,801,815,763
8343c1820c0f9974eae2895a22cfd56b5d05fbdc
/src/main/java/com/pinke/uni/lottery/receiver/IssueInfoChangeReceiver.java
68d0d0beb7e024f77f9a92928b567825dc79c212
[]
no_license
Edifierlurker/EduServer
https://github.com/Edifierlurker/EduServer
8638d4f1523225e8a938646cad140ee4136ce2d9
47896cb29ed1ac16724d04b2f0f05d1593faf54a
refs/heads/master
"2021-01-02T09:25:48.270000"
"2015-03-02T14:04:17"
"2015-03-02T14:04:17"
31,405,081
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pinke.uni.lottery.receiver; import com.pinke.uni.lottery.ParamsUtil; import com.pinke.uni.lottery.common.GameErrors; import com.pinke.uni.mobile.protal.common.page.handle.BaseServiceHandle; import com.pinke.uni.mobile.protal.common.page.handle.IPageServiceHandle; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; /** * 彩种信息变更通知 */ public class IssueInfoChangeReceiver extends BaseServiceHandle { private static final String[] PARAM = {"lottery", "status", "note", "award", "startTime", "endTime", "periods", "interval", "open"}; @Override public IPageServiceHandle proccess(HttpServletRequest request, HttpServletResponse response) { Map<String, String> map = request.getParameterMap(); String sign = map.get("sign"); if (map.get("t") == null || sign == null || map.get("partner") == null) { result.set(GameErrors.INFO_ERROR + ""); } else { if (ParamsUtil.verifySign(sign, map)) { //todo 彩种信息变更通知 } } result.set("0"); return this; } }
UTF-8
Java
1,176
java
IssueInfoChangeReceiver.java
Java
[]
null
[]
package com.pinke.uni.lottery.receiver; import com.pinke.uni.lottery.ParamsUtil; import com.pinke.uni.lottery.common.GameErrors; import com.pinke.uni.mobile.protal.common.page.handle.BaseServiceHandle; import com.pinke.uni.mobile.protal.common.page.handle.IPageServiceHandle; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; /** * 彩种信息变更通知 */ public class IssueInfoChangeReceiver extends BaseServiceHandle { private static final String[] PARAM = {"lottery", "status", "note", "award", "startTime", "endTime", "periods", "interval", "open"}; @Override public IPageServiceHandle proccess(HttpServletRequest request, HttpServletResponse response) { Map<String, String> map = request.getParameterMap(); String sign = map.get("sign"); if (map.get("t") == null || sign == null || map.get("partner") == null) { result.set(GameErrors.INFO_ERROR + ""); } else { if (ParamsUtil.verifySign(sign, map)) { //todo 彩种信息变更通知 } } result.set("0"); return this; } }
1,176
0.668706
0.667832
33
33.666668
32.474388
136
false
false
0
0
0
0
0
0
0.878788
false
false
7
94bd1f4ab44773f8cc6476d265b8de7a4ec4f6ca
21,157,008,941,057
113a96f15e6f580e93d805b49ef8b2312441ff1b
/liba-fast-mvc/src/main/java/oms/mmc/android/fast/framwork/util/IViewFinderAction.java
6bdeebef17c99ad9cbb8387bc776779f299f13b9
[]
no_license
hezihaog/FastMvc
https://github.com/hezihaog/FastMvc
314bd8530ca46eb3ee8c76bf83a777964911f3b1
74b273181fb2cc2904827a368adbd38fa3aac38c
refs/heads/master
"2021-05-11T05:19:54.997000"
"2018-04-28T02:44:10"
"2018-04-28T02:44:10"
117,958,298
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package oms.mmc.android.fast.framwork.util; import android.support.annotation.DrawableRes; import android.support.annotation.IdRes; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import mmc.image.ImageLoader; import mmc.image.LoadImageCallback; /** * Package: oms.mmc.android.fast.framwork.util * FileName: IViewFinderAction * Date: on 2018/3/8 上午10:14 * Auther: zihe * Descirbe: * Email: hezihao@linghit.com */ public interface IViewFinderAction { //------------------------ 控件操作 ------------------------ /** * 抽象方法,子类实现返回ViewFinder */ IViewFinder getViewFinder(); /** * 获取布局View * * @return 布局View */ View getRootView(); /** * 字符串是否是空的 * * @param str 要判断的文字 */ boolean isEmpty(CharSequence str); /** * 字符串是否不是空的 */ boolean isNotEmpty(CharSequence str); /** * 判断View显示的文字是否为空 * * @param viewId 控件id * @param isFilterSpace 是否调用trim,就是如果是空格符的话,则不当是有文字内容 */ boolean viewTextIsEmpty(@IdRes int viewId, boolean isFilterSpace); /** * 判断View显示的文字是否为空 * * @param view 控件对象 * @param isFilterSpace 是否调用trim,就是如果是空格符的话,则不当是有文字内容 */ boolean viewTextIsEmpty(TextView view, boolean isFilterSpace); /** * 判断View显示的文字是否为空,该方法是包含过滤前后空格 * * @param viewId 控件id */ boolean viewTextIsEmptyWithTrim(@IdRes int viewId); /** * 判断View显示的文字是否为空,该方法是包含过滤前后空格 * * @param view 控件对象 */ boolean viewTextIsEmptyWithTrim(TextView view); /** * 判断View显示的文字是否不为空 * * @param viewId 控件id */ boolean viewTextIsNotEmpty(@IdRes int viewId); /** * 判断View显示的文字是否不为空 * * @param view 控件对象 */ boolean viewTextIsNotEmpty(TextView view); //-------------------------------- 设置文字 -------------------------------- /** * 直接控件id设置文字 * * @param text 文字 * @param viewId 控件id,必须是TextView以及子类 */ void setViewText(CharSequence text, @IdRes int viewId); /** * 直接控件id设置文字 * * @param text 文字 * @param defaultText 如果传入文字的值为null,设置的默认文字 * @param viewId 控件id,必须是TextView以及子类 */ void setTextWithDefault(CharSequence text, CharSequence defaultText, @IdRes int viewId); /** * 为TextView设置文字,如果传入的Text为null,则设置为空字符串 * * @param text 要设置的文字 * @param view TextView对象 */ void setViewText(CharSequence text, TextView view); /** * 为Text设置文字,如果传入的Text为null,则设置为默认值 * * @param text 要设置的问题 * @param defaultText 传入的文字为null时,设置的默认文本 * @param view TextView */ void setTextWithDefault(CharSequence text, CharSequence defaultText, TextView view); //-------------------------------- 获取TextView及其子类的文字 -------------------------------- /** * 使用TextView,获取View上的文字,当获取为""时,返回空字符串 "" * * @param view TextView对象 * @return View上的文字 */ CharSequence getViewText(TextView view); /** * 使用View id,获取View上的文字,当获取为""时,返回空字符串 "" * * @param viewId TextView的id * @return View上的文字 */ CharSequence getViewText(@IdRes int viewId); /** * 使用View Id,获取文字,当获取为""时,可指定返回默认文字 * * @param viewId View id * @param defaultText 默认文字 */ CharSequence getTextWithDefault(@IdRes int viewId, CharSequence defaultText); /** * 使用View,获取文字,当获取为""时,可指定返回默认文字 * * @param textView View id * @param defaultText 默认文字 */ CharSequence getTextWithDefault(TextView textView, CharSequence defaultText); /** * 获取View上的文字,并且toString和trim去掉前后空格 * * @param viewId View的id */ CharSequence getViewTextWithTrim(@IdRes int viewId); /** * 获取View上的文字,并且toString和trim去掉前后空格 * * @param view View对象 */ CharSequence getViewTextWithTrim(TextView view); //-------------------------------- 单次设置监听器 -------------------------------- /** * 查找并且设置点击监听器 * * @param listener 监听器 * @param id view 的 id */ View findAndSetOnClick(@IdRes int id, View.OnClickListener listener); /** * 查找并设置长按监听器 * * @param id View的id * @param listener 监听器 */ View findAndSetOnLongClick(@IdRes int id, View.OnLongClickListener listener); //-------------------------------- 批量设置监听器 -------------------------------- /** * 批量id,设置同一个点击监听器 * * @param listener 点击监听器 * @param ids view 的 id */ void setOnClickListener(View.OnClickListener listener, @IdRes int... ids); /** * 批量View,设置同一个点击监听器 * * @param listener 点击监听器 * @param views 多个View对象 */ void setOnClickListener(View.OnClickListener listener, View... views); /** * 批量View id,设置同一个长按监听器 * * @param listener 长按监听器 * @param ids View 的id */ void setOnLongClickListener(View.OnLongClickListener listener, @IdRes int... ids); /** * 批量View,设置同一个长按监听器 * * @param listener 长按监听器 * @param views 多个View对象 */ void setOnLongClickListener(View.OnLongClickListener listener, View... views); //-------------------------------- 设置View的显示隐藏 -------------------------------- /** * 以多个id的方式,批量设置View为显示 * * @param ids 多个View的id */ void setVisible(@IdRes int... ids); /** * 以多个id的方式,批量设置View为隐藏占位 * * @param ids 多个View的id */ void setInVisible(@IdRes int... ids); /** * 以多个id的方式,批量设置View为隐藏 * * @param ids 多个View的id */ void setGone(@IdRes int... ids); /** * 设置多个View显示 */ void setVisible(View... views); /** * 设置多个View为隐藏占位 * * @param views 多个View对象 */ void setInVisible(View... views); /** * 设置多个View隐藏 */ void setGone(View... views); //-------------------------------- 图片加载 -------------------------------- /** * 获取图片加载器 */ ImageLoader getImageLoader(); /** * 加载网络图片 */ void loadUrlImage(String url, ImageView imageView, @IdRes int defaultImage); /** * 加载网络圆形图片 */ void loadUrlImageToRound(String url, ImageView imageView, @IdRes int defaultImage); /** * 加载网络圆角图片 */ void loadUrlImageToCorner(String url, ImageView imageView, @IdRes int defaultImage); /** * 加载内存卡图片 */ void loadFileImage(String filePath, ImageView imageView, @IdRes int defaultImage); /** * 加载图片bitmap */ void loadImageToBitmap(String url, LoadImageCallback loadImageCallback); /** * 加载本地Res图片 */ void loadDrawableResId(@IdRes int imageViewId, @DrawableRes int resId); /** * 加载本地Res图片 */ void loadDrawableResId(ImageView imageView, @DrawableRes int resId); /** * 清除图片缓存 */ void clearImageMemoryCache(); }
UTF-8
Java
8,475
java
IViewFinderAction.java
Java
[ { "context": "derAction\n * Date: on 2018/3/8 上午10:14\n * Auther: zihe\n * Descirbe:\n * Email: hezihao@linghit.com\n */\n\np", "end": 419, "score": 0.9996542930603027, "start": 415, "tag": "USERNAME", "value": "zihe" }, { "context": "/8 上午10:14\n * Auther: zihe\n * Descirbe:\n * Email: hezihao@linghit.com\n */\n\npublic interface IViewFinderAction {\n //-", "end": 462, "score": 0.9999263286590576, "start": 443, "tag": "EMAIL", "value": "hezihao@linghit.com" } ]
null
[]
package oms.mmc.android.fast.framwork.util; import android.support.annotation.DrawableRes; import android.support.annotation.IdRes; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import mmc.image.ImageLoader; import mmc.image.LoadImageCallback; /** * Package: oms.mmc.android.fast.framwork.util * FileName: IViewFinderAction * Date: on 2018/3/8 上午10:14 * Auther: zihe * Descirbe: * Email: <EMAIL> */ public interface IViewFinderAction { //------------------------ 控件操作 ------------------------ /** * 抽象方法,子类实现返回ViewFinder */ IViewFinder getViewFinder(); /** * 获取布局View * * @return 布局View */ View getRootView(); /** * 字符串是否是空的 * * @param str 要判断的文字 */ boolean isEmpty(CharSequence str); /** * 字符串是否不是空的 */ boolean isNotEmpty(CharSequence str); /** * 判断View显示的文字是否为空 * * @param viewId 控件id * @param isFilterSpace 是否调用trim,就是如果是空格符的话,则不当是有文字内容 */ boolean viewTextIsEmpty(@IdRes int viewId, boolean isFilterSpace); /** * 判断View显示的文字是否为空 * * @param view 控件对象 * @param isFilterSpace 是否调用trim,就是如果是空格符的话,则不当是有文字内容 */ boolean viewTextIsEmpty(TextView view, boolean isFilterSpace); /** * 判断View显示的文字是否为空,该方法是包含过滤前后空格 * * @param viewId 控件id */ boolean viewTextIsEmptyWithTrim(@IdRes int viewId); /** * 判断View显示的文字是否为空,该方法是包含过滤前后空格 * * @param view 控件对象 */ boolean viewTextIsEmptyWithTrim(TextView view); /** * 判断View显示的文字是否不为空 * * @param viewId 控件id */ boolean viewTextIsNotEmpty(@IdRes int viewId); /** * 判断View显示的文字是否不为空 * * @param view 控件对象 */ boolean viewTextIsNotEmpty(TextView view); //-------------------------------- 设置文字 -------------------------------- /** * 直接控件id设置文字 * * @param text 文字 * @param viewId 控件id,必须是TextView以及子类 */ void setViewText(CharSequence text, @IdRes int viewId); /** * 直接控件id设置文字 * * @param text 文字 * @param defaultText 如果传入文字的值为null,设置的默认文字 * @param viewId 控件id,必须是TextView以及子类 */ void setTextWithDefault(CharSequence text, CharSequence defaultText, @IdRes int viewId); /** * 为TextView设置文字,如果传入的Text为null,则设置为空字符串 * * @param text 要设置的文字 * @param view TextView对象 */ void setViewText(CharSequence text, TextView view); /** * 为Text设置文字,如果传入的Text为null,则设置为默认值 * * @param text 要设置的问题 * @param defaultText 传入的文字为null时,设置的默认文本 * @param view TextView */ void setTextWithDefault(CharSequence text, CharSequence defaultText, TextView view); //-------------------------------- 获取TextView及其子类的文字 -------------------------------- /** * 使用TextView,获取View上的文字,当获取为""时,返回空字符串 "" * * @param view TextView对象 * @return View上的文字 */ CharSequence getViewText(TextView view); /** * 使用View id,获取View上的文字,当获取为""时,返回空字符串 "" * * @param viewId TextView的id * @return View上的文字 */ CharSequence getViewText(@IdRes int viewId); /** * 使用View Id,获取文字,当获取为""时,可指定返回默认文字 * * @param viewId View id * @param defaultText 默认文字 */ CharSequence getTextWithDefault(@IdRes int viewId, CharSequence defaultText); /** * 使用View,获取文字,当获取为""时,可指定返回默认文字 * * @param textView View id * @param defaultText 默认文字 */ CharSequence getTextWithDefault(TextView textView, CharSequence defaultText); /** * 获取View上的文字,并且toString和trim去掉前后空格 * * @param viewId View的id */ CharSequence getViewTextWithTrim(@IdRes int viewId); /** * 获取View上的文字,并且toString和trim去掉前后空格 * * @param view View对象 */ CharSequence getViewTextWithTrim(TextView view); //-------------------------------- 单次设置监听器 -------------------------------- /** * 查找并且设置点击监听器 * * @param listener 监听器 * @param id view 的 id */ View findAndSetOnClick(@IdRes int id, View.OnClickListener listener); /** * 查找并设置长按监听器 * * @param id View的id * @param listener 监听器 */ View findAndSetOnLongClick(@IdRes int id, View.OnLongClickListener listener); //-------------------------------- 批量设置监听器 -------------------------------- /** * 批量id,设置同一个点击监听器 * * @param listener 点击监听器 * @param ids view 的 id */ void setOnClickListener(View.OnClickListener listener, @IdRes int... ids); /** * 批量View,设置同一个点击监听器 * * @param listener 点击监听器 * @param views 多个View对象 */ void setOnClickListener(View.OnClickListener listener, View... views); /** * 批量View id,设置同一个长按监听器 * * @param listener 长按监听器 * @param ids View 的id */ void setOnLongClickListener(View.OnLongClickListener listener, @IdRes int... ids); /** * 批量View,设置同一个长按监听器 * * @param listener 长按监听器 * @param views 多个View对象 */ void setOnLongClickListener(View.OnLongClickListener listener, View... views); //-------------------------------- 设置View的显示隐藏 -------------------------------- /** * 以多个id的方式,批量设置View为显示 * * @param ids 多个View的id */ void setVisible(@IdRes int... ids); /** * 以多个id的方式,批量设置View为隐藏占位 * * @param ids 多个View的id */ void setInVisible(@IdRes int... ids); /** * 以多个id的方式,批量设置View为隐藏 * * @param ids 多个View的id */ void setGone(@IdRes int... ids); /** * 设置多个View显示 */ void setVisible(View... views); /** * 设置多个View为隐藏占位 * * @param views 多个View对象 */ void setInVisible(View... views); /** * 设置多个View隐藏 */ void setGone(View... views); //-------------------------------- 图片加载 -------------------------------- /** * 获取图片加载器 */ ImageLoader getImageLoader(); /** * 加载网络图片 */ void loadUrlImage(String url, ImageView imageView, @IdRes int defaultImage); /** * 加载网络圆形图片 */ void loadUrlImageToRound(String url, ImageView imageView, @IdRes int defaultImage); /** * 加载网络圆角图片 */ void loadUrlImageToCorner(String url, ImageView imageView, @IdRes int defaultImage); /** * 加载内存卡图片 */ void loadFileImage(String filePath, ImageView imageView, @IdRes int defaultImage); /** * 加载图片bitmap */ void loadImageToBitmap(String url, LoadImageCallback loadImageCallback); /** * 加载本地Res图片 */ void loadDrawableResId(@IdRes int imageViewId, @DrawableRes int resId); /** * 加载本地Res图片 */ void loadDrawableResId(ImageView imageView, @DrawableRes int resId); /** * 清除图片缓存 */ void clearImageMemoryCache(); }
8,463
0.561825
0.560386
314
21.124205
22.736664
92
false
false
0
0
0
0
0
0
0.242038
false
false
7
83a617dbb1eadebabad8ee8783de8b022c74f03b
5,291,399,745,104
3e3f5af294a14bcf0fde90b4bb21b5010dd3a0f7
/GUIAssignment_AsmerBracho/src/admin/Admin.java
39a674f4dba78ddf2d13673803e920375dbff1e6
[]
no_license
AsmerBracho/Tech-Support-System
https://github.com/AsmerBracho/Tech-Support-System
a407736f47b0c2090811a22f1db72644711bf46a
bd7413bcd6aac289e56fd1a5acba4b6d23d115ea
refs/heads/master
"2020-04-01T21:48:14.029000"
"2018-10-18T19:38:39"
"2018-10-18T19:38:39"
153,676,047
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package admin; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.Border; import login.Login; public class Admin extends JFrame { DataPanel data = null; Update u = null; RegisterPanel registerPanel = null; String cabecera = ""; public Admin(String n) { super("Admin Dashboard"); cabecera = n; this.setSize(1200, 890); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); setLayout(new BorderLayout()); //---------------Toolbar------------------// JPanel toolbar = new JPanel(); FlowLayout fl = new FlowLayout(); fl.setAlignment(2); toolbar.setLayout(new BorderLayout()); toolbar.setBackground(Color.gray); Border outerBorder = BorderFactory.createEtchedBorder(); Border innerBorder = BorderFactory.createEmptyBorder(5, 10, 5, 10); toolbar.setBorder(BorderFactory.createCompoundBorder(outerBorder, innerBorder)); JPanel right = new JPanel(); right.setBackground(Color.gray); right.setLayout(fl); JLabel img = new JLabel(""); Image image = new ImageIcon(this.getClass().getResource("/user.png")).getImage(); img.setIcon(new ImageIcon(image)); right.add(img); JLabel wel = new JLabel("Welcome: "); JLabel user = new JLabel(cabecera + " "); user.setFont (user.getFont ().deriveFont (18.0f)); user.setForeground(Color.blue); right.add(wel); right.add(user); JButton logout = new JButton("Logout"); Image imageL = new ImageIcon(this.getClass().getResource("/logoutIcon.png")).getImage(); logout.setIcon(new ImageIcon(imageL)); right.add(logout); JPanel left = new JPanel(); left.setBackground(Color.gray); JLabel users = new JLabel(); Image image2 = new ImageIcon(this.getClass().getResource("/users.png")).getImage(); users.setIcon(new ImageIcon(image2)); left.add(users); JLabel title = new JLabel("Admin Dashboard"); title.setFont (title.getFont ().deriveFont (20.0f)); left.add(title); toolbar.add(left, BorderLayout.LINE_START); toolbar.add(right, BorderLayout.LINE_END); //----------------------botton panel Toolbar -----------------------------// JPanel botton = new JPanel(); FlowLayout f2 = new FlowLayout(); f2.setAlignment(0); botton.setLayout(f2); Border outerBorder0 = BorderFactory.createEtchedBorder(); Border innerBorder0 = BorderFactory.createEmptyBorder(5, 10, 5, 10); botton.setBorder(BorderFactory.createCompoundBorder(outerBorder0, innerBorder0)); JLabel refresh = new JLabel(""); Image image3 = new ImageIcon(this.getClass().getResource("/refresh.png")).getImage(); refresh.setIcon(new ImageIcon(image3)); botton.add(refresh); //----------------------ADD BIG TOOLBAR-----------------------------// JPanel big = new JPanel(); big.setLayout(new BorderLayout()); big.add(toolbar, BorderLayout.NORTH); big.add(botton, BorderLayout.SOUTH); //------------------------------------------------------------------// //--------------Register------------------// JPanel register = new JPanel(); register.setLayout(new BorderLayout()); Border innerBorder2 = BorderFactory.createTitledBorder("Register"); Border outerBorder2 = BorderFactory.createEmptyBorder(10,10,10,10); register.setBorder(BorderFactory.createCompoundBorder(outerBorder2, innerBorder2)); // resizing the panel Dimension d = getPreferredSize(); d.width = 400; register.setPreferredSize(d); u = new Update(this); registerPanel = new RegisterPanel(this); register.add(registerPanel, BorderLayout.NORTH); register.add(u, BorderLayout.SOUTH); //----------------------------------------// data = new DataPanel(this); this.add(big, BorderLayout.PAGE_START); this.add(register, BorderLayout.WEST); this.add(data, BorderLayout.CENTER); logout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { optionLogout(); } }); refresh.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent arg0) { ver(); new Admin(cabecera); } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }); } public void optionLogout() { Object[] options = {"Yes", "No"}; int n = JOptionPane.showOptionDialog( this, "Are you sure you want to logout?" + "", "Logout", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == 0) { this.dispose(); new Login(); } } public void ver() { this.dispose(); } }
UTF-8
Java
5,790
java
Admin.java
Java
[]
null
[]
package admin; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.Border; import login.Login; public class Admin extends JFrame { DataPanel data = null; Update u = null; RegisterPanel registerPanel = null; String cabecera = ""; public Admin(String n) { super("Admin Dashboard"); cabecera = n; this.setSize(1200, 890); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); setLayout(new BorderLayout()); //---------------Toolbar------------------// JPanel toolbar = new JPanel(); FlowLayout fl = new FlowLayout(); fl.setAlignment(2); toolbar.setLayout(new BorderLayout()); toolbar.setBackground(Color.gray); Border outerBorder = BorderFactory.createEtchedBorder(); Border innerBorder = BorderFactory.createEmptyBorder(5, 10, 5, 10); toolbar.setBorder(BorderFactory.createCompoundBorder(outerBorder, innerBorder)); JPanel right = new JPanel(); right.setBackground(Color.gray); right.setLayout(fl); JLabel img = new JLabel(""); Image image = new ImageIcon(this.getClass().getResource("/user.png")).getImage(); img.setIcon(new ImageIcon(image)); right.add(img); JLabel wel = new JLabel("Welcome: "); JLabel user = new JLabel(cabecera + " "); user.setFont (user.getFont ().deriveFont (18.0f)); user.setForeground(Color.blue); right.add(wel); right.add(user); JButton logout = new JButton("Logout"); Image imageL = new ImageIcon(this.getClass().getResource("/logoutIcon.png")).getImage(); logout.setIcon(new ImageIcon(imageL)); right.add(logout); JPanel left = new JPanel(); left.setBackground(Color.gray); JLabel users = new JLabel(); Image image2 = new ImageIcon(this.getClass().getResource("/users.png")).getImage(); users.setIcon(new ImageIcon(image2)); left.add(users); JLabel title = new JLabel("Admin Dashboard"); title.setFont (title.getFont ().deriveFont (20.0f)); left.add(title); toolbar.add(left, BorderLayout.LINE_START); toolbar.add(right, BorderLayout.LINE_END); //----------------------botton panel Toolbar -----------------------------// JPanel botton = new JPanel(); FlowLayout f2 = new FlowLayout(); f2.setAlignment(0); botton.setLayout(f2); Border outerBorder0 = BorderFactory.createEtchedBorder(); Border innerBorder0 = BorderFactory.createEmptyBorder(5, 10, 5, 10); botton.setBorder(BorderFactory.createCompoundBorder(outerBorder0, innerBorder0)); JLabel refresh = new JLabel(""); Image image3 = new ImageIcon(this.getClass().getResource("/refresh.png")).getImage(); refresh.setIcon(new ImageIcon(image3)); botton.add(refresh); //----------------------ADD BIG TOOLBAR-----------------------------// JPanel big = new JPanel(); big.setLayout(new BorderLayout()); big.add(toolbar, BorderLayout.NORTH); big.add(botton, BorderLayout.SOUTH); //------------------------------------------------------------------// //--------------Register------------------// JPanel register = new JPanel(); register.setLayout(new BorderLayout()); Border innerBorder2 = BorderFactory.createTitledBorder("Register"); Border outerBorder2 = BorderFactory.createEmptyBorder(10,10,10,10); register.setBorder(BorderFactory.createCompoundBorder(outerBorder2, innerBorder2)); // resizing the panel Dimension d = getPreferredSize(); d.width = 400; register.setPreferredSize(d); u = new Update(this); registerPanel = new RegisterPanel(this); register.add(registerPanel, BorderLayout.NORTH); register.add(u, BorderLayout.SOUTH); //----------------------------------------// data = new DataPanel(this); this.add(big, BorderLayout.PAGE_START); this.add(register, BorderLayout.WEST); this.add(data, BorderLayout.CENTER); logout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { optionLogout(); } }); refresh.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent arg0) { ver(); new Admin(cabecera); } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }); } public void optionLogout() { Object[] options = {"Yes", "No"}; int n = JOptionPane.showOptionDialog( this, "Are you sure you want to logout?" + "", "Logout", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == 0) { this.dispose(); new Login(); } } public void ver() { this.dispose(); } }
5,790
0.619516
0.608981
214
26.056074
21.768679
92
false
false
0
0
0
0
0
0
0.640187
false
false
7
5eab59b882cdc1dfe4bb6008eec5248f6cbfe145
16,114,717,339,662
8811964838d6f6cf329e21a890f127ae76784d5c
/dresscode/GUI.java
90ee59d022322757dac19e50ab6416f836f716db
[]
no_license
Duxanlol/dresscode_tic_tac_toe
https://github.com/Duxanlol/dresscode_tic_tac_toe
18d4a7b62b2597b1c457110729634747aaa4d436
8a6586210f392212e1adb889a0f4eb366bdb3ae6
refs/heads/main
"2023-02-09T10:39:15.100000"
"2023-01-13T17:31:29"
"2023-01-13T17:31:29"
326,824,580
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dresscode; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.Random; import java.awt.Color; import javax.swing.JButton; public class GUI extends JFrame implements ActionListener { JLabel gameGridBackground, bottomMenuBackground; boolean isPlayerOne, isOver; Field[] fields = new Field[16]; Random random; State state; DecisionEngine de; private JButton exitButton, resetButton; public GUI() { super("Dresscode 4x4 Tic Tac Toe"); random = new Random(); getContentPane().setBackground(Color.WHITE); setBackground(Color.WHITE); setDefaultCloseOperation(EXIT_ON_CLOSE); // setUndecorated(true); setSize(512 + 15, 640 + 25); // +15 +25 to adjust for Window borders and title bar. displayGame(); resetGame(); setLocationRelativeTo(null); setResizable(false); setVisible(true); } public void initFields() { int xCordStart = 8; int yCordStart = 8; int width = 112; int height = 112; for (int i = 0; i < 16; i++) { fields[i] = new Field(); fields[i].setIndex(i); fields[i].setBounds(xCordStart, yCordStart, width, height); getContentPane().add(fields[i]); xCordStart += 128; if (i % 4 == 3) { xCordStart = 8; yCordStart += 128; } fields[i].addActionListener(this); Field curButton = fields[i]; curButton.addMouseListener(new MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { if(!isOver) { curButton.onMouseEnter(isPlayerOne); } } public void mouseExited(java.awt.event.MouseEvent evt) { curButton.onMouseExit(); } }); fields[i].update(); } } public void displayGame() { getContentPane().setLayout(null); gameGridBackground = new JLabel(SpriteManager.getInstance().getGrid()); // ImageIcon(this.getClass().getResource("sprites/board_with_borders.png"))); gameGridBackground.setBounds(0, 0, 512, 512); bottomMenuBackground = new JLabel(); bottomMenuBackground.setBounds(0, 512, 512, 128); getContentPane().add(gameGridBackground); getContentPane().add(bottomMenuBackground); initFields(); gameGridBackground.setLayout(null); bottomMenuBackground.setLayout(null); resetButton = new JButton(""); resetButton.setBounds(236, 586, 132, 39); resetButton.setBorderPainted(false); resetButton.setFocusPainted(false); resetButton.setContentAreaFilled(false); resetButton.addActionListener(this); getContentPane().add(resetButton); exitButton = new JButton(""); exitButton.setBounds(393, 586, 100, 39); exitButton.setBorderPainted(false); exitButton.setFocusPainted(false); exitButton.setContentAreaFilled(false); exitButton.addActionListener(this); getContentPane().add(exitButton); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof Field) { Field clicked = (Field) e.getSource(); onFieldClick(clicked.getIndex()); }else if (e.getSource().equals(resetButton)) { resetGame(); }else if (e.getSource().equals(exitButton)) { System.exit(0); } } public void onFieldClick(int index) { if(isOver) return; boolean playerOnePlaysNext = false; if (state.getTurnNumber() % 2 == 0) { playerOnePlaysNext = true; } if (isPlayerOne == playerOnePlaysNext) { if (state.playMove(index)) { update(state); if (state.hasVictor(index)) { finishedGame("won"); } else if (state.getTurnNumber() == 16) { finishedGame("draw"); } else { index = de.findMaxValuePlay(state.toString()); state.playMove(index); update(state); if (state.hasVictor(index)) { finishedGame("lost"); } else if (state.getTurnNumber() == 16) { finishedGame("draw"); } } } } } public void resetGame() { state = new State(); isPlayerOne = random.nextBoolean(); de = new DecisionEngine(); if (isPlayerOne) { bottomMenuBackground.setIcon(SpriteManager.getInstance().getBottomMenuX()); }else { bottomMenuBackground.setIcon(SpriteManager.getInstance().getBottomMenuO()); state.playMove(de.findMaxValuePlay(state.toString())); } update(state); isOver = false; } public void update(State state) { String stateString = state.toString(); for (int i = 0; i < 16; i++) { fields[i].setValue(stateString.charAt(i)); fields[i].update(); } } public void finishedGame(String message) { isOver = true; if (message.equalsIgnoreCase("won")) { bottomMenuBackground.setIcon(SpriteManager.getInstance().getBottomMenuWon()); } else if (message.equalsIgnoreCase("lost")) { bottomMenuBackground.setIcon(SpriteManager.getInstance().getBottomMenuLost()); } else { bottomMenuBackground.setIcon(SpriteManager.getInstance().getBottomMenuDraw()); } } }
UTF-8
Java
5,178
java
GUI.java
Java
[]
null
[]
package dresscode; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.Random; import java.awt.Color; import javax.swing.JButton; public class GUI extends JFrame implements ActionListener { JLabel gameGridBackground, bottomMenuBackground; boolean isPlayerOne, isOver; Field[] fields = new Field[16]; Random random; State state; DecisionEngine de; private JButton exitButton, resetButton; public GUI() { super("Dresscode 4x4 Tic Tac Toe"); random = new Random(); getContentPane().setBackground(Color.WHITE); setBackground(Color.WHITE); setDefaultCloseOperation(EXIT_ON_CLOSE); // setUndecorated(true); setSize(512 + 15, 640 + 25); // +15 +25 to adjust for Window borders and title bar. displayGame(); resetGame(); setLocationRelativeTo(null); setResizable(false); setVisible(true); } public void initFields() { int xCordStart = 8; int yCordStart = 8; int width = 112; int height = 112; for (int i = 0; i < 16; i++) { fields[i] = new Field(); fields[i].setIndex(i); fields[i].setBounds(xCordStart, yCordStart, width, height); getContentPane().add(fields[i]); xCordStart += 128; if (i % 4 == 3) { xCordStart = 8; yCordStart += 128; } fields[i].addActionListener(this); Field curButton = fields[i]; curButton.addMouseListener(new MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { if(!isOver) { curButton.onMouseEnter(isPlayerOne); } } public void mouseExited(java.awt.event.MouseEvent evt) { curButton.onMouseExit(); } }); fields[i].update(); } } public void displayGame() { getContentPane().setLayout(null); gameGridBackground = new JLabel(SpriteManager.getInstance().getGrid()); // ImageIcon(this.getClass().getResource("sprites/board_with_borders.png"))); gameGridBackground.setBounds(0, 0, 512, 512); bottomMenuBackground = new JLabel(); bottomMenuBackground.setBounds(0, 512, 512, 128); getContentPane().add(gameGridBackground); getContentPane().add(bottomMenuBackground); initFields(); gameGridBackground.setLayout(null); bottomMenuBackground.setLayout(null); resetButton = new JButton(""); resetButton.setBounds(236, 586, 132, 39); resetButton.setBorderPainted(false); resetButton.setFocusPainted(false); resetButton.setContentAreaFilled(false); resetButton.addActionListener(this); getContentPane().add(resetButton); exitButton = new JButton(""); exitButton.setBounds(393, 586, 100, 39); exitButton.setBorderPainted(false); exitButton.setFocusPainted(false); exitButton.setContentAreaFilled(false); exitButton.addActionListener(this); getContentPane().add(exitButton); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof Field) { Field clicked = (Field) e.getSource(); onFieldClick(clicked.getIndex()); }else if (e.getSource().equals(resetButton)) { resetGame(); }else if (e.getSource().equals(exitButton)) { System.exit(0); } } public void onFieldClick(int index) { if(isOver) return; boolean playerOnePlaysNext = false; if (state.getTurnNumber() % 2 == 0) { playerOnePlaysNext = true; } if (isPlayerOne == playerOnePlaysNext) { if (state.playMove(index)) { update(state); if (state.hasVictor(index)) { finishedGame("won"); } else if (state.getTurnNumber() == 16) { finishedGame("draw"); } else { index = de.findMaxValuePlay(state.toString()); state.playMove(index); update(state); if (state.hasVictor(index)) { finishedGame("lost"); } else if (state.getTurnNumber() == 16) { finishedGame("draw"); } } } } } public void resetGame() { state = new State(); isPlayerOne = random.nextBoolean(); de = new DecisionEngine(); if (isPlayerOne) { bottomMenuBackground.setIcon(SpriteManager.getInstance().getBottomMenuX()); }else { bottomMenuBackground.setIcon(SpriteManager.getInstance().getBottomMenuO()); state.playMove(de.findMaxValuePlay(state.toString())); } update(state); isOver = false; } public void update(State state) { String stateString = state.toString(); for (int i = 0; i < 16; i++) { fields[i].setValue(stateString.charAt(i)); fields[i].update(); } } public void finishedGame(String message) { isOver = true; if (message.equalsIgnoreCase("won")) { bottomMenuBackground.setIcon(SpriteManager.getInstance().getBottomMenuWon()); } else if (message.equalsIgnoreCase("lost")) { bottomMenuBackground.setIcon(SpriteManager.getInstance().getBottomMenuLost()); } else { bottomMenuBackground.setIcon(SpriteManager.getInstance().getBottomMenuDraw()); } } }
5,178
0.670722
0.653727
177
27.265537
22.327116
181
false
false
0
0
0
0
0
0
2.858757
false
false
7
5515b8c1357f379ab0106253387b046a942856d5
6,021,544,181,849
1a069d8dcecd17288ac26fdf6b99366c41381ed1
/spring/src/main/java/com/demo/spring/repository/DepartRepository.java
8e42bddb68308cb9ee8bb1ed0d9fdbcc12edc721
[ "Apache-2.0" ]
permissive
nagesh1213/Spring-Boot-Project
https://github.com/nagesh1213/Spring-Boot-Project
b8e26a3740561bf435be15022a7aa6231b15deb8
63c552f42813c09d8de055eb552b5a080d10e876
refs/heads/master
"2021-01-09T13:12:09.215000"
"2020-02-22T11:05:05"
"2020-02-22T11:05:05"
242,313,358
0
0
Apache-2.0
false
"2020-07-02T02:20:08"
"2020-02-22T09:21:46"
"2020-02-22T11:08:32"
"2020-07-02T02:20:06"
5,859
0
0
1
HTML
false
false
package com.demo.spring.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.demo.spring.model.Department; public interface DepartRepository extends JpaRepository<Department, Integer>{ }
UTF-8
Java
225
java
DepartRepository.java
Java
[]
null
[]
package com.demo.spring.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.demo.spring.model.Department; public interface DepartRepository extends JpaRepository<Department, Integer>{ }
225
0.826667
0.826667
10
21.5
28.025881
77
false
false
0
0
0
0
0
0
0.5
false
false
7
d7ef9f68e3477ffb1aaeb0d18b52ab6ba87c89ec
10,969,346,512,029
a137224d471c5586e3200a8badd736715cb826a6
/Universal-Space-Operations-Center/src/main/java/com/ksatstuttgart/usoc/gui/setup/USOCTabPane.java
a50d5440b8f5ab24ad5eedf2c0b420617d976903
[ "MIT" ]
permissive
Gyanesha/Universal-Space-Operations-Center
https://github.com/Gyanesha/Universal-Space-Operations-Center
49bd2cf87da424eeb59fb18d04a42a8fc032d405
36a3a51395aadcbfc02ed9175ec7ed9074381cef
refs/heads/master
"2021-01-25T14:10:45.299000"
"2018-02-28T22:24:56"
"2018-02-28T22:24:56"
123,663,441
0
1
MIT
true
"2018-10-26T19:33:02"
"2018-03-03T05:43:05"
"2018-03-03T05:43:08"
"2018-02-28T22:24:57"
498
0
1
1
Java
false
null
/* * The MIT License * * Copyright 2017 KSat Stuttgart e.V.. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.ksatstuttgart.usoc.gui.setup; import com.ksatstuttgart.usoc.gui.controller.DataController; import java.io.IOException; import javafx.fxml.FXMLLoader; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.Pane; /** * * @author Victor */ public class USOCTabPane extends TabPane { public USOCTabPane(){ super(); } public void addFXMLTab(String resourcePath, String text){ try { Tab tab = new Tab(); FXMLLoader fxmlLoader = new FXMLLoader(getClass().getClassLoader().getResource(resourcePath)); Pane pane = fxmlLoader.load(); tab.setContent(pane); tab.setText(text); this.getTabs().add(tab); } catch (IOException ex) { ex.printStackTrace(); } } public void addFXMLTab(String resourcePath, DataController controller, String text) { try { Tab tab = new Tab(); FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(resourcePath)); fxmlLoader.setController(controller); Pane pane = fxmlLoader.load(); tab.setContent(pane); tab.setText(text); this.getTabs().add(tab); } catch (IOException ex) { ex.printStackTrace(); } } }
UTF-8
Java
2,540
java
USOCTabPane.java
Java
[ { "context": "mport javafx.scene.layout.Pane;\n\n/**\n *\n * @author Victor\n */\npublic class USOCTabPane extends TabPane {\n ", "end": 1473, "score": 0.9992834329605103, "start": 1467, "tag": "NAME", "value": "Victor" } ]
null
[]
/* * The MIT License * * Copyright 2017 KSat Stuttgart e.V.. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.ksatstuttgart.usoc.gui.setup; import com.ksatstuttgart.usoc.gui.controller.DataController; import java.io.IOException; import javafx.fxml.FXMLLoader; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.Pane; /** * * @author Victor */ public class USOCTabPane extends TabPane { public USOCTabPane(){ super(); } public void addFXMLTab(String resourcePath, String text){ try { Tab tab = new Tab(); FXMLLoader fxmlLoader = new FXMLLoader(getClass().getClassLoader().getResource(resourcePath)); Pane pane = fxmlLoader.load(); tab.setContent(pane); tab.setText(text); this.getTabs().add(tab); } catch (IOException ex) { ex.printStackTrace(); } } public void addFXMLTab(String resourcePath, DataController controller, String text) { try { Tab tab = new Tab(); FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(resourcePath)); fxmlLoader.setController(controller); Pane pane = fxmlLoader.load(); tab.setContent(pane); tab.setText(text); this.getTabs().add(tab); } catch (IOException ex) { ex.printStackTrace(); } } }
2,540
0.679921
0.678346
70
35.285713
28.616251
106
false
false
0
0
0
0
0
0
0.7
false
false
7
c0c5c8c719f9ae444c2b10111a1548778b1a9110
2,181,843,446,427
6adea47740bccfbcfffc410e3d86f9d3e1dfaca5
/util-services/util-service-delivery/src/main/java/com/clemble/social/service/delivery/format/impl/SimpleDeliveryFormatAdapterFactory.java
de1f1b59dac2e6abc335e7a1457375c046c78a39
[]
no_license
clemble/clemble-social
https://github.com/clemble/clemble-social
7c3adb7337098d7fb0e7c018fb1d32f8b2ffdd1f
54fb08f51680556d7a0f23f434372fe20e4c9236
refs/heads/master
"2020-05-17T18:47:33.164000"
"2015-05-09T04:58:41"
"2015-05-09T04:58:41"
7,006,329
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.clemble.social.service.delivery.format.impl; import org.springframework.stereotype.Component; import com.clemble.social.provider.data.callback.delivery.DeliveryFormat; import com.clemble.social.service.delivery.format.DeliveryFormatAdapter; import com.clemble.social.service.delivery.format.DeliveryFormatAdapterFactory; import com.clemble.social.service.factory.AbstractBeanMapFactory; import com.google.common.base.Function; @Component public class SimpleDeliveryFormatAdapterFactory extends AbstractBeanMapFactory<DeliveryFormat, DeliveryFormatAdapter> implements DeliveryFormatAdapterFactory { public SimpleDeliveryFormatAdapterFactory() { super(DeliveryFormatAdapter.class, new Function<DeliveryFormatAdapter, DeliveryFormat>(){ @Override public DeliveryFormat apply(DeliveryFormatAdapter input) { return input != null ? input.getDeliveryFormat() : null; }}); } }
UTF-8
Java
954
java
SimpleDeliveryFormatAdapterFactory.java
Java
[]
null
[]
package com.clemble.social.service.delivery.format.impl; import org.springframework.stereotype.Component; import com.clemble.social.provider.data.callback.delivery.DeliveryFormat; import com.clemble.social.service.delivery.format.DeliveryFormatAdapter; import com.clemble.social.service.delivery.format.DeliveryFormatAdapterFactory; import com.clemble.social.service.factory.AbstractBeanMapFactory; import com.google.common.base.Function; @Component public class SimpleDeliveryFormatAdapterFactory extends AbstractBeanMapFactory<DeliveryFormat, DeliveryFormatAdapter> implements DeliveryFormatAdapterFactory { public SimpleDeliveryFormatAdapterFactory() { super(DeliveryFormatAdapter.class, new Function<DeliveryFormatAdapter, DeliveryFormat>(){ @Override public DeliveryFormat apply(DeliveryFormatAdapter input) { return input != null ? input.getDeliveryFormat() : null; }}); } }
954
0.790356
0.790356
22
42.363636
40.706875
159
false
false
0
0
0
0
0
0
0.545455
false
false
7
d23911abd995c294b149b93263c82e2f6e9f939c
3,324,304,690,983
587c677bb5c9b4a7683e9fb7ad4d9a9428a93bfc
/ACR/src/main/java/ui/pages/bookingDetailsPage/RefundButtonElement.java
21c75b8dc8a277a9995006c7e9bf26becc727cda
[]
no_license
abakhtiozin/acrUI
https://github.com/abakhtiozin/acrUI
371ffba25d8f016f314bbfe4999dd3f610f56e3e
ff09f221c47a9d7eace74852be3d7e78dbcc10ef
refs/heads/master
"2020-03-13T04:24:16.739000"
"2015-10-29T11:48:35"
"2015-10-29T11:48:35"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main.java.ui.pages.bookingDetailsPage; import com.codeborne.selenide.SelenideElement; import static com.codeborne.selenide.Condition.appear; import static com.codeborne.selenide.Selenide.$; /** * Created by Andrii.Bakhtiozin on 05.08.2015. * andrii.bakhtiozin@viaamadeus.com */ public interface RefundButtonElement { default SelenideElement refundButtonElement() { return $(".btn.pull-right.btn-warning.mL5").waitUntil(appear, 35000); } }
UTF-8
Java
469
java
RefundButtonElement.java
Java
[ { "context": ".codeborne.selenide.Selenide.$;\n\n/**\n * Created by Andrii.Bakhtiozin on 05.08.2015.\n * andrii.bakhtiozin@viaamadeus.co", "end": 236, "score": 0.9998469352722168, "start": 219, "tag": "NAME", "value": "Andrii.Bakhtiozin" }, { "context": "\n * Created by Andrii.Bakhtiozin on 05.08.2015.\n * andrii.bakhtiozin@viaamadeus.com\n */\npublic interface RefundButtonElement {\n de", "end": 287, "score": 0.9999128580093384, "start": 255, "tag": "EMAIL", "value": "andrii.bakhtiozin@viaamadeus.com" } ]
null
[]
package main.java.ui.pages.bookingDetailsPage; import com.codeborne.selenide.SelenideElement; import static com.codeborne.selenide.Condition.appear; import static com.codeborne.selenide.Selenide.$; /** * Created by Andrii.Bakhtiozin on 05.08.2015. * <EMAIL> */ public interface RefundButtonElement { default SelenideElement refundButtonElement() { return $(".btn.pull-right.btn-warning.mL5").waitUntil(appear, 35000); } }
444
0.763326
0.733476
16
28.3125
24.981791
77
false
false
0
0
0
0
0
0
0.375
false
false
7
a362c44781ef8aad8204f91b3df14955bf0247e0
14,774,687,516,315
bd93b6bdfcbd81e792fc1793ff82c7cc7d7f7213
/Palindrome/ComplexityLaboratory.java
514dd5be3845ebf296fc29d8dbb0dceb7780171c
[]
no_license
anthonyjl92/Data-Structure
https://github.com/anthonyjl92/Data-Structure
a24a185ded682ab073d86513bd00ebdab7185494
c7829399536500c5d22fa75a79b48927f4cb2268
refs/heads/master
"2016-08-12T04:40:07.838000"
"2016-03-24T01:44:20"
"2016-03-24T01:44:20"
54,599,352
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/*File: ComplexityLaboratory.java * Anthony Lin * U77967536 * HW 3 * Purpose: Compare the complexity of Shell, Insertion, Merge, Selection and Quick Sort * by plotting it on a graph * */ import java.util.Random; //import Random @SuppressWarnings("unchecked") public class ComplexityLaboratory{ private static Random R = new Random(); //private field that creates random private static int counter; //private field counter that stores comparisons private static Integer[] generateRandomArray(int size) { // create an array with size elements and fill it with random four-digit numbers Integer[] A=new Integer[size]; //creates array type Integer with size from parameter for(int i=0;i<size;i++){ //loop through array A[i]= (Integer) R.nextInt(10000); // this generates a random number from 0 .. 9999 } return A; //returns the array } // is v < w ? private static boolean less(Comparable v, Comparable w) { //taken from the textbook website, checks if < than ++counter; return (v.compareTo(w) < 0); } // exchange a[i] and a[j] private static void exch(Object[] a, int i, int j) { //taken from the textbook website, swaps two elements in an array Object swap = a[i]; a[i] = a[j]; a[j] = swap; } // stably merge a[lo .. mid] with a[mid+1 ..hi] using aux[lo .. hi] private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) { //taken from the textbook website // copy to aux[] for (int k = lo; k <= hi; k++) { aux[k] = a[k]; } // merge back to a[] int i = lo, j = mid+1; for (int k = lo; k <= hi; k++) { if (i > mid) a[k] = aux[j++]; // this copying is unnecessary else if (j > hi) a[k] = aux[i++]; else if (less(aux[j], aux[i])) a[k] = aux[j++]; else a[k] = aux[i++]; } } // mergesort a[lo..hi] using auxiliary array aux[lo..hi] private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) { //taken from the textbook website if (hi <= lo) return; int mid = lo + (hi - lo) / 2; sort(a, aux, lo, mid); sort(a, aux, mid + 1, hi); merge(a, aux, lo, mid, hi); } public static void sort(Comparable[] a) { //taken from the textbook website, helper method sort(a, 0, a.length - 1); } // quicksort the subarray from a[lo] to a[hi] private static void sort(Comparable[] a, int lo, int hi) { //taken from the textbook website if (hi <= lo) return; int j = partition(a, lo, hi); sort(a, lo, j-1); sort(a, j+1, hi); } // partition the subarray a[lo..hi] so that a[lo..j-1] <= a[j] <= a[j+1..hi] // and return the index j. private static int partition(Comparable[] a, int lo, int hi) { //taken from the textbook website int i = lo; int j = hi + 1; Comparable v = a[lo]; while (true) { // find item on lo to swap while (less(a[++i], v)) if (i == hi) break; // find item on hi to swap while (less(v, a[--j])) if (j == lo) break; // redundant since a[lo] acts as sentinel // check if pointers cross if (i >= j) break; exch(a, i, j); } // put partitioning item v at a[j] exch(a, lo, j); // now, a[lo .. j-1] <= a[j] <= a[j+1 .. hi] return j; } public static void InsertionSort(Comparable[] a) { //taken from the textbook website, Insertion sort code int N = a.length; for (int i = 0; i < N; i++) { for (int j = i; j > 0 && less(a[j], a[j-1]); j--) { exch(a, j, j-1); } } } public static void MergeSort(Comparable[] a) { //taken from the textbook website, merge sort code Comparable[] aux = new Comparable[a.length]; sort(a, aux, 0, a.length-1); } public static void QuickSort(Comparable[] a) { //taken from the textbook website, quick sort code sort(a, 0, a.length - 1); } public static void SelectionSort(Comparable[] a) { //taken from the textbook website, selection sort code int N = a.length; for (int i = 0; i < N; i++) { int min = i; for (int j = i+1; j < N; j++) { if (less(a[j], a[min])) min = j; } exch(a, i, min); } } public static void ShellSort(Comparable[] a) { //taken from the textbook website, shellsort code int N = a.length; // 3x+1 increment sequence: 1, 4, 13, 40, 121, 364, 1093, ... int h = 1; while (h < N/3) h = 3*h + 1; while (h >= 1) { // h-sort the array for (int i = h; i < N; i++) { for (int j = i; j >= h && less(a[j], a[j-h]); j -= h) { exch(a, j, j-h); } } h /= 3; } } public static void main(String [] args) { //main method where we graph Grapher G = new Grapher("Comparison of Average Case Sort for Five Algorithms"); // initialize the grapher with a title int[] insert=new int[42]; //array to store data for insertion sort insert[0]=0; //first two slots are 0 because there are no comparisons when array is size 0 insert[1]=0; int[] merge=new int[42]; //array to store data for merge sort merge[0]=0; //first two slots are 0 because there are no comparisons when array is size 0 merge[1]=0; int[] quick=new int[42]; //array to store data for quick sort quick[0]=0; //first two slots are 0 because there are no comparisons when array is size 0 quick[1]=0; int[] shell=new int[42]; //array to store data for shell sort shell[0]=0; //first two slots are 0 because there are no comparisons when array is size 0 shell[1]=0; int[] select=new int[42]; //array to store data for select sort select[0]=0; //first two slots are 0 because there are no comparisons when array is size 0 select[1]=0; int i=5; //i represents the array size for(int j=2;j<select.length;j+=2){ //loops through array of data for each sorting algorithm counter=0; //reset counter to 0 //System.out.println("SelectionSort "); SelectionSort(generateRandomArray(i)); //generate random array //System.out.println("counter: " +counter + ", Arraysize: "+i); select[j]=i; //[j] is arraysize and [j+1] like in the problem select[j+1]=counter; counter=0; // System.out.println("MergeSort "); MergeSort(generateRandomArray(i)); //generate random array // System.out.println("counter: " +counter + ", Arraysize: "+i); merge[j]=i; //[j] is arraysize and [j+1] like in the problem merge[j+1]=counter; counter=0; // System.out.println("ShellSort "); ShellSort(generateRandomArray(i)); //generate random array // System.out.println("counter: " +counter + ", Arraysize: "+i); shell[j]=i; //[j] is arraysize and [j+1] like in the problem shell[j+1]=counter; counter=0; //System.out.println("InsertionSort "); InsertionSort(generateRandomArray(i)); //generate random array // System.out.println("counter: " +counter + ", Arraysize: "+i); insert[j]=i; //[j] is arraysize and [j+1] like in the problem insert[j+1]=counter; counter=0; // System.out.println("QuickSort "); QuickSort(generateRandomArray(i)); //generate random array // System.out.println("counter: " +counter + ", Arraysize: "+i); quick[j]=i; //[j] is arraysize and [j+1] like in the problem quick[j+1]=counter; i+=5; //increment the array size by 5 after one iteration } System.out.println("Insertion Sort"); //prints out data in insertion array for(int j=0; j<insert.length;j++){ System.out.print(insert[j]+ ", "); } System.out.println(); System.out.println("Merge Sort"); //prints out data in merge array for(int k=0; k<merge.length;k++){ System.out.print(merge[k]+", "); } System.out.println(); System.out.println("Shell Sort"); //prints out data in shell array for(int n=0; n<shell.length;n++){ System.out.print(shell[n]+", "); } System.out.println(); System.out.println("Selection Sort"); //prints out data in select array for(int m=0; m<select.length;m++){ System.out.print(select[m]+", "); } System.out.println(); System.out.println("Quick Sort"); //prints out data in quick array for(int q=0; q<quick.length;q++){ System.out.print(quick[q]+", "); } //draws the graph for each sorting algoritm G.drawCurve(insert, "Insertion Sort"); G.drawCurve(shell, "Shell Sort"); G.drawCurve(select, "Selection Sort"); G.drawCurve(quick, "Quick Sort"); G.drawCurve(merge, "Merge Sort"); } }
UTF-8
Java
9,882
java
ComplexityLaboratory.java
Java
[ { "context": "/*File: ComplexityLaboratory.java\n * Anthony Lin\n * U77967536\n * HW 3\n * Purpose: Compare the comp", "end": 48, "score": 0.9998399019241333, "start": 37, "tag": "NAME", "value": "Anthony Lin" } ]
null
[]
/*File: ComplexityLaboratory.java * <NAME> * U77967536 * HW 3 * Purpose: Compare the complexity of Shell, Insertion, Merge, Selection and Quick Sort * by plotting it on a graph * */ import java.util.Random; //import Random @SuppressWarnings("unchecked") public class ComplexityLaboratory{ private static Random R = new Random(); //private field that creates random private static int counter; //private field counter that stores comparisons private static Integer[] generateRandomArray(int size) { // create an array with size elements and fill it with random four-digit numbers Integer[] A=new Integer[size]; //creates array type Integer with size from parameter for(int i=0;i<size;i++){ //loop through array A[i]= (Integer) R.nextInt(10000); // this generates a random number from 0 .. 9999 } return A; //returns the array } // is v < w ? private static boolean less(Comparable v, Comparable w) { //taken from the textbook website, checks if < than ++counter; return (v.compareTo(w) < 0); } // exchange a[i] and a[j] private static void exch(Object[] a, int i, int j) { //taken from the textbook website, swaps two elements in an array Object swap = a[i]; a[i] = a[j]; a[j] = swap; } // stably merge a[lo .. mid] with a[mid+1 ..hi] using aux[lo .. hi] private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) { //taken from the textbook website // copy to aux[] for (int k = lo; k <= hi; k++) { aux[k] = a[k]; } // merge back to a[] int i = lo, j = mid+1; for (int k = lo; k <= hi; k++) { if (i > mid) a[k] = aux[j++]; // this copying is unnecessary else if (j > hi) a[k] = aux[i++]; else if (less(aux[j], aux[i])) a[k] = aux[j++]; else a[k] = aux[i++]; } } // mergesort a[lo..hi] using auxiliary array aux[lo..hi] private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) { //taken from the textbook website if (hi <= lo) return; int mid = lo + (hi - lo) / 2; sort(a, aux, lo, mid); sort(a, aux, mid + 1, hi); merge(a, aux, lo, mid, hi); } public static void sort(Comparable[] a) { //taken from the textbook website, helper method sort(a, 0, a.length - 1); } // quicksort the subarray from a[lo] to a[hi] private static void sort(Comparable[] a, int lo, int hi) { //taken from the textbook website if (hi <= lo) return; int j = partition(a, lo, hi); sort(a, lo, j-1); sort(a, j+1, hi); } // partition the subarray a[lo..hi] so that a[lo..j-1] <= a[j] <= a[j+1..hi] // and return the index j. private static int partition(Comparable[] a, int lo, int hi) { //taken from the textbook website int i = lo; int j = hi + 1; Comparable v = a[lo]; while (true) { // find item on lo to swap while (less(a[++i], v)) if (i == hi) break; // find item on hi to swap while (less(v, a[--j])) if (j == lo) break; // redundant since a[lo] acts as sentinel // check if pointers cross if (i >= j) break; exch(a, i, j); } // put partitioning item v at a[j] exch(a, lo, j); // now, a[lo .. j-1] <= a[j] <= a[j+1 .. hi] return j; } public static void InsertionSort(Comparable[] a) { //taken from the textbook website, Insertion sort code int N = a.length; for (int i = 0; i < N; i++) { for (int j = i; j > 0 && less(a[j], a[j-1]); j--) { exch(a, j, j-1); } } } public static void MergeSort(Comparable[] a) { //taken from the textbook website, merge sort code Comparable[] aux = new Comparable[a.length]; sort(a, aux, 0, a.length-1); } public static void QuickSort(Comparable[] a) { //taken from the textbook website, quick sort code sort(a, 0, a.length - 1); } public static void SelectionSort(Comparable[] a) { //taken from the textbook website, selection sort code int N = a.length; for (int i = 0; i < N; i++) { int min = i; for (int j = i+1; j < N; j++) { if (less(a[j], a[min])) min = j; } exch(a, i, min); } } public static void ShellSort(Comparable[] a) { //taken from the textbook website, shellsort code int N = a.length; // 3x+1 increment sequence: 1, 4, 13, 40, 121, 364, 1093, ... int h = 1; while (h < N/3) h = 3*h + 1; while (h >= 1) { // h-sort the array for (int i = h; i < N; i++) { for (int j = i; j >= h && less(a[j], a[j-h]); j -= h) { exch(a, j, j-h); } } h /= 3; } } public static void main(String [] args) { //main method where we graph Grapher G = new Grapher("Comparison of Average Case Sort for Five Algorithms"); // initialize the grapher with a title int[] insert=new int[42]; //array to store data for insertion sort insert[0]=0; //first two slots are 0 because there are no comparisons when array is size 0 insert[1]=0; int[] merge=new int[42]; //array to store data for merge sort merge[0]=0; //first two slots are 0 because there are no comparisons when array is size 0 merge[1]=0; int[] quick=new int[42]; //array to store data for quick sort quick[0]=0; //first two slots are 0 because there are no comparisons when array is size 0 quick[1]=0; int[] shell=new int[42]; //array to store data for shell sort shell[0]=0; //first two slots are 0 because there are no comparisons when array is size 0 shell[1]=0; int[] select=new int[42]; //array to store data for select sort select[0]=0; //first two slots are 0 because there are no comparisons when array is size 0 select[1]=0; int i=5; //i represents the array size for(int j=2;j<select.length;j+=2){ //loops through array of data for each sorting algorithm counter=0; //reset counter to 0 //System.out.println("SelectionSort "); SelectionSort(generateRandomArray(i)); //generate random array //System.out.println("counter: " +counter + ", Arraysize: "+i); select[j]=i; //[j] is arraysize and [j+1] like in the problem select[j+1]=counter; counter=0; // System.out.println("MergeSort "); MergeSort(generateRandomArray(i)); //generate random array // System.out.println("counter: " +counter + ", Arraysize: "+i); merge[j]=i; //[j] is arraysize and [j+1] like in the problem merge[j+1]=counter; counter=0; // System.out.println("ShellSort "); ShellSort(generateRandomArray(i)); //generate random array // System.out.println("counter: " +counter + ", Arraysize: "+i); shell[j]=i; //[j] is arraysize and [j+1] like in the problem shell[j+1]=counter; counter=0; //System.out.println("InsertionSort "); InsertionSort(generateRandomArray(i)); //generate random array // System.out.println("counter: " +counter + ", Arraysize: "+i); insert[j]=i; //[j] is arraysize and [j+1] like in the problem insert[j+1]=counter; counter=0; // System.out.println("QuickSort "); QuickSort(generateRandomArray(i)); //generate random array // System.out.println("counter: " +counter + ", Arraysize: "+i); quick[j]=i; //[j] is arraysize and [j+1] like in the problem quick[j+1]=counter; i+=5; //increment the array size by 5 after one iteration } System.out.println("Insertion Sort"); //prints out data in insertion array for(int j=0; j<insert.length;j++){ System.out.print(insert[j]+ ", "); } System.out.println(); System.out.println("Merge Sort"); //prints out data in merge array for(int k=0; k<merge.length;k++){ System.out.print(merge[k]+", "); } System.out.println(); System.out.println("Shell Sort"); //prints out data in shell array for(int n=0; n<shell.length;n++){ System.out.print(shell[n]+", "); } System.out.println(); System.out.println("Selection Sort"); //prints out data in select array for(int m=0; m<select.length;m++){ System.out.print(select[m]+", "); } System.out.println(); System.out.println("Quick Sort"); //prints out data in quick array for(int q=0; q<quick.length;q++){ System.out.print(quick[q]+", "); } //draws the graph for each sorting algoritm G.drawCurve(insert, "Insertion Sort"); G.drawCurve(shell, "Shell Sort"); G.drawCurve(select, "Selection Sort"); G.drawCurve(quick, "Quick Sort"); G.drawCurve(merge, "Merge Sort"); } }
9,877
0.520846
0.507286
265
36.294338
31.28355
141
false
false
0
0
0
0
0
0
0.886792
false
false
7
cbe2687293ac57999f9885cd28b8dd9f5218b752
9,448,928,065,906
e3b5a78f4340ed653a56b8daeb03fc1b17be7466
/mobile/src/test/java/com/appsimobile/weekly/utils/DateConstants.java
9755bece392d57fee34ec8c2ebbfe4856e11dc85
[]
no_license
nickmartens/Weekly
https://github.com/nickmartens/Weekly
0dc044a43a2dfabe269e05bb2acecbb450551b83
fec09565f8c82a242f4f2411e16b017d39325297
refs/heads/master
"2018-01-10T09:26:33.705000"
"2015-12-21T07:14:19"
"2015-12-21T07:14:19"
44,096,860
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.appsimobile.weekly.utils; import android.text.format.DateUtils; /** * Created by nmartens on 03/12/15. */ public class DateConstants { public static final long date_2015_01_01 = 1420070400000L; public static final long date_2015_01_02 = date_2015_01_01 + DateUtils.DAY_IN_MILLIS; public static final long date_2015_01_03 = date_2015_01_02 + DateUtils.DAY_IN_MILLIS; public static final long date_2015_01_04 = date_2015_01_03 + DateUtils.DAY_IN_MILLIS; // This time is known to be in DST in TimeZone Europe/Amsterdam public static final long date_2015_08_01 = 1438387200000L; public static final long date_2015_09_01 = date_2015_08_01 + 31 * DateUtils.DAY_IN_MILLIS; public static final int jd_2015_01_01 = 2457024; public static final int jd_2015_01_02 = jd_2015_01_01 + 1; public static final int jd_2015_01_03 = jd_2015_01_02 + 1; public static final int jd_2015_01_04 = jd_2015_01_03 + 1; public static final int jd_2015_08_01 = 2457236; public static long time(long part1, int hours) { return part1 + hours * DateUtils.HOUR_IN_MILLIS; } }
UTF-8
Java
1,126
java
DateConstants.java
Java
[ { "context": " android.text.format.DateUtils;\n\n/**\n * Created by nmartens on 03/12/15.\n */\npublic class DateConstants {\n\n ", "end": 104, "score": 0.999576985836029, "start": 96, "tag": "USERNAME", "value": "nmartens" } ]
null
[]
package com.appsimobile.weekly.utils; import android.text.format.DateUtils; /** * Created by nmartens on 03/12/15. */ public class DateConstants { public static final long date_2015_01_01 = 1420070400000L; public static final long date_2015_01_02 = date_2015_01_01 + DateUtils.DAY_IN_MILLIS; public static final long date_2015_01_03 = date_2015_01_02 + DateUtils.DAY_IN_MILLIS; public static final long date_2015_01_04 = date_2015_01_03 + DateUtils.DAY_IN_MILLIS; // This time is known to be in DST in TimeZone Europe/Amsterdam public static final long date_2015_08_01 = 1438387200000L; public static final long date_2015_09_01 = date_2015_08_01 + 31 * DateUtils.DAY_IN_MILLIS; public static final int jd_2015_01_01 = 2457024; public static final int jd_2015_01_02 = jd_2015_01_01 + 1; public static final int jd_2015_01_03 = jd_2015_01_02 + 1; public static final int jd_2015_01_04 = jd_2015_01_03 + 1; public static final int jd_2015_08_01 = 2457236; public static long time(long part1, int hours) { return part1 + hours * DateUtils.HOUR_IN_MILLIS; } }
1,126
0.70071
0.525755
27
40.703705
31.980104
94
false
false
0
0
0
0
0
0
0.555556
false
false
7
05bdd5d22c8f40d4b1f3dbff30df3f2507fc0e16
4,071,629,001,510
14e3fa292c1e7f93695c72863374499bfb083b17
/HelloWorld.java
fa02827f071d14fc8f6b8e0555444d3d6ab4823e
[]
no_license
ECManning/Hello-World
https://github.com/ECManning/Hello-World
0c91ed60005b53278d7b3000704d71824aa8c9f8
bcc75fd110417cc0ec0d1820910dc575758cf843
refs/heads/master
"2021-06-22T05:13:10.720000"
"2017-08-15T19:08:07"
"2017-08-15T19:08:07"
100,401,321
0
0
null
false
"2017-08-15T17:31:29"
"2017-08-15T17:19:11"
"2017-08-15T17:19:11"
"2017-08-15T17:31:29"
0
0
0
0
null
null
null
package hello; public class HelloWorld { public static void main(String[] args) { // TODO Auto-generated method stub int variableName= 5;//this is the first variable char character = 'c';//this is the first character String hello = "Hello, world! "; int x = 6;//be careful of integer division int y = 10;//use "(double)" to typecast and get the correct answer //System.out.println(x<y || x!=y); int n = 15; int answer = 1; for(int i=1; i < 5; i=i+1); { answer = i*answer; } System.out.println(answer); } //while(true) { //System.out.println(x); //x = x+1; } int m = 5 if(m == 0) { System.out.println((double)1/m); } }}
UTF-8
Java
720
java
HelloWorld.java
Java
[]
null
[]
package hello; public class HelloWorld { public static void main(String[] args) { // TODO Auto-generated method stub int variableName= 5;//this is the first variable char character = 'c';//this is the first character String hello = "Hello, world! "; int x = 6;//be careful of integer division int y = 10;//use "(double)" to typecast and get the correct answer //System.out.println(x<y || x!=y); int n = 15; int answer = 1; for(int i=1; i < 5; i=i+1); { answer = i*answer; } System.out.println(answer); } //while(true) { //System.out.println(x); //x = x+1; } int m = 5 if(m == 0) { System.out.println((double)1/m); } }}
720
0.569444
0.55
35
18.628571
17.811852
68
false
false
0
0
0
0
0
0
2.342857
false
false
7
34aaa6ba1df640486a46449b00464fe60821a790
9,749,575,767,565
6f672fb72caedccb841ee23f53e32aceeaf1895e
/Fitbit_source/src/com/fitbit/runtrack/ExerciseLocationService.java
c266f463541c2ac76d499db08734b41d0fcb8004
[]
no_license
cha63506/CompSecurity
https://github.com/cha63506/CompSecurity
5c69743f660b9899146ed3cf21eceabe3d5f4280
eee7e74f4088b9c02dd711c061fc04fb1e4e2654
refs/heads/master
"2018-03-23T04:15:18.480000"
"2015-12-19T01:29:58"
"2015-12-19T01:29:58"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.fitbit.runtrack; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.text.TextUtils; import android.text.format.DateUtils; import android.util.Pair; import android.widget.RemoteViews; import com.fitbit.data.bl.an; import com.fitbit.data.domain.Length; import com.fitbit.data.domain.Profile; import com.fitbit.e.a; import com.fitbit.maps.g; import com.fitbit.runtrack.data.ExerciseSegment; import com.fitbit.runtrack.data.ExerciseSession; import com.fitbit.runtrack.data.ExerciseStat; import com.fitbit.runtrack.data.b; import com.fitbit.runtrack.ui.RecordExerciseSessionActivity; import com.fitbit.util.threading.c; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; // Referenced classes of package com.fitbit.runtrack: // j, Duration, SupportedActivity, g, // e, c public class ExerciseLocationService extends Service implements android.os.Handler.Callback, com.fitbit.maps.g.a, com.fitbit.maps.g.b { private static abstract class a extends c { public abstract void a(Intent intent); private a() { } } private static final String c = "com.fitbit.runtrack.START_EXERCISE_TRACKING"; private static final String d = "com.fitbit.runtrack.END_EXERCISE_TRACKING"; private static final String e = "com.fitbit.runtrack.PAUSE_EXERICSE_TRACKING"; private static final String f = "com.fitbit.runtrack.RESUME_EXERICSE_TRACKING"; private static final String g = "com.fitbit.runtrack.CLEAR_STALE_DATA"; private static final String h = "com.fitbit.runtrack.LOCATION_UPDATE"; private static final String i = "com.fitbit.runtrack.xtra.EXERCISE_SESSION"; private static final String j = com/fitbit/runtrack/ExerciseLocationService.getSimpleName(); private static final int k = 0; private static final int l = 1; private static final int m = 2; private static final int n = 3; private static final int o = 4; private static final float p = 80F; private static final long q = 50L; private g r; private ExecutorService s; private Queue t; private b u; private com.fitbit.runtrack.c v; private Handler w; private Notification x; private a y; public ExerciseLocationService() { y = new a() { final ExerciseLocationService a; public void a(Intent intent) { if (!com.fitbit.runtrack.ExerciseLocationService.a(a)) { a.startService(com.fitbit.runtrack.ExerciseLocationService.b(a)); } else if (TextUtils.equals("com.fitbit.runtrack.EXERCISE_SESSION_UPDATE", intent.getAction())) { ExerciseSession exercisesession = com.fitbit.runtrack.c.c(intent); List list = com.fitbit.runtrack.c.a(intent); com.fitbit.runtrack.ExerciseLocationService.a(a, exercisesession, list); com.fitbit.runtrack.ExerciseLocationService.a(a, exercisesession, list, com.fitbit.runtrack.c.e(intent)); return; } } { a = ExerciseLocationService.this; super(); } }; } public static final Intent a(Context context) { return a(context, "com.fitbit.runtrack.CLEAR_STALE_DATA"); } public static final Intent a(Context context, ExerciseSession exercisesession) { context = a(context, "com.fitbit.runtrack.START_EXERCISE_TRACKING"); context.putExtra("com.fitbit.runtrack.xtra.EXERCISE_SESSION", exercisesession); return context; } private static final Intent a(Context context, String s1) { s1 = new Intent(s1); s1.setClass(context, com/fitbit/runtrack/ExerciseLocationService); return s1; } static String a() { return j; } private void a(Intent intent, int i1) { ExerciseSession exercisesession; for (intent = u.a(com.fitbit.runtrack.data.ExerciseSession.Status.b).iterator(); intent.hasNext(); u.h(exercisesession)) { exercisesession = (ExerciseSession)intent.next(); } ExerciseSession exercisesession1; for (intent = u.a(com.fitbit.runtrack.data.ExerciseSession.Status.a).iterator(); intent.hasNext(); u.h(exercisesession1)) { exercisesession1 = (ExerciseSession)intent.next(); } b(b(this), i1); } static void a(ExerciseLocationService exerciselocationservice, ExerciseSession exercisesession, List list) { exerciselocationservice.a(exercisesession, list); } static void a(ExerciseLocationService exerciselocationservice, ExerciseSession exercisesession, List list, ExerciseStat exercisestat) { exerciselocationservice.a(exercisesession, list, exercisestat); } private void a(ExerciseSession exercisesession) { RemoteViews remoteviews = new RemoteViews(getPackageName(), 0x7f0401c6); remoteviews.setTextViewText(0x7f11011f, b(exercisesession)); Intent intent = b(this, exercisesession); exercisesession = e(exercisesession); remoteviews.setOnClickPendingIntent(0x7f110494, PendingIntent.getBroadcast(this, 0, intent, 0x8000000)); startForeground(0x7f11031d, (new android.support.v4.app.NotificationCompat.Builder(this)).setContent(remoteviews).setOngoing(true).setSmallIcon(0x7f0201dd, 0).setContentIntent(PendingIntent.getActivity(this, 0, exercisesession, 0x8000000)).build()); } private void a(ExerciseSession exercisesession, List list) { j j1 = new j(this); if (((ExerciseSegment)list.get(list.size() - 1)).a()) { j1.b(exercisesession); return; } else { j1.a(exercisesession, new Duration(u.a(list))); return; } } private void a(ExerciseSession exercisesession, List list, ExerciseStat exercisestat) { ((NotificationManager)getSystemService("notification")).notify(0x7f11031d, b(exercisesession, list, exercisestat)); } static boolean a(ExerciseLocationService exerciselocationservice) { return exerciselocationservice.g(); } private Notification b(ExerciseSession exercisesession, List list, ExerciseStat exercisestat) { byte byte0 = 8; Intent intent = RecordExerciseSessionActivity.a(this, exercisesession); intent.setFlags(0x24000000); boolean flag = ((ExerciseSegment)list.get(list.size() - 1)).a(); RemoteViews remoteviews = new RemoteViews(getPackageName(), 0x7f0401c6); remoteviews.setTextViewText(0x7f11011f, b(exercisesession)); Intent intent1; int i1; long l1; if (flag) { i1 = 0; } else { i1 = 8; } remoteviews.setViewVisibility(0x7f110495, i1); if (flag) { i1 = 0; } else { i1 = 8; } remoteviews.setViewVisibility(0x7f110496, i1); if (flag) { i1 = byte0; } else { i1 = 0; } remoteviews.setViewVisibility(0x7f110494, i1); intent1 = b(((Context) (this)), exercisesession); remoteviews.setOnClickPendingIntent(0x7f110495, PendingIntent.getService(this, 0, c(this, exercisesession), 0x8000000)); remoteviews.setOnClickPendingIntent(0x7f110494, PendingIntent.getService(this, 0, intent1, 0x8000000)); remoteviews.setOnClickPendingIntent(0x7f110496, PendingIntent.getActivity(this, 0, intent, 0x8000000)); if (flag) { i1 = 0x7f02028e; } else { i1 = 0x7f02028d; } remoteviews.setImageViewResource(0x7f1101ec, i1); l1 = u.a(list); remoteviews.setTextViewText(0x7f1102b5, DateUtils.formatElapsedTime(TimeUnit.SECONDS.convert(l1, TimeUnit.MILLISECONDS))); if (exercisestat != null) { exercisesession = an.a().b(); remoteviews.setTextViewText(0x7f110107, exercisestat.a().a(exercisesession.t()).toString()); } if (x == null) { x = (new android.support.v4.app.NotificationCompat.Builder(this)).setOngoing(true).setSmallIcon(0x7f020283, 0).setContentIntent(PendingIntent.getActivity(this, 0, intent, 0x8000000)).setContent(remoteviews).setPriority(1).build(); } x.contentView = remoteviews; return x; } public static final Intent b(Context context) { return a(context, "com.fitbit.runtrack.END_EXERCISE_TRACKING"); } public static final Intent b(Context context, ExerciseSession exercisesession) { context = a(context, "com.fitbit.runtrack.PAUSE_EXERICSE_TRACKING"); context.putExtra("com.fitbit.runtrack.xtra.EXERCISE_SESSION", exercisesession); return context; } static b b(ExerciseLocationService exerciselocationservice) { return exerciselocationservice.u; } private CharSequence b(ExerciseSession exercisesession) { exercisesession = com.fitbit.runtrack.SupportedActivity.a(exercisesession); static class _cls4 { static final int a[]; static { a = new int[SupportedActivity.values().length]; try { a[com.fitbit.runtrack.SupportedActivity.c.ordinal()] = 1; } catch (NoSuchFieldError nosuchfielderror2) { } try { a[com.fitbit.runtrack.SupportedActivity.b.ordinal()] = 2; } catch (NoSuchFieldError nosuchfielderror1) { } try { a[com.fitbit.runtrack.SupportedActivity.a.ordinal()] = 3; } catch (NoSuchFieldError nosuchfielderror) { return; } } } com.fitbit.runtrack._cls4.a[exercisesession.ordinal()]; JVM INSTR tableswitch 1 2: default 36 // 1 46 // 2 53; goto _L1 _L2 _L3 _L1: int i1 = 0x7f08047b; _L5: return getText(i1); _L2: i1 = 0x7f08047a; continue; /* Loop/switch isn't completed */ _L3: i1 = 0x7f08047c; if (true) goto _L5; else goto _L4 _L4: } private void b() { w.removeMessages(3); y.d(); } private void b(Intent intent, int i1, int j1) { if (TextUtils.equals("com.fitbit.runtrack.START_EXERCISE_TRACKING", intent.getAction())) { e(intent, i1, j1); } else { if (TextUtils.equals("com.fitbit.runtrack.LOCATION_UPDATE", intent.getAction())) { a(intent, i1, j1); return; } if (TextUtils.equals("com.fitbit.runtrack.PAUSE_EXERICSE_TRACKING", intent.getAction())) { c(intent, i1, j1); return; } if (TextUtils.equals("com.fitbit.runtrack.RESUME_EXERICSE_TRACKING", intent.getAction())) { d(intent, i1, j1); return; } if (TextUtils.equals("com.fitbit.runtrack.CLEAR_STALE_DATA", intent.getAction())) { a(intent, j1); return; } if (TextUtils.equals("com.fitbit.runtrack.END_EXERCISE_TRACKING", intent.getAction()) && !b(intent, j1)) { f(); return; } } } private boolean b(Intent intent, int i1) { if (!r.b()) { t.add(Pair.create(intent, Integer.valueOf(i1))); if (!r.c()) { r.a(); } return true; } else { return false; } } public static final Intent c(Context context, ExerciseSession exercisesession) { context = a(context, "com.fitbit.runtrack.RESUME_EXERICSE_TRACKING"); context.putExtra("com.fitbit.runtrack.xtra.EXERCISE_SESSION", exercisesession); return context; } private void c() { if (r.b()) { r.b(d()); } com.fitbit.e.a.d(j, "Finished Run, disconnecting location client", new Object[0]); r.d(); } private void c(Intent intent, int i1, int j1) { intent = (ExerciseSession)intent.getParcelableExtra("com.fitbit.runtrack.xtra.EXERCISE_SESSION"); com.fitbit.e.a.a(j, String.format("Attempt to pause Session %s", new Object[] { intent.getUuid() }), new Object[0]); s.submit(new Runnable(intent) { final ExerciseSession a; final ExerciseLocationService b; public void run() { Object obj = com.fitbit.runtrack.ExerciseLocationService.b(b).i(a); if (!((List) (obj)).isEmpty()) { obj = (ExerciseSegment)((List) (obj)).get(((List) (obj)).size() - 1); if (!((ExerciseSegment) (obj)).a()) { com.fitbit.runtrack.ExerciseLocationService.b(b).a(((ExerciseSegment) (obj))); com.fitbit.e.a.d(com.fitbit.runtrack.ExerciseLocationService.a(), String.format("Paused Session %s", new Object[] { a.getUuid() }), new Object[0]); } } com.fitbit.runtrack.ExerciseLocationService.c(b); obj = (new e(a, com.fitbit.runtrack.ExerciseLocationService.b(b), ExerciseLocationService.d(b))).a(); /* block-local class not found */ class _cls1 {} ExerciseLocationService.f(b).post(new _cls1(((Intent) (obj)))); } { b = ExerciseLocationService.this; a = exercisesession; super(); } }); } static void c(ExerciseLocationService exerciselocationservice) { exerciselocationservice.b(); } private void c(ExerciseSession exercisesession) { IntentFilter intentfilter = new IntentFilter("com.fitbit.runtrack.EXERCISE_SESSION_UPDATE"); y.a(intentfilter); w.sendMessageDelayed(w.obtainMessage(3, exercisesession), 50L); } private PendingIntent d() { Intent intent = new Intent(this, getClass()); intent.setAction("com.fitbit.runtrack.LOCATION_UPDATE"); return PendingIntent.getService(this, 0, intent, 0x8000000); } static com.fitbit.runtrack.c d(ExerciseLocationService exerciselocationservice) { return exerciselocationservice.v; } private void d(Intent intent, int i1, int j1) { intent = (ExerciseSession)intent.getParcelableExtra("com.fitbit.runtrack.xtra.EXERCISE_SESSION"); com.fitbit.e.a.a(j, String.format("Attempt to resume Session %s", new Object[] { intent.getUuid() }), new Object[0]); s.submit(new Runnable(intent) { final ExerciseSession a; final ExerciseLocationService b; public void run() { List list = com.fitbit.runtrack.ExerciseLocationService.b(b).i(a); if (!list.isEmpty() && ((ExerciseSegment)list.get(list.size() - 1)).a()) { com.fitbit.runtrack.ExerciseLocationService.b(b).b(a); com.fitbit.e.a.d(com.fitbit.runtrack.ExerciseLocationService.a(), String.format("Resumed Session %s", new Object[] { a.getUuid() }), new Object[0]); } ExerciseLocationService.f(b).removeMessages(3, null); ExerciseLocationService.f(b).sendMessage(ExerciseLocationService.f(b).obtainMessage(4, a)); } { b = ExerciseLocationService.this; a = exercisesession; super(); } }); } private void d(ExerciseSession exercisesession) { r.b(d()); r.a(d()); } private Intent e(ExerciseSession exercisesession) { exercisesession = RecordExerciseSessionActivity.a(this, exercisesession); exercisesession.setFlags(0x24000000); return exercisesession; } static a e(ExerciseLocationService exerciselocationservice) { return exerciselocationservice.y; } private void e() { r = new g(this, this, this); } private void e(Intent intent, int i1, int j1) { if (!b(intent, j1)) { intent = (ExerciseSession)intent.getParcelableExtra("com.fitbit.runtrack.xtra.EXERCISE_SESSION"); a(intent); d(intent); c(intent); } } static Handler f(ExerciseLocationService exerciselocationservice) { return exerciselocationservice.w; } private void f() { stopForeground(true); c(); b(); w.removeCallbacksAndMessages(null); stopSelf(); } private boolean g() { return an.a().b() != null; } public void a(Intent intent, int i1, int j1) { if (!g()) { startService(b(this)); return; } intent = (Location)intent.getParcelableExtra("com.google.android.location.LOCATION"); if (intent.hasAccuracy() && intent.getAccuracy() > 80F) { com.fitbit.e.a.a(j, "Location received but ignoring due to low accuracy", new Object[0]); return; } else { intent = new com.fitbit.runtrack.g(u, intent, v); s.submit(intent); return; } } public void a(Bundle bundle) { w.sendEmptyMessage(0); } public void a(String s1) { com.fitbit.e.a.d(j, "Location Client connection failed, location client remade", new Object[0]); w.sendEmptyMessage(2); } public void h_(int i1) { com.fitbit.e.a.d(j, "Location Client was disconnected, location client remade", new Object[0]); w.sendEmptyMessage(1); } public boolean handleMessage(Message message) { switch (message.what) { default: return false; case 0: // '\0' for (; !t.isEmpty(); b((Intent)((Pair) (message)).first, 1, ((Integer)((Pair) (message)).second).intValue())) { message = (Pair)t.remove(); } return true; case 1: // '\001' case 2: // '\002' e(); return true; case 3: // '\003' w.removeMessages(3); Object obj = (ExerciseSession)message.obj; s.submit(new e(((ExerciseSession) (obj)), u, v)); obj = w.obtainMessage(); ((Message) (obj)).copyFrom(message); w.sendMessageDelayed(((Message) (obj)), 50L); return true; case 4: // '\004' b(); c((ExerciseSession)message.obj); s.submit(new e((ExerciseSession)message.obj, u, v)); return true; } } public IBinder onBind(Intent intent) { return null; } public void onCreate() { super.onCreate(); e(); t = new LinkedList(); u = new b(); s = Executors.newSingleThreadExecutor(); v = new com.fitbit.runtrack.c(); w = new Handler(this); } public void onDestroy() { super.onDestroy(); s.shutdown(); w.removeCallbacksAndMessages(null); } public int onStartCommand(Intent intent, int i1, int j1) { if (intent == null) { stopSelf(j1); return 2; } else { b(intent, i1, j1); return 3; } } }
UTF-8
Java
20,973
java
ExerciseLocationService.java
Java
[ { "context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus", "end": 61, "score": 0.9996889233589172, "start": 45, "tag": "NAME", "value": "Pavel Kouznetsov" } ]
null
[]
// Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.fitbit.runtrack; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.text.TextUtils; import android.text.format.DateUtils; import android.util.Pair; import android.widget.RemoteViews; import com.fitbit.data.bl.an; import com.fitbit.data.domain.Length; import com.fitbit.data.domain.Profile; import com.fitbit.e.a; import com.fitbit.maps.g; import com.fitbit.runtrack.data.ExerciseSegment; import com.fitbit.runtrack.data.ExerciseSession; import com.fitbit.runtrack.data.ExerciseStat; import com.fitbit.runtrack.data.b; import com.fitbit.runtrack.ui.RecordExerciseSessionActivity; import com.fitbit.util.threading.c; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; // Referenced classes of package com.fitbit.runtrack: // j, Duration, SupportedActivity, g, // e, c public class ExerciseLocationService extends Service implements android.os.Handler.Callback, com.fitbit.maps.g.a, com.fitbit.maps.g.b { private static abstract class a extends c { public abstract void a(Intent intent); private a() { } } private static final String c = "com.fitbit.runtrack.START_EXERCISE_TRACKING"; private static final String d = "com.fitbit.runtrack.END_EXERCISE_TRACKING"; private static final String e = "com.fitbit.runtrack.PAUSE_EXERICSE_TRACKING"; private static final String f = "com.fitbit.runtrack.RESUME_EXERICSE_TRACKING"; private static final String g = "com.fitbit.runtrack.CLEAR_STALE_DATA"; private static final String h = "com.fitbit.runtrack.LOCATION_UPDATE"; private static final String i = "com.fitbit.runtrack.xtra.EXERCISE_SESSION"; private static final String j = com/fitbit/runtrack/ExerciseLocationService.getSimpleName(); private static final int k = 0; private static final int l = 1; private static final int m = 2; private static final int n = 3; private static final int o = 4; private static final float p = 80F; private static final long q = 50L; private g r; private ExecutorService s; private Queue t; private b u; private com.fitbit.runtrack.c v; private Handler w; private Notification x; private a y; public ExerciseLocationService() { y = new a() { final ExerciseLocationService a; public void a(Intent intent) { if (!com.fitbit.runtrack.ExerciseLocationService.a(a)) { a.startService(com.fitbit.runtrack.ExerciseLocationService.b(a)); } else if (TextUtils.equals("com.fitbit.runtrack.EXERCISE_SESSION_UPDATE", intent.getAction())) { ExerciseSession exercisesession = com.fitbit.runtrack.c.c(intent); List list = com.fitbit.runtrack.c.a(intent); com.fitbit.runtrack.ExerciseLocationService.a(a, exercisesession, list); com.fitbit.runtrack.ExerciseLocationService.a(a, exercisesession, list, com.fitbit.runtrack.c.e(intent)); return; } } { a = ExerciseLocationService.this; super(); } }; } public static final Intent a(Context context) { return a(context, "com.fitbit.runtrack.CLEAR_STALE_DATA"); } public static final Intent a(Context context, ExerciseSession exercisesession) { context = a(context, "com.fitbit.runtrack.START_EXERCISE_TRACKING"); context.putExtra("com.fitbit.runtrack.xtra.EXERCISE_SESSION", exercisesession); return context; } private static final Intent a(Context context, String s1) { s1 = new Intent(s1); s1.setClass(context, com/fitbit/runtrack/ExerciseLocationService); return s1; } static String a() { return j; } private void a(Intent intent, int i1) { ExerciseSession exercisesession; for (intent = u.a(com.fitbit.runtrack.data.ExerciseSession.Status.b).iterator(); intent.hasNext(); u.h(exercisesession)) { exercisesession = (ExerciseSession)intent.next(); } ExerciseSession exercisesession1; for (intent = u.a(com.fitbit.runtrack.data.ExerciseSession.Status.a).iterator(); intent.hasNext(); u.h(exercisesession1)) { exercisesession1 = (ExerciseSession)intent.next(); } b(b(this), i1); } static void a(ExerciseLocationService exerciselocationservice, ExerciseSession exercisesession, List list) { exerciselocationservice.a(exercisesession, list); } static void a(ExerciseLocationService exerciselocationservice, ExerciseSession exercisesession, List list, ExerciseStat exercisestat) { exerciselocationservice.a(exercisesession, list, exercisestat); } private void a(ExerciseSession exercisesession) { RemoteViews remoteviews = new RemoteViews(getPackageName(), 0x7f0401c6); remoteviews.setTextViewText(0x7f11011f, b(exercisesession)); Intent intent = b(this, exercisesession); exercisesession = e(exercisesession); remoteviews.setOnClickPendingIntent(0x7f110494, PendingIntent.getBroadcast(this, 0, intent, 0x8000000)); startForeground(0x7f11031d, (new android.support.v4.app.NotificationCompat.Builder(this)).setContent(remoteviews).setOngoing(true).setSmallIcon(0x7f0201dd, 0).setContentIntent(PendingIntent.getActivity(this, 0, exercisesession, 0x8000000)).build()); } private void a(ExerciseSession exercisesession, List list) { j j1 = new j(this); if (((ExerciseSegment)list.get(list.size() - 1)).a()) { j1.b(exercisesession); return; } else { j1.a(exercisesession, new Duration(u.a(list))); return; } } private void a(ExerciseSession exercisesession, List list, ExerciseStat exercisestat) { ((NotificationManager)getSystemService("notification")).notify(0x7f11031d, b(exercisesession, list, exercisestat)); } static boolean a(ExerciseLocationService exerciselocationservice) { return exerciselocationservice.g(); } private Notification b(ExerciseSession exercisesession, List list, ExerciseStat exercisestat) { byte byte0 = 8; Intent intent = RecordExerciseSessionActivity.a(this, exercisesession); intent.setFlags(0x24000000); boolean flag = ((ExerciseSegment)list.get(list.size() - 1)).a(); RemoteViews remoteviews = new RemoteViews(getPackageName(), 0x7f0401c6); remoteviews.setTextViewText(0x7f11011f, b(exercisesession)); Intent intent1; int i1; long l1; if (flag) { i1 = 0; } else { i1 = 8; } remoteviews.setViewVisibility(0x7f110495, i1); if (flag) { i1 = 0; } else { i1 = 8; } remoteviews.setViewVisibility(0x7f110496, i1); if (flag) { i1 = byte0; } else { i1 = 0; } remoteviews.setViewVisibility(0x7f110494, i1); intent1 = b(((Context) (this)), exercisesession); remoteviews.setOnClickPendingIntent(0x7f110495, PendingIntent.getService(this, 0, c(this, exercisesession), 0x8000000)); remoteviews.setOnClickPendingIntent(0x7f110494, PendingIntent.getService(this, 0, intent1, 0x8000000)); remoteviews.setOnClickPendingIntent(0x7f110496, PendingIntent.getActivity(this, 0, intent, 0x8000000)); if (flag) { i1 = 0x7f02028e; } else { i1 = 0x7f02028d; } remoteviews.setImageViewResource(0x7f1101ec, i1); l1 = u.a(list); remoteviews.setTextViewText(0x7f1102b5, DateUtils.formatElapsedTime(TimeUnit.SECONDS.convert(l1, TimeUnit.MILLISECONDS))); if (exercisestat != null) { exercisesession = an.a().b(); remoteviews.setTextViewText(0x7f110107, exercisestat.a().a(exercisesession.t()).toString()); } if (x == null) { x = (new android.support.v4.app.NotificationCompat.Builder(this)).setOngoing(true).setSmallIcon(0x7f020283, 0).setContentIntent(PendingIntent.getActivity(this, 0, intent, 0x8000000)).setContent(remoteviews).setPriority(1).build(); } x.contentView = remoteviews; return x; } public static final Intent b(Context context) { return a(context, "com.fitbit.runtrack.END_EXERCISE_TRACKING"); } public static final Intent b(Context context, ExerciseSession exercisesession) { context = a(context, "com.fitbit.runtrack.PAUSE_EXERICSE_TRACKING"); context.putExtra("com.fitbit.runtrack.xtra.EXERCISE_SESSION", exercisesession); return context; } static b b(ExerciseLocationService exerciselocationservice) { return exerciselocationservice.u; } private CharSequence b(ExerciseSession exercisesession) { exercisesession = com.fitbit.runtrack.SupportedActivity.a(exercisesession); static class _cls4 { static final int a[]; static { a = new int[SupportedActivity.values().length]; try { a[com.fitbit.runtrack.SupportedActivity.c.ordinal()] = 1; } catch (NoSuchFieldError nosuchfielderror2) { } try { a[com.fitbit.runtrack.SupportedActivity.b.ordinal()] = 2; } catch (NoSuchFieldError nosuchfielderror1) { } try { a[com.fitbit.runtrack.SupportedActivity.a.ordinal()] = 3; } catch (NoSuchFieldError nosuchfielderror) { return; } } } com.fitbit.runtrack._cls4.a[exercisesession.ordinal()]; JVM INSTR tableswitch 1 2: default 36 // 1 46 // 2 53; goto _L1 _L2 _L3 _L1: int i1 = 0x7f08047b; _L5: return getText(i1); _L2: i1 = 0x7f08047a; continue; /* Loop/switch isn't completed */ _L3: i1 = 0x7f08047c; if (true) goto _L5; else goto _L4 _L4: } private void b() { w.removeMessages(3); y.d(); } private void b(Intent intent, int i1, int j1) { if (TextUtils.equals("com.fitbit.runtrack.START_EXERCISE_TRACKING", intent.getAction())) { e(intent, i1, j1); } else { if (TextUtils.equals("com.fitbit.runtrack.LOCATION_UPDATE", intent.getAction())) { a(intent, i1, j1); return; } if (TextUtils.equals("com.fitbit.runtrack.PAUSE_EXERICSE_TRACKING", intent.getAction())) { c(intent, i1, j1); return; } if (TextUtils.equals("com.fitbit.runtrack.RESUME_EXERICSE_TRACKING", intent.getAction())) { d(intent, i1, j1); return; } if (TextUtils.equals("com.fitbit.runtrack.CLEAR_STALE_DATA", intent.getAction())) { a(intent, j1); return; } if (TextUtils.equals("com.fitbit.runtrack.END_EXERCISE_TRACKING", intent.getAction()) && !b(intent, j1)) { f(); return; } } } private boolean b(Intent intent, int i1) { if (!r.b()) { t.add(Pair.create(intent, Integer.valueOf(i1))); if (!r.c()) { r.a(); } return true; } else { return false; } } public static final Intent c(Context context, ExerciseSession exercisesession) { context = a(context, "com.fitbit.runtrack.RESUME_EXERICSE_TRACKING"); context.putExtra("com.fitbit.runtrack.xtra.EXERCISE_SESSION", exercisesession); return context; } private void c() { if (r.b()) { r.b(d()); } com.fitbit.e.a.d(j, "Finished Run, disconnecting location client", new Object[0]); r.d(); } private void c(Intent intent, int i1, int j1) { intent = (ExerciseSession)intent.getParcelableExtra("com.fitbit.runtrack.xtra.EXERCISE_SESSION"); com.fitbit.e.a.a(j, String.format("Attempt to pause Session %s", new Object[] { intent.getUuid() }), new Object[0]); s.submit(new Runnable(intent) { final ExerciseSession a; final ExerciseLocationService b; public void run() { Object obj = com.fitbit.runtrack.ExerciseLocationService.b(b).i(a); if (!((List) (obj)).isEmpty()) { obj = (ExerciseSegment)((List) (obj)).get(((List) (obj)).size() - 1); if (!((ExerciseSegment) (obj)).a()) { com.fitbit.runtrack.ExerciseLocationService.b(b).a(((ExerciseSegment) (obj))); com.fitbit.e.a.d(com.fitbit.runtrack.ExerciseLocationService.a(), String.format("Paused Session %s", new Object[] { a.getUuid() }), new Object[0]); } } com.fitbit.runtrack.ExerciseLocationService.c(b); obj = (new e(a, com.fitbit.runtrack.ExerciseLocationService.b(b), ExerciseLocationService.d(b))).a(); /* block-local class not found */ class _cls1 {} ExerciseLocationService.f(b).post(new _cls1(((Intent) (obj)))); } { b = ExerciseLocationService.this; a = exercisesession; super(); } }); } static void c(ExerciseLocationService exerciselocationservice) { exerciselocationservice.b(); } private void c(ExerciseSession exercisesession) { IntentFilter intentfilter = new IntentFilter("com.fitbit.runtrack.EXERCISE_SESSION_UPDATE"); y.a(intentfilter); w.sendMessageDelayed(w.obtainMessage(3, exercisesession), 50L); } private PendingIntent d() { Intent intent = new Intent(this, getClass()); intent.setAction("com.fitbit.runtrack.LOCATION_UPDATE"); return PendingIntent.getService(this, 0, intent, 0x8000000); } static com.fitbit.runtrack.c d(ExerciseLocationService exerciselocationservice) { return exerciselocationservice.v; } private void d(Intent intent, int i1, int j1) { intent = (ExerciseSession)intent.getParcelableExtra("com.fitbit.runtrack.xtra.EXERCISE_SESSION"); com.fitbit.e.a.a(j, String.format("Attempt to resume Session %s", new Object[] { intent.getUuid() }), new Object[0]); s.submit(new Runnable(intent) { final ExerciseSession a; final ExerciseLocationService b; public void run() { List list = com.fitbit.runtrack.ExerciseLocationService.b(b).i(a); if (!list.isEmpty() && ((ExerciseSegment)list.get(list.size() - 1)).a()) { com.fitbit.runtrack.ExerciseLocationService.b(b).b(a); com.fitbit.e.a.d(com.fitbit.runtrack.ExerciseLocationService.a(), String.format("Resumed Session %s", new Object[] { a.getUuid() }), new Object[0]); } ExerciseLocationService.f(b).removeMessages(3, null); ExerciseLocationService.f(b).sendMessage(ExerciseLocationService.f(b).obtainMessage(4, a)); } { b = ExerciseLocationService.this; a = exercisesession; super(); } }); } private void d(ExerciseSession exercisesession) { r.b(d()); r.a(d()); } private Intent e(ExerciseSession exercisesession) { exercisesession = RecordExerciseSessionActivity.a(this, exercisesession); exercisesession.setFlags(0x24000000); return exercisesession; } static a e(ExerciseLocationService exerciselocationservice) { return exerciselocationservice.y; } private void e() { r = new g(this, this, this); } private void e(Intent intent, int i1, int j1) { if (!b(intent, j1)) { intent = (ExerciseSession)intent.getParcelableExtra("com.fitbit.runtrack.xtra.EXERCISE_SESSION"); a(intent); d(intent); c(intent); } } static Handler f(ExerciseLocationService exerciselocationservice) { return exerciselocationservice.w; } private void f() { stopForeground(true); c(); b(); w.removeCallbacksAndMessages(null); stopSelf(); } private boolean g() { return an.a().b() != null; } public void a(Intent intent, int i1, int j1) { if (!g()) { startService(b(this)); return; } intent = (Location)intent.getParcelableExtra("com.google.android.location.LOCATION"); if (intent.hasAccuracy() && intent.getAccuracy() > 80F) { com.fitbit.e.a.a(j, "Location received but ignoring due to low accuracy", new Object[0]); return; } else { intent = new com.fitbit.runtrack.g(u, intent, v); s.submit(intent); return; } } public void a(Bundle bundle) { w.sendEmptyMessage(0); } public void a(String s1) { com.fitbit.e.a.d(j, "Location Client connection failed, location client remade", new Object[0]); w.sendEmptyMessage(2); } public void h_(int i1) { com.fitbit.e.a.d(j, "Location Client was disconnected, location client remade", new Object[0]); w.sendEmptyMessage(1); } public boolean handleMessage(Message message) { switch (message.what) { default: return false; case 0: // '\0' for (; !t.isEmpty(); b((Intent)((Pair) (message)).first, 1, ((Integer)((Pair) (message)).second).intValue())) { message = (Pair)t.remove(); } return true; case 1: // '\001' case 2: // '\002' e(); return true; case 3: // '\003' w.removeMessages(3); Object obj = (ExerciseSession)message.obj; s.submit(new e(((ExerciseSession) (obj)), u, v)); obj = w.obtainMessage(); ((Message) (obj)).copyFrom(message); w.sendMessageDelayed(((Message) (obj)), 50L); return true; case 4: // '\004' b(); c((ExerciseSession)message.obj); s.submit(new e((ExerciseSession)message.obj, u, v)); return true; } } public IBinder onBind(Intent intent) { return null; } public void onCreate() { super.onCreate(); e(); t = new LinkedList(); u = new b(); s = Executors.newSingleThreadExecutor(); v = new com.fitbit.runtrack.c(); w = new Handler(this); } public void onDestroy() { super.onDestroy(); s.shutdown(); w.removeCallbacksAndMessages(null); } public int onStartCommand(Intent intent, int i1, int j1) { if (intent == null) { stopSelf(j1); return 2; } else { b(intent, i1, j1); return 3; } } }
20,963
0.578649
0.558623
666
30.490992
32.111351
257
false
false
0
0
0
0
0
0
0.659159
false
false
7
5d5d9e6a0f395b3b0b1e6006f9a6b833d90d372d
7,172,595,385,983
87375b7aa676d2e41301bd0c69bb373b82a4c24a
/Boletin5_4/src/boletin5_4/Boletin5_4.java
a9eea07053a450fa0f105ba7f47cd2050bfbcd59
[]
no_license
YasminLago/Boletin5
https://github.com/YasminLago/Boletin5
faccf0e6fc39463bbb4cdfa384415ad1bb1af088
21ce7dc451c9208a0452bca34c1724cfe9937fff
refs/heads/master
"2021-01-10T14:39:22"
"2015-10-30T20:34:57"
"2015-10-30T20:34:57"
44,490,411
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package boletin5_4; //Yasmin import javax.swing.JOptionPane; public class Boletin5_4 { public static void main(String[] args) { float polbo,patacas,engadir; String res=JOptionPane.showInputDialog("Kg polvo"); polbo=Float.parseFloat(res); String res1=JOptionPane.showInputDialog("Kg patacas"); patacas=Float.parseFloat(res1); Clientes cli=new Clientes(polbo,patacas); JOptionPane.showMessageDialog(null,"Nº clientes" +cli.numeroClientes(polbo, patacas)); String res2=JOptionPane.showInputDialog("Engadir Kg polbo"); engadir=Float.parseFloat(res2); String res3=JOptionPane.showInputDialog("Engadir Kg patacas"); engadir=Float.parseFloat(res3); Clientes cli1=new Clientes(polbo,patacas); JOptionPane.showMessageDialog(null,"Nº total kg polvo" +cli1.amosarPolbo(20)); JOptionPane.showMessageDialog(null,"Nº total kg patacas"+cli1.amosarPatacas(50)); } }
UTF-8
Java
988
java
Boletin5_4.java
Java
[ { "context": "package boletin5_4;\r\n//Yasmin\r\nimport javax.swing.JOptionPane;\r\n\r\npublic class ", "end": 29, "score": 0.8178035616874695, "start": 23, "tag": "NAME", "value": "Yasmin" } ]
null
[]
package boletin5_4; //Yasmin import javax.swing.JOptionPane; public class Boletin5_4 { public static void main(String[] args) { float polbo,patacas,engadir; String res=JOptionPane.showInputDialog("Kg polvo"); polbo=Float.parseFloat(res); String res1=JOptionPane.showInputDialog("Kg patacas"); patacas=Float.parseFloat(res1); Clientes cli=new Clientes(polbo,patacas); JOptionPane.showMessageDialog(null,"Nº clientes" +cli.numeroClientes(polbo, patacas)); String res2=JOptionPane.showInputDialog("Engadir Kg polbo"); engadir=Float.parseFloat(res2); String res3=JOptionPane.showInputDialog("Engadir Kg patacas"); engadir=Float.parseFloat(res3); Clientes cli1=new Clientes(polbo,patacas); JOptionPane.showMessageDialog(null,"Nº total kg polvo" +cli1.amosarPolbo(20)); JOptionPane.showMessageDialog(null,"Nº total kg patacas"+cli1.amosarPatacas(50)); } }
988
0.693401
0.676142
28
33.25
27.783121
92
false
false
0
0
0
0
0
0
0.857143
false
false
7
df5583978211268f4776a5589a454653eff52b24
13,778,255,094,570
360e969658f71948c3f81e8eb2cc57ca08963917
/src/main/java/com/codeh/questionbank/data/DbInitializer.java
189ebee311859b56ad2de85fc484288e25e8e1de
[]
no_license
Loogibot/questionbank
https://github.com/Loogibot/questionbank
5160c64c2227fd09b6355c204315ace33ecf2245
e65f73eb495c915bb370463e4acb8d167333c139
refs/heads/master
"2023-03-27T06:09:50.347000"
"2020-08-19T09:50:07"
"2020-08-19T09:50:07"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.codeh.questionbank.data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; @Component public class DbInitializer implements CommandLineRunner { private static final Logger logger = LoggerFactory.getLogger(DbInitializer.class); @Autowired private UserInfoRepository userInfoRepository; @Autowired private PasswordEncoder passwordEncoder; @Override public void run(String... args) throws Exception { logger.info("Inside the DbInitializer"); userInfoRepository.deleteAll(); List<UserInfo> userList = new ArrayList<>(); userList.add(new UserInfo("user1", passwordEncoder.encode("pass1"),"USER")); userList.add(new UserInfo("user2", passwordEncoder.encode("pass2"),"USER")); userList.add(new UserInfo("admin1", passwordEncoder.encode("admin1"),"ADMIN")); userList.add(new UserInfo("admin2", passwordEncoder.encode("admin2"),"")); userInfoRepository.saveAll(userList); logger.info("Successfully inserted records inside user table!"); } }
UTF-8
Java
1,345
java
DbInitializer.java
Java
[ { "context": "add(new UserInfo(\"user1\", passwordEncoder.encode(\"pass1\"),\"USER\"));\n userList.add(new UserInfo(\"us", "end": 949, "score": 0.9963186383247375, "start": 944, "tag": "PASSWORD", "value": "pass1" }, { "context": "add(new UserInfo(\"user2\", passwordEncoder.encode(\"pass2\"),\"USER\"));\n userList.add(new UserInfo(\"ad", "end": 1034, "score": 0.9940022230148315, "start": 1029, "tag": "PASSWORD", "value": "pass2" }, { "context": "dd(new UserInfo(\"admin1\", passwordEncoder.encode(\"admin1\"),\"ADMIN\"));\n userList.add(new UserInfo(\"a", "end": 1121, "score": 0.9888239502906799, "start": 1115, "tag": "PASSWORD", "value": "admin1" }, { "context": "dd(new UserInfo(\"admin2\", passwordEncoder.encode(\"admin2\"),\"\"));\n userInfoRepository.saveAll(userLi", "end": 1209, "score": 0.9969507455825806, "start": 1203, "tag": "PASSWORD", "value": "admin2" } ]
null
[]
package com.codeh.questionbank.data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; @Component public class DbInitializer implements CommandLineRunner { private static final Logger logger = LoggerFactory.getLogger(DbInitializer.class); @Autowired private UserInfoRepository userInfoRepository; @Autowired private PasswordEncoder passwordEncoder; @Override public void run(String... args) throws Exception { logger.info("Inside the DbInitializer"); userInfoRepository.deleteAll(); List<UserInfo> userList = new ArrayList<>(); userList.add(new UserInfo("user1", passwordEncoder.encode("<PASSWORD>"),"USER")); userList.add(new UserInfo("user2", passwordEncoder.encode("<PASSWORD>"),"USER")); userList.add(new UserInfo("admin1", passwordEncoder.encode("<PASSWORD>"),"ADMIN")); userList.add(new UserInfo("admin2", passwordEncoder.encode("<PASSWORD>"),"")); userInfoRepository.saveAll(userList); logger.info("Successfully inserted records inside user table!"); } }
1,363
0.744981
0.737546
36
36.361111
29.130123
87
false
false
0
0
0
0
0
0
0.805556
false
false
7
6f1b72c6b4c89fbdc2601a3ceb678bf284f51bca
21,801,254,001,224
5351a18ec516e87711bc6d39936fa34a21f28407
/app/src/main/java/net/ajcloud/wansviewplusw/support/utils/CipherUtil.java
b95d92a93d30741351251223d2fb2623eb4476a7
[]
no_license
cloverc1022/wanviewplusPc
https://github.com/cloverc1022/wanviewplusPc
1ef9a0e5b0b4d0c269699c9d0609195210bfc1d5
257a4b93dc0659f76d7f356e9f74026cbe215e94
refs/heads/master
"2022-01-05T14:15:36.751000"
"2019-06-03T02:05:43"
"2019-06-03T02:05:43"
166,205,495
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.ajcloud.wansviewplusw.support.utils; import net.ajcloud.wansviewplusw.support.jnacl.NaCl; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.BufferedInputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Random; import static net.ajcloud.wansviewplusw.support.jnacl.curve25519xsalsa20poly1305.crypto_secretbox_NONCEBYTES; /** * Created by mamengchao on 2018/05/23. * 加解密 */ public class CipherUtil { private static String TAG = "CipherUtil"; private static int SALT_LENGTH = 12; public static String PUBLICKEY = "0cba66066896ffb51e92bc3c36ffa627c2493770d9b0b4368a2466c801b0184e"; public static String PRIVATEKEY = "176970653848be5242059e2308dfa30245b93a13befd2ebd09f09b971273b728"; //uac /** * 生成随机nonce */ public static byte[] getNonce() { byte[] nonce = new byte[crypto_secretbox_NONCEBYTES]; Random random = new Random(); for (int i = 0; i < nonce.length; i++) { nonce[i] = (byte) random.nextInt(256); } return nonce; } public static String naclEncode(String text, String privateKey, String publicKey, byte[] nonce) { String encodeMsgContent = null; try { byte[] encryptPrivateKey = Base64.getDecoder().decode(privateKey); byte[] encryptPublicKey = Base64.getDecoder().decode(publicKey); byte[] ciphertext = NaCl.encrypt(text.getBytes(), nonce, encryptPublicKey, encryptPrivateKey); ciphertext = clearZero(ciphertext); encodeMsgContent = new String(Base64.getEncoder().encode(ciphertext), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { return encodeMsgContent; } } private static byte[] clearZero(byte[] oldArr) { List<Byte> list = new ArrayList<>(); boolean isBefore = true; for (int i = 0; i < oldArr.length; i++) { if (i == 0) { isBefore = oldArr[i] == 0; } if (isBefore) { if (oldArr[i] != 0) { list.add(oldArr[i]); isBefore = false; } } else { list.add(oldArr[i]); } } byte newArr[] = new byte[list.size()]; for (int i = 0; i < list.size(); i++) { newArr[i] = list.get(i); } return newArr; } public static String naclDecode(String text, String privateKey, String publicKey, byte[] nonce) { String decodeMsgContent = null; try { byte[] decryptPrivateKey = Base64.getDecoder().decode(privateKey); byte[] decryptPublicKey = Base64.getDecoder().decode(publicKey); byte[] decryptValue = Base64.getDecoder().decode(text); decodeMsgContent = new String(NaCl.decrypt(decryptValue, nonce, decryptPublicKey, decryptPrivateKey), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { return decodeMsgContent; } } //local public static String md5Encode(String strIN, String salt) { String msg = strIN + salt; MessageDigest alg; try { alg = MessageDigest.getInstance("MD5"); alg.update(msg.getBytes()); byte[] bytes = alg.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { String temp = Integer.toHexString(0xFF & bytes[i]); if (temp.length() == 1) { hexString.append("0"); hexString.append(temp); } else if (temp.length() == 2) { hexString.append(temp); } else { WLog.w("MD5Util", "error str:" + msg); } } return hexString.toString(); } catch (NoSuchAlgorithmException e) { WLog.w(TAG, e.getMessage()); } return msg; } public static String getRandomSalt() { SecureRandom secureRandom = new SecureRandom(); byte[] saltByte = new byte[crypto_secretbox_NONCEBYTES]; secureRandom.nextBytes(saltByte); return Base64.getEncoder().encodeToString(saltByte); } //本地nacl加密 public static String naclEncodeLocal(String text, String salt) { try { byte[] publicKey = PUBLICKEY.getBytes(); byte[] privateKey = PRIVATEKEY.getBytes(); byte[] nonce = Base64.getDecoder().decode(salt); // return new String(NaCl.encrypt(text.getBytes(), nonce, publicKey, privateKey)); return new String(Base64.getEncoder().encode(NaCl.encrypt(text.getBytes(), nonce, publicKey, privateKey)), "UTF-8"); } catch (Exception e) { e.printStackTrace(); return null; } } //本地nacl解密 public static String naclDecodeLocal(String text, String salt) { try { byte[] publicKey = PUBLICKEY.getBytes(); byte[] privateKey = PRIVATEKEY.getBytes(); byte[] nonce = Base64.getDecoder().decode(salt); return new String(NaCl.decrypt(Base64.getDecoder().decode(text), nonce, publicKey, privateKey), "UTF-8"); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 获取Api请求中需要的签名sign字段 */ public static String getClondApiSign(String key, String data) { String signature = null; try { Mac mac = Mac.getInstance("HmacSHA256"); SecretKeySpec secret = new SecretKeySpec( key.getBytes("UTF-8"), mac.getAlgorithm()); mac.init(secret); signature = urlSafe_base64(mac.doFinal(data.getBytes())); } catch (NoSuchAlgorithmException e) { WLog.w(TAG, "Hash algorithm SHA-1 is not supported", e); } catch (UnsupportedEncodingException e) { WLog.w(TAG, "Encoding UTF-8 is not supported", e); } catch (InvalidKeyException e) { WLog.w(TAG, "Invalid key", e); } return signature; } /** * sha256加密 */ public static String getSha256(String str) { if (null == str || 0 == str.length()) { return null; } char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; try { MessageDigest mdTemp = MessageDigest.getInstance("SHA-256"); mdTemp.update(str.getBytes("UTF-8")); byte[] md = mdTemp.digest(); int j = md.length; char[] buf = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; buf[k++] = hexDigits[byte0 >>> 4 & 0xf]; buf[k++] = hexDigits[byte0 & 0xf]; } return new String(buf); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } /** * 字符串转hex字符串 */ public static String strToHex(String str) throws UnsupportedEncodingException { return String.format("%x", new BigInteger(1, str.getBytes("UTF-8"))); } /** * byte[]转hex字符串 */ public static String bytesToHex(byte[] bytes) { StringBuilder buf = new StringBuilder(bytes.length * 2); for (byte b : bytes) { // 使用String的format方法进行转换 buf.append(String.format("%02x", new Integer(b & 0xff))); } return buf.toString(); } /** * urlsafe-base64 */ public static String urlSafe_base64(byte[] bytes) { String result = null; try { result = new String(Base64.getEncoder().encode(bytes), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result .replace("+", "-") .replace("/", "_") .replace("=", ""); } /** * sha1加密 */ public static String getSha1(InputStream in) { MessageDigest messageDigest; InputStream inputStream = null; try { messageDigest = MessageDigest.getInstance("SHA-1"); inputStream = new BufferedInputStream(in); byte[] buffer = new byte[8192]; int len = inputStream.read(buffer); while (len != -1) { messageDigest.update(buffer, 0, len); len = inputStream.read(buffer); } return bytesToHex(messageDigest.digest()); } catch (Exception e) { e.printStackTrace(); } return null; } }
UTF-8
Java
9,293
java
CipherUtil.java
Java
[ { "context": "05.crypto_secretbox_NONCEBYTES;\n\n/**\n * Created by mamengchao on 2018/05/23.\n * 加解密\n */\npublic class CipherUtil", "end": 708, "score": 0.9996289014816284, "start": 698, "tag": "USERNAME", "value": "mamengchao" }, { "context": "ENGTH = 12;\n public static String PUBLICKEY = \"0cba66066896ffb51e92bc3c36ffa627c2493770d9b0b4368a2466c801b0184e\";\n public static String PRIVATEKEY = \"17697065", "end": 951, "score": 0.9997789263725281, "start": 887, "tag": "KEY", "value": "0cba66066896ffb51e92bc3c36ffa627c2493770d9b0b4368a2466c801b0184e" }, { "context": "01b0184e\";\n public static String PRIVATEKEY = \"176970653848be5242059e2308dfa30245b93a13befd2ebd09f09b971273b728\";\n\n //uac\n\n /**\n * 生成随机nonce\n */\n ", "end": 1057, "score": 0.9997667074203491, "start": 993, "tag": "KEY", "value": "176970653848be5242059e2308dfa30245b93a13befd2ebd09f09b971273b728" } ]
null
[]
package net.ajcloud.wansviewplusw.support.utils; import net.ajcloud.wansviewplusw.support.jnacl.NaCl; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.BufferedInputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Random; import static net.ajcloud.wansviewplusw.support.jnacl.curve25519xsalsa20poly1305.crypto_secretbox_NONCEBYTES; /** * Created by mamengchao on 2018/05/23. * 加解密 */ public class CipherUtil { private static String TAG = "CipherUtil"; private static int SALT_LENGTH = 12; public static String PUBLICKEY = "<KEY>"; public static String PRIVATEKEY = "176970653848be5242059e2308dfa30245b93a13befd2ebd09f09b971273b728"; //uac /** * 生成随机nonce */ public static byte[] getNonce() { byte[] nonce = new byte[crypto_secretbox_NONCEBYTES]; Random random = new Random(); for (int i = 0; i < nonce.length; i++) { nonce[i] = (byte) random.nextInt(256); } return nonce; } public static String naclEncode(String text, String privateKey, String publicKey, byte[] nonce) { String encodeMsgContent = null; try { byte[] encryptPrivateKey = Base64.getDecoder().decode(privateKey); byte[] encryptPublicKey = Base64.getDecoder().decode(publicKey); byte[] ciphertext = NaCl.encrypt(text.getBytes(), nonce, encryptPublicKey, encryptPrivateKey); ciphertext = clearZero(ciphertext); encodeMsgContent = new String(Base64.getEncoder().encode(ciphertext), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { return encodeMsgContent; } } private static byte[] clearZero(byte[] oldArr) { List<Byte> list = new ArrayList<>(); boolean isBefore = true; for (int i = 0; i < oldArr.length; i++) { if (i == 0) { isBefore = oldArr[i] == 0; } if (isBefore) { if (oldArr[i] != 0) { list.add(oldArr[i]); isBefore = false; } } else { list.add(oldArr[i]); } } byte newArr[] = new byte[list.size()]; for (int i = 0; i < list.size(); i++) { newArr[i] = list.get(i); } return newArr; } public static String naclDecode(String text, String privateKey, String publicKey, byte[] nonce) { String decodeMsgContent = null; try { byte[] decryptPrivateKey = Base64.getDecoder().decode(privateKey); byte[] decryptPublicKey = Base64.getDecoder().decode(publicKey); byte[] decryptValue = Base64.getDecoder().decode(text); decodeMsgContent = new String(NaCl.decrypt(decryptValue, nonce, decryptPublicKey, decryptPrivateKey), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { return decodeMsgContent; } } //local public static String md5Encode(String strIN, String salt) { String msg = strIN + salt; MessageDigest alg; try { alg = MessageDigest.getInstance("MD5"); alg.update(msg.getBytes()); byte[] bytes = alg.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { String temp = Integer.toHexString(0xFF & bytes[i]); if (temp.length() == 1) { hexString.append("0"); hexString.append(temp); } else if (temp.length() == 2) { hexString.append(temp); } else { WLog.w("MD5Util", "error str:" + msg); } } return hexString.toString(); } catch (NoSuchAlgorithmException e) { WLog.w(TAG, e.getMessage()); } return msg; } public static String getRandomSalt() { SecureRandom secureRandom = new SecureRandom(); byte[] saltByte = new byte[crypto_secretbox_NONCEBYTES]; secureRandom.nextBytes(saltByte); return Base64.getEncoder().encodeToString(saltByte); } //本地nacl加密 public static String naclEncodeLocal(String text, String salt) { try { byte[] publicKey = PUBLICKEY.getBytes(); byte[] privateKey = PRIVATEKEY.getBytes(); byte[] nonce = Base64.getDecoder().decode(salt); // return new String(NaCl.encrypt(text.getBytes(), nonce, publicKey, privateKey)); return new String(Base64.getEncoder().encode(NaCl.encrypt(text.getBytes(), nonce, publicKey, privateKey)), "UTF-8"); } catch (Exception e) { e.printStackTrace(); return null; } } //本地nacl解密 public static String naclDecodeLocal(String text, String salt) { try { byte[] publicKey = PUBLICKEY.getBytes(); byte[] privateKey = PRIVATEKEY.getBytes(); byte[] nonce = Base64.getDecoder().decode(salt); return new String(NaCl.decrypt(Base64.getDecoder().decode(text), nonce, publicKey, privateKey), "UTF-8"); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 获取Api请求中需要的签名sign字段 */ public static String getClondApiSign(String key, String data) { String signature = null; try { Mac mac = Mac.getInstance("HmacSHA256"); SecretKeySpec secret = new SecretKeySpec( key.getBytes("UTF-8"), mac.getAlgorithm()); mac.init(secret); signature = urlSafe_base64(mac.doFinal(data.getBytes())); } catch (NoSuchAlgorithmException e) { WLog.w(TAG, "Hash algorithm SHA-1 is not supported", e); } catch (UnsupportedEncodingException e) { WLog.w(TAG, "Encoding UTF-8 is not supported", e); } catch (InvalidKeyException e) { WLog.w(TAG, "Invalid key", e); } return signature; } /** * sha256加密 */ public static String getSha256(String str) { if (null == str || 0 == str.length()) { return null; } char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; try { MessageDigest mdTemp = MessageDigest.getInstance("SHA-256"); mdTemp.update(str.getBytes("UTF-8")); byte[] md = mdTemp.digest(); int j = md.length; char[] buf = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; buf[k++] = hexDigits[byte0 >>> 4 & 0xf]; buf[k++] = hexDigits[byte0 & 0xf]; } return new String(buf); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } /** * 字符串转hex字符串 */ public static String strToHex(String str) throws UnsupportedEncodingException { return String.format("%x", new BigInteger(1, str.getBytes("UTF-8"))); } /** * byte[]转hex字符串 */ public static String bytesToHex(byte[] bytes) { StringBuilder buf = new StringBuilder(bytes.length * 2); for (byte b : bytes) { // 使用String的format方法进行转换 buf.append(String.format("%02x", new Integer(b & 0xff))); } return buf.toString(); } /** * urlsafe-base64 */ public static String urlSafe_base64(byte[] bytes) { String result = null; try { result = new String(Base64.getEncoder().encode(bytes), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result .replace("+", "-") .replace("/", "_") .replace("=", ""); } /** * sha1加密 */ public static String getSha1(InputStream in) { MessageDigest messageDigest; InputStream inputStream = null; try { messageDigest = MessageDigest.getInstance("SHA-1"); inputStream = new BufferedInputStream(in); byte[] buffer = new byte[8192]; int len = inputStream.read(buffer); while (len != -1) { messageDigest.update(buffer, 0, len); len = inputStream.read(buffer); } return bytesToHex(messageDigest.digest()); } catch (Exception e) { e.printStackTrace(); } return null; } }
9,234
0.557828
0.534436
271
32.915131
26.102625
128
false
false
0
0
0
0
64
0.013927
0.726937
false
false
7
698888019d8accfbbefb4c158ec939970e144def
1,726,576,864,271
b00e9aecc3aa7d20054f94695da2feb1f8217de5
/src/test/java/org/opentestsystem/ap/item/history/service/DefaultItemHistoryServiceTest.java
932a28996b4e63d236776ed1b5dfab658ccc7b6c
[ "ECL-2.0" ]
permissive
SmarterApp/AP_ItemHistoryService
https://github.com/SmarterApp/AP_ItemHistoryService
a3b2927a0cd89dff28d09642955a6c07f704143e
ac4fe70a6f121d93a68712a421a5f1ea6a113817
refs/heads/develop
"2020-06-10T21:05:53.495000"
"2020-01-13T18:22:43"
"2020-01-13T18:22:43"
193,747,167
0
0
NOASSERTION
false
"2019-12-18T16:22:26"
"2019-06-25T16:44:07"
"2019-12-17T23:52:30"
"2019-12-18T16:22:25"
1,871
0
0
0
Java
false
false
package org.opentestsystem.ap.item.history.service; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.opentestsystem.ap.common.datastore.entity.ItemEntity; import org.opentestsystem.ap.common.datastore.entity.ItemHistoryEntity; import org.opentestsystem.ap.common.datastore.repository.ItemEntityRepository; import org.opentestsystem.ap.common.datastore.repository.ItemHistoryRepository; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import static org.opentestsystem.ap.item.history.service.DefaultItemHistoryService.BEGAN_CREATION_COMMIT_MESSAGE; @RunWith(MockitoJUnitRunner.class) public class DefaultItemHistoryServiceTest { @Mock private ItemHistoryRepository itemHistoryRepository; @Mock private ItemEntityRepository itemEntityRepository; private DefaultItemHistoryService itemHistoryService; @Before public void setUp() { itemHistoryService = new DefaultItemHistoryService(itemHistoryRepository, itemEntityRepository); } @Test public void shouldReturnHistoryRecordById() { UUID id = UUID.randomUUID(); ItemHistoryEntity itemHistoryEntity = new ItemHistoryEntity(); when(itemHistoryRepository.findOne(id)).thenReturn(itemHistoryEntity); Optional<ItemHistoryEntity> persistedEntity = itemHistoryService.findItemHistoryById(id); verify(itemHistoryRepository).findOne(id); assertThat(persistedEntity).isPresent(); assertThat(persistedEntity.get()).isEqualTo(itemHistoryEntity); } @Test public void shouldReturnPreviewableHistory() { final String itemId = "1"; ItemHistoryEntity itemHistoryEntity = new ItemHistoryEntity(); when(itemHistoryRepository.findSupportsPreview("1")).thenReturn(Collections.singletonList(itemHistoryEntity)); List<ItemHistoryEntity> histories = itemHistoryService.findSupportsPreview(itemId); verify(itemHistoryRepository).findSupportsPreview(itemId); assertThat(histories).containsExactly(itemHistoryEntity); } @Test public void shouldFindHistoryRecords() { final String itemId = "1"; ItemHistoryEntity itemHistoryEntity = new ItemHistoryEntity(); itemHistoryEntity.setCommitMessage(BEGAN_CREATION_COMMIT_MESSAGE); when(itemHistoryRepository.findByItemId(itemId)).thenReturn(Collections.singletonList(itemHistoryEntity)); List<ItemHistoryEntity> histories = itemHistoryService.findHistoryResults(itemId); verifyZeroInteractions(itemEntityRepository); verify(itemHistoryRepository).findByItemId(itemId); assertThat(histories).containsExactly(itemHistoryEntity); } @Test public void shouldUseFirstItemEntityRecordIfHistoryRecordMissing() { final String itemId = "1"; ItemHistoryEntity itemHistoryEntity = new ItemHistoryEntity(); itemHistoryEntity.setCommitBy("test@test.com"); itemHistoryEntity.setCommitByFullname("Test User"); itemHistoryEntity.setCommitMessage("Some other message"); ItemEntity itemEntity = new ItemEntity("1", "master"); itemEntity.setCreatedBy("test@test.com"); List<ItemHistoryEntity> entities = new ArrayList<>(); entities.add(itemHistoryEntity); when(itemHistoryRepository.findByItemId(itemId)).thenReturn(entities); when(itemEntityRepository.findFirstMaster(itemId)).thenReturn(itemEntity); List<ItemHistoryEntity> histories = itemHistoryService.findHistoryResults(itemId); verify(itemHistoryRepository).findByItemId(itemId); verify(itemEntityRepository).findFirstMaster(itemId); assertThat(histories).hasSize(2); assertThat(histories.get(0).getCommitMessage()).isEqualTo("Some other message"); ItemHistoryEntity create = histories.get(1); assertThat(create.getCommitMessage()).isEqualTo(BEGAN_CREATION_COMMIT_MESSAGE); assertThat(create.getCommitByFullname()).isEqualTo("Test User"); } @Test public void shouldUseItemEntityCreatedByWhenHistoryCommitDoesNotMatch() { final String itemId = "1"; ItemHistoryEntity itemHistoryEntity = new ItemHistoryEntity(); itemHistoryEntity.setCommitBy("test@test.com"); itemHistoryEntity.setCommitByFullname("Test User"); itemHistoryEntity.setCommitMessage("Some other message"); ItemEntity itemEntity = new ItemEntity("1", "master"); itemEntity.setCreatedBy("item-migration@smarterbalanced.com"); List<ItemHistoryEntity> entities = new ArrayList<>(); entities.add(itemHistoryEntity); when(itemHistoryRepository.findByItemId(itemId)).thenReturn(entities); when(itemEntityRepository.findFirstMaster(itemId)).thenReturn(itemEntity); List<ItemHistoryEntity> histories = itemHistoryService.findHistoryResults(itemId); verify(itemHistoryRepository).findByItemId(itemId); verify(itemEntityRepository).findFirstMaster(itemId); assertThat(histories).hasSize(2); ItemHistoryEntity historyRecord = histories.get(0); assertThat(historyRecord.getCommitMessage()).isEqualTo("Some other message"); assertThat(historyRecord.getCommitBy()).isEqualTo("test@test.com"); assertThat(historyRecord.getCommitByFullname()).isEqualTo("Test User"); assertThat(historyRecord.getCommitMessage()).isEqualTo("Some other message"); ItemHistoryEntity create = histories.get(1); assertThat(create.getCommitMessage()).isEqualTo(BEGAN_CREATION_COMMIT_MESSAGE); assertThat(create.getCommitByFullname()).isEqualTo("item-migration@smarterbalanced.com"); assertThat(create.getCommitBy()).isEqualTo("item-migration@smarterbalanced.com"); } }
UTF-8
Java
6,139
java
DefaultItemHistoryServiceTest.java
Java
[ { "context": "yEntity();\n itemHistoryEntity.setCommitBy(\"test@test.com\");\n itemHistoryEntity.setCommitByFullname(", "end": 3295, "score": 0.9999204874038696, "start": 3282, "tag": "EMAIL", "value": "test@test.com" }, { "context": ");\n itemHistoryEntity.setCommitByFullname(\"Test User\");\n itemHistoryEntity.setCommitMessage(\"So", "end": 3355, "score": 0.6242247223854065, "start": 3346, "tag": "NAME", "value": "Test User" }, { "context": "(\"1\", \"master\");\n itemEntity.setCreatedBy(\"test@test.com\");\n\n List<ItemHistoryEntity> entities = ne", "end": 3535, "score": 0.9999195337295532, "start": 3522, "tag": "EMAIL", "value": "test@test.com" }, { "context": "sertThat(create.getCommitByFullname()).isEqualTo(\"Test User\");\n }\n\n @Test\n public void shouldUseItem", "end": 4365, "score": 0.609074056148529, "start": 4356, "tag": "NAME", "value": "Test User" }, { "context": "yEntity();\n itemHistoryEntity.setCommitBy(\"test@test.com\");\n itemHistoryEntity.setCommitByFullname(", "end": 4622, "score": 0.9999265670776367, "start": 4609, "tag": "EMAIL", "value": "test@test.com" }, { "context": ");\n itemHistoryEntity.setCommitByFullname(\"Test User\");\n itemHistoryEntity.setCommitMessage(\"So", "end": 4682, "score": 0.9751056432723999, "start": 4673, "tag": "NAME", "value": "Test User" }, { "context": "(\"1\", \"master\");\n itemEntity.setCreatedBy(\"item-migration@smarterbalanced.com\");\n\n List<ItemHistoryEntity> entities = ne", "end": 4883, "score": 0.9999234080314636, "start": 4849, "tag": "EMAIL", "value": "item-migration@smarterbalanced.com" }, { "context": "ssertThat(historyRecord.getCommitBy()).isEqualTo(\"test@test.com\");\n assertThat(historyRecord.getCommitByFu", "end": 5631, "score": 0.9999249577522278, "start": 5618, "tag": "EMAIL", "value": "test@test.com" }, { "context": "t(historyRecord.getCommitByFullname()).isEqualTo(\"Test User\");\n assertThat(historyRecord.getCommitMess", "end": 5711, "score": 0.9798377752304077, "start": 5702, "tag": "NAME", "value": "Test User" }, { "context": "sertThat(create.getCommitByFullname()).isEqualTo(\"item-migration@smarterbalanced.com\");\n assertThat(create.getCommitBy()).isEqu", "end": 6038, "score": 0.9999245405197144, "start": 6004, "tag": "EMAIL", "value": "item-migration@smarterbalanced.com" }, { "context": " assertThat(create.getCommitBy()).isEqualTo(\"item-migration@smarterbalanced.com\");\n }\n}", "end": 6128, "score": 0.9999237060546875, "start": 6094, "tag": "EMAIL", "value": "item-migration@smarterbalanced.com" } ]
null
[]
package org.opentestsystem.ap.item.history.service; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.opentestsystem.ap.common.datastore.entity.ItemEntity; import org.opentestsystem.ap.common.datastore.entity.ItemHistoryEntity; import org.opentestsystem.ap.common.datastore.repository.ItemEntityRepository; import org.opentestsystem.ap.common.datastore.repository.ItemHistoryRepository; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import static org.opentestsystem.ap.item.history.service.DefaultItemHistoryService.BEGAN_CREATION_COMMIT_MESSAGE; @RunWith(MockitoJUnitRunner.class) public class DefaultItemHistoryServiceTest { @Mock private ItemHistoryRepository itemHistoryRepository; @Mock private ItemEntityRepository itemEntityRepository; private DefaultItemHistoryService itemHistoryService; @Before public void setUp() { itemHistoryService = new DefaultItemHistoryService(itemHistoryRepository, itemEntityRepository); } @Test public void shouldReturnHistoryRecordById() { UUID id = UUID.randomUUID(); ItemHistoryEntity itemHistoryEntity = new ItemHistoryEntity(); when(itemHistoryRepository.findOne(id)).thenReturn(itemHistoryEntity); Optional<ItemHistoryEntity> persistedEntity = itemHistoryService.findItemHistoryById(id); verify(itemHistoryRepository).findOne(id); assertThat(persistedEntity).isPresent(); assertThat(persistedEntity.get()).isEqualTo(itemHistoryEntity); } @Test public void shouldReturnPreviewableHistory() { final String itemId = "1"; ItemHistoryEntity itemHistoryEntity = new ItemHistoryEntity(); when(itemHistoryRepository.findSupportsPreview("1")).thenReturn(Collections.singletonList(itemHistoryEntity)); List<ItemHistoryEntity> histories = itemHistoryService.findSupportsPreview(itemId); verify(itemHistoryRepository).findSupportsPreview(itemId); assertThat(histories).containsExactly(itemHistoryEntity); } @Test public void shouldFindHistoryRecords() { final String itemId = "1"; ItemHistoryEntity itemHistoryEntity = new ItemHistoryEntity(); itemHistoryEntity.setCommitMessage(BEGAN_CREATION_COMMIT_MESSAGE); when(itemHistoryRepository.findByItemId(itemId)).thenReturn(Collections.singletonList(itemHistoryEntity)); List<ItemHistoryEntity> histories = itemHistoryService.findHistoryResults(itemId); verifyZeroInteractions(itemEntityRepository); verify(itemHistoryRepository).findByItemId(itemId); assertThat(histories).containsExactly(itemHistoryEntity); } @Test public void shouldUseFirstItemEntityRecordIfHistoryRecordMissing() { final String itemId = "1"; ItemHistoryEntity itemHistoryEntity = new ItemHistoryEntity(); itemHistoryEntity.setCommitBy("<EMAIL>"); itemHistoryEntity.setCommitByFullname("<NAME>"); itemHistoryEntity.setCommitMessage("Some other message"); ItemEntity itemEntity = new ItemEntity("1", "master"); itemEntity.setCreatedBy("<EMAIL>"); List<ItemHistoryEntity> entities = new ArrayList<>(); entities.add(itemHistoryEntity); when(itemHistoryRepository.findByItemId(itemId)).thenReturn(entities); when(itemEntityRepository.findFirstMaster(itemId)).thenReturn(itemEntity); List<ItemHistoryEntity> histories = itemHistoryService.findHistoryResults(itemId); verify(itemHistoryRepository).findByItemId(itemId); verify(itemEntityRepository).findFirstMaster(itemId); assertThat(histories).hasSize(2); assertThat(histories.get(0).getCommitMessage()).isEqualTo("Some other message"); ItemHistoryEntity create = histories.get(1); assertThat(create.getCommitMessage()).isEqualTo(BEGAN_CREATION_COMMIT_MESSAGE); assertThat(create.getCommitByFullname()).isEqualTo("<NAME>"); } @Test public void shouldUseItemEntityCreatedByWhenHistoryCommitDoesNotMatch() { final String itemId = "1"; ItemHistoryEntity itemHistoryEntity = new ItemHistoryEntity(); itemHistoryEntity.setCommitBy("<EMAIL>"); itemHistoryEntity.setCommitByFullname("<NAME>"); itemHistoryEntity.setCommitMessage("Some other message"); ItemEntity itemEntity = new ItemEntity("1", "master"); itemEntity.setCreatedBy("<EMAIL>"); List<ItemHistoryEntity> entities = new ArrayList<>(); entities.add(itemHistoryEntity); when(itemHistoryRepository.findByItemId(itemId)).thenReturn(entities); when(itemEntityRepository.findFirstMaster(itemId)).thenReturn(itemEntity); List<ItemHistoryEntity> histories = itemHistoryService.findHistoryResults(itemId); verify(itemHistoryRepository).findByItemId(itemId); verify(itemEntityRepository).findFirstMaster(itemId); assertThat(histories).hasSize(2); ItemHistoryEntity historyRecord = histories.get(0); assertThat(historyRecord.getCommitMessage()).isEqualTo("Some other message"); assertThat(historyRecord.getCommitBy()).isEqualTo("<EMAIL>"); assertThat(historyRecord.getCommitByFullname()).isEqualTo("<NAME>"); assertThat(historyRecord.getCommitMessage()).isEqualTo("Some other message"); ItemHistoryEntity create = histories.get(1); assertThat(create.getCommitMessage()).isEqualTo(BEGAN_CREATION_COMMIT_MESSAGE); assertThat(create.getCommitByFullname()).isEqualTo("<EMAIL>"); assertThat(create.getCommitBy()).isEqualTo("<EMAIL>"); } }
6,022
0.750774
0.748656
152
39.394737
33.654232
118
false
false
0
0
0
0
0
0
0.598684
false
false
7
c54ec0c050f4e48d2c8fc4d9fef8b55d027fdfba
22,033,182,241,628
8e12e4ed9c3da26b05cab92b1bc3e4cae65e0c1d
/spring-boot-example-dubbo/dubbo-common/src/main/java/org/example/dubbo/config/ZipKinConfig.java
2cd2349b5c973be5f05d9f7c31c3ed3b5b79d6a1
[]
no_license
jjch99/spring-boot-examples
https://github.com/jjch99/spring-boot-examples
d216fa6e70b8c996b470f32dc97de355d01750b9
ce12acf000d896aaee0a6913ce77a62eef3bdee6
refs/heads/master
"2022-11-17T23:39:09.962000"
"2021-12-29T06:03:50"
"2021-12-29T06:03:50"
146,997,039
5
2
null
false
"2022-11-16T02:54:52"
"2018-09-01T12:37:20"
"2021-12-29T06:03:56"
"2022-11-16T02:54:48"
1,157
6
2
7
Java
false
false
package org.example.dubbo.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import brave.Tracing; import brave.http.HttpTracing; import zipkin2.Span; import zipkin2.codec.Encoding; import zipkin2.reporter.AsyncReporter; import zipkin2.reporter.Reporter; import zipkin2.reporter.Sender; import zipkin2.reporter.kafka11.KafkaSender; import zipkin2.reporter.okhttp3.OkHttpSender; @Configuration public class ZipKinConfig { @Value("${spring.application.name}") private String localServiceName; @Value("${zipkin.tracing.endpoint}") private String zipkinEndPoint; @Autowired(required = false) private ZipKinKafkaProperties kafkaProperties; @Autowired private Sender sender; @Bean @ConditionalOnClass(KafkaSender.class) @ConditionalOnBean(ZipKinKafkaProperties.class) public KafkaSender kafkaSender() { KafkaSender.Builder builder = KafkaSender.newBuilder() .bootstrapServers(kafkaProperties.getBootstrapServers()) .topic(kafkaProperties.getTopic()) .encoding(Encoding.JSON); if (kafkaProperties.getMessageMaxBytes() != null){ builder.messageMaxBytes(kafkaProperties.getMessageMaxBytes()); } if (kafkaProperties.getOverrides() != null) { builder.overrides(kafkaProperties.getOverrides()); } KafkaSender sender = builder.build(); return sender; } @Bean @ConditionalOnMissingBean(KafkaSender.class) public Sender okHttpSender() { Sender sender = OkHttpSender .newBuilder() .endpoint(zipkinEndPoint) .encoding(Encoding.JSON) .build(); return sender; } @Bean public Reporter<Span> reporter() { return AsyncReporter.builder(sender).build(); } @Bean public Tracing tracing() { return Tracing.newBuilder() .localServiceName(localServiceName) .spanReporter(reporter()) .build(); } @Bean public HttpTracing httpTracing() { HttpTracing httpTracing = HttpTracing.create(tracing()); return httpTracing; } }
UTF-8
Java
2,621
java
ZipKinConfig.java
Java
[]
null
[]
package org.example.dubbo.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import brave.Tracing; import brave.http.HttpTracing; import zipkin2.Span; import zipkin2.codec.Encoding; import zipkin2.reporter.AsyncReporter; import zipkin2.reporter.Reporter; import zipkin2.reporter.Sender; import zipkin2.reporter.kafka11.KafkaSender; import zipkin2.reporter.okhttp3.OkHttpSender; @Configuration public class ZipKinConfig { @Value("${spring.application.name}") private String localServiceName; @Value("${zipkin.tracing.endpoint}") private String zipkinEndPoint; @Autowired(required = false) private ZipKinKafkaProperties kafkaProperties; @Autowired private Sender sender; @Bean @ConditionalOnClass(KafkaSender.class) @ConditionalOnBean(ZipKinKafkaProperties.class) public KafkaSender kafkaSender() { KafkaSender.Builder builder = KafkaSender.newBuilder() .bootstrapServers(kafkaProperties.getBootstrapServers()) .topic(kafkaProperties.getTopic()) .encoding(Encoding.JSON); if (kafkaProperties.getMessageMaxBytes() != null){ builder.messageMaxBytes(kafkaProperties.getMessageMaxBytes()); } if (kafkaProperties.getOverrides() != null) { builder.overrides(kafkaProperties.getOverrides()); } KafkaSender sender = builder.build(); return sender; } @Bean @ConditionalOnMissingBean(KafkaSender.class) public Sender okHttpSender() { Sender sender = OkHttpSender .newBuilder() .endpoint(zipkinEndPoint) .encoding(Encoding.JSON) .build(); return sender; } @Bean public Reporter<Span> reporter() { return AsyncReporter.builder(sender).build(); } @Bean public Tracing tracing() { return Tracing.newBuilder() .localServiceName(localServiceName) .spanReporter(reporter()) .build(); } @Bean public HttpTracing httpTracing() { HttpTracing httpTracing = HttpTracing.create(tracing()); return httpTracing; } }
2,621
0.696681
0.692865
86
29.476744
22.55728
81
false
false
0
0
0
0
0
0
0.372093
false
false
7
bf8163cdeacc68ca9833a491ef94200865010fad
12,060,268,180,026
74a394b86b5210dc0537b47023a194cf10003d22
/src/main/java/com/muxi/wxchat/services/logicservices/createMenu/MenuFunctionImpl/MenuFunctionImpl.java
2584e545d0dd0437c22fec9581c0ba22ea5f4429
[]
no_license
Rookie259/WXChatOnlin
https://github.com/Rookie259/WXChatOnlin
b16d7b7e570061261de6a08a93b0937553af5d87
d9fecf8e0c117c6cefc2430fc04d9847f1442870
refs/heads/master
"2020-03-24T16:02:30.752000"
"2018-08-15T13:28:04"
"2018-08-15T13:28:04"
142,810,440
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.muxi.wxchat.services.logicservices.createMenu.MenuFunctionImpl; /* *------------------------------. *@ClassName : MenuFunctionImpl *@创建人 : 沐惜 *@创建时间 : 2018/7/30 2:00 *@描述 : TODO *@Version : 1.0 *------------------------------ */ import com.muxi.wxchat.function.menu.CreateMenu; import com.muxi.wxchat.function.menu.MenuManager; import com.muxi.wxchat.pojo.AccessToken; import com.muxi.wxchat.services.logicservices.createMenu.MenuFunction; import com.muxi.wxchat.util.LoggerUtil; import org.springframework.stereotype.Service; @Service public class MenuFunctionImpl implements MenuFunction { @Override public void createMenu(AccessToken accessToken) { if (null != accessToken) { MenuManager menuManager = new MenuManager(); CreateMenu createMenu = new CreateMenu(); int result = createMenu.createMenu(menuManager.getMenu(), accessToken.getToken()); if (0 == result) LoggerUtil.setLogger("菜单创建成功"); else { LoggerUtil.setLogger("菜单创建失败"); } } } }
UTF-8
Java
1,148
java
MenuFunctionImpl.java
Java
[ { "context": "--------.\n *@ClassName : MenuFunctionImpl\n *@创建人 : 沐惜\n *@创建时间 : 2018/7/30 2:00\n *@描述 : TODO\n *@Version ", "end": 158, "score": 0.9360147714614868, "start": 156, "tag": "NAME", "value": "沐惜" } ]
null
[]
package com.muxi.wxchat.services.logicservices.createMenu.MenuFunctionImpl; /* *------------------------------. *@ClassName : MenuFunctionImpl *@创建人 : 沐惜 *@创建时间 : 2018/7/30 2:00 *@描述 : TODO *@Version : 1.0 *------------------------------ */ import com.muxi.wxchat.function.menu.CreateMenu; import com.muxi.wxchat.function.menu.MenuManager; import com.muxi.wxchat.pojo.AccessToken; import com.muxi.wxchat.services.logicservices.createMenu.MenuFunction; import com.muxi.wxchat.util.LoggerUtil; import org.springframework.stereotype.Service; @Service public class MenuFunctionImpl implements MenuFunction { @Override public void createMenu(AccessToken accessToken) { if (null != accessToken) { MenuManager menuManager = new MenuManager(); CreateMenu createMenu = new CreateMenu(); int result = createMenu.createMenu(menuManager.getMenu(), accessToken.getToken()); if (0 == result) LoggerUtil.setLogger("菜单创建成功"); else { LoggerUtil.setLogger("菜单创建失败"); } } } }
1,148
0.635209
0.623412
37
28.783783
24.274483
94
false
false
0
0
0
0
0
0
0.351351
false
false
7
4d1aa9ec45bdc74390814326e4655eb38e5ae5bd
19,000,935,328,373
b0ce9dec49235b402e4d98b6843d345de682711a
/src/main/java/hyperskill/cancurrency/pizza/Tomatoes.java
19b3405da7899095efb4b413c5f89c1d4ac133a0
[]
no_license
OlegAryukov/algoFW
https://github.com/OlegAryukov/algoFW
e3abb1a543907cc6fd20ef139da5af6ae3136451
94780a1aacee4cfc931d21c5af065a6f00ad34c3
refs/heads/master
"2021-07-08T17:25:30.864000"
"2020-11-30T13:14:10"
"2020-11-30T13:14:10"
215,790,890
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hyperskill.cancurrency.pizza; class Tomatoes extends Thread { @Override public void run() { for (int i = 3; i >= 1; i--) { System.out.println("slice tomatoes " + i); } } }
UTF-8
Java
221
java
Tomatoes.java
Java
[]
null
[]
package hyperskill.cancurrency.pizza; class Tomatoes extends Thread { @Override public void run() { for (int i = 3; i >= 1; i--) { System.out.println("slice tomatoes " + i); } } }
221
0.547511
0.538462
10
21.1
17.443911
54
false
false
0
0
0
0
0
0
0.4
false
false
7
51b7a7906019739c2492ce59cb0fc10dedb4521d
23,854,248,429,267
1e1cf638ea8b033eadf581ba7ab0d25b9602bb84
/dependency-package/utils/src/main/java/top/toptimus/formula/batch/CommandHelper.java
8c7cd46561be0d0bff14ca862c3133f6db9ba2fc
[]
no_license
gaoyussdut/EIOS
https://github.com/gaoyussdut/EIOS
48f521105012cfff0a2a350002af92aac2188c68
db9153d1f6b571962a3df57775f7cc45d8e6b11c
refs/heads/master
"2022-09-20T19:46:34.623000"
"2019-09-19T07:04:20"
"2019-09-19T07:04:20"
199,361,380
2
1
null
false
"2022-09-16T21:07:29"
"2019-07-29T02:08:49"
"2019-11-11T02:57:16"
"2022-09-16T21:07:27"
34,378
2
2
14
Java
false
false
package top.toptimus.formula.batch; import java.io.PrintStream; /** * 指令帮助 * <p> * <p>负责向PrintStream打印帮助信息。 * * @author gaoyu */ public interface CommandHelper { /** * 向PrintStream打印帮助 * * @param ps 打印流 */ public void printHelp(PrintStream ps); }
UTF-8
Java
329
java
CommandHelper.java
Java
[ { "context": "助\n * <p>\n * <p>负责向PrintStream打印帮助信息。\n *\n * @author gaoyu\n */\npublic interface CommandHelper {\n\n /**\n ", "end": 133, "score": 0.9995150566101074, "start": 128, "tag": "USERNAME", "value": "gaoyu" } ]
null
[]
package top.toptimus.formula.batch; import java.io.PrintStream; /** * 指令帮助 * <p> * <p>负责向PrintStream打印帮助信息。 * * @author gaoyu */ public interface CommandHelper { /** * 向PrintStream打印帮助 * * @param ps 打印流 */ public void printHelp(PrintStream ps); }
329
0.617544
0.617544
21
12.571428
13.05509
42
false
false
0
0
0
0
0
0
0.142857
false
false
7
0fc77acc469db3b722d6386e42fedb4813070d1f
3,779,571,230,625
1125dbf7c880987072fb4cddff2d7126a249e383
/app/src/main/java/com/example/cmamapplication/ChuHolder.java
db1b40ac503ecafadd8549a5e583eb6de8dfe856
[]
no_license
GSuleh/CMAM_Mobile_Application
https://github.com/GSuleh/CMAM_Mobile_Application
d4a143cbe1c20089f115da2816a499644bc1a371
5b0d5eae59f9c1a6ecd30a80c95bbf86030aa02d
refs/heads/master
"2023-02-18T00:08:02.241000"
"2021-01-22T13:18:17"
"2021-01-22T13:18:17"
304,405,261
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.cmamapplication; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class ChuHolder extends RecyclerView.ViewHolder { TextView name,code; LinearLayout parent; public ChuHolder(@NonNull View itemView) { super(itemView); this.name = (TextView) itemView.findViewById(R.id.chunameid); this.code = (TextView) itemView.findViewById(R.id.code); this.parent = (LinearLayout) itemView.findViewById(R.id.chuparent); } }
UTF-8
Java
620
java
ChuHolder.java
Java
[]
null
[]
package com.example.cmamapplication; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class ChuHolder extends RecyclerView.ViewHolder { TextView name,code; LinearLayout parent; public ChuHolder(@NonNull View itemView) { super(itemView); this.name = (TextView) itemView.findViewById(R.id.chunameid); this.code = (TextView) itemView.findViewById(R.id.code); this.parent = (LinearLayout) itemView.findViewById(R.id.chuparent); } }
620
0.743548
0.743548
22
27.181818
24.233028
75
false
false
0
0
0
0
0
0
0.590909
false
false
7
8e9457563797ffafb943d6353cadfb5938d78e1d
14,035,953,169,361
0c52eb05efae4b4324c33d2399f910eb54741142
/src/main/java/com/crud/tasks/service/MailMessageType.java
1203e0a6c7cfe7d19b45341d035c953f2e98331b
[]
no_license
PiotrOlchawa/tasks
https://github.com/PiotrOlchawa/tasks
4304f3968e77909ac93c547685ef4fe70556f238
ad9d5774c8482e01a2deae47fe7138ae710d18f9
refs/heads/master
"2021-07-05T18:08:36.216000"
"2019-03-26T11:30:45"
"2019-03-26T11:30:45"
146,167,471
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.crud.tasks.service; public enum MailMessageType { NORMAL, SCHEDULE; }
UTF-8
Java
87
java
MailMessageType.java
Java
[]
null
[]
package com.crud.tasks.service; public enum MailMessageType { NORMAL, SCHEDULE; }
87
0.747126
0.747126
5
16.4
13.410443
31
false
false
0
0
0
0
0
0
0.6
false
false
7
990b994ae3fd69785500a7a6f859093ded805f33
33,715,493,319,661
a14f8c2cfe66f5d351f41e5d12f94db820d1be72
/src/Service/BlogVisitArticle2DBService.java
47d2e1b0b7a55e0b917f92ce209ca96aa6ef5594
[ "Apache-2.0" ]
permissive
yhswjtuILMARE/Blog
https://github.com/yhswjtuILMARE/Blog
fea7572089784bc4a85b27ea9961477da70e708f
32afdf843888f02177243d73bc97ddb5ab157c1f
refs/heads/master
"2021-04-26T23:56:23.392000"
"2019-11-20T01:56:13"
"2019-11-20T01:56:13"
123,882,426
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Service; import Factory.DataAccessFactory; import ServiceImpl.DataObject2DB; import domain.blog_page; import domain.blog_visit_article; public class BlogVisitArticle2DBService { private DataObject2DB<blog_visit_article> impl = null; public BlogVisitArticle2DBService(){ impl = DataAccessFactory.getFactory("DAO.BlogVisitArticle2DB").getImpleInstance(); } public int getTotalRecord(){ return impl.getTotalRecord(); } //增加一个条目 public int insertVisitArticle(blog_visit_article visitArticle){ return impl.insertData(visitArticle); } //查询一个条目 public blog_page selectVisitArticle(int currentPage, int pageContain, int pageInFrame){ return impl.selectData(currentPage, pageContain, pageInFrame); } //删除一个条目 public int deleteVisitArticle(String visit_id){ return impl.deleteData(visit_id); } }
GB18030
Java
860
java
BlogVisitArticle2DBService.java
Java
[]
null
[]
package Service; import Factory.DataAccessFactory; import ServiceImpl.DataObject2DB; import domain.blog_page; import domain.blog_visit_article; public class BlogVisitArticle2DBService { private DataObject2DB<blog_visit_article> impl = null; public BlogVisitArticle2DBService(){ impl = DataAccessFactory.getFactory("DAO.BlogVisitArticle2DB").getImpleInstance(); } public int getTotalRecord(){ return impl.getTotalRecord(); } //增加一个条目 public int insertVisitArticle(blog_visit_article visitArticle){ return impl.insertData(visitArticle); } //查询一个条目 public blog_page selectVisitArticle(int currentPage, int pageContain, int pageInFrame){ return impl.selectData(currentPage, pageContain, pageInFrame); } //删除一个条目 public int deleteVisitArticle(String visit_id){ return impl.deleteData(visit_id); } }
860
0.788835
0.782767
30
26.466667
25.343945
88
false
false
0
0
0
0
0
0
1.366667
false
false
7
6b9a64a95a1da9d6029ef7e5312eb6df97bd5d06
25,331,717,156,346
8bbfb214e761fd199cf7d8490052d5e9e3dd9cf7
/src/leet/_355_DesignTwitter.java
a49b9fa2b9c9e3fd52d80c0b5793a2878fdace90
[]
no_license
simplenaive/LC-OJ-Java
https://github.com/simplenaive/LC-OJ-Java
86a3e0b409bf06fb224408b7111fdd2c7d1df101
76bb32cc7c17144138050b3e7380c3f8696032b2
refs/heads/master
"2018-12-31T12:35:41.609000"
"2017-02-12T05:43:49"
"2017-02-12T05:43:49"
64,721,114
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package leet; /* Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and is able to see the 10 most recent tweets in the user's news feed. Your design should support the following methods: postTweet(userId, tweetId): Compose a new tweet. getNewsFeed(userId): Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. follow(followerId, followeeId): Follower follows a followee. unfollow(followerId, followeeId): Follower unfollows a followee. Example: Twitter twitter = new Twitter(); // User 1 posts a new tweet (id = 5). twitter.postTweet(1, 5); // User 1's news feed should return a list with 1 tweet id -> [5]. twitter.getNewsFeed(1); // User 1 follows user 2. twitter.follow(1, 2); // User 2 posts a new tweet (id = 6). twitter.postTweet(2, 6); // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. // Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. twitter.getNewsFeed(1); // User 1 unfollows user 2. twitter.unfollow(1, 2); // User 1's news feed should return a list with 1 tweet id -> [5], // since user 1 is no longer following user 2. twitter.getNewsFeed(1); */ import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; public class _355_DesignTwitter { static class Twitter { class Tweet { int id; int ts; public Tweet(int id, int ts) { this.id = id; this.ts = ts; } } int time; Map<Integer, Set<Integer>> p2followers; Map<Integer, Set<Integer>> p2followings; Map<Integer, List<Tweet>> p2Tweets; /** * Initialize your data structure here. */ public Twitter() { time = 1; p2followers = new HashMap<>(); p2followings = new HashMap<>(); p2Tweets = new HashMap<>(); } /** * Compose a new tweet. */ public void postTweet(int userId, int tweetId) { List<Tweet> tweets = p2Tweets.getOrDefault(userId, new ArrayList<>()); tweets.add(new Tweet(tweetId, time++)); p2Tweets.put(userId, tweets); } /** * Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed * must be posted by users who the user followed or by the user herself. Tweets must be * ordered from most recent to least recent. */ //TODO use max heap to increase performance public List<Integer> getNewsFeed(int userId) { List<Tweet> tweets = new ArrayList<>(); if (p2Tweets.containsKey(userId)) tweets.addAll(p2Tweets.get(userId)); if (p2followings.containsKey(userId)) { for (int following : p2followings.get(userId)) if (p2Tweets.containsKey(following)) tweets.addAll(p2Tweets.get(following)); } return tweets.stream() .sorted((t1, t2) -> t2.ts - t1.ts) .limit(10) .map(t -> t.id) .collect(Collectors.toList()); } /** * Follower follows a followee. If the operation is invalid, it should be a no-op. */ public void follow(int followerId, int followeeId) { if (followerId == followeeId) return; Set<Integer> followings = p2followings.getOrDefault(followerId, new HashSet<>()); followings.add(followeeId); p2followings.put(followerId, followings); } /** * Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ public void unfollow(int followerId, int followeeId) { if (followerId == followeeId) return; Set<Integer> followings = p2followings.getOrDefault(followerId, new HashSet<>()); if (followings.contains(followeeId)) followings.remove(followeeId); } } /** * Your Twitter object will be instantiated and called as such: * Twitter obj = new Twitter(); * obj.postTweet(userId,tweetId); * List<Integer> param_2 = obj.getNewsFeed(userId); * obj.follow(followerId,followeeId); * obj.unfollow(followerId,followeeId); */ public static void main(String[] args) { Twitter twt = new Twitter(); twt.postTweet(1, 5); twt.postTweet(1, 3); twt.postTweet(1, 101); twt.postTweet(1, 13); twt.postTweet(1, 10); twt.postTweet(1, 2); twt.postTweet(1, 94); twt.postTweet(1, 505); twt.postTweet(1, 333); twt.postTweet(1, 22); twt.postTweet(1, 11); System.out.println(twt.getNewsFeed(1)); } }
UTF-8
Java
5,116
java
_355_DesignTwitter.java
Java
[]
null
[]
package leet; /* Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and is able to see the 10 most recent tweets in the user's news feed. Your design should support the following methods: postTweet(userId, tweetId): Compose a new tweet. getNewsFeed(userId): Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. follow(followerId, followeeId): Follower follows a followee. unfollow(followerId, followeeId): Follower unfollows a followee. Example: Twitter twitter = new Twitter(); // User 1 posts a new tweet (id = 5). twitter.postTweet(1, 5); // User 1's news feed should return a list with 1 tweet id -> [5]. twitter.getNewsFeed(1); // User 1 follows user 2. twitter.follow(1, 2); // User 2 posts a new tweet (id = 6). twitter.postTweet(2, 6); // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. // Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. twitter.getNewsFeed(1); // User 1 unfollows user 2. twitter.unfollow(1, 2); // User 1's news feed should return a list with 1 tweet id -> [5], // since user 1 is no longer following user 2. twitter.getNewsFeed(1); */ import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; public class _355_DesignTwitter { static class Twitter { class Tweet { int id; int ts; public Tweet(int id, int ts) { this.id = id; this.ts = ts; } } int time; Map<Integer, Set<Integer>> p2followers; Map<Integer, Set<Integer>> p2followings; Map<Integer, List<Tweet>> p2Tweets; /** * Initialize your data structure here. */ public Twitter() { time = 1; p2followers = new HashMap<>(); p2followings = new HashMap<>(); p2Tweets = new HashMap<>(); } /** * Compose a new tweet. */ public void postTweet(int userId, int tweetId) { List<Tweet> tweets = p2Tweets.getOrDefault(userId, new ArrayList<>()); tweets.add(new Tweet(tweetId, time++)); p2Tweets.put(userId, tweets); } /** * Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed * must be posted by users who the user followed or by the user herself. Tweets must be * ordered from most recent to least recent. */ //TODO use max heap to increase performance public List<Integer> getNewsFeed(int userId) { List<Tweet> tweets = new ArrayList<>(); if (p2Tweets.containsKey(userId)) tweets.addAll(p2Tweets.get(userId)); if (p2followings.containsKey(userId)) { for (int following : p2followings.get(userId)) if (p2Tweets.containsKey(following)) tweets.addAll(p2Tweets.get(following)); } return tweets.stream() .sorted((t1, t2) -> t2.ts - t1.ts) .limit(10) .map(t -> t.id) .collect(Collectors.toList()); } /** * Follower follows a followee. If the operation is invalid, it should be a no-op. */ public void follow(int followerId, int followeeId) { if (followerId == followeeId) return; Set<Integer> followings = p2followings.getOrDefault(followerId, new HashSet<>()); followings.add(followeeId); p2followings.put(followerId, followings); } /** * Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ public void unfollow(int followerId, int followeeId) { if (followerId == followeeId) return; Set<Integer> followings = p2followings.getOrDefault(followerId, new HashSet<>()); if (followings.contains(followeeId)) followings.remove(followeeId); } } /** * Your Twitter object will be instantiated and called as such: * Twitter obj = new Twitter(); * obj.postTweet(userId,tweetId); * List<Integer> param_2 = obj.getNewsFeed(userId); * obj.follow(followerId,followeeId); * obj.unfollow(followerId,followeeId); */ public static void main(String[] args) { Twitter twt = new Twitter(); twt.postTweet(1, 5); twt.postTweet(1, 3); twt.postTweet(1, 101); twt.postTweet(1, 13); twt.postTweet(1, 10); twt.postTweet(1, 2); twt.postTweet(1, 94); twt.postTweet(1, 505); twt.postTweet(1, 333); twt.postTweet(1, 22); twt.postTweet(1, 11); System.out.println(twt.getNewsFeed(1)); } }
5,116
0.600078
0.580141
152
32.651318
26.625389
100
false
false
0
0
0
0
0
0
0.657895
false
false
7
28b9ed72ae4afa46e797ad29103fa8a2a474f4b1
30,648,886,668,288
7a2acc52f935adfe80c2ee462df3b2f1dbe12619
/src/edt/Frame/New_Intervenant.java
17d3b0ca8d9df6ec6f5ebd1ab58038b5320dca07
[]
no_license
Mariefrancois/EDT
https://github.com/Mariefrancois/EDT
ae8886ca7322a702d719c93218adbcbc30760669
6217b8026a881ef60d272ce8fb88cabe97a217b4
refs/heads/master
"2020-05-18T07:35:34.013000"
"2012-05-03T21:38:43"
"2012-05-03T21:38:43"
3,640,303
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. */ /* * New_Intervenant.java * * Created on 6 avr. 2012, 00:10:18 */ package edt.Frame; import edt.Classe.Creneau_Intervenant; import edt.Classe.Intervenant; import edt.mysql.BD_MySQL; import edt.view.Donner; import java.awt.Toolkit; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.table.DefaultTableModel; /** * * @author Marie */ public class New_Intervenant extends javax.swing.JDialog { private Donner donner; private int id; private Intervenant intervenant; private Creneau_Intervenant creneauInt; private ArrayList<Creneau_Intervenant> list_creneauInter; /** Creates new form New_Intervenant */ public New_Intervenant(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } public New_Intervenant(java.awt.Frame parent,String titre, boolean modal,Donner donner, String etat, int id) { super(parent,titre, modal); initComponents(); init(etat,id); this.donner = donner; this.setLocation( Toolkit.getDefaultToolkit().getScreenSize().width/2-this.getWidth()/2,Toolkit.getDefaultToolkit().getScreenSize().height/2-this.getHeight()/2); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); recurrence = new javax.swing.JCheckBox(); jLabel8 = new javax.swing.JLabel(); nom = new javax.swing.JTextField(); prenom = new javax.swing.JTextField(); date = new javax.swing.JTextField(); periode = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); h_debut = new javax.swing.JComboBox(); h_fin = new javax.swing.JComboBox(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); m_debut = new javax.swing.JComboBox(); m_fin = new javax.swing.JComboBox(); jScrollPane2 = new javax.swing.JScrollPane(); jTable2 = new javax.swing.JTable(); ajout_dispo = new javax.swing.JButton(); valider = new javax.swing.JButton(); annuler = new javax.swing.JButton(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); email = new javax.swing.JTextField(); telephone = new javax.swing.JTextField(); jScrollPane1.setName("jScrollPane1"); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jTable1.setName("jTable1"); jScrollPane1.setViewportView(jTable1); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setResizable(false); jLabel1.setText("Nom"); jLabel1.setName("jLabel1"); jLabel2.setText("Prénom"); jLabel2.setName("jLabel2"); jLabel3.setText("Disponibilité"); jLabel3.setName("jLabel3"); jLabel4.setText("Date"); jLabel4.setName("jLabel4"); jLabel5.setText("Heure début"); jLabel5.setName("jLabel5"); jLabel6.setText("Heure fin"); jLabel6.setName("jLabel6"); jLabel7.setText("Récurrence"); jLabel7.setName("jLabel7"); recurrence.setText("récurrence"); recurrence.setName("recurrence"); jLabel8.setText("Période de "); jLabel8.setName("jLabel8"); nom.setName("nom"); prenom.setName("prenom"); date.setText("jj/mm/aaaa"); date.setName("date"); periode.setName("periode"); jLabel9.setText("semaine"); jLabel9.setName("jLabel9"); h_debut.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" })); h_debut.setName("h_debut"); h_debut.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { h_debutActionPerformed(evt); } }); h_fin.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" })); h_fin.setName("h_fin"); jLabel10.setText("h"); jLabel10.setName("jLabel10"); jLabel11.setText("h"); jLabel11.setName("jLabel11"); m_debut.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "0", "15", "30", "45" })); m_debut.setName("m_debut"); m_fin.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "0", "15", "30", "45" })); m_fin.setName("m_fin"); jScrollPane2.setName("jScrollPane2"); jTable2.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null} }, new String [] { "Date", "Heure Début", "Heure Fin" } ) { boolean[] canEdit = new boolean [] { true, false, true }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jTable2.setName("jTable2"); jScrollPane2.setViewportView(jTable2); ajout_dispo.setText("Ajouter une disponibilité"); ajout_dispo.setName("ajout_dispo"); ajout_dispo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ajout_dispoActionPerformed(evt); } }); valider.setText("Valider"); valider.setName("valider"); valider.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { validerActionPerformed(evt); } }); annuler.setText("Annuler"); annuler.setName("annuler"); annuler.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { annulerActionPerformed(evt); } }); jLabel12.setText("Email"); jLabel12.setName("jLabel12"); jLabel13.setText("Téléphone"); jLabel13.setName("jLabel13"); email.setName("email"); telephone.setName("telephone"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(43, 43, 43) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(h_debut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(m_debut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(h_fin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(m_fin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(date, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(jLabel13) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(telephone) .addGap(78, 78, 78)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel12)) .addGap(30, 30, 30)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel2) .addGap(18, 18, 18))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(email, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(prenom, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE) .addComponent(nom, javax.swing.GroupLayout.Alignment.LEADING))))))) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel7)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3)) .addGroup(layout.createSequentialGroup() .addGap(40, 40, 40) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel8) .addComponent(recurrence)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(periode, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel9)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(ajout_dispo))) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(annuler) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(valider) .addGap(27, 27, 27)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(22, 22, 22) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(nom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(prenom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(3, 3, 3) .addComponent(email, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel12))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel13) .addComponent(telephone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(date, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(h_debut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10) .addComponent(m_debut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(h_fin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(m_fin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel11)) .addGap(18, 18, 18) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(recurrence) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(periode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(ajout_dispo) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(annuler) .addComponent(valider)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void refresh(){ this.prenom.setText(""); this.nom.setText(""); this.email.setText(""); this.telephone.setText(""); this.periode.setText("jj/mm/aaaa"); this.date.setText(""); this.recurrence.setSelected(false); this.donner.desactive_sup_modif(); this.intervenant = null; this.donner.refreshIntervenant(); } public ArrayList<String> list_Date(ArrayList<Creneau_Intervenant> liste_CI){ ArrayList<String> list_Date = new ArrayList(); for (Creneau_Intervenant l : liste_CI) { list_Date.add(afficherDate(l.getTsDebut())); } return list_Date; } public ArrayList<String> list_Heure_Debut(ArrayList<Creneau_Intervenant> liste_CI){ ArrayList<String> list_Heure_Debut = new ArrayList(); for (Creneau_Intervenant l : liste_CI) { list_Heure_Debut.add(afficherHeure(l.getTsDebut())); } return list_Heure_Debut; } public ArrayList<String> list_Heure_Fin(ArrayList<Creneau_Intervenant> liste_CI){ ArrayList<String> list_Heure_Fin = new ArrayList(); for (Creneau_Intervenant l : liste_CI) { list_Heure_Fin.add(afficherHeure(l.getTsFin())); } return list_Heure_Fin; } private void refreshRecurence(){ this.date.setText("jj/mm/aaaa"); this.periode.setText(""); this.recurrence.setSelected(false); // this.donner.desactive_sup_modif(); // this.donner.refreshIntervenant(); // this.jTable1.doLayout(); DefaultTableModel modell = new DefaultTableModel( new Object [4][5] , new String [] {}); this.jTable2.setModel(modell); try { this.list_creneauInter = Creneau_Intervenant.liste_Creneau_Intervenant(this.intervenant.getId()); } catch (SQLException ex) { Logger.getLogger(Donner.class.getName()).log(Level.SEVERE, null, ex); } ArrayList<String> listeDate = list_Date(this.list_creneauInter); modell.addColumn("Date", listeDate.toArray()); System.out.println(listeDate); ArrayList<String> listeheuredebut = list_Heure_Debut(this.list_creneauInter); modell.addColumn("Heure Début", listeheuredebut.toArray()); System.out.println(listeheuredebut); ArrayList<String> listheureFin = list_Heure_Fin(this.list_creneauInter); modell.addColumn("Heure Fin", listheureFin.toArray()); System.out.println(listheureFin); } private void creer(){ this.intervenant.setNom(this.nom.getText()); this.intervenant.setPrenom(this.prenom.getText()); this.intervenant.setTelephone(this.telephone.getText()); this.intervenant.setEmail(this.email.getText()); } public String afficherHeure(Timestamp tim){ String date = String.valueOf(tim); int h = Integer.parseInt(date.substring(11,13)); int min = Integer.parseInt(date.substring(14, 16)); return h+" h "+min; } public String afficherDate(Timestamp tim){ String date = String.valueOf(tim); int an = Integer.parseInt(date.substring(0, 4)); int mois = Integer.parseInt(date.substring(5, 7)); int jour = Integer.parseInt(date.substring(8, 10)); return jour+"/"+mois+"/"+an; } private Timestamp afficherTimestamp(String date,int heure, int minute, int recu){ int an = Integer.parseInt(date.substring(6, 10)); int mois = Integer.parseInt(date.substring(3, 5)); int jour = Integer.parseInt(date.substring(0, 2)); Timestamp ts = new Timestamp(an-1900,mois-1,jour+recu,heure,minute,0,0); return ts; } private void ajout_dispoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ajout_dispoActionPerformed // TODO add your handling code here: int n; switch(etat){ case Intervenant: this.intervenant = new Intervenant(this.nom.getText(),this.prenom.getText(),this.email.getText(),this.telephone.getText(),true,true); this.intervenant.save(); n = 1; if(this.recurrence.isSelected()){ n = Integer.parseInt(this.periode.getText()); } for(int i = 0;i< n; i++){ this.creneauInt = new Creneau_Intervenant( this.intervenant.getId(), afficherTimestamp(this.date.getText(), Integer.parseInt(this.h_debut.getSelectedItem().toString()), Integer.parseInt(this.m_debut.getSelectedItem().toString()), i*7), afficherTimestamp(this.date.getText(), Integer.parseInt(this.h_fin.getSelectedItem().toString()), Integer.parseInt(this.m_fin.getSelectedItem().toString()), i*7)); this.creneauInt.save(); } refreshRecurence(); this.etat = Etat.Intervenant1; break; case Intervenant1: n = 1; if(this.recurrence.isSelected()){ n = Integer.parseInt(this.periode.getText()); } for(int i = 0;i< n; i++){ this.creneauInt = new Creneau_Intervenant( this.intervenant.getId(), afficherTimestamp(this.date.getText(), Integer.parseInt(this.h_debut.getSelectedItem().toString()), Integer.parseInt(this.m_debut.getSelectedItem().toString()), i*7), afficherTimestamp(this.date.getText(), Integer.parseInt(this.h_fin.getSelectedItem().toString()), Integer.parseInt(this.m_fin.getSelectedItem().toString()), i*7)); this.creneauInt.save(); } refreshRecurence(); this.etat = Etat.Intervenant1; break; } }//GEN-LAST:event_ajout_dispoActionPerformed private void annulerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_annulerActionPerformed // TODO add your handling code here: switch(etat){ case Intervenant: this.dispose(); this.donner.desactive_sup_modif(); break; case Intervenant1: this.dispose(); this.donner.desactive_sup_modif(); break; } }//GEN-LAST:event_annulerActionPerformed private void validerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_validerActionPerformed // TODO add your handling code here: switch(etat){ case Intervenant: this.intervenant = new Intervenant(this.nom.getText(),this.prenom.getText(),this.email.getText(),this.telephone.getText(),true,true); this.intervenant.save(); refresh(); etat = Etat.Intervenant; break; case Intervenant1: creer(); this.intervenant.save(); refresh(); this.dispose(); break; } }//GEN-LAST:event_validerActionPerformed private void h_debutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_h_debutActionPerformed // TODO add your handling code here: }//GEN-LAST:event_h_debutActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(New_Intervenant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(New_Intervenant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(New_Intervenant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(New_Intervenant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { New_Intervenant dialog = new New_Intervenant(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton ajout_dispo; private javax.swing.JButton annuler; private javax.swing.JTextField date; private javax.swing.JTextField email; private javax.swing.JComboBox h_debut; private javax.swing.JComboBox h_fin; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTable1; private javax.swing.JTable jTable2; private javax.swing.JComboBox m_debut; private javax.swing.JComboBox m_fin; private javax.swing.JTextField nom; private javax.swing.JTextField periode; private javax.swing.JTextField prenom; private javax.swing.JCheckBox recurrence; private javax.swing.JTextField telephone; private javax.swing.JButton valider; // End of variables declaration//GEN-END:variables private enum Etat{ Intervenant, Intervenant1 } private Etat etat; public void init(String n,int id){ if(n.equals("Intervenant")) etat = Etat.Intervenant; else if (n.equals("Intervenant1")){ etat = Etat.Intervenant1; try { this.intervenant = new Intervenant(id); } catch (SQLException ex) { Logger.getLogger(New_Etudiant.class.getName()).log(Level.SEVERE, null, ex); } this.nom.setText(intervenant.getNom()); this.prenom.setText(intervenant.getPrenom()); this.email.setText(intervenant.getEmail()); this.telephone.setText(intervenant.getTelephone()); refreshRecurence(); } } }
UTF-8
Java
32,332
java
New_Intervenant.java
Java
[ { "context": "ng.table.DefaultTableModel;\r\n\r\n/**\r\n *\r\n * @author Marie\r\n */\r\npublic class New_Intervenant extends javax.", "end": 581, "score": 0.9996179342269897, "start": 576, "tag": "NAME", "value": "Marie" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * New_Intervenant.java * * Created on 6 avr. 2012, 00:10:18 */ package edt.Frame; import edt.Classe.Creneau_Intervenant; import edt.Classe.Intervenant; import edt.mysql.BD_MySQL; import edt.view.Donner; import java.awt.Toolkit; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.table.DefaultTableModel; /** * * @author Marie */ public class New_Intervenant extends javax.swing.JDialog { private Donner donner; private int id; private Intervenant intervenant; private Creneau_Intervenant creneauInt; private ArrayList<Creneau_Intervenant> list_creneauInter; /** Creates new form New_Intervenant */ public New_Intervenant(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } public New_Intervenant(java.awt.Frame parent,String titre, boolean modal,Donner donner, String etat, int id) { super(parent,titre, modal); initComponents(); init(etat,id); this.donner = donner; this.setLocation( Toolkit.getDefaultToolkit().getScreenSize().width/2-this.getWidth()/2,Toolkit.getDefaultToolkit().getScreenSize().height/2-this.getHeight()/2); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); recurrence = new javax.swing.JCheckBox(); jLabel8 = new javax.swing.JLabel(); nom = new javax.swing.JTextField(); prenom = new javax.swing.JTextField(); date = new javax.swing.JTextField(); periode = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); h_debut = new javax.swing.JComboBox(); h_fin = new javax.swing.JComboBox(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); m_debut = new javax.swing.JComboBox(); m_fin = new javax.swing.JComboBox(); jScrollPane2 = new javax.swing.JScrollPane(); jTable2 = new javax.swing.JTable(); ajout_dispo = new javax.swing.JButton(); valider = new javax.swing.JButton(); annuler = new javax.swing.JButton(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); email = new javax.swing.JTextField(); telephone = new javax.swing.JTextField(); jScrollPane1.setName("jScrollPane1"); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jTable1.setName("jTable1"); jScrollPane1.setViewportView(jTable1); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setResizable(false); jLabel1.setText("Nom"); jLabel1.setName("jLabel1"); jLabel2.setText("Prénom"); jLabel2.setName("jLabel2"); jLabel3.setText("Disponibilité"); jLabel3.setName("jLabel3"); jLabel4.setText("Date"); jLabel4.setName("jLabel4"); jLabel5.setText("Heure début"); jLabel5.setName("jLabel5"); jLabel6.setText("Heure fin"); jLabel6.setName("jLabel6"); jLabel7.setText("Récurrence"); jLabel7.setName("jLabel7"); recurrence.setText("récurrence"); recurrence.setName("recurrence"); jLabel8.setText("Période de "); jLabel8.setName("jLabel8"); nom.setName("nom"); prenom.setName("prenom"); date.setText("jj/mm/aaaa"); date.setName("date"); periode.setName("periode"); jLabel9.setText("semaine"); jLabel9.setName("jLabel9"); h_debut.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" })); h_debut.setName("h_debut"); h_debut.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { h_debutActionPerformed(evt); } }); h_fin.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" })); h_fin.setName("h_fin"); jLabel10.setText("h"); jLabel10.setName("jLabel10"); jLabel11.setText("h"); jLabel11.setName("jLabel11"); m_debut.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "0", "15", "30", "45" })); m_debut.setName("m_debut"); m_fin.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "0", "15", "30", "45" })); m_fin.setName("m_fin"); jScrollPane2.setName("jScrollPane2"); jTable2.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null} }, new String [] { "Date", "Heure Début", "Heure Fin" } ) { boolean[] canEdit = new boolean [] { true, false, true }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jTable2.setName("jTable2"); jScrollPane2.setViewportView(jTable2); ajout_dispo.setText("Ajouter une disponibilité"); ajout_dispo.setName("ajout_dispo"); ajout_dispo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ajout_dispoActionPerformed(evt); } }); valider.setText("Valider"); valider.setName("valider"); valider.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { validerActionPerformed(evt); } }); annuler.setText("Annuler"); annuler.setName("annuler"); annuler.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { annulerActionPerformed(evt); } }); jLabel12.setText("Email"); jLabel12.setName("jLabel12"); jLabel13.setText("Téléphone"); jLabel13.setName("jLabel13"); email.setName("email"); telephone.setName("telephone"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(43, 43, 43) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(h_debut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(m_debut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(h_fin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(m_fin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(date, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(jLabel13) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(telephone) .addGap(78, 78, 78)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel12)) .addGap(30, 30, 30)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel2) .addGap(18, 18, 18))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(email, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(prenom, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE) .addComponent(nom, javax.swing.GroupLayout.Alignment.LEADING))))))) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel7)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3)) .addGroup(layout.createSequentialGroup() .addGap(40, 40, 40) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel8) .addComponent(recurrence)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(periode, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel9)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(ajout_dispo))) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(annuler) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(valider) .addGap(27, 27, 27)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(22, 22, 22) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(nom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(prenom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(3, 3, 3) .addComponent(email, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel12))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel13) .addComponent(telephone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(date, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(h_debut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10) .addComponent(m_debut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(h_fin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(m_fin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel11)) .addGap(18, 18, 18) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(recurrence) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(periode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(ajout_dispo) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(annuler) .addComponent(valider)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void refresh(){ this.prenom.setText(""); this.nom.setText(""); this.email.setText(""); this.telephone.setText(""); this.periode.setText("jj/mm/aaaa"); this.date.setText(""); this.recurrence.setSelected(false); this.donner.desactive_sup_modif(); this.intervenant = null; this.donner.refreshIntervenant(); } public ArrayList<String> list_Date(ArrayList<Creneau_Intervenant> liste_CI){ ArrayList<String> list_Date = new ArrayList(); for (Creneau_Intervenant l : liste_CI) { list_Date.add(afficherDate(l.getTsDebut())); } return list_Date; } public ArrayList<String> list_Heure_Debut(ArrayList<Creneau_Intervenant> liste_CI){ ArrayList<String> list_Heure_Debut = new ArrayList(); for (Creneau_Intervenant l : liste_CI) { list_Heure_Debut.add(afficherHeure(l.getTsDebut())); } return list_Heure_Debut; } public ArrayList<String> list_Heure_Fin(ArrayList<Creneau_Intervenant> liste_CI){ ArrayList<String> list_Heure_Fin = new ArrayList(); for (Creneau_Intervenant l : liste_CI) { list_Heure_Fin.add(afficherHeure(l.getTsFin())); } return list_Heure_Fin; } private void refreshRecurence(){ this.date.setText("jj/mm/aaaa"); this.periode.setText(""); this.recurrence.setSelected(false); // this.donner.desactive_sup_modif(); // this.donner.refreshIntervenant(); // this.jTable1.doLayout(); DefaultTableModel modell = new DefaultTableModel( new Object [4][5] , new String [] {}); this.jTable2.setModel(modell); try { this.list_creneauInter = Creneau_Intervenant.liste_Creneau_Intervenant(this.intervenant.getId()); } catch (SQLException ex) { Logger.getLogger(Donner.class.getName()).log(Level.SEVERE, null, ex); } ArrayList<String> listeDate = list_Date(this.list_creneauInter); modell.addColumn("Date", listeDate.toArray()); System.out.println(listeDate); ArrayList<String> listeheuredebut = list_Heure_Debut(this.list_creneauInter); modell.addColumn("Heure Début", listeheuredebut.toArray()); System.out.println(listeheuredebut); ArrayList<String> listheureFin = list_Heure_Fin(this.list_creneauInter); modell.addColumn("Heure Fin", listheureFin.toArray()); System.out.println(listheureFin); } private void creer(){ this.intervenant.setNom(this.nom.getText()); this.intervenant.setPrenom(this.prenom.getText()); this.intervenant.setTelephone(this.telephone.getText()); this.intervenant.setEmail(this.email.getText()); } public String afficherHeure(Timestamp tim){ String date = String.valueOf(tim); int h = Integer.parseInt(date.substring(11,13)); int min = Integer.parseInt(date.substring(14, 16)); return h+" h "+min; } public String afficherDate(Timestamp tim){ String date = String.valueOf(tim); int an = Integer.parseInt(date.substring(0, 4)); int mois = Integer.parseInt(date.substring(5, 7)); int jour = Integer.parseInt(date.substring(8, 10)); return jour+"/"+mois+"/"+an; } private Timestamp afficherTimestamp(String date,int heure, int minute, int recu){ int an = Integer.parseInt(date.substring(6, 10)); int mois = Integer.parseInt(date.substring(3, 5)); int jour = Integer.parseInt(date.substring(0, 2)); Timestamp ts = new Timestamp(an-1900,mois-1,jour+recu,heure,minute,0,0); return ts; } private void ajout_dispoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ajout_dispoActionPerformed // TODO add your handling code here: int n; switch(etat){ case Intervenant: this.intervenant = new Intervenant(this.nom.getText(),this.prenom.getText(),this.email.getText(),this.telephone.getText(),true,true); this.intervenant.save(); n = 1; if(this.recurrence.isSelected()){ n = Integer.parseInt(this.periode.getText()); } for(int i = 0;i< n; i++){ this.creneauInt = new Creneau_Intervenant( this.intervenant.getId(), afficherTimestamp(this.date.getText(), Integer.parseInt(this.h_debut.getSelectedItem().toString()), Integer.parseInt(this.m_debut.getSelectedItem().toString()), i*7), afficherTimestamp(this.date.getText(), Integer.parseInt(this.h_fin.getSelectedItem().toString()), Integer.parseInt(this.m_fin.getSelectedItem().toString()), i*7)); this.creneauInt.save(); } refreshRecurence(); this.etat = Etat.Intervenant1; break; case Intervenant1: n = 1; if(this.recurrence.isSelected()){ n = Integer.parseInt(this.periode.getText()); } for(int i = 0;i< n; i++){ this.creneauInt = new Creneau_Intervenant( this.intervenant.getId(), afficherTimestamp(this.date.getText(), Integer.parseInt(this.h_debut.getSelectedItem().toString()), Integer.parseInt(this.m_debut.getSelectedItem().toString()), i*7), afficherTimestamp(this.date.getText(), Integer.parseInt(this.h_fin.getSelectedItem().toString()), Integer.parseInt(this.m_fin.getSelectedItem().toString()), i*7)); this.creneauInt.save(); } refreshRecurence(); this.etat = Etat.Intervenant1; break; } }//GEN-LAST:event_ajout_dispoActionPerformed private void annulerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_annulerActionPerformed // TODO add your handling code here: switch(etat){ case Intervenant: this.dispose(); this.donner.desactive_sup_modif(); break; case Intervenant1: this.dispose(); this.donner.desactive_sup_modif(); break; } }//GEN-LAST:event_annulerActionPerformed private void validerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_validerActionPerformed // TODO add your handling code here: switch(etat){ case Intervenant: this.intervenant = new Intervenant(this.nom.getText(),this.prenom.getText(),this.email.getText(),this.telephone.getText(),true,true); this.intervenant.save(); refresh(); etat = Etat.Intervenant; break; case Intervenant1: creer(); this.intervenant.save(); refresh(); this.dispose(); break; } }//GEN-LAST:event_validerActionPerformed private void h_debutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_h_debutActionPerformed // TODO add your handling code here: }//GEN-LAST:event_h_debutActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(New_Intervenant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(New_Intervenant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(New_Intervenant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(New_Intervenant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { New_Intervenant dialog = new New_Intervenant(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton ajout_dispo; private javax.swing.JButton annuler; private javax.swing.JTextField date; private javax.swing.JTextField email; private javax.swing.JComboBox h_debut; private javax.swing.JComboBox h_fin; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTable1; private javax.swing.JTable jTable2; private javax.swing.JComboBox m_debut; private javax.swing.JComboBox m_fin; private javax.swing.JTextField nom; private javax.swing.JTextField periode; private javax.swing.JTextField prenom; private javax.swing.JCheckBox recurrence; private javax.swing.JTextField telephone; private javax.swing.JButton valider; // End of variables declaration//GEN-END:variables private enum Etat{ Intervenant, Intervenant1 } private Etat etat; public void init(String n,int id){ if(n.equals("Intervenant")) etat = Etat.Intervenant; else if (n.equals("Intervenant1")){ etat = Etat.Intervenant1; try { this.intervenant = new Intervenant(id); } catch (SQLException ex) { Logger.getLogger(New_Etudiant.class.getName()).log(Level.SEVERE, null, ex); } this.nom.setText(intervenant.getNom()); this.prenom.setText(intervenant.getPrenom()); this.email.setText(intervenant.getEmail()); this.telephone.setText(intervenant.getTelephone()); refreshRecurence(); } } }
32,332
0.582531
0.571331
637
48.739403
39.125263
194
false
false
0
0
0
0
0
0
0.816327
false
false
7
9b1f88b1d4d0106a07327ef09400a2f62411d217
549,755,875,143
6c6f48632a6c2283ee50c78834e0773cec5aa5cb
/SFJava/spenefett/tmp/gua.java
dd35853be6fd42bba8fa1171f32412307193b497
[]
no_license
kinghussien/darkfall_emu
https://github.com/kinghussien/darkfall_emu
263a9525b8c9cb62e5751163e419a3127acad7a1
3e3b76b2a892fb27c4b68fb5483664de4559bf98
refs/heads/master
"2016-09-02T04:32:02.404000"
"2015-01-07T05:21:13"
"2015-01-07T05:21:13"
27,749,321
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package spenefett.tmp; class gua { public int KM; public String FirstName; public String LastName; }
UTF-8
Java
114
java
gua.java
Java
[]
null
[]
package spenefett.tmp; class gua { public int KM; public String FirstName; public String LastName; }
114
0.692982
0.692982
7
14.285714
9.967294
26
false
false
0
0
0
0
0
0
0.571429
false
false
7
d61113af80316b8e010b9c0b3ce71ad4dd90062d
20,830,591,403,949
2d7f0a590f22adba7a44c8304bf6057ad3200d8f
/src/main/java/com/modapi/main/api/Mod/Mod.java
6fda75a997c4982bb7784eb06922064ce6d8e2e1
[]
no_license
RoboRave/Mod-API-1.7
https://github.com/RoboRave/Mod-API-1.7
c28b4425bc98ceace153fa85a3ae99bee4d0ca5d
6b4fae2a4fe9e8738185e05c2feefee5e6de9951
refs/heads/master
"2021-01-22T21:00:12.717000"
"2014-06-06T17:20:48"
"2014-06-06T17:20:48"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.modapi.main.api.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; public interface Mod { @EventHandler public abstract void PreInit(FMLPreInitializationEvent event); @EventHandler public abstract void Init(FMLInitializationEvent event); @EventHandler public abstract void PostInit(FMLPostInitializationEvent event); }
UTF-8
Java
521
java
Mod.java
Java
[]
null
[]
package com.modapi.main.api.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; public interface Mod { @EventHandler public abstract void PreInit(FMLPreInitializationEvent event); @EventHandler public abstract void Init(FMLInitializationEvent event); @EventHandler public abstract void PostInit(FMLPostInitializationEvent event); }
521
0.829175
0.829175
18
27.944445
25.428488
65
false
false
0
0
0
0
0
0
0.888889
false
false
7
e1e449863bf01df7812f03e11a035034ec0038be
146,028,953,463
a1b1100590e087b44c3a75e75956f4ff32105380
/csbs/src/main/java/com/acube/unitel/roam/veri/service/RoamVeriService.java
bb467b295a4cb5c3539c0c9bf3349cd5461302c7
[]
no_license
kangyou7/csbs
https://github.com/kangyou7/csbs
f63434e809fbe38ba56e1142d70e42b8128b90fa
1958a0060d19d8c89139688ad8c12116dd2635e7
refs/heads/master
"2017-12-22T03:51:19.055000"
"2014-07-02T06:50:05"
"2014-07-02T06:50:05"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.acube.unitel.roam.veri.service; import java.util.List; import javax.servlet.http.HttpServletResponse; import com.acube.unitel.common.domain.pagination.Pagination; import com.acube.unitel.roam.domain.RoamInvi; public interface RoamVeriService { //count public int getRoamVeriListCnt(RoamInvi roamInvi); //list public List<RoamInvi> getRoamVeriList(RoamInvi roamInvi, Pagination pagination); //detail public RoamInvi getRoamVeriDetail(RoamInvi roamInvi); //update public int upateRoamVeriDetail(RoamInvi roamInvi); //Detail count public int getRoamVeriDetailListCnt(RoamInvi roamInvi); //Detail list public List<RoamInvi> getRoamVeriDetailList(RoamInvi roamInvi, Pagination pagination); //Detail count public int getRoamVeriHistlListCnt(RoamInvi roamInvi); //Detail list public List<RoamInvi> getRoamVeriHistlList(RoamInvi roamInvi, Pagination pagination); public void getExcelData(HttpServletResponse response, List<RoamInvi> roamInvi); }
UTF-8
Java
972
java
RoamVeriService.java
Java
[]
null
[]
package com.acube.unitel.roam.veri.service; import java.util.List; import javax.servlet.http.HttpServletResponse; import com.acube.unitel.common.domain.pagination.Pagination; import com.acube.unitel.roam.domain.RoamInvi; public interface RoamVeriService { //count public int getRoamVeriListCnt(RoamInvi roamInvi); //list public List<RoamInvi> getRoamVeriList(RoamInvi roamInvi, Pagination pagination); //detail public RoamInvi getRoamVeriDetail(RoamInvi roamInvi); //update public int upateRoamVeriDetail(RoamInvi roamInvi); //Detail count public int getRoamVeriDetailListCnt(RoamInvi roamInvi); //Detail list public List<RoamInvi> getRoamVeriDetailList(RoamInvi roamInvi, Pagination pagination); //Detail count public int getRoamVeriHistlListCnt(RoamInvi roamInvi); //Detail list public List<RoamInvi> getRoamVeriHistlList(RoamInvi roamInvi, Pagination pagination); public void getExcelData(HttpServletResponse response, List<RoamInvi> roamInvi); }
972
0.81893
0.81893
28
33.75
28.486368
87
false
false
0
0
0
0
0
0
1.428571
false
false
7
7947fea677074c7cda1f924fe43d197328789e87
31,061,203,511,813
6a7c43bad2ec43b90835e9d116514bd7e39a5309
/push/src/main/java/org/aerogear/mobile/push/PushService.java
38df2af076538144bce7a13f9edf79830223e601
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
laurafitzgerald/aerogear-android-sdk
https://github.com/laurafitzgerald/aerogear-android-sdk
44a7ddbf89a89c3789eac497b1504dce3d5d8b17
cc078f55e0d72eb548dcf2cdffb4e94f77dcaa0a
refs/heads/master
"2020-03-18T07:09:42.893000"
"2018-05-22T13:56:53"
"2018-05-22T13:56:53"
134,436,809
0
0
null
true
"2018-05-22T15:34:35"
"2018-05-22T15:34:35"
"2018-05-22T13:56:57"
"2018-05-22T13:56:54"
1,758
0
0
0
null
false
null
package org.aerogear.mobile.push; import static java.net.HttpURLConnection.HTTP_NO_CONTENT; import static java.net.HttpURLConnection.HTTP_OK; import static org.aerogear.mobile.core.utils.SanityCheck.nonNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.messaging.FirebaseMessaging; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.util.Base64; import org.aerogear.mobile.core.Callback; import org.aerogear.mobile.core.MobileCore; import org.aerogear.mobile.core.ServiceModule; import org.aerogear.mobile.core.configuration.ServiceConfiguration; import org.aerogear.mobile.core.exception.ConfigurationNotFoundException; import org.aerogear.mobile.core.exception.HttpException; import org.aerogear.mobile.core.executor.AppExecutors; import org.aerogear.mobile.core.http.HttpRequest; import org.aerogear.mobile.core.http.HttpResponse; import org.aerogear.mobile.core.reactive.Responder; /** * The entry point for communication with Unified Push Server */ public class PushService implements ServiceModule { private static final String DEFAULT_MESSAGE_HANDLER_KEY = "DEFAULT_MESSAGE_HANDLER_KEY"; private static final String SHARED_PREFERENCE_PUSH_NAME = "UnifiedPushServer"; private static final String SHARED_PREFERENCE_PUSH_KEY = "UnifiedPushServer_Cache"; private static final String registryDeviceEndpoint = "rest/registry/device"; private static final String JSON_ANDROID_CONFIG_KEY = "android"; private static final String JSON_VARIANT_ID_KEY = "variantId"; private static final String JSON_VARIANT_SECRET_KEY = "variantSecret"; private static final String JSON_SENDER_ID_KEY = "senderId"; private static final List<MessageHandler> MAIN_THREAD_HANDLERS = Collections.synchronizedList(new ArrayList<>()); private static final List<MessageHandler> BACKGROUND_THREAD_HANDLERS = Collections.synchronizedList(new ArrayList<>()); private final String deviceType = "ANDROID"; private final String operatingSystem = "android"; private final String osVersion = android.os.Build.VERSION.RELEASE; private MobileCore core; private String url; private UnifiedPushCredentials unifiedPushCredentials; private SharedPreferences sharedPreferences; private static MessageHandler defaultHandler; @Override public String type() { return "push"; } @Override public void configure(MobileCore core, ServiceConfiguration serviceConfiguration) { this.core = core; this.url = serviceConfiguration.getUrl(); getDefaultHandler(core.getContext()); try { JSONObject android = new JSONObject( serviceConfiguration.getProperties().get(JSON_ANDROID_CONFIG_KEY)); unifiedPushCredentials = new UnifiedPushCredentials(); unifiedPushCredentials.setVariant(android.getString(JSON_VARIANT_ID_KEY)); unifiedPushCredentials.setSecret(android.getString(JSON_VARIANT_SECRET_KEY)); unifiedPushCredentials.setSenderId(android.getString(JSON_SENDER_ID_KEY)); } catch (JSONException e) { MobileCore.getLogger().error(e.getMessage(), e); throw new ConfigurationNotFoundException( "An error occurred while trying to load the push config"); } sharedPreferences = core.getContext().getSharedPreferences(SHARED_PREFERENCE_PUSH_NAME, Context.MODE_PRIVATE); } @Override public boolean requiresConfiguration() { return true; } /** * Register the device on Unified Push Server * * @param callback A callback to handle successful or failed registration */ public void registerDevice(final Callback callback) { registerDevice(new UnifiedPushConfig(), callback); } /** * Register the device on Unified Push Server * * @param unifiedPushConfig Unified Push configuration to be send to the Unified Push Server * @param callback A callback to handle successful or failed registration */ public void registerDevice(final UnifiedPushConfig unifiedPushConfig, final Callback callback) { nonNull(unifiedPushConfig, "unifiedPushConfig"); nonNull(callback, "callback"); try { JSONObject data = new JSONObject(); data.put("deviceType", deviceType); data.put("operatingSystem", operatingSystem); data.put("osVersion", osVersion); data.put("alias", unifiedPushConfig.getAlias()); final List<String> categories = unifiedPushConfig.getCategories(); if (!categories.isEmpty()) { JSONArray jsonCategories = new JSONArray(); for (String category : categories) { jsonCategories.put(category); } data.put("categories", jsonCategories); } registerDevice(data, callback); } catch (JSONException e) { MobileCore.getLogger().error(e.getMessage(), e); callback.onError(e); } } /** * Register the device on Unified Push Server * * @param data Unified Push data to be send to the Unified Push Server * @param callback A callback to handle successful or failed registration */ private void registerDevice(JSONObject data, Callback callback) { nonNull(data, "data"); nonNull(callback, "callback"); try { data.put("deviceToken", FirebaseInstanceId.getInstance().getToken()); String authHash = getHashedAuth(unifiedPushCredentials.getVariant(), unifiedPushCredentials.getSecret().toCharArray()); final HttpRequest httpRequest = core.getHttpLayer().newRequest(); httpRequest.addHeader("Authorization", authHash); // Invalidate old on Unified Push Server String oldDeviceToken = retrieveOldDeviceToken(); if (oldDeviceToken != null) { httpRequest.addHeader("x-ag-old-token", oldDeviceToken); } httpRequest.post(url + registryDeviceEndpoint, data.toString().getBytes()) .respondWith(new Responder<HttpResponse>() { @Override public void onResult(HttpResponse httpResponse) { switch (httpResponse.getStatus()) { case HTTP_OK: FirebaseMessaging firebaseMessaging = FirebaseMessaging.getInstance(); try { JSONArray categories = data.getJSONArray("categories"); for (int i = 0; i < categories.length(); i++) { String category = categories.getJSONObject(i) .toString(); firebaseMessaging.subscribeToTopic(category); } } catch (JSONException e) { // ignore } firebaseMessaging.subscribeToTopic( unifiedPushCredentials.getVariant()); saveCache(data); callback.onSuccess(); break; default: callback.onError(new HttpException( httpResponse.getStatus())); break; } } @Override public void onException(Exception error) { MobileCore.getLogger().error(error.getMessage(), error); callback.onError(error); } }); } catch (JSONException e) { MobileCore.getLogger().error(e.getMessage(), e); callback.onError(e); } } /** * Unregister the device on Unified Push Server * * @param callback A callback to handle successful or failed unregistration */ public void unregisterDevice(final Callback callback) { nonNull(callback, "callback"); String authHash = getHashedAuth(unifiedPushCredentials.getVariant(), unifiedPushCredentials.getSecret().toCharArray()); final HttpRequest httpRequest = core.getHttpLayer().newRequest(); httpRequest.addHeader("Authorization", authHash); httpRequest.delete(url + registryDeviceEndpoint + "/" + FirebaseInstanceId.getInstance().getToken()) .respondWith(new Responder<HttpResponse>() { @Override public void onResult(HttpResponse httpResponse) { switch (httpResponse.getStatus()) { case HTTP_NO_CONTENT: FirebaseMessaging firebaseMessaging = FirebaseMessaging.getInstance(); try { JSONObject data = retrieveCache(); if (data != null) { JSONArray categories = data.getJSONArray("categories"); for (int i = 0; i < categories.length(); i++) { String category = categories.getString(i); firebaseMessaging .unsubscribeFromTopic(category); } } } catch (JSONException e) { // ignore } firebaseMessaging.unsubscribeFromTopic( unifiedPushCredentials.getVariant()); clearCache(); callback.onSuccess(); break; default: callback.onError(new HttpException( httpResponse.getStatus())); break; } } @Override public void onException(Exception error) { MobileCore.getLogger().error(error.getMessage(), error); callback.onError(error); } }); } /** * Provide an auth hash to be used to authenticate in Unified Push Service * * @param variant Unified Push variant id * @param secret Unified Push variant secret * @return Auth hash */ private String getHashedAuth(final String variant, final char[] secret) { StringBuilder headerValueBuilder = new StringBuilder("Basic").append(" "); String unhashedCredentials = variant + ":" + String.valueOf(secret); String hashedCrentials = Base64.encodeToString(unhashedCredentials.getBytes(), Base64.NO_WRAP); return headerValueBuilder.append(hashedCrentials).toString(); } /** * Update the device token on Unified Push Server */ public void refreshToken() { JSONObject jsonObject = retrieveCache(); if (jsonObject != null) { this.registerDevice(jsonObject, error -> MobileCore.getLogger().error(error.getMessage(), error)); } } /** * Save info sent to the Unified Push Server * * @param data JSONObject sent to Unified Push Server */ private void saveCache(JSONObject data) { sharedPreferences.edit().putString(SHARED_PREFERENCE_PUSH_KEY, data.toString()).apply(); } /** * Retrieve info sent to the Unified Push Server * * @return JSONObject sent to Unified Push Server */ private JSONObject retrieveCache() { try { String jsonString = sharedPreferences.getString(SHARED_PREFERENCE_PUSH_KEY, ""); return (!jsonString.isEmpty()) ? new JSONObject(jsonString) : null; } catch (JSONException e) { MobileCore.getLogger().error(e.getMessage(), e); return null; } } /** * Retrive the last device token sent to the Unified Push Server * * @return Device Token */ private String retrieveOldDeviceToken() { JSONObject data = retrieveCache(); try { return (data == null) ? null : data.getString("deviceToken"); } catch (JSONException e) { MobileCore.getLogger().error(e.getMessage(), e); return null; } } /** * Clear cache of info sent to the Unified Push Server */ private void clearCache() { sharedPreferences.edit().remove(SHARED_PREFERENCE_PUSH_KEY).apply(); } /** * When a push message is received, all main thread handlers will be notified on the main(UI) * thread. This is very convenient for Activities and Fragments. * * @param handler a handler to added to the list of handlers to be notified. */ public static void registerMainThreadHandler(final MessageHandler handler) { MAIN_THREAD_HANDLERS.add(nonNull(handler, "handle")); } /** * When a push message is received, all background thread handlers will be notified on a non UI * thread. This should be used by classes which need to update internal state or preform some * action which doesn't change the UI. * * @param handler a handler to added to the list of handlers to be notified. */ public static void registerBackgroundThreadHandler(final MessageHandler handler) { BACKGROUND_THREAD_HANDLERS.add(nonNull(handler, "handle")); } /** * This will remove the given handler from the collection of main thread handlers. This MUST be * called when a Fragment or activity is backgrounded via onPause. * * @param handler a handler to be removed to the list of handlers */ public static void unregisterMainThreadHandler(final MessageHandler handler) { MAIN_THREAD_HANDLERS.remove(nonNull(handler, "handle")); } /** * This will remove the given handler from the collection of background thread handlers. * * @param handler a handler to be removed to the list of handlers */ public static void unregisterBackgroundThreadHandler(final MessageHandler handler) { BACKGROUND_THREAD_HANDLERS.remove(nonNull(handler, "handle")); } /** * Notify all registered handlers. * * @param context the Android context * @param message the push message */ public static void notifyHandlers(final Context context, final Map<String, String> message) { nonNull(context, "context"); if (defaultHandler == null) { getDefaultHandler(context); } if (BACKGROUND_THREAD_HANDLERS.isEmpty() && MAIN_THREAD_HANDLERS.isEmpty() && defaultHandler != null) { new AppExecutors().singleThreadService().execute(() -> defaultHandler.onMessage(context, Collections.unmodifiableMap(message))); } else { for (final MessageHandler handler : BACKGROUND_THREAD_HANDLERS) { new AppExecutors().singleThreadService().execute(() -> handler.onMessage(context, Collections.unmodifiableMap(message))); } for (final MessageHandler handler : MAIN_THREAD_HANDLERS) { new AppExecutors().mainThread().execute(() -> handler.onMessage(context, Collections.unmodifiableMap(message))); } } } /** * Get a default handler from AndroidManifest.xml if exists * <p> * <code> * <meta-data * android:name="DEFAULT_MESSAGE_HANDLER_KEY" android:value="my.package.HandlerClassName" /> * </code> */ @SuppressWarnings("unchecked") private static void getDefaultHandler(final Context context) { nonNull(context, "context"); try { ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo( context.getPackageName(), PackageManager.GET_META_DATA); Bundle metaData = applicationInfo.metaData; if (metaData != null) { String defaultHandlerClassName = metaData.getString(DEFAULT_MESSAGE_HANDLER_KEY); if (defaultHandlerClassName != null) { try { Class<? extends MessageHandler> defaultHandlerClass = (Class<? extends MessageHandler>) Class .forName(defaultHandlerClassName); defaultHandler = defaultHandlerClass.newInstance(); } catch (Exception ex) { MobileCore.getLogger().error(ex.getMessage(), ex); } } } } catch (PackageManager.NameNotFoundException e) { MobileCore.getLogger().warning(e.getMessage(), e); } } }
UTF-8
Java
19,050
java
PushService.java
Java
[ { "context": "static final String SHARED_PREFERENCE_PUSH_KEY = \"UnifiedPushServer_Cache\";\n\n private static final String registryDevice", "end": 1649, "score": 0.657986044883728, "start": 1626, "tag": "KEY", "value": "UnifiedPushServer_Cache" }, { "context": "rivate static final String JSON_VARIANT_ID_KEY = \"variantId\";\n private static final String JSON_VARIANT_SE", "end": 1867, "score": 0.7454035878181458, "start": 1858, "tag": "KEY", "value": "variantId" }, { "context": "te static final String JSON_VARIANT_SECRET_KEY = \"variantSecret\";\n private static final String JSON_SENDER_ID_", "end": 1942, "score": 0.9315218925476074, "start": 1929, "tag": "KEY", "value": "variantSecret" }, { "context": "private static final String JSON_SENDER_ID_KEY = \"senderId\";\n\n\n private static final List<MessageHandler>", "end": 2007, "score": 0.8875369429588318, "start": 1999, "tag": "KEY", "value": "senderId" } ]
null
[]
package org.aerogear.mobile.push; import static java.net.HttpURLConnection.HTTP_NO_CONTENT; import static java.net.HttpURLConnection.HTTP_OK; import static org.aerogear.mobile.core.utils.SanityCheck.nonNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.messaging.FirebaseMessaging; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.util.Base64; import org.aerogear.mobile.core.Callback; import org.aerogear.mobile.core.MobileCore; import org.aerogear.mobile.core.ServiceModule; import org.aerogear.mobile.core.configuration.ServiceConfiguration; import org.aerogear.mobile.core.exception.ConfigurationNotFoundException; import org.aerogear.mobile.core.exception.HttpException; import org.aerogear.mobile.core.executor.AppExecutors; import org.aerogear.mobile.core.http.HttpRequest; import org.aerogear.mobile.core.http.HttpResponse; import org.aerogear.mobile.core.reactive.Responder; /** * The entry point for communication with Unified Push Server */ public class PushService implements ServiceModule { private static final String DEFAULT_MESSAGE_HANDLER_KEY = "DEFAULT_MESSAGE_HANDLER_KEY"; private static final String SHARED_PREFERENCE_PUSH_NAME = "UnifiedPushServer"; private static final String SHARED_PREFERENCE_PUSH_KEY = "UnifiedPushServer_Cache"; private static final String registryDeviceEndpoint = "rest/registry/device"; private static final String JSON_ANDROID_CONFIG_KEY = "android"; private static final String JSON_VARIANT_ID_KEY = "variantId"; private static final String JSON_VARIANT_SECRET_KEY = "variantSecret"; private static final String JSON_SENDER_ID_KEY = "senderId"; private static final List<MessageHandler> MAIN_THREAD_HANDLERS = Collections.synchronizedList(new ArrayList<>()); private static final List<MessageHandler> BACKGROUND_THREAD_HANDLERS = Collections.synchronizedList(new ArrayList<>()); private final String deviceType = "ANDROID"; private final String operatingSystem = "android"; private final String osVersion = android.os.Build.VERSION.RELEASE; private MobileCore core; private String url; private UnifiedPushCredentials unifiedPushCredentials; private SharedPreferences sharedPreferences; private static MessageHandler defaultHandler; @Override public String type() { return "push"; } @Override public void configure(MobileCore core, ServiceConfiguration serviceConfiguration) { this.core = core; this.url = serviceConfiguration.getUrl(); getDefaultHandler(core.getContext()); try { JSONObject android = new JSONObject( serviceConfiguration.getProperties().get(JSON_ANDROID_CONFIG_KEY)); unifiedPushCredentials = new UnifiedPushCredentials(); unifiedPushCredentials.setVariant(android.getString(JSON_VARIANT_ID_KEY)); unifiedPushCredentials.setSecret(android.getString(JSON_VARIANT_SECRET_KEY)); unifiedPushCredentials.setSenderId(android.getString(JSON_SENDER_ID_KEY)); } catch (JSONException e) { MobileCore.getLogger().error(e.getMessage(), e); throw new ConfigurationNotFoundException( "An error occurred while trying to load the push config"); } sharedPreferences = core.getContext().getSharedPreferences(SHARED_PREFERENCE_PUSH_NAME, Context.MODE_PRIVATE); } @Override public boolean requiresConfiguration() { return true; } /** * Register the device on Unified Push Server * * @param callback A callback to handle successful or failed registration */ public void registerDevice(final Callback callback) { registerDevice(new UnifiedPushConfig(), callback); } /** * Register the device on Unified Push Server * * @param unifiedPushConfig Unified Push configuration to be send to the Unified Push Server * @param callback A callback to handle successful or failed registration */ public void registerDevice(final UnifiedPushConfig unifiedPushConfig, final Callback callback) { nonNull(unifiedPushConfig, "unifiedPushConfig"); nonNull(callback, "callback"); try { JSONObject data = new JSONObject(); data.put("deviceType", deviceType); data.put("operatingSystem", operatingSystem); data.put("osVersion", osVersion); data.put("alias", unifiedPushConfig.getAlias()); final List<String> categories = unifiedPushConfig.getCategories(); if (!categories.isEmpty()) { JSONArray jsonCategories = new JSONArray(); for (String category : categories) { jsonCategories.put(category); } data.put("categories", jsonCategories); } registerDevice(data, callback); } catch (JSONException e) { MobileCore.getLogger().error(e.getMessage(), e); callback.onError(e); } } /** * Register the device on Unified Push Server * * @param data Unified Push data to be send to the Unified Push Server * @param callback A callback to handle successful or failed registration */ private void registerDevice(JSONObject data, Callback callback) { nonNull(data, "data"); nonNull(callback, "callback"); try { data.put("deviceToken", FirebaseInstanceId.getInstance().getToken()); String authHash = getHashedAuth(unifiedPushCredentials.getVariant(), unifiedPushCredentials.getSecret().toCharArray()); final HttpRequest httpRequest = core.getHttpLayer().newRequest(); httpRequest.addHeader("Authorization", authHash); // Invalidate old on Unified Push Server String oldDeviceToken = retrieveOldDeviceToken(); if (oldDeviceToken != null) { httpRequest.addHeader("x-ag-old-token", oldDeviceToken); } httpRequest.post(url + registryDeviceEndpoint, data.toString().getBytes()) .respondWith(new Responder<HttpResponse>() { @Override public void onResult(HttpResponse httpResponse) { switch (httpResponse.getStatus()) { case HTTP_OK: FirebaseMessaging firebaseMessaging = FirebaseMessaging.getInstance(); try { JSONArray categories = data.getJSONArray("categories"); for (int i = 0; i < categories.length(); i++) { String category = categories.getJSONObject(i) .toString(); firebaseMessaging.subscribeToTopic(category); } } catch (JSONException e) { // ignore } firebaseMessaging.subscribeToTopic( unifiedPushCredentials.getVariant()); saveCache(data); callback.onSuccess(); break; default: callback.onError(new HttpException( httpResponse.getStatus())); break; } } @Override public void onException(Exception error) { MobileCore.getLogger().error(error.getMessage(), error); callback.onError(error); } }); } catch (JSONException e) { MobileCore.getLogger().error(e.getMessage(), e); callback.onError(e); } } /** * Unregister the device on Unified Push Server * * @param callback A callback to handle successful or failed unregistration */ public void unregisterDevice(final Callback callback) { nonNull(callback, "callback"); String authHash = getHashedAuth(unifiedPushCredentials.getVariant(), unifiedPushCredentials.getSecret().toCharArray()); final HttpRequest httpRequest = core.getHttpLayer().newRequest(); httpRequest.addHeader("Authorization", authHash); httpRequest.delete(url + registryDeviceEndpoint + "/" + FirebaseInstanceId.getInstance().getToken()) .respondWith(new Responder<HttpResponse>() { @Override public void onResult(HttpResponse httpResponse) { switch (httpResponse.getStatus()) { case HTTP_NO_CONTENT: FirebaseMessaging firebaseMessaging = FirebaseMessaging.getInstance(); try { JSONObject data = retrieveCache(); if (data != null) { JSONArray categories = data.getJSONArray("categories"); for (int i = 0; i < categories.length(); i++) { String category = categories.getString(i); firebaseMessaging .unsubscribeFromTopic(category); } } } catch (JSONException e) { // ignore } firebaseMessaging.unsubscribeFromTopic( unifiedPushCredentials.getVariant()); clearCache(); callback.onSuccess(); break; default: callback.onError(new HttpException( httpResponse.getStatus())); break; } } @Override public void onException(Exception error) { MobileCore.getLogger().error(error.getMessage(), error); callback.onError(error); } }); } /** * Provide an auth hash to be used to authenticate in Unified Push Service * * @param variant Unified Push variant id * @param secret Unified Push variant secret * @return Auth hash */ private String getHashedAuth(final String variant, final char[] secret) { StringBuilder headerValueBuilder = new StringBuilder("Basic").append(" "); String unhashedCredentials = variant + ":" + String.valueOf(secret); String hashedCrentials = Base64.encodeToString(unhashedCredentials.getBytes(), Base64.NO_WRAP); return headerValueBuilder.append(hashedCrentials).toString(); } /** * Update the device token on Unified Push Server */ public void refreshToken() { JSONObject jsonObject = retrieveCache(); if (jsonObject != null) { this.registerDevice(jsonObject, error -> MobileCore.getLogger().error(error.getMessage(), error)); } } /** * Save info sent to the Unified Push Server * * @param data JSONObject sent to Unified Push Server */ private void saveCache(JSONObject data) { sharedPreferences.edit().putString(SHARED_PREFERENCE_PUSH_KEY, data.toString()).apply(); } /** * Retrieve info sent to the Unified Push Server * * @return JSONObject sent to Unified Push Server */ private JSONObject retrieveCache() { try { String jsonString = sharedPreferences.getString(SHARED_PREFERENCE_PUSH_KEY, ""); return (!jsonString.isEmpty()) ? new JSONObject(jsonString) : null; } catch (JSONException e) { MobileCore.getLogger().error(e.getMessage(), e); return null; } } /** * Retrive the last device token sent to the Unified Push Server * * @return Device Token */ private String retrieveOldDeviceToken() { JSONObject data = retrieveCache(); try { return (data == null) ? null : data.getString("deviceToken"); } catch (JSONException e) { MobileCore.getLogger().error(e.getMessage(), e); return null; } } /** * Clear cache of info sent to the Unified Push Server */ private void clearCache() { sharedPreferences.edit().remove(SHARED_PREFERENCE_PUSH_KEY).apply(); } /** * When a push message is received, all main thread handlers will be notified on the main(UI) * thread. This is very convenient for Activities and Fragments. * * @param handler a handler to added to the list of handlers to be notified. */ public static void registerMainThreadHandler(final MessageHandler handler) { MAIN_THREAD_HANDLERS.add(nonNull(handler, "handle")); } /** * When a push message is received, all background thread handlers will be notified on a non UI * thread. This should be used by classes which need to update internal state or preform some * action which doesn't change the UI. * * @param handler a handler to added to the list of handlers to be notified. */ public static void registerBackgroundThreadHandler(final MessageHandler handler) { BACKGROUND_THREAD_HANDLERS.add(nonNull(handler, "handle")); } /** * This will remove the given handler from the collection of main thread handlers. This MUST be * called when a Fragment or activity is backgrounded via onPause. * * @param handler a handler to be removed to the list of handlers */ public static void unregisterMainThreadHandler(final MessageHandler handler) { MAIN_THREAD_HANDLERS.remove(nonNull(handler, "handle")); } /** * This will remove the given handler from the collection of background thread handlers. * * @param handler a handler to be removed to the list of handlers */ public static void unregisterBackgroundThreadHandler(final MessageHandler handler) { BACKGROUND_THREAD_HANDLERS.remove(nonNull(handler, "handle")); } /** * Notify all registered handlers. * * @param context the Android context * @param message the push message */ public static void notifyHandlers(final Context context, final Map<String, String> message) { nonNull(context, "context"); if (defaultHandler == null) { getDefaultHandler(context); } if (BACKGROUND_THREAD_HANDLERS.isEmpty() && MAIN_THREAD_HANDLERS.isEmpty() && defaultHandler != null) { new AppExecutors().singleThreadService().execute(() -> defaultHandler.onMessage(context, Collections.unmodifiableMap(message))); } else { for (final MessageHandler handler : BACKGROUND_THREAD_HANDLERS) { new AppExecutors().singleThreadService().execute(() -> handler.onMessage(context, Collections.unmodifiableMap(message))); } for (final MessageHandler handler : MAIN_THREAD_HANDLERS) { new AppExecutors().mainThread().execute(() -> handler.onMessage(context, Collections.unmodifiableMap(message))); } } } /** * Get a default handler from AndroidManifest.xml if exists * <p> * <code> * <meta-data * android:name="DEFAULT_MESSAGE_HANDLER_KEY" android:value="my.package.HandlerClassName" /> * </code> */ @SuppressWarnings("unchecked") private static void getDefaultHandler(final Context context) { nonNull(context, "context"); try { ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo( context.getPackageName(), PackageManager.GET_META_DATA); Bundle metaData = applicationInfo.metaData; if (metaData != null) { String defaultHandlerClassName = metaData.getString(DEFAULT_MESSAGE_HANDLER_KEY); if (defaultHandlerClassName != null) { try { Class<? extends MessageHandler> defaultHandlerClass = (Class<? extends MessageHandler>) Class .forName(defaultHandlerClassName); defaultHandler = defaultHandlerClass.newInstance(); } catch (Exception ex) { MobileCore.getLogger().error(ex.getMessage(), ex); } } } } catch (PackageManager.NameNotFoundException e) { MobileCore.getLogger().warning(e.getMessage(), e); } } }
19,050
0.552913
0.552493
475
39.105263
32.058918
100
false
false
0
0
0
0
0
0
0.431579
false
false
7
98f0fa6d6e9311d603839167f5c6fc8e0493ce21
9,345,848,876,746
9dfac3eb24dfcff6f26f9d8ec8e1df53c60c6426
/src/main/java/com/ecommerce/flashsales/PolicyValidationR.java
e5980cb84ef4814b7cb3da670a3974027a9a0a1b
[]
no_license
danzelmcavoy/gatekeeper
https://github.com/danzelmcavoy/gatekeeper
a34f8342963effe1f8a8999ea9d21f1d4c5b6bc5
6d0403f4336d3766fc47a2e3cb48443b262d0647
refs/heads/master
"2021-06-02T05:17:18.507000"
"2016-09-07T09:49:14"
"2016-09-07T09:49:14"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ecommerce.flashsales; import java.io.Serializable; /*** * * @author wuwesley * the class for user's order info */ @SuppressWarnings("serial") public class PolicyValidationR implements Serializable { public String sessionID; public String userID; public String goodsSKU; public int userLevel; public int orderQuantity; public int quantityLimit; public boolean isAllowed = true; public boolean isThrottled = false; public String version = "1.0"; public String getSessionID() { return sessionID; } public void setSessionID(String sessionID) { this.sessionID = sessionID; } public String getUserID() { return userID; } public void setUserID(String userID) { this.userID = userID; } public String getGoodsSKU() { return goodsSKU; } public void setGoodsSKU(String goodsSKU) { this.goodsSKU = goodsSKU; } public int getUserLevel() { return userLevel; } public void setUserLevel(int userLevel) { this.userLevel = userLevel; } public int getOrderQuantity() { return orderQuantity; } public void setOrderQuantity(int orderQuantity) { this.orderQuantity = orderQuantity; } public int getQuantityLimit() { return quantityLimit; } public void setQuantityLimit(int quantityLimit) { this.quantityLimit = quantityLimit; } public boolean getIsAllowed() { return isAllowed; } public void setIsAllowed(boolean isAllowed) { this.isAllowed = isAllowed; } public boolean getIsThrottled() { return isThrottled; } public void setIsThrottled(boolean isThrottled) { this.isThrottled = isThrottled; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } @Override public String toString() { return "PolicyValidationR [sessionID=" + sessionID + ", userID=" + userID + ", goodsSKU=" + goodsSKU + ", userLevel=" + userLevel + ", orderQuantity=" + orderQuantity + ", quantityLimit=" + quantityLimit + ", isAllowed=" + isAllowed + ", isThrottled=" + isThrottled + ", version=" + version + "]"; } }
UTF-8
Java
2,050
java
PolicyValidationR.java
Java
[ { "context": "\nimport java.io.Serializable;\n\n/***\n * \n * @author wuwesley\n * the class for user's order info\n */\n\n@Suppress", "end": 93, "score": 0.9994140863418579, "start": 85, "tag": "USERNAME", "value": "wuwesley" } ]
null
[]
package com.ecommerce.flashsales; import java.io.Serializable; /*** * * @author wuwesley * the class for user's order info */ @SuppressWarnings("serial") public class PolicyValidationR implements Serializable { public String sessionID; public String userID; public String goodsSKU; public int userLevel; public int orderQuantity; public int quantityLimit; public boolean isAllowed = true; public boolean isThrottled = false; public String version = "1.0"; public String getSessionID() { return sessionID; } public void setSessionID(String sessionID) { this.sessionID = sessionID; } public String getUserID() { return userID; } public void setUserID(String userID) { this.userID = userID; } public String getGoodsSKU() { return goodsSKU; } public void setGoodsSKU(String goodsSKU) { this.goodsSKU = goodsSKU; } public int getUserLevel() { return userLevel; } public void setUserLevel(int userLevel) { this.userLevel = userLevel; } public int getOrderQuantity() { return orderQuantity; } public void setOrderQuantity(int orderQuantity) { this.orderQuantity = orderQuantity; } public int getQuantityLimit() { return quantityLimit; } public void setQuantityLimit(int quantityLimit) { this.quantityLimit = quantityLimit; } public boolean getIsAllowed() { return isAllowed; } public void setIsAllowed(boolean isAllowed) { this.isAllowed = isAllowed; } public boolean getIsThrottled() { return isThrottled; } public void setIsThrottled(boolean isThrottled) { this.isThrottled = isThrottled; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } @Override public String toString() { return "PolicyValidationR [sessionID=" + sessionID + ", userID=" + userID + ", goodsSKU=" + goodsSKU + ", userLevel=" + userLevel + ", orderQuantity=" + orderQuantity + ", quantityLimit=" + quantityLimit + ", isAllowed=" + isAllowed + ", isThrottled=" + isThrottled + ", version=" + version + "]"; } }
2,050
0.719024
0.718049
86
22.83721
21.541124
106
false
false
0
0
0
0
0
0
1.593023
false
false
7
3c2262048a185d7f9777a374b49936d0b84acaf0
16,673,063,096,218
c6bf3723ace47658643a982f23a73ff0092e2b46
/Final-Project/src/main/controller/Navigator.java
3f1a29f63787917514fd5af5b361c66cc1fabde2
[]
no_license
durham-abric/dpm-group11
https://github.com/durham-abric/dpm-group11
ff66d166b60b318593162fc251845839ce82bfa2
a3691755e9f6b5ea1d066c4cfac0d81bf188b7e9
refs/heads/master
"2021-01-22T21:32:22.568000"
"2017-03-15T15:53:53"
"2017-03-15T15:53:53"
85,439,371
0
0
null
true
"2017-03-18T23:49:23"
"2017-03-18T23:49:23"
"2017-03-15T15:53:57"
"2017-03-15T15:53:54"
33,822
0
0
0
null
null
null
package main.controller; import lejos.hardware.motor.EV3LargeRegulatedMotor; import main.resource.Constants; /** * Navigator object used to navigate the vehicle. * * @author JohnWu */ public class Navigator { // objects private Odometer odometer; private EV3LargeRegulatedMotor leftMotor, rightMotor; /** * Default constructor for Navigator object. * * @param leftMotor the left motor EV3 object used in the robot * @param rightMotor the right motor EV3 object used in the robot * @param odometer the odometer controller used in the robot */ public Navigator( EV3LargeRegulatedMotor leftMotor , EV3LargeRegulatedMotor rightMotor , Odometer odometer ) { this.odometer = odometer; this.leftMotor = leftMotor; this.rightMotor = rightMotor; } /** * A method to drive our vehicle to a certain cartesian coordinate. * * @param x X-Coordinate * @param y Y-Coordinate */ public void travelTo( double x , double y ) { double deltaX = x - odometer.getX(); double deltaY = y - odometer.getY(); travelToX( odometer.getX() + deltaX ); travelToY( odometer.getY() + deltaY ); } /** * A method to travel to a specific x coordinate * * @param xCoordinate the x coordinate we want to travel to */ public void travelToX( double xCoordinate ) { // turn to the minimum angle turnTo( calculateMinAngle( xCoordinate - odometer.getX(), 0 ) ); // move to the specified point driveForward(); while ( Math.abs( odometer.getX() - xCoordinate ) > Constants.POINT_REACHED_THRESHOLD ) { if ( odometer.isCorrecting() ) { waitUntilCorrectionIsFinished(); driveForward(); } } stopMotors(); } /** * A method to travel to a specific y coordinate * * @param yCoordinate the y coordinate we want to travel to */ public void travelToY( double yCoordinate ) { // turn to the minimum angle turnTo( calculateMinAngle( 0, yCoordinate - odometer.getY() ) ); // move to the specified point driveForward(); while ( Math.abs( odometer.getY() - yCoordinate ) > Constants.POINT_REACHED_THRESHOLD ) { if ( odometer.isCorrecting() ) { waitUntilCorrectionIsFinished(); driveForward(); } } stopMotors(); } /** * A method to turn our vehicle to a certain angle in either direction * * @param theta the theta angle that we want to turn our vehicle */ public void turnTo( double theta ) { leftMotor.setSpeed( Constants.VEHICLE_ROTATE_SPEED ); rightMotor.setSpeed( Constants.VEHICLE_ROTATE_SPEED ); if( theta < 0 ) { // if angle is negative, turn to the left leftMotor.rotate( -convertAngle( -(theta*180)/Math.PI ) , true ); rightMotor.rotate( convertAngle( -(theta*180)/Math.PI ) , false ); } else { // angle is positive, turn to the right leftMotor.rotate( convertAngle( (theta*180)/Math.PI ) , true); rightMotor.rotate( -convertAngle( (theta*180)/Math.PI ) , false); } } /** * A method to rotate the left motor forward */ public void rotateLeftMotorForward() { leftMotor.setSpeed( Constants.VEHICLE_FORWARD_SPEED_LOW ); leftMotor.forward(); } /** * A method to rotate the right motor forward */ public void rotateRightMotorForward() { rightMotor.setSpeed( Constants.VEHICLE_FORWARD_SPEED_LOW ); rightMotor.forward(); } /** * A method to drive the vehicle forward */ public void driveForward() { leftMotor.setAcceleration( Constants.VEHICLE_ACCELERATION ); rightMotor.setAcceleration( Constants.VEHICLE_ACCELERATION ); leftMotor.setSpeed( Constants.VEHICLE_ROTATE_SPEED ); rightMotor.setSpeed( Constants.VEHICLE_ROTATE_SPEED ); leftMotor.forward(); rightMotor.forward(); } /** * A method to rotate our vehicle counter-clockwise */ public void rotateCounterClockwise() { leftMotor.setSpeed( -Constants.VEHICLE_ROTATE_SPEED ); rightMotor.setSpeed( Constants.VEHICLE_ROTATE_SPEED ); leftMotor.backward(); rightMotor.forward(); } /** * A method to stopMotors our motors */ public void stopMotors() { leftMotor.stop(true); rightMotor.stop(false); } /** * Calculates the minimum angle to turn to. * * @param deltaX the x coordinate of our destination * @param deltaY the y coordinate of our destination * * @return the minimum angle we need to turn */ public double calculateMinAngle( double deltaX , double deltaY ) { // calculate the minimum angle double theta = Math.atan2( deltaX , deltaY ) - odometer.getTheta(); if ( theta < -Math.PI ) { theta += ( 2*Math.PI ); } else if ( theta > Math.PI ) { theta -= ( 2*Math.PI ); } return theta; } /** * Calculates the distance to a specific point. * * @param deltaX the x coordinate of our destination * @param deltaY the y coordinate of out destination * @return the distance to the point */ public double calculateDistanceToPoint( double deltaX , double deltaY ) { return Math.hypot( deltaX , deltaY ); } /** * Determine the angle our motors need to rotate in order for vehicle to turn a certain angle. * * @param angle the angle we want to turn * @return the tacho count that we need to rotate */ public int convertAngle( double angle ) { return convertDistance( Math.PI * Constants.TRACK_LENGTH * angle / 360.0 ); } /** * Determine how much the motor must rotate for vehicle to reach a certain distance. * * @param distance the distance we want to travel * @return the tacho count that we need to rotate */ public int convertDistance( double distance ) { return (int) ( (180.0 * distance) / (Math.PI * Constants.WHEEL_RADIUS) ); } /** * A method which waits until odometry correction finishes */ public void waitUntilCorrectionIsFinished() { stopMotors(); while ( odometer.isCorrecting() ) { // do nothing } } }
UTF-8
Java
6,546
java
Navigator.java
Java
[ { "context": "object used to navigate the vehicle.\n *\n * @author JohnWu\n */\npublic class Navigator {\n\n // objects\n ", "end": 185, "score": 0.9979896545410156, "start": 179, "tag": "NAME", "value": "JohnWu" } ]
null
[]
package main.controller; import lejos.hardware.motor.EV3LargeRegulatedMotor; import main.resource.Constants; /** * Navigator object used to navigate the vehicle. * * @author JohnWu */ public class Navigator { // objects private Odometer odometer; private EV3LargeRegulatedMotor leftMotor, rightMotor; /** * Default constructor for Navigator object. * * @param leftMotor the left motor EV3 object used in the robot * @param rightMotor the right motor EV3 object used in the robot * @param odometer the odometer controller used in the robot */ public Navigator( EV3LargeRegulatedMotor leftMotor , EV3LargeRegulatedMotor rightMotor , Odometer odometer ) { this.odometer = odometer; this.leftMotor = leftMotor; this.rightMotor = rightMotor; } /** * A method to drive our vehicle to a certain cartesian coordinate. * * @param x X-Coordinate * @param y Y-Coordinate */ public void travelTo( double x , double y ) { double deltaX = x - odometer.getX(); double deltaY = y - odometer.getY(); travelToX( odometer.getX() + deltaX ); travelToY( odometer.getY() + deltaY ); } /** * A method to travel to a specific x coordinate * * @param xCoordinate the x coordinate we want to travel to */ public void travelToX( double xCoordinate ) { // turn to the minimum angle turnTo( calculateMinAngle( xCoordinate - odometer.getX(), 0 ) ); // move to the specified point driveForward(); while ( Math.abs( odometer.getX() - xCoordinate ) > Constants.POINT_REACHED_THRESHOLD ) { if ( odometer.isCorrecting() ) { waitUntilCorrectionIsFinished(); driveForward(); } } stopMotors(); } /** * A method to travel to a specific y coordinate * * @param yCoordinate the y coordinate we want to travel to */ public void travelToY( double yCoordinate ) { // turn to the minimum angle turnTo( calculateMinAngle( 0, yCoordinate - odometer.getY() ) ); // move to the specified point driveForward(); while ( Math.abs( odometer.getY() - yCoordinate ) > Constants.POINT_REACHED_THRESHOLD ) { if ( odometer.isCorrecting() ) { waitUntilCorrectionIsFinished(); driveForward(); } } stopMotors(); } /** * A method to turn our vehicle to a certain angle in either direction * * @param theta the theta angle that we want to turn our vehicle */ public void turnTo( double theta ) { leftMotor.setSpeed( Constants.VEHICLE_ROTATE_SPEED ); rightMotor.setSpeed( Constants.VEHICLE_ROTATE_SPEED ); if( theta < 0 ) { // if angle is negative, turn to the left leftMotor.rotate( -convertAngle( -(theta*180)/Math.PI ) , true ); rightMotor.rotate( convertAngle( -(theta*180)/Math.PI ) , false ); } else { // angle is positive, turn to the right leftMotor.rotate( convertAngle( (theta*180)/Math.PI ) , true); rightMotor.rotate( -convertAngle( (theta*180)/Math.PI ) , false); } } /** * A method to rotate the left motor forward */ public void rotateLeftMotorForward() { leftMotor.setSpeed( Constants.VEHICLE_FORWARD_SPEED_LOW ); leftMotor.forward(); } /** * A method to rotate the right motor forward */ public void rotateRightMotorForward() { rightMotor.setSpeed( Constants.VEHICLE_FORWARD_SPEED_LOW ); rightMotor.forward(); } /** * A method to drive the vehicle forward */ public void driveForward() { leftMotor.setAcceleration( Constants.VEHICLE_ACCELERATION ); rightMotor.setAcceleration( Constants.VEHICLE_ACCELERATION ); leftMotor.setSpeed( Constants.VEHICLE_ROTATE_SPEED ); rightMotor.setSpeed( Constants.VEHICLE_ROTATE_SPEED ); leftMotor.forward(); rightMotor.forward(); } /** * A method to rotate our vehicle counter-clockwise */ public void rotateCounterClockwise() { leftMotor.setSpeed( -Constants.VEHICLE_ROTATE_SPEED ); rightMotor.setSpeed( Constants.VEHICLE_ROTATE_SPEED ); leftMotor.backward(); rightMotor.forward(); } /** * A method to stopMotors our motors */ public void stopMotors() { leftMotor.stop(true); rightMotor.stop(false); } /** * Calculates the minimum angle to turn to. * * @param deltaX the x coordinate of our destination * @param deltaY the y coordinate of our destination * * @return the minimum angle we need to turn */ public double calculateMinAngle( double deltaX , double deltaY ) { // calculate the minimum angle double theta = Math.atan2( deltaX , deltaY ) - odometer.getTheta(); if ( theta < -Math.PI ) { theta += ( 2*Math.PI ); } else if ( theta > Math.PI ) { theta -= ( 2*Math.PI ); } return theta; } /** * Calculates the distance to a specific point. * * @param deltaX the x coordinate of our destination * @param deltaY the y coordinate of out destination * @return the distance to the point */ public double calculateDistanceToPoint( double deltaX , double deltaY ) { return Math.hypot( deltaX , deltaY ); } /** * Determine the angle our motors need to rotate in order for vehicle to turn a certain angle. * * @param angle the angle we want to turn * @return the tacho count that we need to rotate */ public int convertAngle( double angle ) { return convertDistance( Math.PI * Constants.TRACK_LENGTH * angle / 360.0 ); } /** * Determine how much the motor must rotate for vehicle to reach a certain distance. * * @param distance the distance we want to travel * @return the tacho count that we need to rotate */ public int convertDistance( double distance ) { return (int) ( (180.0 * distance) / (Math.PI * Constants.WHEEL_RADIUS) ); } /** * A method which waits until odometry correction finishes */ public void waitUntilCorrectionIsFinished() { stopMotors(); while ( odometer.isCorrecting() ) { // do nothing } } }
6,546
0.609074
0.604186
209
30.320574
26.610744
114
false
false
0
0
0
0
0
0
0.325359
false
false
7
05a4a15250b74868cde0f0f8269aa30e7d2e3876
21,294,447,890,846
18de9b202e2982d0991c82ea9caf02b8a7dcf355
/src/com/dabbility/auskunft/model/Verbindung.java
97785671951d4b2d3f4fa27af6946c558197bbbb
[]
no_license
cfgCarl/MobilitaetsauskunftUpload
https://github.com/cfgCarl/MobilitaetsauskunftUpload
030c99c7081b5d60eac77e09a37a69ed5f1f2473
6ed041ee363e9a6814c42ce08c7932179e83bf16
refs/heads/master
"2020-06-23T16:15:28.417000"
"2019-07-24T17:37:26"
"2019-07-24T17:37:26"
198,675,930
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dabbility.auskunft.model; import com.sothawo.mapjfx.Coordinate; import java.util.Date; import java.util.List; //Verbindungsobjekt public class Verbindung { Ort startPunkt; Ort zielPunkt; long dauer;//millisekunden Date abfahrtsZeit; Date ankunftsZeit; Verkehrsmittel verkehrsmittel; List<Coordinate> coordListe; double entfernung; String name = null; public String getName() { return name; } public void setName(String name) { this.name = name; } public Emissionen getEmmissionen() { Emissionen emi; emi = new Emissionen(verkehrsmittel.emissionen.getTreibhausgase() * entfernung, verkehrsmittel.emissionen.getKohlenmonoxid() * entfernung, verkehrsmittel.emissionen.getKohlenwasserstoffe() * entfernung, verkehrsmittel.emissionen.getStickoxid() * entfernung, verkehrsmittel.emissionen.getFeinstaub() * entfernung); return emi; } public double getEntfernung() { return entfernung; } public void setEntfernung(double entfernung) { this.entfernung = entfernung; } public void setEntfernung(List<Coordinate> coordListe) { double entf = 0; for(int i = 0; i< (coordListe.size() - 1); i++) { double distance = 9999999; double dx = (111.3 * Math.cos((coordListe.get(i).getLatitude() + coordListe.get(i+1).getLatitude()) / 2)) * (coordListe.get(i).getLongitude() - coordListe.get(i+1).getLongitude()); double dy = 111.3 * (coordListe.get(i).getLatitude() - coordListe.get(i+1).getLatitude()); distance = Math.sqrt((dx * dx) + (dy * dy)); entf = entf + distance; } this.entfernung = entf; } public List<Coordinate> getCoordListe() { return coordListe; } public void setCoordListe(List<Coordinate> coordListe) { setEntfernung(coordListe); this.coordListe = coordListe; } public Verkehrsmittel getVerkehrsmittel() { return verkehrsmittel; } public void setVerkehrsmittel(Verkehrsmittel verkehrsmittel) { this.verkehrsmittel = verkehrsmittel; } public Ort getStartPunkt() { return startPunkt; } public void setStartPunkt(Ort startPunkt) { this.startPunkt = startPunkt; } public Ort getZielPunkt() { return zielPunkt; } public void setZielPunkt(Ort zielPunkt) { this.zielPunkt = zielPunkt; } public long getDauer() { return dauer; } public void setDauer(long dauer) { this.dauer = dauer; } public Date getAbfahrtsZeit() { return abfahrtsZeit; } public void setAbfahrtsZeit(Date abfahrtsZeit) { this.abfahrtsZeit = abfahrtsZeit; } public Date getAnkunftsZeit() { return ankunftsZeit; } public void setAnkunftsZeit(Date ankunftsZeit) { this.ankunftsZeit = ankunftsZeit; } public Emissionen emissionenBerechnen(Emissionen vmEmi, double km) { vmEmi.setFeinstaub(vmEmi.getFeinstaub() * km); vmEmi.setKohlenmonoxid(vmEmi.getKohlenmonoxid() * km); vmEmi.setKohlenwasserstoffe(vmEmi.getKohlenwasserstoffe() * km); vmEmi.setStickoxid(vmEmi.getStickoxid() * km); vmEmi.setTreibhausgase(vmEmi.getTreibhausgase() * km); return vmEmi; } }
UTF-8
Java
3,371
java
Verbindung.java
Java
[]
null
[]
package com.dabbility.auskunft.model; import com.sothawo.mapjfx.Coordinate; import java.util.Date; import java.util.List; //Verbindungsobjekt public class Verbindung { Ort startPunkt; Ort zielPunkt; long dauer;//millisekunden Date abfahrtsZeit; Date ankunftsZeit; Verkehrsmittel verkehrsmittel; List<Coordinate> coordListe; double entfernung; String name = null; public String getName() { return name; } public void setName(String name) { this.name = name; } public Emissionen getEmmissionen() { Emissionen emi; emi = new Emissionen(verkehrsmittel.emissionen.getTreibhausgase() * entfernung, verkehrsmittel.emissionen.getKohlenmonoxid() * entfernung, verkehrsmittel.emissionen.getKohlenwasserstoffe() * entfernung, verkehrsmittel.emissionen.getStickoxid() * entfernung, verkehrsmittel.emissionen.getFeinstaub() * entfernung); return emi; } public double getEntfernung() { return entfernung; } public void setEntfernung(double entfernung) { this.entfernung = entfernung; } public void setEntfernung(List<Coordinate> coordListe) { double entf = 0; for(int i = 0; i< (coordListe.size() - 1); i++) { double distance = 9999999; double dx = (111.3 * Math.cos((coordListe.get(i).getLatitude() + coordListe.get(i+1).getLatitude()) / 2)) * (coordListe.get(i).getLongitude() - coordListe.get(i+1).getLongitude()); double dy = 111.3 * (coordListe.get(i).getLatitude() - coordListe.get(i+1).getLatitude()); distance = Math.sqrt((dx * dx) + (dy * dy)); entf = entf + distance; } this.entfernung = entf; } public List<Coordinate> getCoordListe() { return coordListe; } public void setCoordListe(List<Coordinate> coordListe) { setEntfernung(coordListe); this.coordListe = coordListe; } public Verkehrsmittel getVerkehrsmittel() { return verkehrsmittel; } public void setVerkehrsmittel(Verkehrsmittel verkehrsmittel) { this.verkehrsmittel = verkehrsmittel; } public Ort getStartPunkt() { return startPunkt; } public void setStartPunkt(Ort startPunkt) { this.startPunkt = startPunkt; } public Ort getZielPunkt() { return zielPunkt; } public void setZielPunkt(Ort zielPunkt) { this.zielPunkt = zielPunkt; } public long getDauer() { return dauer; } public void setDauer(long dauer) { this.dauer = dauer; } public Date getAbfahrtsZeit() { return abfahrtsZeit; } public void setAbfahrtsZeit(Date abfahrtsZeit) { this.abfahrtsZeit = abfahrtsZeit; } public Date getAnkunftsZeit() { return ankunftsZeit; } public void setAnkunftsZeit(Date ankunftsZeit) { this.ankunftsZeit = ankunftsZeit; } public Emissionen emissionenBerechnen(Emissionen vmEmi, double km) { vmEmi.setFeinstaub(vmEmi.getFeinstaub() * km); vmEmi.setKohlenmonoxid(vmEmi.getKohlenmonoxid() * km); vmEmi.setKohlenwasserstoffe(vmEmi.getKohlenwasserstoffe() * km); vmEmi.setStickoxid(vmEmi.getStickoxid() * km); vmEmi.setTreibhausgase(vmEmi.getTreibhausgase() * km); return vmEmi; } }
3,371
0.649362
0.642836
121
26.859505
37.411781
321
false
false
0
0
0
0
0
0
0.454545
false
false
7
0d73d484e55b0727a3265f61894d7100cb673668
8,272,107,019,315
50e3616c7d13c78f493082762b5b65caec730d2f
/opensrp-app/src/main/java/org/smartregister/view/contract/SmartRegisterClient.java
21fe46c9dbabf94f303b9069a7440ce559feed81
[ "Apache-2.0" ]
permissive
d-tree-org/opensrp-client-core
https://github.com/d-tree-org/opensrp-client-core
70ce6db85577cc9f94efaea8fb2d872d0305d9db
57a0f70d51985a8d60abe552d9eb67f9f257046f
refs/heads/master
"2023-01-31T04:00:03.093000"
"2021-03-10T13:12:33"
"2021-03-10T13:12:33"
215,468,074
1
0
NOASSERTION
false
"2023-01-23T14:47:05"
"2019-10-16T05:55:42"
"2021-03-10T13:13:24"
"2023-01-23T14:47:04"
19,668
1
0
2
Java
false
false
package org.smartregister.view.contract; import org.smartregister.util.IntegerUtil; import java.util.Comparator; public interface SmartRegisterClient { Comparator<SmartRegisterClient> NAME_COMPARATOR = new Comparator<SmartRegisterClient>() { @Override public int compare(SmartRegisterClient client, SmartRegisterClient anotherClient) { return client.compareName(anotherClient); } }; Comparator<SmartRegisterClient> HIGH_PRIORITY_COMPARATOR = new Comparator<SmartRegisterClient>() { @Override public int compare(SmartRegisterClient client, SmartRegisterClient anotherClient) { return client.isHighPriority() == anotherClient.isHighPriority() ? client.name() .compareToIgnoreCase(anotherClient.name()) : anotherClient.isHighPriority() ? 1 : -1; } }; Comparator<SmartRegisterClient> HIGH_RISK_COMPARATOR = new Comparator<SmartRegisterClient>() { @Override public int compare(SmartRegisterClient client, SmartRegisterClient anotherClient) { return client.isHighRisk() == anotherClient.isHighRisk() ? client.name() .compareToIgnoreCase(anotherClient.name()) : anotherClient.isHighRisk() ? 1 : -1; } }; Comparator<SmartRegisterClient> BPL_COMPARATOR = new Comparator<SmartRegisterClient>() { @Override public int compare(SmartRegisterClient client, SmartRegisterClient anotherClient) { if ((client.isBPL() && anotherClient.isBPL()) || (!client.isBPL() && !anotherClient .isBPL())) { return client.compareName(anotherClient); } else { return anotherClient.isBPL() ? 1 : -1; } } }; Comparator<SmartRegisterClient> SC_COMPARATOR = new Comparator<SmartRegisterClient>() { @Override public int compare(SmartRegisterClient client, SmartRegisterClient anotherClient) { if ((client.isSC() && anotherClient.isSC()) || (!client.isSC() && !anotherClient .isSC())) { return client.compareName(anotherClient); } else { return anotherClient.isSC() ? 1 : -1; } } }; Comparator<SmartRegisterClient> ST_COMPARATOR = new Comparator<SmartRegisterClient>() { @Override public int compare(SmartRegisterClient client, SmartRegisterClient anotherClient) { if ((client.isST() && anotherClient.isST()) || (!client.isST() && !anotherClient .isST())) { return client.compareName(anotherClient); } else { return anotherClient.isST() ? 1 : -1; } } }; Comparator<SmartRegisterClient> AGE_COMPARATOR = new Comparator<SmartRegisterClient>() { @Override public int compare(SmartRegisterClient client, SmartRegisterClient anotherClient) { return IntegerUtil.compare(client.ageInDays(), anotherClient.ageInDays()); } }; Comparator<SmartRegisterClient> HR_COMPARATOR = new Comparator<SmartRegisterClient>() { @Override public int compare(SmartRegisterClient client, SmartRegisterClient anotherClient) { if ((client.isHighRisk() && anotherClient.isHighRisk()) || (!client.isHighRisk() && !anotherClient.isHighRisk())) { return client.compareName(anotherClient); } else { return anotherClient.isHighRisk() ? 1 : -1; } } }; String entityId(); String name(); String displayName(); String village(); String wifeName(); String husbandName(); int age(); int ageInDays(); String ageInString(); boolean isSC(); boolean isST(); boolean isHighRisk(); boolean isHighPriority(); boolean isBPL(); String profilePhotoPath(); String locationStatus(); boolean satisfiesFilter(String filterCriterion); int compareName(SmartRegisterClient client); }
UTF-8
Java
4,194
java
SmartRegisterClient.java
Java
[]
null
[]
package org.smartregister.view.contract; import org.smartregister.util.IntegerUtil; import java.util.Comparator; public interface SmartRegisterClient { Comparator<SmartRegisterClient> NAME_COMPARATOR = new Comparator<SmartRegisterClient>() { @Override public int compare(SmartRegisterClient client, SmartRegisterClient anotherClient) { return client.compareName(anotherClient); } }; Comparator<SmartRegisterClient> HIGH_PRIORITY_COMPARATOR = new Comparator<SmartRegisterClient>() { @Override public int compare(SmartRegisterClient client, SmartRegisterClient anotherClient) { return client.isHighPriority() == anotherClient.isHighPriority() ? client.name() .compareToIgnoreCase(anotherClient.name()) : anotherClient.isHighPriority() ? 1 : -1; } }; Comparator<SmartRegisterClient> HIGH_RISK_COMPARATOR = new Comparator<SmartRegisterClient>() { @Override public int compare(SmartRegisterClient client, SmartRegisterClient anotherClient) { return client.isHighRisk() == anotherClient.isHighRisk() ? client.name() .compareToIgnoreCase(anotherClient.name()) : anotherClient.isHighRisk() ? 1 : -1; } }; Comparator<SmartRegisterClient> BPL_COMPARATOR = new Comparator<SmartRegisterClient>() { @Override public int compare(SmartRegisterClient client, SmartRegisterClient anotherClient) { if ((client.isBPL() && anotherClient.isBPL()) || (!client.isBPL() && !anotherClient .isBPL())) { return client.compareName(anotherClient); } else { return anotherClient.isBPL() ? 1 : -1; } } }; Comparator<SmartRegisterClient> SC_COMPARATOR = new Comparator<SmartRegisterClient>() { @Override public int compare(SmartRegisterClient client, SmartRegisterClient anotherClient) { if ((client.isSC() && anotherClient.isSC()) || (!client.isSC() && !anotherClient .isSC())) { return client.compareName(anotherClient); } else { return anotherClient.isSC() ? 1 : -1; } } }; Comparator<SmartRegisterClient> ST_COMPARATOR = new Comparator<SmartRegisterClient>() { @Override public int compare(SmartRegisterClient client, SmartRegisterClient anotherClient) { if ((client.isST() && anotherClient.isST()) || (!client.isST() && !anotherClient .isST())) { return client.compareName(anotherClient); } else { return anotherClient.isST() ? 1 : -1; } } }; Comparator<SmartRegisterClient> AGE_COMPARATOR = new Comparator<SmartRegisterClient>() { @Override public int compare(SmartRegisterClient client, SmartRegisterClient anotherClient) { return IntegerUtil.compare(client.ageInDays(), anotherClient.ageInDays()); } }; Comparator<SmartRegisterClient> HR_COMPARATOR = new Comparator<SmartRegisterClient>() { @Override public int compare(SmartRegisterClient client, SmartRegisterClient anotherClient) { if ((client.isHighRisk() && anotherClient.isHighRisk()) || (!client.isHighRisk() && !anotherClient.isHighRisk())) { return client.compareName(anotherClient); } else { return anotherClient.isHighRisk() ? 1 : -1; } } }; String entityId(); String name(); String displayName(); String village(); String wifeName(); String husbandName(); int age(); int ageInDays(); String ageInString(); boolean isSC(); boolean isST(); boolean isHighRisk(); boolean isHighPriority(); boolean isBPL(); String profilePhotoPath(); String locationStatus(); boolean satisfiesFilter(String filterCriterion); int compareName(SmartRegisterClient client); }
4,194
0.609919
0.607058
125
32.551998
33.077717
100
false
false
0
0
0
0
0
0
0.464
false
false
7
cf1805cadb290a173b2af0046bd1af8da62e2468
24,850,680,825,628
c51454a93d93ef1b87a5f0e0db9ffdb193763246
/Practice/src/JavaLearning/arrayParticularNumber.java
e8e0306fc8a254ae9e350baec038d73f5ff12be0
[]
no_license
ViktoryaKaramyan/QA
https://github.com/ViktoryaKaramyan/QA
e8c1931763ec6e1f2d8b6291a746dbe174c85538
54fa21d4cff66b043e3cfe38bd20c372f3ea776b
refs/heads/master
"2021-05-05T23:34:21.898000"
"2018-11-26T07:32:55"
"2018-11-26T07:32:55"
116,800,633
0
0
null
false
"2018-01-09T10:39:08"
"2018-01-09T10:20:05"
"2018-01-09T10:20:05"
"2018-01-09T10:39:08"
0
0
0
0
null
false
null
package JavaLearning; import java.util.Scanner; public class arrayParticularNumber { public static void main(String[] args) { // TODO Auto-generated method stub @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array"); int lenght = sc.nextInt(); System.out.println("Enter the numbers of the array"); int[] myArray = new int[lenght]; for (int i = 0; i < myArray.length; i++) { myArray[i] = sc.nextInt(); } int i = 0; for (i = 0; i < myArray.length; i++) { if (myArray[i] == 13) { System.out.println("Number exists"); } } } }
UTF-8
Java
625
java
arrayParticularNumber.java
Java
[]
null
[]
package JavaLearning; import java.util.Scanner; public class arrayParticularNumber { public static void main(String[] args) { // TODO Auto-generated method stub @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array"); int lenght = sc.nextInt(); System.out.println("Enter the numbers of the array"); int[] myArray = new int[lenght]; for (int i = 0; i < myArray.length; i++) { myArray[i] = sc.nextInt(); } int i = 0; for (i = 0; i < myArray.length; i++) { if (myArray[i] == 13) { System.out.println("Number exists"); } } } }
625
0.6464
0.6384
26
23.038462
18.013842
55
false
false
0
0
0
0
0
0
1.961538
false
false
7
ef5aafd083ded46dd67e181293223c6316854761
16,020,228,055,986
fcec678e6152e7359b1a2a654034dcd8ef70977e
/src/main/java/br/inatel/ssic/rsa/controller/ColaboradorController.java
0986006a0ab5560f214aad3e109e853576812599
[]
no_license
gabriel-mars/rsa-manager
https://github.com/gabriel-mars/rsa-manager
3fb911b527b842649620c8c5c2581e7bfa6d18c1
55dac7adb534b3f001ab6aa93d44514458606769
refs/heads/master
"2022-04-24T03:13:52.148000"
"2020-04-24T14:28:19"
"2020-04-24T14:28:19"
230,514,542
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.inatel.ssic.rsa.controller; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import br.inatel.ssic.rsa.model.entity.Colaborador; import br.inatel.ssic.rsa.model.entity.Ferias; import br.inatel.ssic.rsa.model.entity.InatelNRO; import br.inatel.ssic.rsa.model.entity.Item; import br.inatel.ssic.rsa.model.entity.Pessoa; import br.inatel.ssic.rsa.model.service.ColaboradorService; import br.inatel.ssic.rsa.model.service.FeriasService; import br.inatel.ssic.rsa.model.service.RelatorioService; @Controller public class ColaboradorController { @Autowired private ColaboradorService service; @Autowired private RelatorioService relService; @Autowired private FeriasService ferService; @PostMapping("/colaborador/entrar") public String verificarLogin(Pessoa pessoa, HttpSession session, RedirectAttributes attr) { Colaborador sessaoAtual = new Colaborador(); sessaoAtual = (Colaborador) session.getAttribute("colaboradorLogado"); try { if(sessaoAtual != null) { session.removeAttribute("colaboradorLogado"); } Colaborador colaborador = service.verifyLogin(pessoa.getEmail(), pessoa.getSenha()); session.setAttribute("colaboradorLogado", colaborador); return "redirect:/dashboard"; } catch (Exception e) { attr.addFlashAttribute("fail", "Dados incorretos. Tente novamente."); return "redirect:/"; } } @PostMapping("/colaborador/update/senha") public String updateSenha(Pessoa pessoa, HttpSession session, RedirectAttributes attr) throws Exception { Colaborador sessaoAtual = new Colaborador(); sessaoAtual = (Colaborador) session.getAttribute("colaboradorLogado"); Colaborador colaborador = service.verifyLogin(sessaoAtual.getEmail(), sessaoAtual.getSenha()); if(colaborador.getSenha().intern().equals(pessoa.getNome())) { attr.addFlashAttribute("fail", "Sua nova senha não deve ser igual a atual."); return "redirect:/colaborador/senha"; } else if(!colaborador.getSenha().intern().equals(pessoa.getSenha().intern())) { attr.addFlashAttribute("fail", "Necessário informar a senha atual."); return "redirect:/colaborador/senha"; } else if(!pessoa.getEmail().intern().equals(pessoa.getNome())) { attr.addFlashAttribute("fail", "Nova senha e confirmação devem ser iguais."); return "redirect:/colaborador/senha"; } else { try { colaborador.setSenha(pessoa.getEmail()); service.updateSenha(colaborador); attr.addFlashAttribute("success", "Senha alterada."); colaborador = service.verifyLogin(colaborador.getEmail(), colaborador.getSenha()); session.removeAttribute("colaboradorLogado"); session.setAttribute("colaboradorLogado", colaborador); return "redirect:/colaborador/senha"; } catch (Exception e) { attr.addFlashAttribute("fail", "Não foi possível alterar a senha."); return "redirect:/colaborador/senha"; } } } @GetMapping("/dashboard") public String getDashboard(HttpSession session, ModelMap model) { Object[] aux = null; Object[] auxItem = null; Colaborador sessaoAtual = new Colaborador(); Ferias ferias = new Ferias(); Item item = new Item(); Item aux2 = new Item(); Item aux3 = new Item(); int media = 0; int totalMes = 0; sessaoAtual = (Colaborador) session.getAttribute("colaboradorLogado"); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy"); LocalDate lastMouth = LocalDate.now().withDayOfMonth(1).minusDays(1); LocalDate localDate = LocalDate.now(); item.setCentroRsa(sessaoAtual.getOrganizacao().toUpperCase()); item.setDataAnalise(dtf.format(localDate)); // Mês atual List<Object[]> dadosMedia = relService.findItensByMes(item); if(dadosMedia.size() > 0) { aux = dadosMedia.get(0); aux2.setItem(aux[1].toString()); // Máximo do mês for(int i = 0; i < dadosMedia.size(); i++) { aux = dadosMedia.get(i); media += Integer.parseInt(aux[1].toString()); totalMes += Integer.parseInt(aux[2].toString()); } aux2.setCentroRsa("" + totalMes); // Totoal de atividades do mês aux2.setInspetor("" + media); // Total de atividades AP + RE do mês media = media / dadosMedia.size(); aux2.setSite("" + media); // Média do mês // Último mês item.setDataAnalise(dtf.format(lastMouth)); List<Object[]> dadosLastMouth = relService.findItensByMes(item); auxItem = dadosLastMouth.get(0); aux3.setItem(auxItem[1].toString()); // Máximo do mês media = 0; totalMes = 0; for(int i = 0; i < dadosLastMouth.size(); i++) { auxItem = dadosLastMouth.get(i); media += Integer.parseInt(auxItem[1].toString()); totalMes += Integer.parseInt(auxItem[2].toString()); } aux3.setCentroRsa("" + totalMes); // Totoal de atividades do mês aux3.setInspetor("" + media); // Total de atividades AP + RE do mês media = media / dadosLastMouth.size(); aux3.setSite("" + media); // Média do mês } DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); LocalDate today = LocalDate.now(); String dia = today.getDayOfWeek().toString(); switch (dia) { case "MONDAY": ferias.setInicioFerias(formatter.format(today.minusDays(1)).toString()); ferias.setFimFerias(formatter.format(today.plusDays(5)).toString()); break; case "TUESDAY": ferias.setInicioFerias(formatter.format(today.minusDays(2)).toString()); ferias.setFimFerias(formatter.format(today.plusDays(4)).toString()); break; case "WEDNESDAY": ferias.setInicioFerias(formatter.format(today.minusDays(3)).toString()); ferias.setFimFerias(formatter.format(today.plusDays(3)).toString()); break; case "THURSDAY": ferias.setInicioFerias(formatter.format(today.minusDays(4)).toString()); ferias.setFimFerias(formatter.format(today.plusDays(2)).toString()); break; case "FRIDAY": ferias.setInicioFerias(formatter.format(today.minusDays(5)).toString()); ferias.setFimFerias(formatter.format(today.plusDays(1)).toString()); break; case "SATURDAY": ferias.setInicioFerias(formatter.format(today.minusDays(6)).toString()); ferias.setFimFerias(formatter.format(today).toString()); break; case "SUNDAY": ferias.setInicioFerias(formatter.format(today).toString()); ferias.setFimFerias(formatter.format(today.plusDays(7)).toString()); break; default: break; } List<Object[]> colaboradores = ferService.findFeriasBySemana(ferias); model.addAttribute("colaboradores", colaboradores); model.addAttribute("item", aux2); model.addAttribute("item2", aux3); return "fragments/main"; } @PostMapping("/colaborador/sair") public String logoutColaborador(HttpSession session, RedirectAttributes attr) { session.invalidate(); attr.addFlashAttribute("success", "Até logo!"); return "redirect:/"; } @PostMapping("/colaborador/salvar") public String salvarColaborador(Colaborador colaborador, RedirectAttributes attr) { service.save(colaborador); attr.addFlashAttribute("success", "Colaborador cadastrado."); return "redirect:/colaborador/cadastro"; } @RequestMapping(value = "/colaborador/listar", method = RequestMethod.GET) public String listarColaboradores(ModelMap model, HttpSession session) { List<Pessoa> colaboradores = new ArrayList<Pessoa>(); Colaborador sessaoAtual = new Colaborador(); sessaoAtual = (Colaborador) session.getAttribute("colaboradorLogado"); colaboradores = service.findByOrganizacao(sessaoAtual.getOrganizacao()); model.addAttribute("colaboradores", colaboradores); return "colaborador/lista"; } @PostMapping("/colaborador/update") public String editarColaborador(Colaborador colaborador, RedirectAttributes attr) { service.update(colaborador); attr.addFlashAttribute("success", "Colaborador atualizado."); return "redirect:/colaborador/cadastro"; } @PostMapping("/colaborador/cadastro/novo") public String salvarSolicitacao(Colaborador colaborador, RedirectAttributes attr) { if(colaborador.getSenha().intern().equals(colaborador.getDataInicioRSA())) { colaborador.setDataInicioRSA(""); service.save(colaborador); attr.addFlashAttribute("success", "Solicitação realizada."); return "redirect:/"; } else { attr.addFlashAttribute("fail", "As senhas devem ser correspondentes."); return "redirect:/colaborado/solicitar"; } } @PostMapping("/colaborador/vincular/nomes") public String vincularColaboradores(InatelNRO colaborador, RedirectAttributes attr) { try { service.linkNames(colaborador); attr.addFlashAttribute("success", "Nomes vinculados."); } catch (Exception e) { attr.addFlashAttribute("fail", "Não foi possível vincular os nomes."); } return "redirect:/colaborador/vincular"; } }
UTF-8
Java
9,455
java
ColaboradorController.java
Java
[]
null
[]
package br.inatel.ssic.rsa.controller; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import br.inatel.ssic.rsa.model.entity.Colaborador; import br.inatel.ssic.rsa.model.entity.Ferias; import br.inatel.ssic.rsa.model.entity.InatelNRO; import br.inatel.ssic.rsa.model.entity.Item; import br.inatel.ssic.rsa.model.entity.Pessoa; import br.inatel.ssic.rsa.model.service.ColaboradorService; import br.inatel.ssic.rsa.model.service.FeriasService; import br.inatel.ssic.rsa.model.service.RelatorioService; @Controller public class ColaboradorController { @Autowired private ColaboradorService service; @Autowired private RelatorioService relService; @Autowired private FeriasService ferService; @PostMapping("/colaborador/entrar") public String verificarLogin(Pessoa pessoa, HttpSession session, RedirectAttributes attr) { Colaborador sessaoAtual = new Colaborador(); sessaoAtual = (Colaborador) session.getAttribute("colaboradorLogado"); try { if(sessaoAtual != null) { session.removeAttribute("colaboradorLogado"); } Colaborador colaborador = service.verifyLogin(pessoa.getEmail(), pessoa.getSenha()); session.setAttribute("colaboradorLogado", colaborador); return "redirect:/dashboard"; } catch (Exception e) { attr.addFlashAttribute("fail", "Dados incorretos. Tente novamente."); return "redirect:/"; } } @PostMapping("/colaborador/update/senha") public String updateSenha(Pessoa pessoa, HttpSession session, RedirectAttributes attr) throws Exception { Colaborador sessaoAtual = new Colaborador(); sessaoAtual = (Colaborador) session.getAttribute("colaboradorLogado"); Colaborador colaborador = service.verifyLogin(sessaoAtual.getEmail(), sessaoAtual.getSenha()); if(colaborador.getSenha().intern().equals(pessoa.getNome())) { attr.addFlashAttribute("fail", "Sua nova senha não deve ser igual a atual."); return "redirect:/colaborador/senha"; } else if(!colaborador.getSenha().intern().equals(pessoa.getSenha().intern())) { attr.addFlashAttribute("fail", "Necessário informar a senha atual."); return "redirect:/colaborador/senha"; } else if(!pessoa.getEmail().intern().equals(pessoa.getNome())) { attr.addFlashAttribute("fail", "Nova senha e confirmação devem ser iguais."); return "redirect:/colaborador/senha"; } else { try { colaborador.setSenha(pessoa.getEmail()); service.updateSenha(colaborador); attr.addFlashAttribute("success", "Senha alterada."); colaborador = service.verifyLogin(colaborador.getEmail(), colaborador.getSenha()); session.removeAttribute("colaboradorLogado"); session.setAttribute("colaboradorLogado", colaborador); return "redirect:/colaborador/senha"; } catch (Exception e) { attr.addFlashAttribute("fail", "Não foi possível alterar a senha."); return "redirect:/colaborador/senha"; } } } @GetMapping("/dashboard") public String getDashboard(HttpSession session, ModelMap model) { Object[] aux = null; Object[] auxItem = null; Colaborador sessaoAtual = new Colaborador(); Ferias ferias = new Ferias(); Item item = new Item(); Item aux2 = new Item(); Item aux3 = new Item(); int media = 0; int totalMes = 0; sessaoAtual = (Colaborador) session.getAttribute("colaboradorLogado"); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy"); LocalDate lastMouth = LocalDate.now().withDayOfMonth(1).minusDays(1); LocalDate localDate = LocalDate.now(); item.setCentroRsa(sessaoAtual.getOrganizacao().toUpperCase()); item.setDataAnalise(dtf.format(localDate)); // Mês atual List<Object[]> dadosMedia = relService.findItensByMes(item); if(dadosMedia.size() > 0) { aux = dadosMedia.get(0); aux2.setItem(aux[1].toString()); // Máximo do mês for(int i = 0; i < dadosMedia.size(); i++) { aux = dadosMedia.get(i); media += Integer.parseInt(aux[1].toString()); totalMes += Integer.parseInt(aux[2].toString()); } aux2.setCentroRsa("" + totalMes); // Totoal de atividades do mês aux2.setInspetor("" + media); // Total de atividades AP + RE do mês media = media / dadosMedia.size(); aux2.setSite("" + media); // Média do mês // Último mês item.setDataAnalise(dtf.format(lastMouth)); List<Object[]> dadosLastMouth = relService.findItensByMes(item); auxItem = dadosLastMouth.get(0); aux3.setItem(auxItem[1].toString()); // Máximo do mês media = 0; totalMes = 0; for(int i = 0; i < dadosLastMouth.size(); i++) { auxItem = dadosLastMouth.get(i); media += Integer.parseInt(auxItem[1].toString()); totalMes += Integer.parseInt(auxItem[2].toString()); } aux3.setCentroRsa("" + totalMes); // Totoal de atividades do mês aux3.setInspetor("" + media); // Total de atividades AP + RE do mês media = media / dadosLastMouth.size(); aux3.setSite("" + media); // Média do mês } DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); LocalDate today = LocalDate.now(); String dia = today.getDayOfWeek().toString(); switch (dia) { case "MONDAY": ferias.setInicioFerias(formatter.format(today.minusDays(1)).toString()); ferias.setFimFerias(formatter.format(today.plusDays(5)).toString()); break; case "TUESDAY": ferias.setInicioFerias(formatter.format(today.minusDays(2)).toString()); ferias.setFimFerias(formatter.format(today.plusDays(4)).toString()); break; case "WEDNESDAY": ferias.setInicioFerias(formatter.format(today.minusDays(3)).toString()); ferias.setFimFerias(formatter.format(today.plusDays(3)).toString()); break; case "THURSDAY": ferias.setInicioFerias(formatter.format(today.minusDays(4)).toString()); ferias.setFimFerias(formatter.format(today.plusDays(2)).toString()); break; case "FRIDAY": ferias.setInicioFerias(formatter.format(today.minusDays(5)).toString()); ferias.setFimFerias(formatter.format(today.plusDays(1)).toString()); break; case "SATURDAY": ferias.setInicioFerias(formatter.format(today.minusDays(6)).toString()); ferias.setFimFerias(formatter.format(today).toString()); break; case "SUNDAY": ferias.setInicioFerias(formatter.format(today).toString()); ferias.setFimFerias(formatter.format(today.plusDays(7)).toString()); break; default: break; } List<Object[]> colaboradores = ferService.findFeriasBySemana(ferias); model.addAttribute("colaboradores", colaboradores); model.addAttribute("item", aux2); model.addAttribute("item2", aux3); return "fragments/main"; } @PostMapping("/colaborador/sair") public String logoutColaborador(HttpSession session, RedirectAttributes attr) { session.invalidate(); attr.addFlashAttribute("success", "Até logo!"); return "redirect:/"; } @PostMapping("/colaborador/salvar") public String salvarColaborador(Colaborador colaborador, RedirectAttributes attr) { service.save(colaborador); attr.addFlashAttribute("success", "Colaborador cadastrado."); return "redirect:/colaborador/cadastro"; } @RequestMapping(value = "/colaborador/listar", method = RequestMethod.GET) public String listarColaboradores(ModelMap model, HttpSession session) { List<Pessoa> colaboradores = new ArrayList<Pessoa>(); Colaborador sessaoAtual = new Colaborador(); sessaoAtual = (Colaborador) session.getAttribute("colaboradorLogado"); colaboradores = service.findByOrganizacao(sessaoAtual.getOrganizacao()); model.addAttribute("colaboradores", colaboradores); return "colaborador/lista"; } @PostMapping("/colaborador/update") public String editarColaborador(Colaborador colaborador, RedirectAttributes attr) { service.update(colaborador); attr.addFlashAttribute("success", "Colaborador atualizado."); return "redirect:/colaborador/cadastro"; } @PostMapping("/colaborador/cadastro/novo") public String salvarSolicitacao(Colaborador colaborador, RedirectAttributes attr) { if(colaborador.getSenha().intern().equals(colaborador.getDataInicioRSA())) { colaborador.setDataInicioRSA(""); service.save(colaborador); attr.addFlashAttribute("success", "Solicitação realizada."); return "redirect:/"; } else { attr.addFlashAttribute("fail", "As senhas devem ser correspondentes."); return "redirect:/colaborado/solicitar"; } } @PostMapping("/colaborador/vincular/nomes") public String vincularColaboradores(InatelNRO colaborador, RedirectAttributes attr) { try { service.linkNames(colaborador); attr.addFlashAttribute("success", "Nomes vinculados."); } catch (Exception e) { attr.addFlashAttribute("fail", "Não foi possível vincular os nomes."); } return "redirect:/colaborador/vincular"; } }
9,455
0.72171
0.717255
277
33.039711
27.717018
106
false
false
0
0
0
0
0
0
2.830325
false
false
7
b255762718e41049bffbc94e67dc3a66c4c143b0
20,160,576,528,459
8151cc1dcbd10228c6d24c1bb63c7130b78a5642
/dubbo-sdk/src/main/java/com/jxtb/redis/CacheOperation.java
d9c6bc813c92134fded453196e48e41732f71c6b
[]
no_license
qiutianbao/springboot
https://github.com/qiutianbao/springboot
174e2af0226e73af12a2b1b621b8fee348b52b75
193a5ec3e3bfebcefed80950377453fc7898e28f
refs/heads/master
"2022-06-17T08:48:52.467000"
"2019-12-18T14:14:18"
"2019-12-18T14:14:18"
167,697,397
0
0
null
false
"2022-06-17T02:05:00"
"2019-01-26T14:24:17"
"2019-12-18T14:15:22"
"2022-06-17T02:04:56"
137,438
0
0
13
Java
false
false
package com.jxtb.redis; import java.util.List; import java.util.Set; /** * Created by jxtb on 2019/6/12. */ public interface CacheOperation { /** * 加入缓存 * @param key * @param value */ void put(String key, String value); /** * 加入缓存 * @param key * @param value */ void put(byte[] key, byte[] value); /** * 加入缓存 * @param key * @param value * @param timeout */ void put(byte[] key, byte[] value, int timeout); /** * 加入缓存 * @param key * @param value * @param seconds seconds秒之后失效 */ void put(String key, String value, int seconds); void putAll(String key, List<String> value); /** * 从缓存中获取信息 * @param key * @return */ String get(String key); /** * 从缓存中获取信息 * @param key * @return */ byte[] get(byte[] key); List<String> getAll(String key); /** * 缓存失效 * @param key */ void invalid(String key); /** * 删除缓存 * @param key */ void delete(byte[] key); /** * 缓存在seconds秒后失效 * @param key * @param seconds */ void expire(String key, int seconds); /** * 缓存在未来某个时间点失效 * @param key * @param timestamp */ void expire(String key, long timestamp); /**原子性的薪资指定值 * * @param key * @param value * @return */ long incrByValue(String key, long value); /** * 原子性的新增 * @param key * @return */ long incrByOne(String key); /** * 原子性的新增指定浮点值 * @param key * @param value * @return */ double incrByFloat(String key, double value); /** * 返回列表中的内容 * @param key * @param start * @param end * @return */ List<String> lrange(String key, long start, long end); /** * 获取所以符合匹配条件的缓存 * @param pattern * @return */ Set<byte[]> keys(String pattern); /** * 原子性的减一 * @param key * @return */ long decrByOne(String key); /** * 原子性的减vaule * @param key * @param value * @return */ long decrByValue(String key, long value); }
UTF-8
Java
2,447
java
CacheOperation.java
Java
[ { "context": "til.List;\nimport java.util.Set;\n\n/**\n * Created by jxtb on 2019/6/12.\n */\npublic interface CacheOperation", "end": 93, "score": 0.9996450543403625, "start": 89, "tag": "USERNAME", "value": "jxtb" } ]
null
[]
package com.jxtb.redis; import java.util.List; import java.util.Set; /** * Created by jxtb on 2019/6/12. */ public interface CacheOperation { /** * 加入缓存 * @param key * @param value */ void put(String key, String value); /** * 加入缓存 * @param key * @param value */ void put(byte[] key, byte[] value); /** * 加入缓存 * @param key * @param value * @param timeout */ void put(byte[] key, byte[] value, int timeout); /** * 加入缓存 * @param key * @param value * @param seconds seconds秒之后失效 */ void put(String key, String value, int seconds); void putAll(String key, List<String> value); /** * 从缓存中获取信息 * @param key * @return */ String get(String key); /** * 从缓存中获取信息 * @param key * @return */ byte[] get(byte[] key); List<String> getAll(String key); /** * 缓存失效 * @param key */ void invalid(String key); /** * 删除缓存 * @param key */ void delete(byte[] key); /** * 缓存在seconds秒后失效 * @param key * @param seconds */ void expire(String key, int seconds); /** * 缓存在未来某个时间点失效 * @param key * @param timestamp */ void expire(String key, long timestamp); /**原子性的薪资指定值 * * @param key * @param value * @return */ long incrByValue(String key, long value); /** * 原子性的新增 * @param key * @return */ long incrByOne(String key); /** * 原子性的新增指定浮点值 * @param key * @param value * @return */ double incrByFloat(String key, double value); /** * 返回列表中的内容 * @param key * @param start * @param end * @return */ List<String> lrange(String key, long start, long end); /** * 获取所以符合匹配条件的缓存 * @param pattern * @return */ Set<byte[]> keys(String pattern); /** * 原子性的减一 * @param key * @return */ long decrByOne(String key); /** * 原子性的减vaule * @param key * @param value * @return */ long decrByValue(String key, long value); }
2,447
0.498865
0.495688
135
15.318519
12.707334
58
false
false
0
0
0
0
0
0
0.266667
false
false
7
f018e86f49ebecdb45b18ec1fefe17216295343a
8,907,762,214,159
d8a5aef3de0bb9ea7656e934f5b1cd8911a9d5c2
/app/src/main/java/com/amador/fridge/interfaces/IView.java
09e0b857b19c7bdb1649cfb62c9777f0bb3390e4
[]
no_license
AmadorFernandez/Fridge_ContentProvider_DataBase_Service_Receiber
https://github.com/AmadorFernandez/Fridge_ContentProvider_DataBase_Service_Receiber
f4b037077bc8cd00bc679098c005986a68c70fbf
d9287d3a5b1bba4ac6c04a57033d046c075352fe
refs/heads/master
"2021-06-12T11:21:11.396000"
"2017-03-04T20:00:19"
"2017-03-04T20:00:19"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.amador.fridge.interfaces; /** * Created by amador on 4/03/17. */ public interface IView { void showMessage(String message); }
UTF-8
Java
147
java
IView.java
Java
[ { "context": "e com.amador.fridge.interfaces;\n\n/**\n * Created by amador on 4/03/17.\n */\n\npublic interface IView {\n\n vo", "end": 63, "score": 0.9993494153022766, "start": 57, "tag": "USERNAME", "value": "amador" } ]
null
[]
package com.amador.fridge.interfaces; /** * Created by amador on 4/03/17. */ public interface IView { void showMessage(String message); }
147
0.693878
0.659864
10
13.7
15.748333
37
false
false
0
0
0
0
0
0
0.2
false
false
7
0d3b9f85ae0a7b7f19529d037ec4b34813a06c61
12,790,412,650,388
37d0083e6727b48d5ae420b6f7e0e4b4c859b6e5
/readCSV/src/TestRemoveRepetedAndSeqScan.java
ef25f7aa07b15573fe39aa2fe50694cd7f0b96fb
[]
no_license
haachicanoy/Implementacion_BD
https://github.com/haachicanoy/Implementacion_BD
e33762c4ddd713a784813bd6b378f7bc6aeac34d
15da65d6473d595982bab7443f1315100398dc78
refs/heads/master
"2021-08-09T00:27:42.479000"
"2017-11-11T17:26:31"
"2017-11-11T17:26:31"
109,870,129
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.List; public class TestRemoveRepetedAndSeqScan { public static void main(String[] args) { // TODO Auto-generated method stub List<String> tablas = new ArrayList<>(); tablas.add("A"); Node node = new Node(); node.setTableInput(tablas); node.setType("RemoveRepeated"); IOperator op = new RemoveRepeated(); String table = op.apply(node); System.out.println("Tabla Generada: "+table); } }
UTF-8
Java
465
java
TestRemoveRepetedAndSeqScan.java
Java
[]
null
[]
import java.util.ArrayList; import java.util.List; public class TestRemoveRepetedAndSeqScan { public static void main(String[] args) { // TODO Auto-generated method stub List<String> tablas = new ArrayList<>(); tablas.add("A"); Node node = new Node(); node.setTableInput(tablas); node.setType("RemoveRepeated"); IOperator op = new RemoveRepeated(); String table = op.apply(node); System.out.println("Tabla Generada: "+table); } }
465
0.690323
0.690323
22
20.045454
17.123819
47
false
false
0
0
0
0
0
0
1.636364
false
false
7
e645b19c08fa58b1a40f719f10b2e18ef98d82a3
22,479,858,874,003
c081589e2b3396d3dd5be09edd132888907b110f
/src/main/java/br/ce/wcaquino/test/TestAjax.java
f50f2ef59c6b535f085410d88169a6d19650622d
[]
no_license
Jeff-Aug/CursoSelenium
https://github.com/Jeff-Aug/CursoSelenium
93df1bed9a0261ee60c61556472d7f6269891588
997e0f5594530331488de73814dc2917d20d47ef
refs/heads/main
"2023-02-18T12:37:08.429000"
"2021-01-17T14:19:32"
"2021-01-17T14:19:32"
316,859,824
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.ce.wcaquino.test; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import br.ce.wcaquino.core.DSL; import br.ce.wcaquino.core.DriverFactory; public class TestAjax { private DSL dsl; @Before public void inicializa(){ DriverFactory.getDriver().get("https://www.primefaces.org/showcase/ui/ajax/basic.xhtml"); dsl = new DSL(); } @After public void finaliza(){ DriverFactory.KillDriver(); } @Test public void testeAjax() throws InterruptedException { WebDriverWait wait = new WebDriverWait(DriverFactory.getDriver(), 30); dsl.escrever("j_idt727:name", "Test"); //Thread.sleep(5000); dsl.clicarBotao("j_idt727:j_idt730"); // wait.until(ExpectedConditions.textToBe(By.id("j_idt727:display"), "asdfjagsd")); wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("j_idt807"))); Assert.assertEquals("Test", dsl.obterTexto(("j_idt727:display"))); //j_idt727:name } }
UTF-8
Java
1,132
java
TestAjax.java
Java
[]
null
[]
package br.ce.wcaquino.test; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import br.ce.wcaquino.core.DSL; import br.ce.wcaquino.core.DriverFactory; public class TestAjax { private DSL dsl; @Before public void inicializa(){ DriverFactory.getDriver().get("https://www.primefaces.org/showcase/ui/ajax/basic.xhtml"); dsl = new DSL(); } @After public void finaliza(){ DriverFactory.KillDriver(); } @Test public void testeAjax() throws InterruptedException { WebDriverWait wait = new WebDriverWait(DriverFactory.getDriver(), 30); dsl.escrever("j_idt727:name", "Test"); //Thread.sleep(5000); dsl.clicarBotao("j_idt727:j_idt730"); // wait.until(ExpectedConditions.textToBe(By.id("j_idt727:display"), "asdfjagsd")); wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("j_idt807"))); Assert.assertEquals("Test", dsl.obterTexto(("j_idt727:display"))); //j_idt727:name } }
1,132
0.729682
0.70583
49
22.102041
24.947493
91
false
false
0
0
0
0
0
0
1.510204
false
false
7
1b30c1a6e5a87519b88be01587d40e5826339bf7
12,721,693,131,267
b9ad27f1b6fd62e4a0fcf1ee94a9f56f026afb88
/APIAva/src/main/java/br/com/api/ava/rest/TurmaService.java
5354214fd709b9d9eedccc593db1c1520d457b4f
[]
no_license
rafaeldornelleslima/projeto_ava_web
https://github.com/rafaeldornelleslima/projeto_ava_web
29494609dbcba253df21403c5ccc979cf1ed1c75
dbe4cab996d3ac2f4e50301a90c36fde83bfa228
refs/heads/master
"2021-05-31T21:55:35.071000"
"2016-06-09T01:06:04"
"2016-06-09T01:06:04"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * JBoss, Home of Professional Open Source * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * 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 br.com.api.ava.rest; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.ValidationException; import javax.validation.Validator; 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.core.MediaType; import javax.ws.rs.core.Response; import br.com.api.ava.data.TurmaRepository; import br.com.api.ava.decorators.Secured; import br.com.api.ava.model.Turma; import br.com.api.ava.service.TurmaRegistration; @Secured @Path("/turma") @RequestScoped public class TurmaService { @Inject private Logger log; @Inject private Validator validator; @Inject private TurmaRepository repository; @Inject TurmaRegistration registration; @GET @Produces(MediaType.APPLICATION_JSON) public List<Turma> listAll() { return repository.findAll(); } @GET @Path("/{idTurma:[0-9][0-9]*}") @Produces(MediaType.APPLICATION_JSON) public Turma buscarPorId(@PathParam("idTurma") long idTurma) { return (Turma) repository.findById(idTurma); } @GET @Path("/minhasTurmas/{idUsuario:[0-9][0-9]*}") @Produces(MediaType.APPLICATION_JSON) public List<Turma> buscarMinhasTurmas(@PathParam("idUsuario") long idUsuario) { return (ArrayList<Turma>) repository.buscarMinhasTurmas(idUsuario); } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createTurma(Turma turma) { Response.ResponseBuilder builder = null; try { turma.setDtCadastro(Calendar.getInstance().getTime()); turma.setSituacao(true); validarTurma(turma); registration.register(turma); builder = Response.ok(); } catch (ConstraintViolationException ce) { log.log(Level.WARNING, ce.getMessage()); builder = createViolationResponse(ce.getConstraintViolations()); } catch (Exception e) { log.log(Level.SEVERE, e.getMessage()); Map<String, String> responseObj = new HashMap<>(); responseObj.put("error", e.getMessage()); builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj); } return builder.build(); } @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updateBlog(Turma turma) { Response.ResponseBuilder builder = null; try { registration.update(turma); builder = Response.ok(); } catch (Exception e) { log.log(Level.SEVERE, e.getMessage()); Map<String, String> responseObj = new HashMap<>(); responseObj.put("error", e.getMessage()); builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj); } return builder.build(); } @DELETE @Path("/{id:[0-9][0-9]*}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response deleteTurma(@PathParam("id") long id) { Response.ResponseBuilder builder = null; Turma turma = null; try { try { turma = repository.findById(id); } catch (Exception e) { log.log(Level.SEVERE, e.getMessage()); Map<String, String> responseObj = new HashMap<>(); responseObj.put("error", e.getMessage()); builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj); } registration.delete(turma); builder = Response.ok(); } catch (Exception e) { log.log(Level.SEVERE, e.getMessage()); Map<String, String> responseObj = new HashMap<>(); responseObj.put("error", e.getMessage()); builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj); } return builder.build(); } private void validarTurma(Turma turma) throws ConstraintViolationException, ValidationException { // Create a bean validator and check for issues. Set<ConstraintViolation<Turma>> violations = validator.validate(turma); if (!violations.isEmpty()) { log.log(Level.SEVERE, violations.toString()); throw new ConstraintViolationException(new HashSet<ConstraintViolation<?>>(violations)); } } private Response.ResponseBuilder createViolationResponse(Set<ConstraintViolation<?>> violations) { //log.fine("Validation completed. violations found: " + violations.size()); Map<String, String> responseObj = new HashMap<>(); for (ConstraintViolation<?> violation : violations) { responseObj.put("error", violation.getPropertyPath().toString() + " : " + violation.getMessage()); } return Response.status(Response.Status.BAD_REQUEST).entity(responseObj); } }
UTF-8
Java
6,243
java
TurmaService.java
Java
[]
null
[]
/* * JBoss, Home of Professional Open Source * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * 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 br.com.api.ava.rest; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.ValidationException; import javax.validation.Validator; 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.core.MediaType; import javax.ws.rs.core.Response; import br.com.api.ava.data.TurmaRepository; import br.com.api.ava.decorators.Secured; import br.com.api.ava.model.Turma; import br.com.api.ava.service.TurmaRegistration; @Secured @Path("/turma") @RequestScoped public class TurmaService { @Inject private Logger log; @Inject private Validator validator; @Inject private TurmaRepository repository; @Inject TurmaRegistration registration; @GET @Produces(MediaType.APPLICATION_JSON) public List<Turma> listAll() { return repository.findAll(); } @GET @Path("/{idTurma:[0-9][0-9]*}") @Produces(MediaType.APPLICATION_JSON) public Turma buscarPorId(@PathParam("idTurma") long idTurma) { return (Turma) repository.findById(idTurma); } @GET @Path("/minhasTurmas/{idUsuario:[0-9][0-9]*}") @Produces(MediaType.APPLICATION_JSON) public List<Turma> buscarMinhasTurmas(@PathParam("idUsuario") long idUsuario) { return (ArrayList<Turma>) repository.buscarMinhasTurmas(idUsuario); } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createTurma(Turma turma) { Response.ResponseBuilder builder = null; try { turma.setDtCadastro(Calendar.getInstance().getTime()); turma.setSituacao(true); validarTurma(turma); registration.register(turma); builder = Response.ok(); } catch (ConstraintViolationException ce) { log.log(Level.WARNING, ce.getMessage()); builder = createViolationResponse(ce.getConstraintViolations()); } catch (Exception e) { log.log(Level.SEVERE, e.getMessage()); Map<String, String> responseObj = new HashMap<>(); responseObj.put("error", e.getMessage()); builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj); } return builder.build(); } @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updateBlog(Turma turma) { Response.ResponseBuilder builder = null; try { registration.update(turma); builder = Response.ok(); } catch (Exception e) { log.log(Level.SEVERE, e.getMessage()); Map<String, String> responseObj = new HashMap<>(); responseObj.put("error", e.getMessage()); builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj); } return builder.build(); } @DELETE @Path("/{id:[0-9][0-9]*}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response deleteTurma(@PathParam("id") long id) { Response.ResponseBuilder builder = null; Turma turma = null; try { try { turma = repository.findById(id); } catch (Exception e) { log.log(Level.SEVERE, e.getMessage()); Map<String, String> responseObj = new HashMap<>(); responseObj.put("error", e.getMessage()); builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj); } registration.delete(turma); builder = Response.ok(); } catch (Exception e) { log.log(Level.SEVERE, e.getMessage()); Map<String, String> responseObj = new HashMap<>(); responseObj.put("error", e.getMessage()); builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj); } return builder.build(); } private void validarTurma(Turma turma) throws ConstraintViolationException, ValidationException { // Create a bean validator and check for issues. Set<ConstraintViolation<Turma>> violations = validator.validate(turma); if (!violations.isEmpty()) { log.log(Level.SEVERE, violations.toString()); throw new ConstraintViolationException(new HashSet<ConstraintViolation<?>>(violations)); } } private Response.ResponseBuilder createViolationResponse(Set<ConstraintViolation<?>> violations) { //log.fine("Validation completed. violations found: " + violations.size()); Map<String, String> responseObj = new HashMap<>(); for (ConstraintViolation<?> violation : violations) { responseObj.put("error", violation.getPropertyPath().toString() + " : " + violation.getMessage()); } return Response.status(Response.Status.BAD_REQUEST).entity(responseObj); } }
6,243
0.668749
0.665545
199
30.371859
25.571899
110
false
false
0
0
0
0
0
0
0.889447
false
false
7
46fc793a4db4c352d53b150cbfec13dc419d3137
197,568,558,228
db094c2ad72d5df3a41b0b59c654db3bb7640db0
/MovieWebsiteManager/src/movieWebsiteManager/GenreModel.java
46c95db782e712bd5cc787a9693be68b9b27d1d2
[]
no_license
hieuthanh19/prj331-movie-website-management
https://github.com/hieuthanh19/prj331-movie-website-management
c20d9d9f0d28631302700493806e31209a56b2af
e35796f30d8b556b85d3b61e64e2174452003f5f
refs/heads/master
"2023-08-14T19:45:39.806000"
"2021-09-17T02:15:09"
"2021-09-17T02:15:09"
258,223,451
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 movieWebsiteManager; import connection.GetConnection; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; /** * * @author ThanhKH */ public class GenreModel { //attributes private static Connection con; private static GetConnection getCon; private static PreparedStatement pst; private static ResultSet rs; //table info private static String tblName = "Genre"; private static String[] tblCols = {"g_name"}; /** * Create new Genre Model */ public GenreModel() { getCon = new GetConnection(); } /** * Check if Genre ID exist * * @param g_id genre ID * @return true if exist, false if not * @throws SQLException */ public boolean isIdExist(int g_id) throws SQLException { //connect to DB con = getCon.getConnection(); //create sql string String sqlStr = "select top 1 g_id from " + tblName + " where g_id = ?"; //creaste query pst = con.prepareStatement(sqlStr, Statement.RETURN_GENERATED_KEYS); pst.setInt(1, g_id); //eecute query rs = pst.executeQuery(); //if result found if (rs.next() != false) { pst.close(); return true; } pst.close(); return false; } /** * Check if a genre name exist * * @param genreName * @return true if exist, false if not * @throws SQLException */ public boolean isNameExist(String genreName) throws SQLException { //connect to DB con = getCon.getConnection(); //create sql string String sqlStr = "select * from " + tblName + " where " + tblCols[0] + " like ?"; //creaste query pst = con.prepareStatement(sqlStr, Statement.RETURN_GENERATED_KEYS); pst.setString(1, genreName); //eecute query rs = pst.executeQuery(); //if result found if (rs.next() != false) { pst.close(); return true; } pst.close(); return false; } /** * Insert new Genre in DB * * @param g_name genre name * @return g_id if success, -1 if not * @throws SQLException */ public int insert(String g_name) throws SQLException { //connect to DB con = getCon.getConnection(); //create sql string String sqlStr = "INSERT INTO " + tblName + " (g_name) VALUES (?)"; //create query pst = con.prepareStatement(sqlStr, Statement.RETURN_GENERATED_KEYS); //set values pst.setString(1, g_name); //execute query pst.executeUpdate(); //get Genre ID rs = pst.getGeneratedKeys(); rs.next(); int g_id = rs.getInt(1); pst.close(); return g_id; } /** * Update values of Genre * * @param g_id genre ID * @param g_name genre name * @throws SQLException * @throws GenreException */ public void update(int g_id, String g_name) throws SQLException, GenreException { if (isIdExist(g_id)) { //connect to DB con = getCon.getConnection(); //create sql string String sqlStr = "UPDATE " + tblName + " SET " + tblCols[0] + " =? WHERE g_id = ?"; //create query pst = con.prepareStatement(sqlStr, Statement.RETURN_GENERATED_KEYS); //set values pst.setString(1, g_name); pst.setInt(2, g_id); //execute query pst.executeUpdate(); pst.close(); } else { throw new GenreException("Genre ID is not exist!"); } } /** * Get all genre * * @return * @throws SQLException */ public ArrayList<Genre> getAllGenre() throws SQLException { ArrayList<Genre> resultList = new ArrayList<>(); //connect to DB con = getCon.getConnection(); //create sql string String sqlStr = "Select * from " + tblName; //create query pst = con.prepareStatement(sqlStr, Statement.RETURN_GENERATED_KEYS); //get results rs = pst.executeQuery(); while (rs.next() != false) { int g_id = rs.getInt("g_id"); String g_name = rs.getString(tblCols[0]); //add to result list resultList.add(new Genre(g_id, g_name)); } pst.close(); return resultList; } /** * Get genre from genre ID * * @param gId genre ID * @return Genre if success, null if not * @throws SQLException */ public Genre getGenre(int gId) throws SQLException { //check input if (isIdExist(gId)) { //connect to DB con = getCon.getConnection(); //create sql string String sqlStr = "Select * from " + tblName + " where g_id = ?"; //create query pst = con.prepareStatement(sqlStr, Statement.RETURN_GENERATED_KEYS); pst.setInt(1, gId); //get results rs = pst.executeQuery(); while (rs.next() != false) { int g_id = rs.getInt("g_id"); String g_name = rs.getString(tblCols[0]); //add to result list pst.close(); Genre g = new Genre(g_id, g_name); return g; } } return null; } /** * Get Genre with given name * * @param gName genre name * @return Genre if success, -1 if not * @throws SQLException */ public Genre getGenre(String gName) throws SQLException { //check input if (isNameExist(gName)) { //connect to DB con = getCon.getConnection(); //create sql string String sqlStr = "Select * from " + tblName + " where " + tblCols[0] + " like ?"; //create query pst = con.prepareStatement(sqlStr, Statement.RETURN_GENERATED_KEYS); pst.setString(1, gName); //get results rs = pst.executeQuery(); while (rs.next() != false) { int g_id = rs.getInt("g_id"); String g_name = rs.getString(tblCols[0]); //add to result list pst.close(); Genre g = new Genre(g_id, g_name); return g; } } return null; } /** * Sort genre list * * @param list ArrayList that need to be sorted */ public void sort(ArrayList<Genre> list) { Collections.sort(list, new Comparator<Genre>() { @Override public int compare(Genre t, Genre t1) { return t.getG_name().compareTo(t1.getG_name()); } }); } }
UTF-8
Java
7,256
java
GenreModel.java
Java
[ { "context": "s;\nimport java.util.Comparator;\n\n/**\n *\n * @author ThanhKH\n */\npublic class GenreModel {\n\n //attributes\n ", "end": 508, "score": 0.9987592697143555, "start": 501, "tag": "USERNAME", "value": "ThanhKH" } ]
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 movieWebsiteManager; import connection.GetConnection; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; /** * * @author ThanhKH */ public class GenreModel { //attributes private static Connection con; private static GetConnection getCon; private static PreparedStatement pst; private static ResultSet rs; //table info private static String tblName = "Genre"; private static String[] tblCols = {"g_name"}; /** * Create new Genre Model */ public GenreModel() { getCon = new GetConnection(); } /** * Check if Genre ID exist * * @param g_id genre ID * @return true if exist, false if not * @throws SQLException */ public boolean isIdExist(int g_id) throws SQLException { //connect to DB con = getCon.getConnection(); //create sql string String sqlStr = "select top 1 g_id from " + tblName + " where g_id = ?"; //creaste query pst = con.prepareStatement(sqlStr, Statement.RETURN_GENERATED_KEYS); pst.setInt(1, g_id); //eecute query rs = pst.executeQuery(); //if result found if (rs.next() != false) { pst.close(); return true; } pst.close(); return false; } /** * Check if a genre name exist * * @param genreName * @return true if exist, false if not * @throws SQLException */ public boolean isNameExist(String genreName) throws SQLException { //connect to DB con = getCon.getConnection(); //create sql string String sqlStr = "select * from " + tblName + " where " + tblCols[0] + " like ?"; //creaste query pst = con.prepareStatement(sqlStr, Statement.RETURN_GENERATED_KEYS); pst.setString(1, genreName); //eecute query rs = pst.executeQuery(); //if result found if (rs.next() != false) { pst.close(); return true; } pst.close(); return false; } /** * Insert new Genre in DB * * @param g_name genre name * @return g_id if success, -1 if not * @throws SQLException */ public int insert(String g_name) throws SQLException { //connect to DB con = getCon.getConnection(); //create sql string String sqlStr = "INSERT INTO " + tblName + " (g_name) VALUES (?)"; //create query pst = con.prepareStatement(sqlStr, Statement.RETURN_GENERATED_KEYS); //set values pst.setString(1, g_name); //execute query pst.executeUpdate(); //get Genre ID rs = pst.getGeneratedKeys(); rs.next(); int g_id = rs.getInt(1); pst.close(); return g_id; } /** * Update values of Genre * * @param g_id genre ID * @param g_name genre name * @throws SQLException * @throws GenreException */ public void update(int g_id, String g_name) throws SQLException, GenreException { if (isIdExist(g_id)) { //connect to DB con = getCon.getConnection(); //create sql string String sqlStr = "UPDATE " + tblName + " SET " + tblCols[0] + " =? WHERE g_id = ?"; //create query pst = con.prepareStatement(sqlStr, Statement.RETURN_GENERATED_KEYS); //set values pst.setString(1, g_name); pst.setInt(2, g_id); //execute query pst.executeUpdate(); pst.close(); } else { throw new GenreException("Genre ID is not exist!"); } } /** * Get all genre * * @return * @throws SQLException */ public ArrayList<Genre> getAllGenre() throws SQLException { ArrayList<Genre> resultList = new ArrayList<>(); //connect to DB con = getCon.getConnection(); //create sql string String sqlStr = "Select * from " + tblName; //create query pst = con.prepareStatement(sqlStr, Statement.RETURN_GENERATED_KEYS); //get results rs = pst.executeQuery(); while (rs.next() != false) { int g_id = rs.getInt("g_id"); String g_name = rs.getString(tblCols[0]); //add to result list resultList.add(new Genre(g_id, g_name)); } pst.close(); return resultList; } /** * Get genre from genre ID * * @param gId genre ID * @return Genre if success, null if not * @throws SQLException */ public Genre getGenre(int gId) throws SQLException { //check input if (isIdExist(gId)) { //connect to DB con = getCon.getConnection(); //create sql string String sqlStr = "Select * from " + tblName + " where g_id = ?"; //create query pst = con.prepareStatement(sqlStr, Statement.RETURN_GENERATED_KEYS); pst.setInt(1, gId); //get results rs = pst.executeQuery(); while (rs.next() != false) { int g_id = rs.getInt("g_id"); String g_name = rs.getString(tblCols[0]); //add to result list pst.close(); Genre g = new Genre(g_id, g_name); return g; } } return null; } /** * Get Genre with given name * * @param gName genre name * @return Genre if success, -1 if not * @throws SQLException */ public Genre getGenre(String gName) throws SQLException { //check input if (isNameExist(gName)) { //connect to DB con = getCon.getConnection(); //create sql string String sqlStr = "Select * from " + tblName + " where " + tblCols[0] + " like ?"; //create query pst = con.prepareStatement(sqlStr, Statement.RETURN_GENERATED_KEYS); pst.setString(1, gName); //get results rs = pst.executeQuery(); while (rs.next() != false) { int g_id = rs.getInt("g_id"); String g_name = rs.getString(tblCols[0]); //add to result list pst.close(); Genre g = new Genre(g_id, g_name); return g; } } return null; } /** * Sort genre list * * @param list ArrayList that need to be sorted */ public void sort(ArrayList<Genre> list) { Collections.sort(list, new Comparator<Genre>() { @Override public int compare(Genre t, Genre t1) { return t.getG_name().compareTo(t1.getG_name()); } }); } }
7,256
0.536384
0.533765
250
28.024
20.236389
94
false
false
0
0
0
0
0
0
0.464
false
false
7
eaa7a47b74cf5457aec7612612fe7dd948760011
26,792,006,004,229
b65fb782a27cfab63ea5405328ea2fb77a24fb67
/gateway/src/main/java/ma/ocp/gateway/GatewayApplication.java
9c65d0ccd8df9c91dab1b4b1ae8101e15ea88e53
[]
no_license
ocp-digital-factory/spring-cloud-gateway-demo
https://github.com/ocp-digital-factory/spring-cloud-gateway-demo
6ed89dedacb09130bcf066831a7af0a994664545
38232f9d6c4921dabfde7aea1a3b133eec34cbb2
refs/heads/master
"2023-07-09T06:02:43.105000"
"2021-08-13T14:03:41"
"2021-08-13T14:03:41"
395,676,752
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ma.ocp.gateway; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.gateway.filter.factory.TokenRelayGatewayFilterFactory; import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; import org.springframework.context.annotation.Bean; import org.springframework.http.ResponseEntity; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Collections; import java.util.Map; @RestController @SpringBootApplication public class GatewayApplication { @Autowired private TokenRelayGatewayFilterFactory filterFactory; private static final Logger LOG = LoggerFactory.getLogger(GatewayApplication.class); public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes() .route("usine", r -> r.path("/usine") .filters(f -> f.filters(filterFactory.apply()) .removeRequestHeader("Cookie")) // Prevents cookie being sent downstream .uri("http://industrial-ref:9000")) // Taking advantage of docker naming .build(); } @GetMapping("/") public ResponseEntity index(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient, @AuthenticationPrincipal OAuth2User oauth2User) { LOG.info("##### userName : {}", oauth2User.getName()); LOG.info("##### clientName : {}", authorizedClient.getClientRegistration().getClientName()); LOG.info("##### userAttributes : {}", oauth2User.getAttributes().toString()); return ResponseEntity.ok(oauth2User.getName()); } }
UTF-8
Java
2,517
java
GatewayApplication.java
Java
[]
null
[]
package ma.ocp.gateway; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.gateway.filter.factory.TokenRelayGatewayFilterFactory; import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; import org.springframework.context.annotation.Bean; import org.springframework.http.ResponseEntity; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Collections; import java.util.Map; @RestController @SpringBootApplication public class GatewayApplication { @Autowired private TokenRelayGatewayFilterFactory filterFactory; private static final Logger LOG = LoggerFactory.getLogger(GatewayApplication.class); public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes() .route("usine", r -> r.path("/usine") .filters(f -> f.filters(filterFactory.apply()) .removeRequestHeader("Cookie")) // Prevents cookie being sent downstream .uri("http://industrial-ref:9000")) // Taking advantage of docker naming .build(); } @GetMapping("/") public ResponseEntity index(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient, @AuthenticationPrincipal OAuth2User oauth2User) { LOG.info("##### userName : {}", oauth2User.getName()); LOG.info("##### clientName : {}", authorizedClient.getClientRegistration().getClientName()); LOG.info("##### userAttributes : {}", oauth2User.getAttributes().toString()); return ResponseEntity.ok(oauth2User.getName()); } }
2,517
0.746921
0.739372
56
43.94643
32.343258
106
false
false
0
0
0
0
0
0
0.625
false
false
7
c417fef9c5e173760cc60f993d0e9789b5a43b3e
32,332,513,816,131
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/7/7_4c4eca239872ffb5d715c1dc8f7acdb51a33ad45/DefaultAttributeType/7_4c4eca239872ffb5d715c1dc8f7acdb51a33ad45_DefaultAttributeType_s.java
4efadc7fcdb88a974cec8a4bef48cca498aed053
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
"2023-07-06T12:48:55.516000"
"2023-06-22T07:55:56"
"2023-06-22T07:55:56"
259,613,157
6
2
null
false
"2023-06-22T07:55:57"
"2020-04-28T11:07:49"
"2023-06-21T00:53:27"
"2023-06-22T07:55:57"
2,849,868
2
2
0
null
false
false
/* * Geotools2 - OpenSource mapping toolkit * http://geotools.org * (C) 2002, Geotools Project Managment Committee (PMC) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library 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. * */ package org.geotools.feature; import com.vividsolutions.jts.geom.Geometry; import java.util.*; /** * Simple, immutable class to store attributes. This class should be * sufficient for all simple (ie. non-schema) attribute implementations of * this interface. * * @author Rob Hranac, VFNY * @author Chris Holmes, TOPP * @version $Id: DefaultAttributeType.java,v 1.4 2003/07/18 19:55:00 jmacgill Exp $ */ public class DefaultAttributeType implements AttributeType { /** Name of this attribute. */ protected final String name; /** Class type of this attribute. */ protected final Class type; /** Indicates if nulls are allowed for this attribute */ protected final boolean nillable; /** * Constructor with name and type. * * @param name Name of this attribute. * @param type Class type of this attribute. * * @task REVISIT: consider making protected and moving to factory pattern, * though these may be too small to make that worth it. */ public DefaultAttributeType(String name, Class type,boolean nillable) { this.name = name == null ? "" : name; this.type = type == null ? Object.class : type; this.nillable = nillable; } /** * Occurances no longer used, use MultiAttributeType for this * functionality. cholmes Constructor with geometry. * * @param position Name of this attribute. */ /*public DefaultAttributeType (String name, Class type, int occurrences) { this.name = name; this.type = type; this.occurrences = occurrences; }*/ /** * False, since it is not a schema. * * @return False. */ public boolean isNested() { return false; } /** * Gets the name of this attribute. * * @return The name of this attribute. */ public String getName() { return name; } /** * Gets the type of this attribute. All attributes that are assigned to * this AttributeType must be an instance of this class. Subclasses are * allowed as well. * * @return The class that the attribute must match to be valid for this * AttributeType. */ public Class getType() { return type; } /** * Removed from interface, and thus here too -ch. * Gets the occurrences of this attribute. * * @return Occurrences. */ //public int getOccurrences() { // return occurrences; //} /** * Gets the position of this attribute. * Removed - Ian * @return Position. */ // public int getPosition() { // return position; // } /** * Returns whether nulls are allowed for this attribute. * * @return true if nulls are permitted, false otherwise. */ public boolean isNillable() { return nillable; } public int hashCode() { return name.hashCode() * type.hashCode(); } public boolean equals(Object other) { if (other == null) return false; AttributeType att = (AttributeType) other; if (name == null) { if (att.getName() != null) return false; } if (!name.equals(att.getName())) return false; if (!type.equals(att.getType())) return false; return true; } /** * Returns whether the attribute is a geometry. * * @return true if the attribute's type is a geometry. */ public boolean isGeometry() { return Geometry.class.isAssignableFrom(this.type); } public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Gets a representation of this object as a string. * * @return A representation of this object as a string */ public String toString() { String details = "name=" + name; details += " , type=" + type; details += " , nillable=" + nillable; return "DefaultAttributeType [" + details + "]"; } /** * Whether the tested object passes the validity constraints of this * AttributeType. At a minimum it should be of the correct class * specified by {@link #getType()}, non-null if isNillable is * <tt>false</tt>, and a geometry if isGeometry is <tt>true</tt> * * @param attribute The object to be tested for validity. * * @return <tt>true</tt> if the object is allowed to be an attribute for * this type, <tt>false</tt> otherwise. * @task REVISIT: throw exception if not valid? The current way loses * reporting on why the object is not valid. Would be nice if * there was a way to get that back, not null, wrong class, ect. */ public boolean isValid(Object attribute) { boolean isValid = false; if (attribute != null) { //check if attribute is null //if not check to make sure it's the right class. isValid = getType().isAssignableFrom(attribute.getClass()); } else { if (!isNillable()) { isValid = false; //attribute is null but nils not allowed. } else { isValid = true; } } return isValid; } public Object parse(Object value) throws IllegalArgumentException { return value; } public void validate(Object attribute) throws IllegalArgumentException { if (attribute == null){ if(!isNillable()){ throw new IllegalArgumentException(getName() + " is not nillable"); } return; } if (!type.isAssignableFrom(attribute.getClass())) throw new IllegalArgumentException(attribute.getClass().getName() + " is not an acceptable class for " + getName() + " as it is not assignable from " + type); } static class Numeric extends DefaultAttributeType { public Numeric(String name,Class type,boolean nillable) { super(name, type,nillable); if (!Number.class.isAssignableFrom(type)) throw new IllegalArgumentException("Numeric requires Number class, " + "not " + type); } /** * @task REVISIT: When type is Number, should we always be using Double? **/ public Object parse(Object value) throws IllegalArgumentException { if (value == null) return value; if (type == Byte.class) return Byte.decode(value.toString()); if (type == Short.class) return Short.decode(value.toString()); if (type == Integer.class) return Integer.decode(value.toString()); if (type == Float.class) return Float.valueOf(value.toString()); if (type == Double.class) return Double.valueOf(value.toString()); if (type == Long.class) return Long.decode(value.toString()); if (type.isAssignableFrom(Number.class)) return Double.valueOf(value.toString()); throw new RuntimeException("DefaultAttributeType.Numeric is coded wrong"); } } static class Feature extends DefaultAttributeType { private final FeatureType featureType; public Feature(String name,FeatureType type,boolean nillable) { super(name,org.geotools.feature.Feature.class,nillable); this.featureType = type; } public void validate(Object attribute) throws IllegalArgumentException { super.validate(attribute); org.geotools.feature.Feature att = (org.geotools.feature.Feature) attribute; if (! att.getFeatureType().isDescendedFrom(featureType) || ! att.getFeatureType().equals(featureType)) throw new IllegalArgumentException("Not correct FeatureType, expected " + featureType + " got " + att.getFeatureType()); } } }
UTF-8
Java
8,738
java
7_4c4eca239872ffb5d715c1dc8f7acdb51a33ad45_DefaultAttributeType_s.java
Java
[ { "context": "ementations of\n * this interface.\n *\n * @author Rob Hranac, VFNY\n * @author Chris Holmes, TOPP\n * @version ", "end": 956, "score": 0.9998591542243958, "start": 946, "tag": "NAME", "value": "Rob Hranac" }, { "context": "face.\n *\n * @author Rob Hranac, VFNY\n * @author Chris Holmes, TOPP\n * @version $Id: DefaultAttributeType.java,", "end": 987, "score": 0.99985671043396, "start": 975, "tag": "NAME", "value": "Chris Holmes" } ]
null
[]
/* * Geotools2 - OpenSource mapping toolkit * http://geotools.org * (C) 2002, Geotools Project Managment Committee (PMC) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library 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. * */ package org.geotools.feature; import com.vividsolutions.jts.geom.Geometry; import java.util.*; /** * Simple, immutable class to store attributes. This class should be * sufficient for all simple (ie. non-schema) attribute implementations of * this interface. * * @author <NAME>, VFNY * @author <NAME>, TOPP * @version $Id: DefaultAttributeType.java,v 1.4 2003/07/18 19:55:00 jmacgill Exp $ */ public class DefaultAttributeType implements AttributeType { /** Name of this attribute. */ protected final String name; /** Class type of this attribute. */ protected final Class type; /** Indicates if nulls are allowed for this attribute */ protected final boolean nillable; /** * Constructor with name and type. * * @param name Name of this attribute. * @param type Class type of this attribute. * * @task REVISIT: consider making protected and moving to factory pattern, * though these may be too small to make that worth it. */ public DefaultAttributeType(String name, Class type,boolean nillable) { this.name = name == null ? "" : name; this.type = type == null ? Object.class : type; this.nillable = nillable; } /** * Occurances no longer used, use MultiAttributeType for this * functionality. cholmes Constructor with geometry. * * @param position Name of this attribute. */ /*public DefaultAttributeType (String name, Class type, int occurrences) { this.name = name; this.type = type; this.occurrences = occurrences; }*/ /** * False, since it is not a schema. * * @return False. */ public boolean isNested() { return false; } /** * Gets the name of this attribute. * * @return The name of this attribute. */ public String getName() { return name; } /** * Gets the type of this attribute. All attributes that are assigned to * this AttributeType must be an instance of this class. Subclasses are * allowed as well. * * @return The class that the attribute must match to be valid for this * AttributeType. */ public Class getType() { return type; } /** * Removed from interface, and thus here too -ch. * Gets the occurrences of this attribute. * * @return Occurrences. */ //public int getOccurrences() { // return occurrences; //} /** * Gets the position of this attribute. * Removed - Ian * @return Position. */ // public int getPosition() { // return position; // } /** * Returns whether nulls are allowed for this attribute. * * @return true if nulls are permitted, false otherwise. */ public boolean isNillable() { return nillable; } public int hashCode() { return name.hashCode() * type.hashCode(); } public boolean equals(Object other) { if (other == null) return false; AttributeType att = (AttributeType) other; if (name == null) { if (att.getName() != null) return false; } if (!name.equals(att.getName())) return false; if (!type.equals(att.getType())) return false; return true; } /** * Returns whether the attribute is a geometry. * * @return true if the attribute's type is a geometry. */ public boolean isGeometry() { return Geometry.class.isAssignableFrom(this.type); } public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Gets a representation of this object as a string. * * @return A representation of this object as a string */ public String toString() { String details = "name=" + name; details += " , type=" + type; details += " , nillable=" + nillable; return "DefaultAttributeType [" + details + "]"; } /** * Whether the tested object passes the validity constraints of this * AttributeType. At a minimum it should be of the correct class * specified by {@link #getType()}, non-null if isNillable is * <tt>false</tt>, and a geometry if isGeometry is <tt>true</tt> * * @param attribute The object to be tested for validity. * * @return <tt>true</tt> if the object is allowed to be an attribute for * this type, <tt>false</tt> otherwise. * @task REVISIT: throw exception if not valid? The current way loses * reporting on why the object is not valid. Would be nice if * there was a way to get that back, not null, wrong class, ect. */ public boolean isValid(Object attribute) { boolean isValid = false; if (attribute != null) { //check if attribute is null //if not check to make sure it's the right class. isValid = getType().isAssignableFrom(attribute.getClass()); } else { if (!isNillable()) { isValid = false; //attribute is null but nils not allowed. } else { isValid = true; } } return isValid; } public Object parse(Object value) throws IllegalArgumentException { return value; } public void validate(Object attribute) throws IllegalArgumentException { if (attribute == null){ if(!isNillable()){ throw new IllegalArgumentException(getName() + " is not nillable"); } return; } if (!type.isAssignableFrom(attribute.getClass())) throw new IllegalArgumentException(attribute.getClass().getName() + " is not an acceptable class for " + getName() + " as it is not assignable from " + type); } static class Numeric extends DefaultAttributeType { public Numeric(String name,Class type,boolean nillable) { super(name, type,nillable); if (!Number.class.isAssignableFrom(type)) throw new IllegalArgumentException("Numeric requires Number class, " + "not " + type); } /** * @task REVISIT: When type is Number, should we always be using Double? **/ public Object parse(Object value) throws IllegalArgumentException { if (value == null) return value; if (type == Byte.class) return Byte.decode(value.toString()); if (type == Short.class) return Short.decode(value.toString()); if (type == Integer.class) return Integer.decode(value.toString()); if (type == Float.class) return Float.valueOf(value.toString()); if (type == Double.class) return Double.valueOf(value.toString()); if (type == Long.class) return Long.decode(value.toString()); if (type.isAssignableFrom(Number.class)) return Double.valueOf(value.toString()); throw new RuntimeException("DefaultAttributeType.Numeric is coded wrong"); } } static class Feature extends DefaultAttributeType { private final FeatureType featureType; public Feature(String name,FeatureType type,boolean nillable) { super(name,org.geotools.feature.Feature.class,nillable); this.featureType = type; } public void validate(Object attribute) throws IllegalArgumentException { super.validate(attribute); org.geotools.feature.Feature att = (org.geotools.feature.Feature) attribute; if (! att.getFeatureType().isDescendedFrom(featureType) || ! att.getFeatureType().equals(featureType)) throw new IllegalArgumentException("Not correct FeatureType, expected " + featureType + " got " + att.getFeatureType()); } } }
8,728
0.59968
0.597047
261
32.475098
27.349245
131
false
false
0
0
0
0
0
0
0.367816
false
false
7
35480662b69d236758b9893b60e6b9d3a2963d10
6,605,659,745,465
24fb51c914909741b77f0c91dbca2394c36641d4
/app/src/main/java/thefirstchange/example/com/communicationtext/gson/AllPerson.java
d67825e4fcd3f7e47e5ce4347b35347575458db0
[]
no_license
BeggarLan/CommunicationText
https://github.com/BeggarLan/CommunicationText
38cfa86c466c34f9773eae7be02d39346fa8e9ed
b8816a83a3fa16fcf76217edcc5464a9143e94fe
refs/heads/master
"2022-01-21T11:32:53.989000"
"2019-07-04T09:05:23"
"2019-07-04T09:06:40"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package thefirstchange.example.com.communicationtext.gson; import java.util.Vector; public class AllPerson { public static Vector<Student> allPerson = new Vector<>(); }
UTF-8
Java
175
java
AllPerson.java
Java
[]
null
[]
package thefirstchange.example.com.communicationtext.gson; import java.util.Vector; public class AllPerson { public static Vector<Student> allPerson = new Vector<>(); }
175
0.771429
0.771429
7
24
24.512388
61
false
false
0
0
0
0
0
0
0.428571
false
false
7
d2b221b7a20177bfa879cb23b0687b521cf4a937
21,311,627,743,688
73dcd8003cd09bbd87947e0b6ec0d4c723492c54
/Facade/src/main/java/service/Facade.java
6efc648b512e9153815e5d61a157718ad1539a05
[]
no_license
2pecshy/TraficFlow
https://github.com/2pecshy/TraficFlow
008b1add93a8e33554d1678f139395684870800f
e23bdbdff533c63cbf6fb09682e9a6d4af2e3f1d
refs/heads/master
"2021-09-07T02:36:30.201000"
"2018-02-15T22:46:44"
"2018-02-15T22:46:44"
106,793,941
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package service; import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by Jeremy on 18/01/2018. */ public class Facade { private final String hello; public Facade(String s){ this.hello = s; } public String getHello() { return hello; } }
UTF-8
Java
294
java
Facade.java
Java
[ { "context": "ackson.annotation.JsonProperty;\n\n/**\n * Created by Jeremy on 18/01/2018.\n */\npublic class Facade {\n\n pri", "end": 97, "score": 0.9996778964996338, "start": 91, "tag": "NAME", "value": "Jeremy" } ]
null
[]
package service; import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by Jeremy on 18/01/2018. */ public class Facade { private final String hello; public Facade(String s){ this.hello = s; } public String getHello() { return hello; } }
294
0.632653
0.605442
19
14.473684
15.27767
53
false
false
0
0
0
0
0
0
0.263158
false
false
7
832a6d4c019a174aa1ac68574ec97d70ae289456
19,112,604,474,705
c7fce918d0b3c508c1f8398dc15d320430cb84e5
/src/main/java/com/mathewteta/magic/Reference.java
4b8e72f0168460843d715323afe1d1e5a63e79c8
[]
no_license
MatthewTeta/MincraftMods
https://github.com/MatthewTeta/MincraftMods
2d3b22b1a7994d2f065d69c0b8c34a883539b850
9e5c04f2f4f7fa5866741308a8b493759cf0ae21
refs/heads/master
"2016-09-05T16:41:46.281000"
"2015-03-06T03:32:33"
"2015-03-06T03:32:33"
31,748,766
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mathewteta.magic; public class Reference { public static final String MOD_ID = "mm"; public static final String MOD_NAME = "Magic Mod"; public static final String VERSION = "1.0"; public static final String CLIENT_PROXY_CLASS = "com.mathewteta.magic.proxy.ClientProxy"; public static final String SERVER_PROXY_CLASS = "com.mathewteta.magic.proxy.CommonProxy"; }
UTF-8
Java
382
java
Reference.java
Java
[]
null
[]
package com.mathewteta.magic; public class Reference { public static final String MOD_ID = "mm"; public static final String MOD_NAME = "Magic Mod"; public static final String VERSION = "1.0"; public static final String CLIENT_PROXY_CLASS = "com.mathewteta.magic.proxy.ClientProxy"; public static final String SERVER_PROXY_CLASS = "com.mathewteta.magic.proxy.CommonProxy"; }
382
0.76178
0.756545
10
37.200001
31.751535
90
false
false
0
0
0
0
0
0
1.2
false
false
7
05724ef2a3e54a7688dd9fe824ceb9fbb6b0cedc
6,786,048,332,351
5dd4ed12bbdcf9170fb2449f2e16de0ee37acd9b
/payment_client/src/stl/payment/client/PaymentClient.java
3c3c0e6dccff651d8630691a146f2f8f4e3007dc
[]
no_license
danaja/STLCustomerPortal
https://github.com/danaja/STLCustomerPortal
0b64701afdd3e69592df67c8bd891ccf0aef8a4d
5e12cffd0fb59a266257ef89bc5f1acbb818870a
refs/heads/master
"2015-08-09T14:12:37.397000"
"2014-01-24T16:00:59"
"2014-01-24T16:00:59"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package stl.payment.client; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import stl.payment.Charge; import com.google.gson.Gson; import com.sun.research.ws.wadl.Request; public class PaymentClient { final static String BASE_URL = "http://localhost:9763/PaymentService/services/payment_service/paymentservice"; Gson gson; public static void main(String[] args) { PaymentClient paymentClient = new PaymentClient(); // paymentClient.testRetrieveCharge(); paymentClient.testChargeCard(); } private void testChargeCard() { Client client = ClientBuilder.newClient(); WebTarget path = client.target(BASE_URL).path("createCharge"); Charge dummyCharge = new Charge("2233-dummy"); String request = getGson().toJson(dummyCharge, Charge.class); Response response = path.request(MediaType.APPLICATION_JSON).put(Entity.entity(request, MediaType.APPLICATION_JSON), Response.class); System.out.println(response.toString()); if(response.getStatus()==200) { System.out.println(response.getEntity()); } // WebTarget client.close(); } private void testRetrieveCharge() { Client client = ClientBuilder.newClient(); WebTarget base = client.target(BASE_URL); WebTarget retievePath = base.path("retrieveCharge").path("1245"); System.out.println(retievePath.queryParam("sign", "2233").getUri().toString()); String response = retievePath.queryParam("sign", "2233").request(MediaType.APPLICATION_JSON).get(String.class); System.out.println(response); Charge charge = getGson().fromJson(response, Charge.class); client.close(); } private Gson getGson() { if (gson == null) { gson = new Gson(); } return gson; } }
UTF-8
Java
1,856
java
PaymentClient.java
Java
[]
null
[]
package stl.payment.client; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import stl.payment.Charge; import com.google.gson.Gson; import com.sun.research.ws.wadl.Request; public class PaymentClient { final static String BASE_URL = "http://localhost:9763/PaymentService/services/payment_service/paymentservice"; Gson gson; public static void main(String[] args) { PaymentClient paymentClient = new PaymentClient(); // paymentClient.testRetrieveCharge(); paymentClient.testChargeCard(); } private void testChargeCard() { Client client = ClientBuilder.newClient(); WebTarget path = client.target(BASE_URL).path("createCharge"); Charge dummyCharge = new Charge("2233-dummy"); String request = getGson().toJson(dummyCharge, Charge.class); Response response = path.request(MediaType.APPLICATION_JSON).put(Entity.entity(request, MediaType.APPLICATION_JSON), Response.class); System.out.println(response.toString()); if(response.getStatus()==200) { System.out.println(response.getEntity()); } // WebTarget client.close(); } private void testRetrieveCharge() { Client client = ClientBuilder.newClient(); WebTarget base = client.target(BASE_URL); WebTarget retievePath = base.path("retrieveCharge").path("1245"); System.out.println(retievePath.queryParam("sign", "2233").getUri().toString()); String response = retievePath.queryParam("sign", "2233").request(MediaType.APPLICATION_JSON).get(String.class); System.out.println(response); Charge charge = getGson().fromJson(response, Charge.class); client.close(); } private Gson getGson() { if (gson == null) { gson = new Gson(); } return gson; } }
1,856
0.730603
0.718211
69
25.89855
28.776573
135
false
false
0
0
0
0
0
0
1.782609
false
false
7
92a49a7e3c268ca8da8212c76948f0199237fda3
13,786,845,023,563
29a345dff6e2148c15c1bda7ca7f36e19c1d30ab
/Lab Practicals/Assignment 6_1401CS56/Problem1/Test.java
9043c3aa09bcaa18610470a7913628780760610f
[]
no_license
hitzkrieg/JAVA-Lab-coursework
https://github.com/hitzkrieg/JAVA-Lab-coursework
df1aec486dc0703b5e3f830d53846388ab2dd922
9f9b354ee6f26cb1adb6bb7382f3a250bbb27773
refs/heads/master
"2021-01-12T04:46:59.680000"
"2017-01-01T19:22:59"
"2017-01-01T19:22:59"
77,795,005
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner stdIn= new Scanner(System.in); double grade1, grade2; boolean passed1, passed2; System.out.println("Creating a new object of Grad"); System.out.println("Enter grade of the Grad object: "); grade1= stdIn.nextDouble(); Grad g= new Grad("Himesh", "1401pcs26", grade1, 24, "Patna"); System.out.println("Creating a new object of Grad"); System.out.println("Enter grade of the Undergrad object: "); grade2= stdIn.nextDouble(); Undergrad ug= new Undergrad("Hitesh", "1401cs56", grade2, 20, "Patna"); System.out.println("Calling the isPassed() of Grad object"); passed1= g.isPassed(g.grade); if(passed1==true) System.out.println("Passed"); else System.out.println("Not Passed"); System.out.println("Calling the isPassed() of Undergrad object"); passed2= ug.isPassed(ug.grade); if(passed2==true) System.out.println("Passed"); else System.out.println("Not Passed"); } }
UTF-8
Java
1,382
java
Test.java
Java
[ { "context": "1= stdIn.nextDouble();\r\n Grad g= new Grad(\"Himesh\", \"1401pcs26\", grade1, 24, \"Patna\");\r\n \r\n ", "end": 434, "score": 0.9996165633201599, "start": 428, "tag": "NAME", "value": "Himesh" }, { "context": "d g= new Grad(\"Himesh\", \"1401pcs26\", grade1, 24, \"Patna\");\r\n \r\n System.out.println(\"Creatin", "end": 468, "score": 0.9994736909866333, "start": 463, "tag": "NAME", "value": "Patna" }, { "context": "xtDouble();\r\n Undergrad ug= new Undergrad(\"Hitesh\", \"1401cs56\", grade2, 20, \"Patna\");\r\n \r\n ", "end": 695, "score": 0.9995830655097961, "start": 689, "tag": "NAME", "value": "Hitesh" }, { "context": " new Undergrad(\"Hitesh\", \"1401cs56\", grade2, 20, \"Patna\");\r\n \r\n System.out.println(\"Calling", "end": 728, "score": 0.9995405673980713, "start": 723, "tag": "NAME", "value": "Patna" } ]
null
[]
import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner stdIn= new Scanner(System.in); double grade1, grade2; boolean passed1, passed2; System.out.println("Creating a new object of Grad"); System.out.println("Enter grade of the Grad object: "); grade1= stdIn.nextDouble(); Grad g= new Grad("Himesh", "1401pcs26", grade1, 24, "Patna"); System.out.println("Creating a new object of Grad"); System.out.println("Enter grade of the Undergrad object: "); grade2= stdIn.nextDouble(); Undergrad ug= new Undergrad("Hitesh", "1401cs56", grade2, 20, "Patna"); System.out.println("Calling the isPassed() of Grad object"); passed1= g.isPassed(g.grade); if(passed1==true) System.out.println("Passed"); else System.out.println("Not Passed"); System.out.println("Calling the isPassed() of Undergrad object"); passed2= ug.isPassed(ug.grade); if(passed2==true) System.out.println("Passed"); else System.out.println("Not Passed"); } }
1,382
0.51013
0.48987
51
25.137255
22.951799
79
false
false
0
0
0
0
0
0
0.588235
false
false
7
61574c22987ee8a8d75ccddfd1ca8aef90cee578
33,114,197,880,542
eebe7ea49de7cccdb44b6ec1d56e79d4ec3726e3
/2020.05/2020.05.29 - AtCoder - 第三回 アルゴリズム実技検定/J.java
ea9906ff5a9c117cfb85084cd9a1191cbbb78146
[]
no_license
m1kit/cc-archive
https://github.com/m1kit/cc-archive
6dfbe702680230240491a7af4e7ad63f372df312
66ba7fb9e5b1c61af4a016f800d6c90f6f594ed2
refs/heads/master
"2021-06-28T21:54:02.658000"
"2020-09-08T09:38:58"
"2020-09-08T09:38:58"
150,690,803
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dev.mikit.atcoder; import dev.mikit.atcoder.lib.io.LightScanner; import dev.mikit.atcoder.lib.io.LightWriter; import dev.mikit.atcoder.lib.debug.Debug; import java.util.Map; import java.util.TreeMap; public class J { private static final int MOD = (int) 1e9 + 7; public void solve(int testNumber, LightScanner in, LightWriter out) { int n = in.ints(), m = in.ints(); int[] last = new int[n]; for (int i = 0; i < m; i++) { int a = in.ints(); int min = -1, max = n; while (max - min > 1) { int mid = (min + max) / 2; if (last[mid] >= a) min = mid; else max = mid; } if (max == n) { out.ans(-1).ln(); } else { last[max] = a; out.ans(max + 1).ln(); } } } }
UTF-8
Java
890
java
J.java
Java
[]
null
[]
package dev.mikit.atcoder; import dev.mikit.atcoder.lib.io.LightScanner; import dev.mikit.atcoder.lib.io.LightWriter; import dev.mikit.atcoder.lib.debug.Debug; import java.util.Map; import java.util.TreeMap; public class J { private static final int MOD = (int) 1e9 + 7; public void solve(int testNumber, LightScanner in, LightWriter out) { int n = in.ints(), m = in.ints(); int[] last = new int[n]; for (int i = 0; i < m; i++) { int a = in.ints(); int min = -1, max = n; while (max - min > 1) { int mid = (min + max) / 2; if (last[mid] >= a) min = mid; else max = mid; } if (max == n) { out.ans(-1).ln(); } else { last[max] = a; out.ans(max + 1).ln(); } } } }
890
0.473034
0.462921
33
25.969696
17.681499
73
false
false
0
0
0
0
0
0
0.69697
false
false
7
fbbe72f16e3087e6bd7f9b2c43af1e81d2cac207
11,630,771,465,128
4db84581bb50722474058915329228d20ec36640
/kylin-it/src/test/java/org/apache/kylin/storage/hbase/ITHBaseResourceStoreTest.java
314852296be13eceac9d00f3a89c1ea6ee8986eb
[ "Apache-2.0", "MIT" ]
permissive
edouardzyc/kylin
https://github.com/edouardzyc/kylin
27ffd8289981df2b9e49061e5c135b73912c4c7e
dcf5d7d862ed90ea97df73938c87d848b1a769b1
refs/heads/master
"2021-10-11T15:58:31.818000"
"2018-10-11T12:26:39"
"2018-10-15T01:43:15"
120,150,969
0
0
null
true
"2018-02-04T03:17:50"
"2018-02-04T03:17:50"
"2018-02-02T12:50:00"
"2018-02-04T01:44:31"
275,464
0
0
0
null
false
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kylin.storage.hbase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.DataInputStream; import java.io.IOException; import java.util.List; import java.util.UUID; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.kylin.common.KylinConfig; import org.apache.kylin.common.persistence.RawResource; import org.apache.kylin.common.persistence.ResourceStore; import org.apache.kylin.common.persistence.ResourceStoreTest; import org.apache.kylin.common.persistence.StringEntity; import org.apache.kylin.common.persistence.WriteConflictException; import org.apache.kylin.common.util.HBaseMetadataTestCase; import org.apache.kylin.common.util.HadoopUtil; import org.apache.kylin.job.dao.ExecutableOutoutPOSerializer; import org.apache.kylin.job.dao.ExecutableOutputPO; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class ITHBaseResourceStoreTest extends HBaseMetadataTestCase { private KylinConfig kylinConfig; private String path = "/table_snapshot/_test_put_resource_streaming.json"; private String tmpPath = path + ".tmp"; private String contentStr = "THIS_IS_PUT_RESOURCE_STREAMING"; private StringEntity content = new StringEntity(contentStr); private ResourceStore store; private String exceptionStr = "EXCEPTION"; private StringEntity exception = new StringEntity(exceptionStr); private Path realPath; private FileSystem fileSystem; private Configuration originConfiguration; @Before public void setup() throws Exception { this.createTestMetadata(); kylinConfig = KylinConfig.getInstanceFromEnv(); store = ResourceStore.getStore(kylinConfig); realPath = store.resourcePath(path); fileSystem = HadoopUtil.getFileSystem(realPath); originConfiguration = HBaseConnection.getCurrentHBaseConfiguration(); } @After public void after() throws Exception { this.cleanupTestMetadata(); store.deleteResource(path); content.setLastModified(0); HadoopUtil.setCurrentConfiguration(new Configuration()); HBaseConnection.setHBaseConfiguration(originConfiguration); } @Test public void testHBaseStore() throws Exception { String storeName = "org.apache.kylin.storage.hbase.HBaseResourceStore"; ResourceStoreTest.testAStore(ResourceStoreTest.mockUrl("hbase", kylinConfig), kylinConfig); } @Test public void testGetResourceImpl() throws Exception { ExecutableOutoutPOSerializer executableOutputPOSerializer = new ExecutableOutoutPOSerializer(); String uuid = UUID.randomUUID().toString(); String path = ResourceStore.EXECUTE_OUTPUT_RESOURCE_ROOT + "/" + uuid; String largeContent = "THIS_IS_A_LARGE_CELL"; StringEntity largeEntity = new StringEntity(largeContent); String oldUrl = ResourceStoreTest.replaceMetadataUrl(kylinConfig, ResourceStoreTest.mockUrl("hbase", kylinConfig)); HBaseResourceStore store = new HBaseResourceStore(KylinConfig.getInstanceFromEnv()); Configuration hconf = store.getConnection().getConfiguration(); int origSize = Integer.parseInt(hconf.get("hbase.client.keyvalue.maxsize", "10485760")); try { hconf.set("hbase.client.keyvalue.maxsize", String.valueOf(largeContent.length() - 1)); store.deleteResource(path); store.putResource(path, largeEntity, StringEntity.serializer); Path redirectPath = ((HBaseResourceStore) store).bigCellHDFSPath(path); FileSystem fileSystem = HadoopUtil.getWorkingFileSystem(); fileSystem.delete(redirectPath, true); try { RawResource resource1 = store.getResourceImpl(path, false); fail("Expected a IOException to be thrown"); } catch (Exception e) { Assert.assertTrue(e instanceof IOException); } RawResource resource2 = store.getResourceImpl(path, true); ExecutableOutputPO brokenOutput = executableOutputPOSerializer .deserialize(new DataInputStream(resource2.inputStream)); Assert.assertEquals(uuid, brokenOutput.getUuid()); ResourceStoreTest.replaceMetadataUrl(kylinConfig, oldUrl); } finally { hconf.set("hbase.client.keyvalue.maxsize", "" + origSize); store.deleteResource(path); } } @Test public void testGetAllResourcesImpl() throws Exception { String path = ResourceStore.EXECUTE_OUTPUT_RESOURCE_ROOT + "/" + UUID.randomUUID().toString(); String largeContent = "THIS_IS_A_LARGE_CELL"; String samllContent = "SMALL_CELL"; StringEntity largeEntity = new StringEntity(largeContent); StringEntity smallEntity1 = new StringEntity(samllContent); StringEntity smallEntity2 = new StringEntity(samllContent); String oldUrl = ResourceStoreTest.replaceMetadataUrl(kylinConfig, ResourceStoreTest.mockUrl("hbase", kylinConfig)); HBaseResourceStore store = new HBaseResourceStore(KylinConfig.getInstanceFromEnv()); Configuration hconf = store.getConnection().getConfiguration(); int origSize = Integer.parseInt(hconf.get("hbase.client.keyvalue.maxsize", "10485760")); try { hconf.set("hbase.client.keyvalue.maxsize", String.valueOf(largeContent.length() - 1)); store.deleteResource(path); store.deleteResource(path + "00"); store.deleteResource(path + "01"); store.putResource(path, smallEntity1, StringEntity.serializer); store.putResource(path + "-00", largeEntity, StringEntity.serializer); store.putResource(path + "-01", smallEntity2, StringEntity.serializer); Path redirectPath = ((HBaseResourceStore) store).bigCellHDFSPath(path + "-00"); FileSystem fileSystem = HadoopUtil.getWorkingFileSystem(); fileSystem.delete(redirectPath, true); try { List<RawResource> resources1 = store.getAllResourcesImpl(ResourceStore.EXECUTE_OUTPUT_RESOURCE_ROOT, Long.MIN_VALUE, Long.MAX_VALUE, false); fail("Expected a IOException to be thrown"); } catch (Exception e) { Assert.assertTrue(e instanceof IOException); } List<RawResource> resources2 = store.getAllResourcesImpl(ResourceStore.EXECUTE_OUTPUT_RESOURCE_ROOT, Long.MIN_VALUE, Long.MAX_VALUE, true); ResourceStoreTest.replaceMetadataUrl(kylinConfig, oldUrl); } finally { hconf.set("hbase.client.keyvalue.maxsize", "" + origSize); store.deleteResource(path); store.deleteResource(path + "00"); store.deleteResource(path + "01"); } } @Test public void testHBaseStoreWithLargeCell() throws Exception { String path = "/cube/_test_large_cell.json"; String largeContent = "THIS_IS_A_LARGE_CELL"; StringEntity content = new StringEntity(largeContent); String oldUrl = ResourceStoreTest.replaceMetadataUrl(kylinConfig, ResourceStoreTest.mockUrl("hbase", kylinConfig)); HBaseResourceStore store = new HBaseResourceStore(KylinConfig.getInstanceFromEnv()); Configuration hconf = store.getConnection().getConfiguration(); int origSize = Integer.parseInt(hconf.get("hbase.client.keyvalue.maxsize", "10485760")); try { hconf.set("hbase.client.keyvalue.maxsize", String.valueOf(largeContent.length() - 1)); store.deleteResource(path); store.putResource(path, content, StringEntity.serializer); assertTrue(store.exists(path)); StringEntity t = store.getResource(path, StringEntity.class, StringEntity.serializer); assertEquals(content, t); Path redirectPath = ((HBaseResourceStore) store).bigCellHDFSPath(path); FileSystem fileSystem = HadoopUtil.getWorkingFileSystem(); assertTrue(fileSystem.exists(redirectPath)); FSDataInputStream in = fileSystem.open(redirectPath); assertEquals(largeContent, in.readUTF()); in.close(); store.deleteResource(path); ResourceStoreTest.replaceMetadataUrl(kylinConfig, oldUrl); } finally { hconf.set("hbase.client.keyvalue.maxsize", "" + origSize); store.deleteResource(path); } } @Test public void testPutResourceStreaming() throws IOException { store.putResourceStreaming(path, content, StringEntity.serializer); assertTrue(store.exists(path)); StringEntity t = store.getResource(path, StringEntity.class, StringEntity.serializer); assertEquals(content, t); FileSystem fileSystem = HadoopUtil.getWorkingFileSystem(); assertTrue(fileSystem.exists(realPath)); FSDataInputStream in = fileSystem.open(realPath); assertEquals(contentStr, in.readUTF()); in.close(); } @Test public void testWithWriteConflictException() throws IOException { store.putResourceStreaming(path, content, StringEntity.serializer); assertTrue(store.exists(path)); FSDataInputStream in = fileSystem.open(realPath); StringEntity exception = new StringEntity("THIS_IS_EXCEPTION"); try { store.putResourceStreaming(path, exception, StringEntity.serializer); } catch (Exception e) { assertTrue(e instanceof WriteConflictException); in.close(); } StringEntity t = store.getResource(path, StringEntity.class, StringEntity.serializer); assertEquals(content, t); assertFalse(fileSystem.exists(store.resourcePath(tmpPath))); in = fileSystem.open(realPath); assertEquals(contentStr, in.readUTF()); in.close(); } @Test public void testWithException() throws IOException { runExceptionCase("org.apache.kylin.storage.DistributedExceptionFileSystem.RenameExceptionFileSystem", "TEST RENAME EXCEPTION"); } private void runExceptionCase(String className, String expectedMessage) throws IOException { // write a resource long ts = store.putResourceStreaming(path, content, StringEntity.serializer); // use exception file system KylinConfig.destroyInstance(); KylinConfig exceptionConfig = KylinConfig.getInstanceFromEnv(); Configuration conf = new Configuration(); conf.set("fs.hdfs.impl", className); conf.set("fs.hdfs.impl.disable.cache", "true"); HBaseConnection.setHBaseConfiguration(conf); ResourceStore exceptionStore = ResourceStore.getStore(exceptionConfig); ResourceStore.Checkpoint cp = exceptionStore.checkpoint(); try { exception.setLastModified(ts); exceptionStore.putResourceStreaming(path, exception, StringEntity.serializer); } catch (IOException e) { HBaseConnection.setHBaseConfiguration(originConfiguration); HadoopUtil.setCurrentConfiguration(new Configuration()); cp.rollback(); assertFalse(HadoopUtil.getWorkingFileSystem().exists(exceptionStore.resourcePath(tmpPath))); assertEquals(expectedMessage, e.getMessage()); exception.setLastModified(0); } // check rollback success StringEntity t = store.getResource(path, StringEntity.class, StringEntity.serializer); assertEquals(content, t); } }
UTF-8
Java
12,783
java
ITHBaseResourceStoreTest.java
Java
[]
null
[]
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kylin.storage.hbase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.DataInputStream; import java.io.IOException; import java.util.List; import java.util.UUID; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.kylin.common.KylinConfig; import org.apache.kylin.common.persistence.RawResource; import org.apache.kylin.common.persistence.ResourceStore; import org.apache.kylin.common.persistence.ResourceStoreTest; import org.apache.kylin.common.persistence.StringEntity; import org.apache.kylin.common.persistence.WriteConflictException; import org.apache.kylin.common.util.HBaseMetadataTestCase; import org.apache.kylin.common.util.HadoopUtil; import org.apache.kylin.job.dao.ExecutableOutoutPOSerializer; import org.apache.kylin.job.dao.ExecutableOutputPO; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class ITHBaseResourceStoreTest extends HBaseMetadataTestCase { private KylinConfig kylinConfig; private String path = "/table_snapshot/_test_put_resource_streaming.json"; private String tmpPath = path + ".tmp"; private String contentStr = "THIS_IS_PUT_RESOURCE_STREAMING"; private StringEntity content = new StringEntity(contentStr); private ResourceStore store; private String exceptionStr = "EXCEPTION"; private StringEntity exception = new StringEntity(exceptionStr); private Path realPath; private FileSystem fileSystem; private Configuration originConfiguration; @Before public void setup() throws Exception { this.createTestMetadata(); kylinConfig = KylinConfig.getInstanceFromEnv(); store = ResourceStore.getStore(kylinConfig); realPath = store.resourcePath(path); fileSystem = HadoopUtil.getFileSystem(realPath); originConfiguration = HBaseConnection.getCurrentHBaseConfiguration(); } @After public void after() throws Exception { this.cleanupTestMetadata(); store.deleteResource(path); content.setLastModified(0); HadoopUtil.setCurrentConfiguration(new Configuration()); HBaseConnection.setHBaseConfiguration(originConfiguration); } @Test public void testHBaseStore() throws Exception { String storeName = "org.apache.kylin.storage.hbase.HBaseResourceStore"; ResourceStoreTest.testAStore(ResourceStoreTest.mockUrl("hbase", kylinConfig), kylinConfig); } @Test public void testGetResourceImpl() throws Exception { ExecutableOutoutPOSerializer executableOutputPOSerializer = new ExecutableOutoutPOSerializer(); String uuid = UUID.randomUUID().toString(); String path = ResourceStore.EXECUTE_OUTPUT_RESOURCE_ROOT + "/" + uuid; String largeContent = "THIS_IS_A_LARGE_CELL"; StringEntity largeEntity = new StringEntity(largeContent); String oldUrl = ResourceStoreTest.replaceMetadataUrl(kylinConfig, ResourceStoreTest.mockUrl("hbase", kylinConfig)); HBaseResourceStore store = new HBaseResourceStore(KylinConfig.getInstanceFromEnv()); Configuration hconf = store.getConnection().getConfiguration(); int origSize = Integer.parseInt(hconf.get("hbase.client.keyvalue.maxsize", "10485760")); try { hconf.set("hbase.client.keyvalue.maxsize", String.valueOf(largeContent.length() - 1)); store.deleteResource(path); store.putResource(path, largeEntity, StringEntity.serializer); Path redirectPath = ((HBaseResourceStore) store).bigCellHDFSPath(path); FileSystem fileSystem = HadoopUtil.getWorkingFileSystem(); fileSystem.delete(redirectPath, true); try { RawResource resource1 = store.getResourceImpl(path, false); fail("Expected a IOException to be thrown"); } catch (Exception e) { Assert.assertTrue(e instanceof IOException); } RawResource resource2 = store.getResourceImpl(path, true); ExecutableOutputPO brokenOutput = executableOutputPOSerializer .deserialize(new DataInputStream(resource2.inputStream)); Assert.assertEquals(uuid, brokenOutput.getUuid()); ResourceStoreTest.replaceMetadataUrl(kylinConfig, oldUrl); } finally { hconf.set("hbase.client.keyvalue.maxsize", "" + origSize); store.deleteResource(path); } } @Test public void testGetAllResourcesImpl() throws Exception { String path = ResourceStore.EXECUTE_OUTPUT_RESOURCE_ROOT + "/" + UUID.randomUUID().toString(); String largeContent = "THIS_IS_A_LARGE_CELL"; String samllContent = "SMALL_CELL"; StringEntity largeEntity = new StringEntity(largeContent); StringEntity smallEntity1 = new StringEntity(samllContent); StringEntity smallEntity2 = new StringEntity(samllContent); String oldUrl = ResourceStoreTest.replaceMetadataUrl(kylinConfig, ResourceStoreTest.mockUrl("hbase", kylinConfig)); HBaseResourceStore store = new HBaseResourceStore(KylinConfig.getInstanceFromEnv()); Configuration hconf = store.getConnection().getConfiguration(); int origSize = Integer.parseInt(hconf.get("hbase.client.keyvalue.maxsize", "10485760")); try { hconf.set("hbase.client.keyvalue.maxsize", String.valueOf(largeContent.length() - 1)); store.deleteResource(path); store.deleteResource(path + "00"); store.deleteResource(path + "01"); store.putResource(path, smallEntity1, StringEntity.serializer); store.putResource(path + "-00", largeEntity, StringEntity.serializer); store.putResource(path + "-01", smallEntity2, StringEntity.serializer); Path redirectPath = ((HBaseResourceStore) store).bigCellHDFSPath(path + "-00"); FileSystem fileSystem = HadoopUtil.getWorkingFileSystem(); fileSystem.delete(redirectPath, true); try { List<RawResource> resources1 = store.getAllResourcesImpl(ResourceStore.EXECUTE_OUTPUT_RESOURCE_ROOT, Long.MIN_VALUE, Long.MAX_VALUE, false); fail("Expected a IOException to be thrown"); } catch (Exception e) { Assert.assertTrue(e instanceof IOException); } List<RawResource> resources2 = store.getAllResourcesImpl(ResourceStore.EXECUTE_OUTPUT_RESOURCE_ROOT, Long.MIN_VALUE, Long.MAX_VALUE, true); ResourceStoreTest.replaceMetadataUrl(kylinConfig, oldUrl); } finally { hconf.set("hbase.client.keyvalue.maxsize", "" + origSize); store.deleteResource(path); store.deleteResource(path + "00"); store.deleteResource(path + "01"); } } @Test public void testHBaseStoreWithLargeCell() throws Exception { String path = "/cube/_test_large_cell.json"; String largeContent = "THIS_IS_A_LARGE_CELL"; StringEntity content = new StringEntity(largeContent); String oldUrl = ResourceStoreTest.replaceMetadataUrl(kylinConfig, ResourceStoreTest.mockUrl("hbase", kylinConfig)); HBaseResourceStore store = new HBaseResourceStore(KylinConfig.getInstanceFromEnv()); Configuration hconf = store.getConnection().getConfiguration(); int origSize = Integer.parseInt(hconf.get("hbase.client.keyvalue.maxsize", "10485760")); try { hconf.set("hbase.client.keyvalue.maxsize", String.valueOf(largeContent.length() - 1)); store.deleteResource(path); store.putResource(path, content, StringEntity.serializer); assertTrue(store.exists(path)); StringEntity t = store.getResource(path, StringEntity.class, StringEntity.serializer); assertEquals(content, t); Path redirectPath = ((HBaseResourceStore) store).bigCellHDFSPath(path); FileSystem fileSystem = HadoopUtil.getWorkingFileSystem(); assertTrue(fileSystem.exists(redirectPath)); FSDataInputStream in = fileSystem.open(redirectPath); assertEquals(largeContent, in.readUTF()); in.close(); store.deleteResource(path); ResourceStoreTest.replaceMetadataUrl(kylinConfig, oldUrl); } finally { hconf.set("hbase.client.keyvalue.maxsize", "" + origSize); store.deleteResource(path); } } @Test public void testPutResourceStreaming() throws IOException { store.putResourceStreaming(path, content, StringEntity.serializer); assertTrue(store.exists(path)); StringEntity t = store.getResource(path, StringEntity.class, StringEntity.serializer); assertEquals(content, t); FileSystem fileSystem = HadoopUtil.getWorkingFileSystem(); assertTrue(fileSystem.exists(realPath)); FSDataInputStream in = fileSystem.open(realPath); assertEquals(contentStr, in.readUTF()); in.close(); } @Test public void testWithWriteConflictException() throws IOException { store.putResourceStreaming(path, content, StringEntity.serializer); assertTrue(store.exists(path)); FSDataInputStream in = fileSystem.open(realPath); StringEntity exception = new StringEntity("THIS_IS_EXCEPTION"); try { store.putResourceStreaming(path, exception, StringEntity.serializer); } catch (Exception e) { assertTrue(e instanceof WriteConflictException); in.close(); } StringEntity t = store.getResource(path, StringEntity.class, StringEntity.serializer); assertEquals(content, t); assertFalse(fileSystem.exists(store.resourcePath(tmpPath))); in = fileSystem.open(realPath); assertEquals(contentStr, in.readUTF()); in.close(); } @Test public void testWithException() throws IOException { runExceptionCase("org.apache.kylin.storage.DistributedExceptionFileSystem.RenameExceptionFileSystem", "TEST RENAME EXCEPTION"); } private void runExceptionCase(String className, String expectedMessage) throws IOException { // write a resource long ts = store.putResourceStreaming(path, content, StringEntity.serializer); // use exception file system KylinConfig.destroyInstance(); KylinConfig exceptionConfig = KylinConfig.getInstanceFromEnv(); Configuration conf = new Configuration(); conf.set("fs.hdfs.impl", className); conf.set("fs.hdfs.impl.disable.cache", "true"); HBaseConnection.setHBaseConfiguration(conf); ResourceStore exceptionStore = ResourceStore.getStore(exceptionConfig); ResourceStore.Checkpoint cp = exceptionStore.checkpoint(); try { exception.setLastModified(ts); exceptionStore.putResourceStreaming(path, exception, StringEntity.serializer); } catch (IOException e) { HBaseConnection.setHBaseConfiguration(originConfiguration); HadoopUtil.setCurrentConfiguration(new Configuration()); cp.rollback(); assertFalse(HadoopUtil.getWorkingFileSystem().exists(exceptionStore.resourcePath(tmpPath))); assertEquals(expectedMessage, e.getMessage()); exception.setLastModified(0); } // check rollback success StringEntity t = store.getResource(path, StringEntity.class, StringEntity.serializer); assertEquals(content, t); } }
12,783
0.689275
0.684894
296
42.18581
30.63102
116
false
false
0
0
0
0
0
0
0.827703
false
false
7
59dc8f1e3c3f67b992e9f756be089cdd77504aea
22,737,556,906,884
0cb6744a78464e4d949e8b7b60d5363060a69c02
/src/main/java/org/thiki/kanban/teams/teamMembers/MembersResource.java
862d176e90ffa7e3272bb53a5c450320f0bc1711
[]
no_license
eseawind/thiki-kanban-backend
https://github.com/eseawind/thiki-kanban-backend
f614544a7a143bdb871dba6ecc3ce37b4e8aff18
da1209162e84b743ba98662e065b3b0656fb5110
refs/heads/go
"2021-01-11T12:18:57.136000"
"2016-12-05T04:22:49"
"2016-12-05T04:22:49"
76,467,986
0
1
null
true
"2016-12-14T14:43:16"
"2016-12-14T14:43:16"
"2016-10-24T07:18:58"
"2016-12-05T04:23:00"
4,493
0
0
0
null
null
null
package org.thiki.kanban.teams.teamMembers; import org.springframework.hateoas.Link; import org.thiki.kanban.foundation.common.RestResource; import org.thiki.kanban.teams.invitation.InvitationController; import java.util.ArrayList; import java.util.List; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; /** * Created by xubt on 9/10/16. */ public class MembersResource extends RestResource { public MembersResource(String teamId, String userName, List<Member> members) throws Exception { List<MemberResource> memberResources = new ArrayList<>(); for (Member member : members) { MemberResource memberResource = new MemberResource(teamId, member); memberResources.add(memberResource); } this.buildDataObject("members", memberResources); Link invitationLink = linkTo(methodOn(InvitationController.class).invite(null, teamId, userName)).withRel("invitation"); this.add(invitationLink); Link memberLink = linkTo(methodOn(TeamMembersController.class).getMember(teamId, userName)).withRel("member"); this.add(memberLink); } }
UTF-8
Java
1,231
java
MembersResource.java
Java
[ { "context": "ControllerLinkBuilder.methodOn;\n\n/**\n * Created by xubt on 9/10/16.\n */\npublic class MembersResource exte", "end": 435, "score": 0.9996190071105957, "start": 431, "tag": "USERNAME", "value": "xubt" } ]
null
[]
package org.thiki.kanban.teams.teamMembers; import org.springframework.hateoas.Link; import org.thiki.kanban.foundation.common.RestResource; import org.thiki.kanban.teams.invitation.InvitationController; import java.util.ArrayList; import java.util.List; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; /** * Created by xubt on 9/10/16. */ public class MembersResource extends RestResource { public MembersResource(String teamId, String userName, List<Member> members) throws Exception { List<MemberResource> memberResources = new ArrayList<>(); for (Member member : members) { MemberResource memberResource = new MemberResource(teamId, member); memberResources.add(memberResource); } this.buildDataObject("members", memberResources); Link invitationLink = linkTo(methodOn(InvitationController.class).invite(null, teamId, userName)).withRel("invitation"); this.add(invitationLink); Link memberLink = linkTo(methodOn(TeamMembersController.class).getMember(teamId, userName)).withRel("member"); this.add(memberLink); } }
1,231
0.746548
0.742486
33
36.303032
36.013031
128
false
false
0
0
0
0
0
0
0.69697
false
false
7
7851a1bde9e4cba9f214ec7d81326f94b4340ebf
6,055,903,915,761
551636fb0c66b76fcafbd266c915655aab4a0e72
/src/main/java/services/datasource/AggregatedDataSource.java
e4524576170c8557b4f4cd43b46210c67e5d1ed8
[]
no_license
andrewtikhonov/Geuvadis-Browser
https://github.com/andrewtikhonov/Geuvadis-Browser
b83969bc90b4e431fd894133299e52cec612918d
a241ea1c345007fc46986aaa33899fb5c8f1a646
refs/heads/master
"2021-07-14T12:13:52.399000"
"2017-10-19T15:16:42"
"2017-10-19T15:16:42"
107,555,993
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package services.datasource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import services.data.DataFeature; import services.data.LinkedFeature; import services.datasource.eQTL.ExonEQTLSource; import services.datasource.eQTL.TransEQTLSource; import services.datasource.generic.DataSourceInterface; import services.datasource.generic.GenericEQTLDataSource; import services.datasource.generic.GenericQuantDataSource; import services.datasource.quant.ExonQuantSource; import services.datasource.quant.TransQuantSource; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; /** * Created with IntelliJ IDEA. * User: andrew * Date: 04/12/2012 * Time: 11:18 * To change this template use File | Settings | File Templates. */ public class AggregatedDataSource implements AggregatedSourceInterface { private final static Logger log = LoggerFactory.getLogger(AggregatedDataSource.class); public DataSourceInterface quantSource; public DataSourceInterface eQTLSource; public AggregatedDataSource(DataSourceInterface quantSource, DataSourceInterface eQTLSource) throws Exception { this.quantSource = quantSource; this.eQTLSource = eQTLSource; } // // G E T T E R S // public ArrayList<DataFeature> locateQuantFeatures(String segmentId, int start, int stop) { return quantSource.locateSegment(segmentId).locateFeatures(start, stop); } public ArrayList<DataFeature> locateEQTLFeatures(String segmentId, int start, int stop) { return eQTLSource.locateSegment(segmentId).locateFeatures(start, stop); } public ArrayList<DataFeature> locateQuantFeatureByID(String featureId) { return quantSource.locateFeatureByID(featureId); } public ArrayList<DataFeature> locateEQTLFeatureByID(String featureId) { return eQTLSource.locateFeatureByID(featureId); } public ArrayList<DataFeature> locateQuantFeatureByID(String featureId, String segmentId) { return quantSource.locateFeatureByID(featureId, segmentId); } public ArrayList<DataFeature> locateEQTLFeatureByID(String featureId, String segmentId) { return eQTLSource.locateFeatureByID(featureId, segmentId); } // // M A I N // public static void main(String[] a){ try { log.info("loading.."); //ExonQuantSource qs = new ExonQuantSource(new FileInputStream(System.getProperty("exon.quant.source"))); //ExonEQTLSource es = new ExonEQTLSource(new FileInputStream(System.getProperty("exon.eqtl.source")), qs); TransQuantSource qs = new TransQuantSource(new FileInputStream(System.getProperty("exon.quant.source"))); TransEQTLSource es = new TransEQTLSource(new FileInputStream(System.getProperty("exon.eqtl.source")), qs); AggregatedDataSource aggregatedSource = new AggregatedDataSource(qs, es); log.info("loaded"); log.info(" " + ((GenericQuantDataSource)aggregatedSource.quantSource).getStats()); log.info(" " + ((GenericEQTLDataSource)aggregatedSource.eQTLSource).getStats()); String chr = "1"; int start = 1628906; int stop = 1629906; log.info("selecting " + chr + ":" + start + "-" + stop); ArrayList<DataFeature> quantResult = null; ArrayList<DataFeature> eQTLResult = null; long startTime = System.currentTimeMillis(); quantResult = aggregatedSource.locateQuantFeatures(chr, start, stop); eQTLResult = aggregatedSource.locateEQTLFeatures(chr, start, stop); //for(int i=9;i<1000;i++) { //} long estimatedTime = System.currentTimeMillis() - startTime; log.info("Estimated run time:" + estimatedTime + " Millis"); log.info("quantResult.size() = " + quantResult.size()); log.info("eQTLResult.size() = " + eQTLResult.size()); for (DataFeature f : quantResult) { log.info("1 f = " + f.getId() + " start:" + f.getStart() + " end:" + f.getEnd() + " score:" + f.getScore() ); } for (DataFeature f : eQTLResult) { log.info("f = " + f.getId() + " start:" + f.getStart() + " end:" + f.getEnd() + " score:" + f.getScore()); log.info("linked to :"); for (LinkedFeature l0 : f.getLinked()) { log.info(" linked = " + l0.getFeature().getId() + " start:" + l0.getFeature().getStart() + " end:" + l0.getFeature().getEnd() + " link score:" + l0.getLinkScore()); } } } catch (FileNotFoundException e) { // Auto-generated catch block log.error("Error!", e); } catch (Exception e) { // Auto-generated catch block log.error("Error!", e); } } }
UTF-8
Java
4,977
java
AggregatedDataSource.java
Java
[ { "context": "List;\n\n/**\n * Created with IntelliJ IDEA.\n * User: andrew\n * Date: 04/12/2012\n * Time: 11:18\n * To change t", "end": 678, "score": 0.8441452980041504, "start": 672, "tag": "USERNAME", "value": "andrew" } ]
null
[]
package services.datasource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import services.data.DataFeature; import services.data.LinkedFeature; import services.datasource.eQTL.ExonEQTLSource; import services.datasource.eQTL.TransEQTLSource; import services.datasource.generic.DataSourceInterface; import services.datasource.generic.GenericEQTLDataSource; import services.datasource.generic.GenericQuantDataSource; import services.datasource.quant.ExonQuantSource; import services.datasource.quant.TransQuantSource; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; /** * Created with IntelliJ IDEA. * User: andrew * Date: 04/12/2012 * Time: 11:18 * To change this template use File | Settings | File Templates. */ public class AggregatedDataSource implements AggregatedSourceInterface { private final static Logger log = LoggerFactory.getLogger(AggregatedDataSource.class); public DataSourceInterface quantSource; public DataSourceInterface eQTLSource; public AggregatedDataSource(DataSourceInterface quantSource, DataSourceInterface eQTLSource) throws Exception { this.quantSource = quantSource; this.eQTLSource = eQTLSource; } // // G E T T E R S // public ArrayList<DataFeature> locateQuantFeatures(String segmentId, int start, int stop) { return quantSource.locateSegment(segmentId).locateFeatures(start, stop); } public ArrayList<DataFeature> locateEQTLFeatures(String segmentId, int start, int stop) { return eQTLSource.locateSegment(segmentId).locateFeatures(start, stop); } public ArrayList<DataFeature> locateQuantFeatureByID(String featureId) { return quantSource.locateFeatureByID(featureId); } public ArrayList<DataFeature> locateEQTLFeatureByID(String featureId) { return eQTLSource.locateFeatureByID(featureId); } public ArrayList<DataFeature> locateQuantFeatureByID(String featureId, String segmentId) { return quantSource.locateFeatureByID(featureId, segmentId); } public ArrayList<DataFeature> locateEQTLFeatureByID(String featureId, String segmentId) { return eQTLSource.locateFeatureByID(featureId, segmentId); } // // M A I N // public static void main(String[] a){ try { log.info("loading.."); //ExonQuantSource qs = new ExonQuantSource(new FileInputStream(System.getProperty("exon.quant.source"))); //ExonEQTLSource es = new ExonEQTLSource(new FileInputStream(System.getProperty("exon.eqtl.source")), qs); TransQuantSource qs = new TransQuantSource(new FileInputStream(System.getProperty("exon.quant.source"))); TransEQTLSource es = new TransEQTLSource(new FileInputStream(System.getProperty("exon.eqtl.source")), qs); AggregatedDataSource aggregatedSource = new AggregatedDataSource(qs, es); log.info("loaded"); log.info(" " + ((GenericQuantDataSource)aggregatedSource.quantSource).getStats()); log.info(" " + ((GenericEQTLDataSource)aggregatedSource.eQTLSource).getStats()); String chr = "1"; int start = 1628906; int stop = 1629906; log.info("selecting " + chr + ":" + start + "-" + stop); ArrayList<DataFeature> quantResult = null; ArrayList<DataFeature> eQTLResult = null; long startTime = System.currentTimeMillis(); quantResult = aggregatedSource.locateQuantFeatures(chr, start, stop); eQTLResult = aggregatedSource.locateEQTLFeatures(chr, start, stop); //for(int i=9;i<1000;i++) { //} long estimatedTime = System.currentTimeMillis() - startTime; log.info("Estimated run time:" + estimatedTime + " Millis"); log.info("quantResult.size() = " + quantResult.size()); log.info("eQTLResult.size() = " + eQTLResult.size()); for (DataFeature f : quantResult) { log.info("1 f = " + f.getId() + " start:" + f.getStart() + " end:" + f.getEnd() + " score:" + f.getScore() ); } for (DataFeature f : eQTLResult) { log.info("f = " + f.getId() + " start:" + f.getStart() + " end:" + f.getEnd() + " score:" + f.getScore()); log.info("linked to :"); for (LinkedFeature l0 : f.getLinked()) { log.info(" linked = " + l0.getFeature().getId() + " start:" + l0.getFeature().getStart() + " end:" + l0.getFeature().getEnd() + " link score:" + l0.getLinkScore()); } } } catch (FileNotFoundException e) { // Auto-generated catch block log.error("Error!", e); } catch (Exception e) { // Auto-generated catch block log.error("Error!", e); } } }
4,977
0.647378
0.639341
138
35.065216
35.004597
121
false
false
0
0
0
0
0
0
0.717391
false
false
7
4b9b0439353938c27dad0489e1aa23a009ac4abd
15,187,004,416,763
4f5397e50bb7fc8c5e2b4b576757a1651ec0e17e
/lintra/src/transfo/ModelLoader_Single.java
8ff26f64df3716692200bb604bee2c1e38d217f3
[]
no_license
atenearesearchgroup/lintra
https://github.com/atenearesearchgroup/lintra
9f867f97a44ec707c55313a5ce24c5a70be8928b
a59afb22e41542d710a2e6a8bb8b53150e65327e
refs/heads/master
"2020-03-15T11:55:19.173000"
"2018-07-17T14:39:54"
"2018-07-17T14:39:54"
132,132,199
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package transfo; import java.io.EOFException; import java.io.FileInputStream; import java.io.ObjectInputStream; import java.util.LinkedList; import java.util.List; import blackboard.BlackboardException; import blackboard.IArea; import blackboard.IdentifiableElement; public class ModelLoader_Single implements Runnable { protected String modelPath; protected IArea srcModelArea; public ModelLoader_Single(String modelPath, IArea modelArea) { this.modelPath = modelPath; this.srcModelArea = modelArea; } @Override public void run() { // ClassModelGeneration cmg = new ClassModelGeneration(area); // cmg.loadModel(model, area); try { FileInputStream fis = new FileInputStream(modelPath); ObjectInputStream ois = new ObjectInputStream(fis); Object o = ois.readObject(); try { while (o != null) { srcModelArea.write((IdentifiableElement)o); o = ois.readObject(); } ois.close(); fis.close(); } catch (EOFException e) { // when this exception is thrown means that there are no more // objects in the file. ois.close(); fis.close(); } } catch (Exception e) { e.printStackTrace(); } } }
UTF-8
Java
1,193
java
ModelLoader_Single.java
Java
[]
null
[]
package transfo; import java.io.EOFException; import java.io.FileInputStream; import java.io.ObjectInputStream; import java.util.LinkedList; import java.util.List; import blackboard.BlackboardException; import blackboard.IArea; import blackboard.IdentifiableElement; public class ModelLoader_Single implements Runnable { protected String modelPath; protected IArea srcModelArea; public ModelLoader_Single(String modelPath, IArea modelArea) { this.modelPath = modelPath; this.srcModelArea = modelArea; } @Override public void run() { // ClassModelGeneration cmg = new ClassModelGeneration(area); // cmg.loadModel(model, area); try { FileInputStream fis = new FileInputStream(modelPath); ObjectInputStream ois = new ObjectInputStream(fis); Object o = ois.readObject(); try { while (o != null) { srcModelArea.write((IdentifiableElement)o); o = ois.readObject(); } ois.close(); fis.close(); } catch (EOFException e) { // when this exception is thrown means that there are no more // objects in the file. ois.close(); fis.close(); } } catch (Exception e) { e.printStackTrace(); } } }
1,193
0.699078
0.699078
55
20.690908
18.499998
65
false
false
0
0
0
0
0
0
2.327273
false
false
7
63477a5515a50d271ed46a3ad04d6db2a0c32678
11,312,943,901,562
67b11305924ceaa2efcc360ee8cfe9fa238851a6
/src/org/garret/perst/Sphere.java
8c386f4308dc04602f067307ac0d90fc59a559e1
[]
no_license
Manfed/ZAKO2
https://github.com/Manfed/ZAKO2
89b0428bcad2febd1b9f1e0746ae9cafe1c3a494
6b9f962c764d73f09c475ca08e23cb85d700657b
refs/heads/master
"2021-01-10T17:03:29.179000"
"2016-04-03T18:09:38"
"2016-04-03T18:09:38"
54,489,390
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.garret.perst; /** * Floating point operations with error */ class FP { static final double EPSILON = 1.0E-06; static final boolean zero(double x) { return Math.abs(x) <= EPSILON; } static final boolean eq(double x, double y) { return zero(x - y); } static final boolean ne(double x, double y) { return !eq(x, y); } static final boolean lt(double x, double y) { return y - x > EPSILON; } static final boolean le(double x, double y) { return x - y <= EPSILON; } static final boolean gt(double x, double y) { return x - y > EPSILON; } static final boolean ge(double x, double y) { return y - x <= EPSILON; } }; /** * Point in 3D */ class Point3D { double x; double y; double z; final Point3D cross(Point3D p) { return new Point3D(y * p.z - z * p.y, z * p.x - x * p.z, x * p.y - y * p.x); } final double distance() { return Math.sqrt(x*x + y*y + z*z); } public boolean equals(Object o) { if (o instanceof Point3D) { Point3D p = (Point3D)o; return FP.eq(x, p.x) && FP.eq(y, p.y) && FP.eq(z, p.z); } return false; } final RectangleRn toRectangle() { return new RectangleRn(new double[]{x, y, z, x, y, z}); } final Sphere.Point toSpherePoint() { double rho = Math.sqrt(x*x + y*y); double lat, lng; if (0.0 == rho) { if (FP.zero(z)) { lat = 0.0; } else if (z > 0) { lat = Math.PI/2; } else { lat = -Math.PI/2; } } else { lat = Math.atan(z / rho); } lng = Math.atan2(y, x); if (FP.zero(lng)){ lng = 0.0; } else { if (lng < 0.0) { lng += Math.PI*2 ; } } return new Sphere.Point(lng, lat); } void addToRectangle(RectangleRn r) { addToRectangle(r, x, y, z); } static void addToRectangle(RectangleRn r, double ra, double dec) { double x = Math.cos(ra)*Math.cos(dec); double y = Math.sin(ra)*Math.cos(dec); double z = Math.sin(dec); addToRectangle(r, x, y, z); } static void addToRectangle(RectangleRn r, double x, double y, double z) { if (x < r.coords[0]) { r.coords[0] = x; } if (y < r.coords[1]) { r.coords[1] = y; } if (z < r.coords[2]) { r.coords[2] = z; } if (x > r.coords[3]) { r.coords[3] = x; } if (y > r.coords[4]) { r.coords[4] = y; } if (z > r.coords[5]) { r.coords[5] = z; } } Point3D(double ra, double dec) { x = Math.cos(ra)*Math.cos(dec); y = Math.sin(ra)*Math.cos(dec); z = Math.sin(dec); } Point3D() {} Point3D(Sphere.Point p) { this(p.ra, p.dec); } Point3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } } /** * Euler transformation */ class Euler { int phi_a; // first axis int theta_a; // second axis int psi_a; // third axis double phi; // first rotation angle double theta; // second rotation angle double psi; // third rotation angle static final int AXIS_X = 1; static final int AXIS_Y = 2; static final int AXIS_Z = 3; void transform(Point3D out, Point3D in) { int t = 0; double a, sa, ca; double x1, y1, z1; double x2, y2, z2; x1 = in.x; y1 = in.y; z1 = in.z; for (int i=0; i<3; i++) { switch (i) { case 0: a = phi; t = phi_a; break; case 1: a = theta; t = theta_a; break; default: a = psi; t = psi_a; break; } if (FP.zero(a)) { continue; } sa = Math.sin(a); ca = Math.cos(a); switch (t) { case AXIS_X : x2 = x1; y2 = ca*y1 - sa*z1; z2 = sa*y1 + ca*z1; break; case AXIS_Y : x2 = ca*x1 + sa*z1; y2 = y1; z2 = ca*z1 - sa*x1; break; default: x2 = ca*x1 - sa*y1; y2 = sa*x1 + ca*y1; z2 = z1; break; } x1 = x2; y1 = y2; z1 = z2; } out.x = x1; out.y = y1; out.z = z1; } } /** * Class for conversion equatorial coordinates to Cartesian R3 coordinates */ public class Sphere { /** * Common interface for all objects on sphere */ public interface SphereObject extends IValue { /** * Get wrapping 3D rectangle for this object */ public RectangleRn wrappingRectangle(); /** * Check if object contains specified point ( @param p sphere point */ public boolean contains(Point p); }; /** * Class representing point of equatorial coordinate system (astronomic or terrestrial) */ public static class Point implements SphereObject { /** * Right ascension or longitude */ public final double ra; /** * Declination or latitude */ public final double dec; public final double latitude() { return dec; } public final double longitude() { return ra; } // Fast implementation from Q3C public final double distance(Point p) { double x = Math.sin((ra - p.ra) / 2); x *= x; double y = Math.sin((dec - p.dec) / 2); y *= y; double z = Math.cos((dec + p.dec) / 2); z *= z; return 2 * Math.asin(Math.sqrt(x * (z - y) + y)); } public boolean equals(Object o) { if (o instanceof Point) { Point p = (Point)o; return FP.eq(ra, p.ra) && FP.eq(dec, p.dec); } return false; } public RectangleRn wrappingRectangle() { double x = Math.cos(ra)*Math.cos(dec); double y = Math.sin(ra)*Math.cos(dec); double z = Math.sin(dec); return new RectangleRn(new double[]{x, y, z, x, y, z}); } public PointRn toPointRn() { double x = Math.cos(ra)*Math.cos(dec); double y = Math.sin(ra)*Math.cos(dec); double z = Math.sin(dec); return new PointRn(new double[]{x, y, z}); } public boolean contains(Point p) { return equals(p); } public String toString() { return "(" + ra + "," + dec + ")"; } public Point(double ra, double dec) { this.ra = ra; this.dec = dec; } } public static class Box implements SphereObject { public final Point sw; // source-west public final Point ne; // nord-east public boolean equals(Object o) { if (o instanceof Box) { Box b = (Box)o; return sw.equals(b.sw) && ne.equals(b.ne); } return false; } public boolean contains(Point p) { return contains(p.ra, p.dec); } public boolean contains(double ra, double dec) { if ((FP.eq(dec,ne.dec) && FP.eq(dec, Math.PI/2)) || (FP.eq(dec,sw.dec) && FP.eq(dec, -Math.PI/2))) { return true; } if (FP.lt(dec, sw.dec) || FP.gt(dec, ne.dec)) { return false; } if (FP.gt(sw.ra, ne.ra)) { if (FP.gt(ra, sw.ra) || FP.lt(ra, ne.ra)) { return false; } } else { if (FP.lt(ra, sw.ra) || FP.gt(ra, ne.ra)) { return false; } } return true; } public RectangleRn wrappingRectangle() { RectangleRn r = sw.wrappingRectangle(); double ra, dec; Point3D.addToRectangle(r, ne.ra, ne.dec); Point3D.addToRectangle(r, sw.ra, ne.dec); Point3D.addToRectangle(r, ne.ra, sw.dec); // latitude closest to equator if (FP.ge(ne.dec, 0.0) && FP.le(sw.dec, 0.0)) { dec = 0.0; } else if (Math.abs(ne.dec) > Math.abs(sw.dec)) { dec = sw.dec; } else { dec = ne.dec; } for (ra = 0.0; ra < Math.PI*2-0.1; ra += Math.PI/2) { if (contains(ra, dec)) { Point3D.addToRectangle(r, ra, dec); } } return r; } public Box(Point sw, Point ne) { this.sw = sw; this.ne = ne; } }; public static class Circle implements SphereObject { public final Point center; public final double radius; public Circle(Point center, double radius) { this.center = center; this.radius = radius; } public String toString() { return "<" + center + "," + radius + ">"; } public boolean equals(Object o) { if (o instanceof Circle) { Circle c = (Circle)o; return center.equals(c.center) && FP.eq(radius, c.radius); } return false; } public boolean contains(Point p) { double distance = center.distance(p); return FP.le(distance, radius); } public RectangleRn wrappingRectangle() { Point3D[] v = new Point3D[8]; Point3D tv = new Point3D(); Euler euler = new Euler(); double r = Math.sin(radius); double d = Math.cos(radius); v[0] = new Point3D(-r, -r, d); v[1] = new Point3D(-r, +r, d); v[2] = new Point3D(+r, -r, d); v[3] = new Point3D(+r, +r, d); v[4] = new Point3D(-r, -r, 1.0); v[5] = new Point3D(-r, +r, 1.0); v[6] = new Point3D(+r, -r, 1.0); v[7] = new Point3D(+r, +r, 1.0); euler.psi_a = Euler.AXIS_X; euler.theta_a = Euler.AXIS_Z; euler.phi_a = Euler.AXIS_X; euler.phi = Math.PI/2 - center.dec; euler.theta = Math.PI/2 + center.ra; euler.psi = 0.0; Point3D min = new Point3D(1.0, 1.0, 1.0); Point3D max = new Point3D(-1.0, -1.0, -1.0); for (int i=0; i<8; i++) { euler.transform(tv, v[i]); if (tv.x < -1.0) { min.x = -1.0; } else if (tv.x > 1.0) { max.x = 1.0; } else { if (tv.x < min.x) { min.x = tv.x; } if (tv.x > max.x) { max.x = tv.x; } } if (tv.y < -1.0) { min.y = -1.0; } else if ( tv.y > 1.0 ) { max.y = 1.0; } else { if (tv.y < min.y) { min.y = tv.y; } if (tv.y > max.y) { max.y = tv.y; } } if (tv.z < -1.0) { min.z = -1.0; } else if (tv.z > 1.0) { max.z = 1.0; } else { if (tv.z < min.z) { min.z = tv.z; } if (tv.z > max.z) { max.z = tv.z; } } } return new RectangleRn(new double[]{min.x, min.y, min.z, max.x, max.y, max.z}); } } /** * A spherical ellipse is represented using two radii and * a Euler transformation ( ZXZ-axis ). The "untransformed" * ellipse is located on equator at position (0,0). The * large radius is along equator. */ public static class Ellipse implements SphereObject { /** * The large radius of an ellipse in radians */ public final double rad0; /** * The small radius of an ellipse in radians */ public final double rad1; /** * The first rotation angle around z axis */ public final double phi; /** * The second rotation angle around x axis */ public final double theta; /** * The last rotation angle around z axis */ public final double psi; public Ellipse(double rad0, double rad1, double phi, double theta, double psi) { this.rad0 = rad0; this.rad1 = rad1; this.phi = phi; this.theta = theta; this.psi = psi; } public Point center() { return new Point(psi, -theta); } public boolean contains(Point p) { // too complex implementation throw new UnsupportedOperationException(); } public boolean equals(Object o) { if (o instanceof Ellipse) { Ellipse e = (Ellipse)o; return FP.eq(rad0, e.rad0) && FP.eq(rad1, e.rad1) && FP.eq(phi, e.phi) && FP.eq(theta, e.theta) && FP.eq(psi, e.psi); } return false; } public RectangleRn wrappingRectangle() { Point3D[] v = new Point3D[8]; Point3D tv = new Point3D(); Euler euler = new Euler(); double r0 = Math.sin(rad0); double r1 = Math.sin(rad1); double d = Math.cos(rad1); v[0] = new Point3D(d, -r0, -r1); v[1] = new Point3D(d, +r0, -r1); v[2] = new Point3D(d, -r0, r1); v[3] = new Point3D(d, +r0, r1); v[4] = new Point3D(1.0, -r0, -r1); v[5] = new Point3D(1.0, +r0, -r1); v[6] = new Point3D(1.0, -r0, r1); v[7] = new Point3D(1.0, +r0, r1); euler.psi_a = Euler.AXIS_Z ; euler.theta_a = Euler.AXIS_Y; euler.phi_a = Euler.AXIS_X; euler.phi = phi; euler.theta = theta; euler.psi = psi; Point3D min = new Point3D(1.0, 1.0, 1.0); Point3D max = new Point3D(-1.0, -1.0, -1.0); for (int i=0; i<8; i++) { euler.transform(tv, v[i]); if (tv.x < -1.0) { min.x = -1.0; } else if (tv.x > 1.0) { max.x = 1.0; } else { if (tv.x < min.x) { min.x = tv.x; } if (tv.x > max.x) { max.x = tv.x; } } if (tv.y < -1.0) { min.y = -1.0; } else if ( tv.y > 1.0 ) { max.y = 1.0; } else { if (tv.y < min.y) { min.y = tv.y; } if (tv.y > max.y) { max.y = tv.y; } } if (tv.z < -1.0) { min.z = -1.0; } else if (tv.z > 1.0) { max.z = 1.0; } else { if (tv.z < min.z) { min.z = tv.z; } if (tv.z > max.z) { max.z = tv.z; } } } return new RectangleRn(new double[]{min.x, min.y, min.z, max.x, max.y, max.z}); } } public static class Line implements SphereObject { /** * The first rotation angle around z axis */ public final double phi; /** * The second rotation angle around x axis */ public final double theta; /** * The last rotation angle around z axis */ public final double psi; /** * The length of the line in radians */ public final double length; public boolean equals(Object o) { if (o instanceof Line) { Line l = (Line)o; return FP.eq(phi, l.phi) && FP.eq(theta, l.theta) && FP.eq(psi, l.psi) && FP.eq(length, l.length); } return false; } public boolean contains(Point p) { Euler euler = new Euler(); Point3D spt = new Point3D(); euler.phi = -psi; euler.theta = -theta; euler.psi = -phi; euler.psi_a = Euler.AXIS_Z; euler.theta_a = Euler.AXIS_X; euler.phi_a = Euler.AXIS_Z; euler.transform(spt, new Point3D(p)); Point sp = spt.toSpherePoint(); return FP.zero(sp.dec) && FP.ge(sp.ra, 0.0) && FP.le(sp.ra, length); } public static Line meridian(double ra) { return new Line(-Math.PI/2, Math.PI/2, ra < 0.0 ? Math.PI*2 + ra : ra, Math.PI); } public Line(double phi, double theta, double psi, double length) { this.phi = phi; this.theta = theta; this.psi = psi; this.length = length; } public Line(Point beg, Point end) { double l = beg.distance(end); if (FP.eq(l, Math.PI)) { Assert.that(FP.eq(beg.ra, end.ra)); phi = -Math.PI/2; theta = Math.PI/2; psi = beg.ra < 0.0 ? Math.PI*2 + beg.ra : beg.ra; length = Math.PI; return; } if (beg.equals(end)) { phi = Math.PI/2; theta = beg.dec; psi = beg.ra - Math.PI/2; length = 0.0; } else { Point3D beg3d = new Point3D(beg); Point3D end3d = new Point3D(end); Point3D tp = new Point3D(); Point spt = beg3d.cross(end3d).toSpherePoint(); Euler euler = new Euler(); euler.phi = - spt.ra - Math.PI/2; euler.theta = spt.dec - Math.PI/2; euler.psi = 0.0 ; euler.psi_a = Euler.AXIS_Z; euler.theta_a = Euler.AXIS_X; euler.phi_a = Euler.AXIS_Z; euler.transform(tp, beg3d); spt = tp.toSpherePoint(); // invert phi = spt.ra; theta = -euler.theta; psi = -euler.phi; length = l; } } public RectangleRn wrappingRectangle() { Euler euler = new Euler(); euler.phi = phi; euler.theta = theta; euler.psi = psi; euler.psi_a = Euler.AXIS_Z ; euler.theta_a = Euler.AXIS_X; euler.phi_a = Euler.AXIS_Z; if (FP.zero(length)) { Point3D beg3d = new Point3D(); Point3D end3d = new Point3D(); euler.transform(beg3d, new Point3D(0.0, 0.0)); euler.transform(end3d, new Point3D(length, 0.0)); RectangleRn r = beg3d.toRectangle(); end3d.addToRectangle(r); return r; } else { double l, ls, lc; Point3D[] v = new Point3D[4]; Point3D tv = new Point3D(); l = length / 2.0; ls = Math.sin(l); lc = Math.cos(l); euler.phi += l; v[0] = new Point3D(lc, lc<0 ? -1.0 : -ls, 0.0); v[1] = new Point3D(1.0, lc<0 ? -1.0 : -ls, 0.0); v[2] = new Point3D(lc, lc<0 ? +1.0 : +ls, 0.0); v[3] = new Point3D(1.0, lc<0 ? +1.0 : +ls, 0.0) ; Point3D min = new Point3D(1.0, 1.0, 1.0); Point3D max = new Point3D(-1.0, -1.0, -1.0); for (int i=0; i<4; i++) { euler.transform(tv, v[i]); if (tv.x < -1.0) { min.x = -1.0; } else if (tv.x > 1.0) { max.x = 1.0; } else { if (tv.x < min.x) { min.x = tv.x; } if (tv.x > max.x) { max.x = tv.x; } } if (tv.y < -1.0) { min.y = -1.0; } else if ( tv.y > 1.0 ) { max.y = 1.0; } else { if (tv.y < min.y) { min.y = tv.y; } if (tv.y > max.y) { max.y = tv.y; } } if (tv.z < -1.0) { min.z = -1.0; } else if (tv.z > 1.0) { max.z = 1.0; } else { if (tv.z < min.z) { min.z = tv.z; } if (tv.z > max.z) { max.z = tv.z; } } } return new RectangleRn(new double[]{min.x, min.y, min.z, max.x, max.y, max.z}); } } } public static class Polygon implements SphereObject { public final Point[] points; public Polygon(Point[] points) { this.points = points; } public boolean contains(Point p) { throw new UnsupportedOperationException(); } public RectangleRn wrappingRectangle() { RectangleRn wr = null; for (int i=0; i < points.length; i++) { Line line = new Line(points[i], points[(i+1) % points.length]); RectangleRn r = line.wrappingRectangle(); if (wr == null) { wr = r; } else { wr.join(r); } } return wr; } } }
UTF-8
Java
23,723
java
Sphere.java
Java
[]
null
[]
package org.garret.perst; /** * Floating point operations with error */ class FP { static final double EPSILON = 1.0E-06; static final boolean zero(double x) { return Math.abs(x) <= EPSILON; } static final boolean eq(double x, double y) { return zero(x - y); } static final boolean ne(double x, double y) { return !eq(x, y); } static final boolean lt(double x, double y) { return y - x > EPSILON; } static final boolean le(double x, double y) { return x - y <= EPSILON; } static final boolean gt(double x, double y) { return x - y > EPSILON; } static final boolean ge(double x, double y) { return y - x <= EPSILON; } }; /** * Point in 3D */ class Point3D { double x; double y; double z; final Point3D cross(Point3D p) { return new Point3D(y * p.z - z * p.y, z * p.x - x * p.z, x * p.y - y * p.x); } final double distance() { return Math.sqrt(x*x + y*y + z*z); } public boolean equals(Object o) { if (o instanceof Point3D) { Point3D p = (Point3D)o; return FP.eq(x, p.x) && FP.eq(y, p.y) && FP.eq(z, p.z); } return false; } final RectangleRn toRectangle() { return new RectangleRn(new double[]{x, y, z, x, y, z}); } final Sphere.Point toSpherePoint() { double rho = Math.sqrt(x*x + y*y); double lat, lng; if (0.0 == rho) { if (FP.zero(z)) { lat = 0.0; } else if (z > 0) { lat = Math.PI/2; } else { lat = -Math.PI/2; } } else { lat = Math.atan(z / rho); } lng = Math.atan2(y, x); if (FP.zero(lng)){ lng = 0.0; } else { if (lng < 0.0) { lng += Math.PI*2 ; } } return new Sphere.Point(lng, lat); } void addToRectangle(RectangleRn r) { addToRectangle(r, x, y, z); } static void addToRectangle(RectangleRn r, double ra, double dec) { double x = Math.cos(ra)*Math.cos(dec); double y = Math.sin(ra)*Math.cos(dec); double z = Math.sin(dec); addToRectangle(r, x, y, z); } static void addToRectangle(RectangleRn r, double x, double y, double z) { if (x < r.coords[0]) { r.coords[0] = x; } if (y < r.coords[1]) { r.coords[1] = y; } if (z < r.coords[2]) { r.coords[2] = z; } if (x > r.coords[3]) { r.coords[3] = x; } if (y > r.coords[4]) { r.coords[4] = y; } if (z > r.coords[5]) { r.coords[5] = z; } } Point3D(double ra, double dec) { x = Math.cos(ra)*Math.cos(dec); y = Math.sin(ra)*Math.cos(dec); z = Math.sin(dec); } Point3D() {} Point3D(Sphere.Point p) { this(p.ra, p.dec); } Point3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } } /** * Euler transformation */ class Euler { int phi_a; // first axis int theta_a; // second axis int psi_a; // third axis double phi; // first rotation angle double theta; // second rotation angle double psi; // third rotation angle static final int AXIS_X = 1; static final int AXIS_Y = 2; static final int AXIS_Z = 3; void transform(Point3D out, Point3D in) { int t = 0; double a, sa, ca; double x1, y1, z1; double x2, y2, z2; x1 = in.x; y1 = in.y; z1 = in.z; for (int i=0; i<3; i++) { switch (i) { case 0: a = phi; t = phi_a; break; case 1: a = theta; t = theta_a; break; default: a = psi; t = psi_a; break; } if (FP.zero(a)) { continue; } sa = Math.sin(a); ca = Math.cos(a); switch (t) { case AXIS_X : x2 = x1; y2 = ca*y1 - sa*z1; z2 = sa*y1 + ca*z1; break; case AXIS_Y : x2 = ca*x1 + sa*z1; y2 = y1; z2 = ca*z1 - sa*x1; break; default: x2 = ca*x1 - sa*y1; y2 = sa*x1 + ca*y1; z2 = z1; break; } x1 = x2; y1 = y2; z1 = z2; } out.x = x1; out.y = y1; out.z = z1; } } /** * Class for conversion equatorial coordinates to Cartesian R3 coordinates */ public class Sphere { /** * Common interface for all objects on sphere */ public interface SphereObject extends IValue { /** * Get wrapping 3D rectangle for this object */ public RectangleRn wrappingRectangle(); /** * Check if object contains specified point ( @param p sphere point */ public boolean contains(Point p); }; /** * Class representing point of equatorial coordinate system (astronomic or terrestrial) */ public static class Point implements SphereObject { /** * Right ascension or longitude */ public final double ra; /** * Declination or latitude */ public final double dec; public final double latitude() { return dec; } public final double longitude() { return ra; } // Fast implementation from Q3C public final double distance(Point p) { double x = Math.sin((ra - p.ra) / 2); x *= x; double y = Math.sin((dec - p.dec) / 2); y *= y; double z = Math.cos((dec + p.dec) / 2); z *= z; return 2 * Math.asin(Math.sqrt(x * (z - y) + y)); } public boolean equals(Object o) { if (o instanceof Point) { Point p = (Point)o; return FP.eq(ra, p.ra) && FP.eq(dec, p.dec); } return false; } public RectangleRn wrappingRectangle() { double x = Math.cos(ra)*Math.cos(dec); double y = Math.sin(ra)*Math.cos(dec); double z = Math.sin(dec); return new RectangleRn(new double[]{x, y, z, x, y, z}); } public PointRn toPointRn() { double x = Math.cos(ra)*Math.cos(dec); double y = Math.sin(ra)*Math.cos(dec); double z = Math.sin(dec); return new PointRn(new double[]{x, y, z}); } public boolean contains(Point p) { return equals(p); } public String toString() { return "(" + ra + "," + dec + ")"; } public Point(double ra, double dec) { this.ra = ra; this.dec = dec; } } public static class Box implements SphereObject { public final Point sw; // source-west public final Point ne; // nord-east public boolean equals(Object o) { if (o instanceof Box) { Box b = (Box)o; return sw.equals(b.sw) && ne.equals(b.ne); } return false; } public boolean contains(Point p) { return contains(p.ra, p.dec); } public boolean contains(double ra, double dec) { if ((FP.eq(dec,ne.dec) && FP.eq(dec, Math.PI/2)) || (FP.eq(dec,sw.dec) && FP.eq(dec, -Math.PI/2))) { return true; } if (FP.lt(dec, sw.dec) || FP.gt(dec, ne.dec)) { return false; } if (FP.gt(sw.ra, ne.ra)) { if (FP.gt(ra, sw.ra) || FP.lt(ra, ne.ra)) { return false; } } else { if (FP.lt(ra, sw.ra) || FP.gt(ra, ne.ra)) { return false; } } return true; } public RectangleRn wrappingRectangle() { RectangleRn r = sw.wrappingRectangle(); double ra, dec; Point3D.addToRectangle(r, ne.ra, ne.dec); Point3D.addToRectangle(r, sw.ra, ne.dec); Point3D.addToRectangle(r, ne.ra, sw.dec); // latitude closest to equator if (FP.ge(ne.dec, 0.0) && FP.le(sw.dec, 0.0)) { dec = 0.0; } else if (Math.abs(ne.dec) > Math.abs(sw.dec)) { dec = sw.dec; } else { dec = ne.dec; } for (ra = 0.0; ra < Math.PI*2-0.1; ra += Math.PI/2) { if (contains(ra, dec)) { Point3D.addToRectangle(r, ra, dec); } } return r; } public Box(Point sw, Point ne) { this.sw = sw; this.ne = ne; } }; public static class Circle implements SphereObject { public final Point center; public final double radius; public Circle(Point center, double radius) { this.center = center; this.radius = radius; } public String toString() { return "<" + center + "," + radius + ">"; } public boolean equals(Object o) { if (o instanceof Circle) { Circle c = (Circle)o; return center.equals(c.center) && FP.eq(radius, c.radius); } return false; } public boolean contains(Point p) { double distance = center.distance(p); return FP.le(distance, radius); } public RectangleRn wrappingRectangle() { Point3D[] v = new Point3D[8]; Point3D tv = new Point3D(); Euler euler = new Euler(); double r = Math.sin(radius); double d = Math.cos(radius); v[0] = new Point3D(-r, -r, d); v[1] = new Point3D(-r, +r, d); v[2] = new Point3D(+r, -r, d); v[3] = new Point3D(+r, +r, d); v[4] = new Point3D(-r, -r, 1.0); v[5] = new Point3D(-r, +r, 1.0); v[6] = new Point3D(+r, -r, 1.0); v[7] = new Point3D(+r, +r, 1.0); euler.psi_a = Euler.AXIS_X; euler.theta_a = Euler.AXIS_Z; euler.phi_a = Euler.AXIS_X; euler.phi = Math.PI/2 - center.dec; euler.theta = Math.PI/2 + center.ra; euler.psi = 0.0; Point3D min = new Point3D(1.0, 1.0, 1.0); Point3D max = new Point3D(-1.0, -1.0, -1.0); for (int i=0; i<8; i++) { euler.transform(tv, v[i]); if (tv.x < -1.0) { min.x = -1.0; } else if (tv.x > 1.0) { max.x = 1.0; } else { if (tv.x < min.x) { min.x = tv.x; } if (tv.x > max.x) { max.x = tv.x; } } if (tv.y < -1.0) { min.y = -1.0; } else if ( tv.y > 1.0 ) { max.y = 1.0; } else { if (tv.y < min.y) { min.y = tv.y; } if (tv.y > max.y) { max.y = tv.y; } } if (tv.z < -1.0) { min.z = -1.0; } else if (tv.z > 1.0) { max.z = 1.0; } else { if (tv.z < min.z) { min.z = tv.z; } if (tv.z > max.z) { max.z = tv.z; } } } return new RectangleRn(new double[]{min.x, min.y, min.z, max.x, max.y, max.z}); } } /** * A spherical ellipse is represented using two radii and * a Euler transformation ( ZXZ-axis ). The "untransformed" * ellipse is located on equator at position (0,0). The * large radius is along equator. */ public static class Ellipse implements SphereObject { /** * The large radius of an ellipse in radians */ public final double rad0; /** * The small radius of an ellipse in radians */ public final double rad1; /** * The first rotation angle around z axis */ public final double phi; /** * The second rotation angle around x axis */ public final double theta; /** * The last rotation angle around z axis */ public final double psi; public Ellipse(double rad0, double rad1, double phi, double theta, double psi) { this.rad0 = rad0; this.rad1 = rad1; this.phi = phi; this.theta = theta; this.psi = psi; } public Point center() { return new Point(psi, -theta); } public boolean contains(Point p) { // too complex implementation throw new UnsupportedOperationException(); } public boolean equals(Object o) { if (o instanceof Ellipse) { Ellipse e = (Ellipse)o; return FP.eq(rad0, e.rad0) && FP.eq(rad1, e.rad1) && FP.eq(phi, e.phi) && FP.eq(theta, e.theta) && FP.eq(psi, e.psi); } return false; } public RectangleRn wrappingRectangle() { Point3D[] v = new Point3D[8]; Point3D tv = new Point3D(); Euler euler = new Euler(); double r0 = Math.sin(rad0); double r1 = Math.sin(rad1); double d = Math.cos(rad1); v[0] = new Point3D(d, -r0, -r1); v[1] = new Point3D(d, +r0, -r1); v[2] = new Point3D(d, -r0, r1); v[3] = new Point3D(d, +r0, r1); v[4] = new Point3D(1.0, -r0, -r1); v[5] = new Point3D(1.0, +r0, -r1); v[6] = new Point3D(1.0, -r0, r1); v[7] = new Point3D(1.0, +r0, r1); euler.psi_a = Euler.AXIS_Z ; euler.theta_a = Euler.AXIS_Y; euler.phi_a = Euler.AXIS_X; euler.phi = phi; euler.theta = theta; euler.psi = psi; Point3D min = new Point3D(1.0, 1.0, 1.0); Point3D max = new Point3D(-1.0, -1.0, -1.0); for (int i=0; i<8; i++) { euler.transform(tv, v[i]); if (tv.x < -1.0) { min.x = -1.0; } else if (tv.x > 1.0) { max.x = 1.0; } else { if (tv.x < min.x) { min.x = tv.x; } if (tv.x > max.x) { max.x = tv.x; } } if (tv.y < -1.0) { min.y = -1.0; } else if ( tv.y > 1.0 ) { max.y = 1.0; } else { if (tv.y < min.y) { min.y = tv.y; } if (tv.y > max.y) { max.y = tv.y; } } if (tv.z < -1.0) { min.z = -1.0; } else if (tv.z > 1.0) { max.z = 1.0; } else { if (tv.z < min.z) { min.z = tv.z; } if (tv.z > max.z) { max.z = tv.z; } } } return new RectangleRn(new double[]{min.x, min.y, min.z, max.x, max.y, max.z}); } } public static class Line implements SphereObject { /** * The first rotation angle around z axis */ public final double phi; /** * The second rotation angle around x axis */ public final double theta; /** * The last rotation angle around z axis */ public final double psi; /** * The length of the line in radians */ public final double length; public boolean equals(Object o) { if (o instanceof Line) { Line l = (Line)o; return FP.eq(phi, l.phi) && FP.eq(theta, l.theta) && FP.eq(psi, l.psi) && FP.eq(length, l.length); } return false; } public boolean contains(Point p) { Euler euler = new Euler(); Point3D spt = new Point3D(); euler.phi = -psi; euler.theta = -theta; euler.psi = -phi; euler.psi_a = Euler.AXIS_Z; euler.theta_a = Euler.AXIS_X; euler.phi_a = Euler.AXIS_Z; euler.transform(spt, new Point3D(p)); Point sp = spt.toSpherePoint(); return FP.zero(sp.dec) && FP.ge(sp.ra, 0.0) && FP.le(sp.ra, length); } public static Line meridian(double ra) { return new Line(-Math.PI/2, Math.PI/2, ra < 0.0 ? Math.PI*2 + ra : ra, Math.PI); } public Line(double phi, double theta, double psi, double length) { this.phi = phi; this.theta = theta; this.psi = psi; this.length = length; } public Line(Point beg, Point end) { double l = beg.distance(end); if (FP.eq(l, Math.PI)) { Assert.that(FP.eq(beg.ra, end.ra)); phi = -Math.PI/2; theta = Math.PI/2; psi = beg.ra < 0.0 ? Math.PI*2 + beg.ra : beg.ra; length = Math.PI; return; } if (beg.equals(end)) { phi = Math.PI/2; theta = beg.dec; psi = beg.ra - Math.PI/2; length = 0.0; } else { Point3D beg3d = new Point3D(beg); Point3D end3d = new Point3D(end); Point3D tp = new Point3D(); Point spt = beg3d.cross(end3d).toSpherePoint(); Euler euler = new Euler(); euler.phi = - spt.ra - Math.PI/2; euler.theta = spt.dec - Math.PI/2; euler.psi = 0.0 ; euler.psi_a = Euler.AXIS_Z; euler.theta_a = Euler.AXIS_X; euler.phi_a = Euler.AXIS_Z; euler.transform(tp, beg3d); spt = tp.toSpherePoint(); // invert phi = spt.ra; theta = -euler.theta; psi = -euler.phi; length = l; } } public RectangleRn wrappingRectangle() { Euler euler = new Euler(); euler.phi = phi; euler.theta = theta; euler.psi = psi; euler.psi_a = Euler.AXIS_Z ; euler.theta_a = Euler.AXIS_X; euler.phi_a = Euler.AXIS_Z; if (FP.zero(length)) { Point3D beg3d = new Point3D(); Point3D end3d = new Point3D(); euler.transform(beg3d, new Point3D(0.0, 0.0)); euler.transform(end3d, new Point3D(length, 0.0)); RectangleRn r = beg3d.toRectangle(); end3d.addToRectangle(r); return r; } else { double l, ls, lc; Point3D[] v = new Point3D[4]; Point3D tv = new Point3D(); l = length / 2.0; ls = Math.sin(l); lc = Math.cos(l); euler.phi += l; v[0] = new Point3D(lc, lc<0 ? -1.0 : -ls, 0.0); v[1] = new Point3D(1.0, lc<0 ? -1.0 : -ls, 0.0); v[2] = new Point3D(lc, lc<0 ? +1.0 : +ls, 0.0); v[3] = new Point3D(1.0, lc<0 ? +1.0 : +ls, 0.0) ; Point3D min = new Point3D(1.0, 1.0, 1.0); Point3D max = new Point3D(-1.0, -1.0, -1.0); for (int i=0; i<4; i++) { euler.transform(tv, v[i]); if (tv.x < -1.0) { min.x = -1.0; } else if (tv.x > 1.0) { max.x = 1.0; } else { if (tv.x < min.x) { min.x = tv.x; } if (tv.x > max.x) { max.x = tv.x; } } if (tv.y < -1.0) { min.y = -1.0; } else if ( tv.y > 1.0 ) { max.y = 1.0; } else { if (tv.y < min.y) { min.y = tv.y; } if (tv.y > max.y) { max.y = tv.y; } } if (tv.z < -1.0) { min.z = -1.0; } else if (tv.z > 1.0) { max.z = 1.0; } else { if (tv.z < min.z) { min.z = tv.z; } if (tv.z > max.z) { max.z = tv.z; } } } return new RectangleRn(new double[]{min.x, min.y, min.z, max.x, max.y, max.z}); } } } public static class Polygon implements SphereObject { public final Point[] points; public Polygon(Point[] points) { this.points = points; } public boolean contains(Point p) { throw new UnsupportedOperationException(); } public RectangleRn wrappingRectangle() { RectangleRn wr = null; for (int i=0; i < points.length; i++) { Line line = new Line(points[i], points[(i+1) % points.length]); RectangleRn r = line.wrappingRectangle(); if (wr == null) { wr = r; } else { wr.join(r); } } return wr; } } }
23,723
0.391477
0.373182
806
28.433002
19.051382
133
false
false
0
0
0
0
0
0
0.683623
false
false
7
aea777bced68d6d943ae3397242c77f2145fcef5
32,375,463,541,298
59edba4abb394ea6fffdfaf0a5a5eb333759d067
/grex/app/src/main/java/com/caffinc/grex/app/App.java
bce6213098a45c865f2d0f2b18627ddf821a63a9
[ "MIT" ]
permissive
caffinc/grex
https://github.com/caffinc/grex
80327cb48a4d36fa6e126cae43faf3e5761336a1
fd626c91535659f2350d87e928a6671104661ae0
refs/heads/master
"2021-01-10T12:56:01.471000"
"2016-12-07T06:05:07"
"2016-12-07T06:05:07"
53,511,633
7
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.caffinc.grex.app; import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterException; import com.caffinc.grex.app.entities.GrexCLParams; import com.caffinc.grex.app.filters.AuthFilter; import com.caffinc.grex.app.resources.NodeResource; import com.caffinc.grex.app.resources.ServerResource; import com.caffinc.grex.app.utils.Api; import com.caffinc.grex.app.utils.AuthToken; import com.caffinc.grex.app.utils.GrexClient; import com.caffinc.grex.common.util.IPUtil; import com.caffinc.grex.core.Load; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.resource.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import retrofit.RetrofitError; /** * Launches Grex * * @author Sriram */ public class App { private static final Logger LOG = LoggerFactory.getLogger(App.class); public static void main(String[] args) throws Exception { final GrexCLParams params = new GrexCLParams(); JCommander jCommander = new JCommander(params); try { jCommander.parse(args); AuthToken.getInstance().setAuthToken(params.getAuth()); // Workaround for resources from JAR files Resource.setDefaultUseCaches(false); Api api = new Api(params.getPort()); api.setBaseUrl(params.getBaseUrl()).addFilter(AuthFilter.class); api.addStaticResource(App.class.getClassLoader().getResource("swaggerui").toURI().toString(), params.getBaseUrl() + "/docs/"); api.addServiceResource(NodeResource.class, "Grex API", "API for managing Grex"); if (params.getHost() == null) { api.addStaticResource(App.class.getClassLoader().getResource("ui").toURI().toString(), params.getBaseUrl() + "/"); } api.enableCors(); Server server = api.startNonBlocking(); final String url = (params.getUrl() == null) ? "http://" + IPUtil.getIp() + ":" + params.getPort() + params.getBaseUrl() : params.getUrl(); LOG.info("Grex Started:\nID: {}\nURL: {}\nAuth: {}\nHost: {}", Load.getInstance().getId(), url + "?auth=" + params.getAuth(), params.getAuth(), params.getHost()); if (params.getHost() != null) { final GrexClient client = new GrexClient(params.getHost(), AuthToken.getInstance().getAuthToken()); client.addNode(Load.getInstance().getId(), url); LOG.info("Successfully added self to host"); new Thread("KeepNodeConnected") { @Override public void run() { boolean connectionStatus = true; while (true) { try { Thread.sleep(5000); client.addNode(Load.getInstance().getId(), url); if (!connectionStatus) { connectionStatus = true; LOG.info("Communications with host resumed"); } } catch (InterruptedException e) { LOG.warn("Interrupted while waiting to contact host", e); } catch (RetrofitError e) { LOG.warn("Communications with host lost: {}", e.getMessage()); connectionStatus = false; } } } }.start(); } else { LOG.info("Successfully started in Host mode"); new GrexClient(url, AuthToken.getInstance().getAuthToken()).addNode(Load.getInstance().getId(), url); } server.join(); } catch (ParameterException e) { jCommander.setProgramName("grex"); jCommander.usage(); } catch (RetrofitError e) { LOG.error("Unable to establish connection with host: {}", e.getMessage()); } catch (Exception e) { LOG.error("Exception while launching Grex", e); System.exit(1); } } }
UTF-8
Java
4,206
java
App.java
Java
[ { "context": "RetrofitError;\n\n/**\n * Launches Grex\n *\n * @author Sriram\n */\npublic class App {\n private static final L", "end": 752, "score": 0.9984560012817383, "start": 746, "tag": "NAME", "value": "Sriram" } ]
null
[]
package com.caffinc.grex.app; import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterException; import com.caffinc.grex.app.entities.GrexCLParams; import com.caffinc.grex.app.filters.AuthFilter; import com.caffinc.grex.app.resources.NodeResource; import com.caffinc.grex.app.resources.ServerResource; import com.caffinc.grex.app.utils.Api; import com.caffinc.grex.app.utils.AuthToken; import com.caffinc.grex.app.utils.GrexClient; import com.caffinc.grex.common.util.IPUtil; import com.caffinc.grex.core.Load; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.resource.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import retrofit.RetrofitError; /** * Launches Grex * * @author Sriram */ public class App { private static final Logger LOG = LoggerFactory.getLogger(App.class); public static void main(String[] args) throws Exception { final GrexCLParams params = new GrexCLParams(); JCommander jCommander = new JCommander(params); try { jCommander.parse(args); AuthToken.getInstance().setAuthToken(params.getAuth()); // Workaround for resources from JAR files Resource.setDefaultUseCaches(false); Api api = new Api(params.getPort()); api.setBaseUrl(params.getBaseUrl()).addFilter(AuthFilter.class); api.addStaticResource(App.class.getClassLoader().getResource("swaggerui").toURI().toString(), params.getBaseUrl() + "/docs/"); api.addServiceResource(NodeResource.class, "Grex API", "API for managing Grex"); if (params.getHost() == null) { api.addStaticResource(App.class.getClassLoader().getResource("ui").toURI().toString(), params.getBaseUrl() + "/"); } api.enableCors(); Server server = api.startNonBlocking(); final String url = (params.getUrl() == null) ? "http://" + IPUtil.getIp() + ":" + params.getPort() + params.getBaseUrl() : params.getUrl(); LOG.info("Grex Started:\nID: {}\nURL: {}\nAuth: {}\nHost: {}", Load.getInstance().getId(), url + "?auth=" + params.getAuth(), params.getAuth(), params.getHost()); if (params.getHost() != null) { final GrexClient client = new GrexClient(params.getHost(), AuthToken.getInstance().getAuthToken()); client.addNode(Load.getInstance().getId(), url); LOG.info("Successfully added self to host"); new Thread("KeepNodeConnected") { @Override public void run() { boolean connectionStatus = true; while (true) { try { Thread.sleep(5000); client.addNode(Load.getInstance().getId(), url); if (!connectionStatus) { connectionStatus = true; LOG.info("Communications with host resumed"); } } catch (InterruptedException e) { LOG.warn("Interrupted while waiting to contact host", e); } catch (RetrofitError e) { LOG.warn("Communications with host lost: {}", e.getMessage()); connectionStatus = false; } } } }.start(); } else { LOG.info("Successfully started in Host mode"); new GrexClient(url, AuthToken.getInstance().getAuthToken()).addNode(Load.getInstance().getId(), url); } server.join(); } catch (ParameterException e) { jCommander.setProgramName("grex"); jCommander.usage(); } catch (RetrofitError e) { LOG.error("Unable to establish connection with host: {}", e.getMessage()); } catch (Exception e) { LOG.error("Exception while launching Grex", e); System.exit(1); } } }
4,206
0.565621
0.563956
93
44.225807
34.397152
177
false
false
0
0
0
0
0
0
0.741935
false
false
7
619c1078251461fdbf491c2d4f47d68baddef511
29,970,281,841,485
c91f866d9eddad6c2f8e1580525b6b29573c7fb2
/src/codingexercise/question3/FunctionExecutionTimeMeasurement.java
41215357a9cc17a1074fc2565c04f9493e91d090
[]
no_license
ITShaker/codingexercise
https://github.com/ITShaker/codingexercise
be695096ad99a254192fdc65aa2aad3cca9fe8ac
cf05e7fb0cc180f5d68b3c803a24165d15ae6f8e
refs/heads/master
"2019-03-08T20:22:40.537000"
"2017-08-20T13:24:02"
"2017-08-20T13:24:02"
100,854,299
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 codingexercise.question3; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * * @author Owner */ public class FunctionExecutionTimeMeasurement { private long startTime; private long endTime; public void functionStartExecute(){ Date startDate = new Date(); startTime = startDate.getTime(); } public void functionEndExecute(){ Date endDate = new Date(); endTime = endDate.getTime(); long executeTime = endTime - startTime;// ms System.out.println("The function execution time:" + executeTime + "ms"); } public static void main(String[] args){ FunctionExecutionTimeMeasurement testObj = new FunctionExecutionTimeMeasurement (); testObj.functionStartExecute(); testExecutionMethod(); testObj.functionEndExecute(); } public static void testExecutionMethod(){ List<String> testList = new ArrayList<String>(); for(int i =0; i < 100000; i++){ testList.add("String" + i); } } }
UTF-8
Java
1,338
java
FunctionExecutionTimeMeasurement.java
Java
[ { "context": "te;\r\nimport java.util.List;\r\n\r\n/**\r\n *\r\n * @author Owner\r\n */\r\npublic class FunctionExecutionTimeMeasureme", "end": 331, "score": 0.5058276653289795, "start": 326, "tag": "USERNAME", "value": "Owner" } ]
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 codingexercise.question3; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * * @author Owner */ public class FunctionExecutionTimeMeasurement { private long startTime; private long endTime; public void functionStartExecute(){ Date startDate = new Date(); startTime = startDate.getTime(); } public void functionEndExecute(){ Date endDate = new Date(); endTime = endDate.getTime(); long executeTime = endTime - startTime;// ms System.out.println("The function execution time:" + executeTime + "ms"); } public static void main(String[] args){ FunctionExecutionTimeMeasurement testObj = new FunctionExecutionTimeMeasurement (); testObj.functionStartExecute(); testExecutionMethod(); testObj.functionEndExecute(); } public static void testExecutionMethod(){ List<String> testList = new ArrayList<String>(); for(int i =0; i < 100000; i++){ testList.add("String" + i); } } }
1,338
0.617339
0.61136
48
25.875
22.967936
91
false
false
0
0
0
0
0
0
0.479167
false
false
7