blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
5a0b347c62877bdf5eea4bd99c148845e4e3ddad
23,845,658,472,219
edefcdd5b61d57844560d67bd51ba898f9268e5d
/Matinee Movie Tickets/Main.java
e6b3a45b8fe4b4aa0c1f2bc8455e3175096a4207
[]
no_license
alvinavarachan/Playground
https://github.com/alvinavarachan/Playground
bf7af047c2d17926953ae916e322f2996ba26845
3db8a4c1849b2e2840cf4d9956321ce4d2ba1a93
refs/heads/master
2022-02-19T14:40:52.732000
2019-09-28T09:58:27
2019-09-28T09:58:27
198,358,643
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; class Main { public static void main(String args[]) { Scanner sc= new Scanner (System.in); int age=sc.nextInt(); float time= sc.nextFloat(); float price=0; if (age>13) { if (time >12.00f && time<16.00f) { price=5.00f; } else { price=8.00f; } } else if (age<=13 && age>0) { if (time >12.00f && time<16.00f) { price=2.00f; } else { price=4.00f; } } else { System.out.println("Not valid"); } System.out.printf("$%.2f",price); } }
UTF-8
Java
720
java
Main.java
Java
[]
null
[]
import java.util.Scanner; class Main { public static void main(String args[]) { Scanner sc= new Scanner (System.in); int age=sc.nextInt(); float time= sc.nextFloat(); float price=0; if (age>13) { if (time >12.00f && time<16.00f) { price=5.00f; } else { price=8.00f; } } else if (age<=13 && age>0) { if (time >12.00f && time<16.00f) { price=2.00f; } else { price=4.00f; } } else { System.out.println("Not valid"); } System.out.printf("$%.2f",price); } }
720
0.401389
0.352778
43
15.767442
12.317198
41
false
false
0
0
0
0
0
0
0.395349
false
false
10
fc480da7ba2f30489b6bb9cdfa7442024bc2f655
3,135,326,153,390
2ea49bfaa6bc1b9301b025c5b2ca6fde7e5bb9df
/contributions/durandj/java/Error Handling/2016-09-11.java
4a55b9d49c3b9d482c1413f1f4794a741df83488
[]
no_license
0x8801/commit
https://github.com/0x8801/commit
18f25a9449f162ee92945b42b93700e12fd4fd77
e7692808585bc7e9726f61f7f6baf43dc83e28ac
refs/heads/master
2021-10-13T08:04:48.200000
2016-12-20T01:59:47
2016-12-20T01:59:47
76,935,980
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
Throwing proper exceptions for unfinished code Be as specific as possible when catching exceptions The distinction between checked and unchecked exceptions Creating new Exceptions Careful Numeric Data Conversions
UTF-8
Java
212
java
2016-09-11.java
Java
[]
null
[]
Throwing proper exceptions for unfinished code Be as specific as possible when catching exceptions The distinction between checked and unchecked exceptions Creating new Exceptions Careful Numeric Data Conversions
212
0.872642
0.872642
5
41.599998
12.273549
56
false
false
0
0
0
0
0
0
0
false
false
10
f2e852cafdc7c07a5d5d6759972a29ee2beb66e5
10,849,087,460,577
497fcb88c10c94fed1caa160ee110561c07b594c
/web/web-lobby/src/main/java/com/yazino/web/payment/PaymentOptionIdTransformer.java
3f273caa77683e883ae777b131547e73feee0331
[]
no_license
ShahakBH/jazzino-master
https://github.com/ShahakBH/jazzino-master
3f116a609c5648c00dfbe6ab89c6c3ce1903fc1a
2401394022106d2321873d15996953f2bbc2a326
refs/heads/master
2016-09-02T01:26:44.514000
2015-08-10T13:06:54
2015-08-10T13:06:54
40,482,590
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yazino.web.payment; import com.yazino.bi.payment.PaymentOption; import com.yazino.platform.community.PaymentPreferences; /** * Transforms a Yazino payment option id into something payment provider specific. */ public interface PaymentOptionIdTransformer { /** * Transform the PaymentOption is into something else... * * @param gameType * @param paymentOption * @param paymentMethod * @return transformed id or null if option id couldn't be transformed. */ String transformPaymentOptionId(String gameType, PaymentOption paymentOption, PaymentPreferences.PaymentMethod paymentMethod); }
UTF-8
Java
645
java
PaymentOptionIdTransformer.java
Java
[]
null
[]
package com.yazino.web.payment; import com.yazino.bi.payment.PaymentOption; import com.yazino.platform.community.PaymentPreferences; /** * Transforms a Yazino payment option id into something payment provider specific. */ public interface PaymentOptionIdTransformer { /** * Transform the PaymentOption is into something else... * * @param gameType * @param paymentOption * @param paymentMethod * @return transformed id or null if option id couldn't be transformed. */ String transformPaymentOptionId(String gameType, PaymentOption paymentOption, PaymentPreferences.PaymentMethod paymentMethod); }
645
0.750388
0.750388
20
31.25
34.193382
130
false
false
0
0
0
0
0
0
0.3
false
false
10
6c7bca0b58676a75c03c7308f8e605adf250a17b
31,370,441,193,294
78352ea36f5d0c53bfea7bc02953b3b735a8c8f0
/src/edu/yccc/cis174/michaellombard/project2recode/QuestionWithAnswer.java
f5d4063d79766265041ba12f18319eea7c2ee5ec
[]
no_license
Mlombardyccc/cis174
https://github.com/Mlombardyccc/cis174
62b6d7616b909c63106fe6e01f703be3cecc8ac2
3d65a9ce0063f8a3ddaae82f736d6c09518b8569
refs/heads/master
2021-05-10T00:25:39.547000
2018-05-02T22:32:19
2018-05-02T22:32:19
118,833,148
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.yccc.cis174.michaellombard.project2recode; public class QuestionWithAnswer { String question, answer, correctAnswer; public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } public String getCorrectAnswer() { return correctAnswer; } public void setCorrectAnswer(String correctAnswer) { this.correctAnswer = correctAnswer; } public QuestionWithAnswer(String question, String answer, String correctAnswer) { this.question = question; this.answer = answer; this.correctAnswer = correctAnswer; } public QuestionWithAnswer() { } }
UTF-8
Java
795
java
QuestionWithAnswer.java
Java
[]
null
[]
package edu.yccc.cis174.michaellombard.project2recode; public class QuestionWithAnswer { String question, answer, correctAnswer; public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } public String getCorrectAnswer() { return correctAnswer; } public void setCorrectAnswer(String correctAnswer) { this.correctAnswer = correctAnswer; } public QuestionWithAnswer(String question, String answer, String correctAnswer) { this.question = question; this.answer = answer; this.correctAnswer = correctAnswer; } public QuestionWithAnswer() { } }
795
0.708176
0.703145
39
18.384615
19.957153
82
false
false
0
0
0
0
0
0
1.333333
false
false
10
b6630ea969af8b46dd485b3a726035686614df4b
23,012,434,831,964
627a8bf8d53cac24cd533b954218fb0459b49365
/TetrisPanel.java
43829582c6f5d12c76abe72b5ea08aa8b9e3d300
[]
no_license
thomashuang2017/TetrisWorking
https://github.com/thomashuang2017/TetrisWorking
ee078019ea1c47bd380206c94d99c2eb19f87cd4
53ae5cce90fbbf7321478fb15ba748023b727b84
refs/heads/master
2022-09-23T10:44:16.671000
2020-05-29T22:05:17
2020-05-29T22:05:17
267,954,170
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.*; import javax.swing.Timer; public class TetrisPanel extends JPanel implements KeyListener { //繼承keylistener static final int spaceX0=150, spaceY0=0; final int holdX0=3, holdY0=80; final int nextX0=530, nextY0=80; static Map map; Piece movingPiece, holdPiece, nextPiece; // holdPiece 拿, nextPiece 看下個 private boolean change; // 換新的Piece // private int flag = 0; //: b4 A6.006.A private boolean notFalling = false; // [] S、Z、L、J、I、O、T [] Rotate [] 4*4 public TetrisPanel() { //創造PANEL this.setLayout(null); this.setBackground(Color.BLACK); //背景 this.map= new Map(10,20); // this.map.colorInit(); JLabel NEXT = new JLabel("NEXT"); //可改成BUTTON NEXT.setFont(new Font("", Font.BOLD, 50)); NEXT.setBounds(500, 0, 200, 100); NEXT.setForeground(Color.white); this.add(NEXT); JLabel HOLD = new JLabel("HOLD"); HOLD.setFont(new Font("", Font.BOLD, 50)); HOLD.setBounds(0, 0, 200, 100); HOLD.setForeground(Color.white); this.add(HOLD); this.map.clearMap();//? this.nextPiece= new Piece((int)(Math.random()*7)); newPiece(); // must after nextPiece is initialized holdPiece=null; Timer timer = new Timer(800, new TimerListener()); //延遲緩面下降 timer.start(); //開始延遲 } // public void newBlock() { //: b4 A6.006.F private void newPiece() { this.notFalling = false; //D if(this.nextPiece==null) throw new Error(); this.movingPiece = this.nextPiece; this.change = true; this.nextPiece= new Piece((int)(Math.random()*7)); //Piece.turnState = 0; this.movingPiece.setPos40(); if(gameOver()) { this.map.clearMap(); //JOptionPane.showMessageDialog(null, "GAME OVER"); } repaint(); } /* private void setBlock(int x, int y, int type, int state) { //this.notFalling = true; for(int i = 0; i < 16; i++) { if(Piece.shapes[type][state][i] == 1) { this.map.map[x+i%4][y+i/4] = type+1; } } } */ //public int gameOver(int x, int y) { public boolean gameOver() { if(this.movingPiece==null) throw new Error(); if(this.movingPiece.free() == false) return true; else{ return false; } } void stopDown(){ //Sleep(500); this.movingPiece.plugPiece(); this.notFalling = true; this.map.updateMap(); newPiece(); } public void paintComponent(Graphics g) { //ok super.paintComponent(g); this.map.paintMap(g); if(this.notFalling == false) { //畫(運動中的)落下的piece this.movingPiece.paintPiece(g, spaceX0, spaceY0); } if(holdPiece!=null) {//畫hold holdPiece.paintPiece(g, holdX0, holdY0); } //for (int i = 0; i < 16; i++) { //畫next // //Piece.paintPiece(g, nextX0, nextY0, this.next, 0, 0, 0); // Piece.paintPiece(g, nextX0, nextY0, this.nextPiece.blockType, 0, 0, 0); this.nextPiece.paintPiece(g, nextX0, nextY0); //} } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_DOWN: if(this.movingPiece.down_shift()==false){ stopDown(); } repaint(); break; case KeyEvent.VK_UP: this.movingPiece.rotate(); repaint(); break; case KeyEvent.VK_RIGHT: this.movingPiece.r_shift(); repaint(); break; case KeyEvent.VK_LEFT: this.movingPiece.l_shift(); repaint(); break; case KeyEvent.VK_SPACE: while(this.movingPiece.down_shift()) { repaint(); } stopDown(); break; case KeyEvent.VK_SHIFT: if(this.change) { if(holdPiece==null) { holdPiece= movingPiece; holdPiece.setPos00(); repaint(); newPiece(); } else { { Piece tmp= holdPiece; holdPiece= movingPiece; movingPiece= tmp; } this.holdPiece.setPos00(); this.movingPiece.setPos40(); this.change= false; repaint(); } } break; } } void Sleep(int milliseconds) { try { Thread.sleep(milliseconds); } catch (InterruptedException e) { System.out.println("Unexcepted interrupt"); System.exit(0); } } void doClock(){ if(this.movingPiece.down_shift()==false){ stopDown(); } else{ repaint(); } } class TimerListener implements ActionListener { public void actionPerformed(ActionEvent e) { doClock(); } } }
BIG5
Java
5,560
java
TetrisPanel.java
Java
[]
null
[]
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.*; import javax.swing.Timer; public class TetrisPanel extends JPanel implements KeyListener { //繼承keylistener static final int spaceX0=150, spaceY0=0; final int holdX0=3, holdY0=80; final int nextX0=530, nextY0=80; static Map map; Piece movingPiece, holdPiece, nextPiece; // holdPiece 拿, nextPiece 看下個 private boolean change; // 換新的Piece // private int flag = 0; //: b4 A6.006.A private boolean notFalling = false; // [] S、Z、L、J、I、O、T [] Rotate [] 4*4 public TetrisPanel() { //創造PANEL this.setLayout(null); this.setBackground(Color.BLACK); //背景 this.map= new Map(10,20); // this.map.colorInit(); JLabel NEXT = new JLabel("NEXT"); //可改成BUTTON NEXT.setFont(new Font("", Font.BOLD, 50)); NEXT.setBounds(500, 0, 200, 100); NEXT.setForeground(Color.white); this.add(NEXT); JLabel HOLD = new JLabel("HOLD"); HOLD.setFont(new Font("", Font.BOLD, 50)); HOLD.setBounds(0, 0, 200, 100); HOLD.setForeground(Color.white); this.add(HOLD); this.map.clearMap();//? this.nextPiece= new Piece((int)(Math.random()*7)); newPiece(); // must after nextPiece is initialized holdPiece=null; Timer timer = new Timer(800, new TimerListener()); //延遲緩面下降 timer.start(); //開始延遲 } // public void newBlock() { //: b4 A6.006.F private void newPiece() { this.notFalling = false; //D if(this.nextPiece==null) throw new Error(); this.movingPiece = this.nextPiece; this.change = true; this.nextPiece= new Piece((int)(Math.random()*7)); //Piece.turnState = 0; this.movingPiece.setPos40(); if(gameOver()) { this.map.clearMap(); //JOptionPane.showMessageDialog(null, "GAME OVER"); } repaint(); } /* private void setBlock(int x, int y, int type, int state) { //this.notFalling = true; for(int i = 0; i < 16; i++) { if(Piece.shapes[type][state][i] == 1) { this.map.map[x+i%4][y+i/4] = type+1; } } } */ //public int gameOver(int x, int y) { public boolean gameOver() { if(this.movingPiece==null) throw new Error(); if(this.movingPiece.free() == false) return true; else{ return false; } } void stopDown(){ //Sleep(500); this.movingPiece.plugPiece(); this.notFalling = true; this.map.updateMap(); newPiece(); } public void paintComponent(Graphics g) { //ok super.paintComponent(g); this.map.paintMap(g); if(this.notFalling == false) { //畫(運動中的)落下的piece this.movingPiece.paintPiece(g, spaceX0, spaceY0); } if(holdPiece!=null) {//畫hold holdPiece.paintPiece(g, holdX0, holdY0); } //for (int i = 0; i < 16; i++) { //畫next // //Piece.paintPiece(g, nextX0, nextY0, this.next, 0, 0, 0); // Piece.paintPiece(g, nextX0, nextY0, this.nextPiece.blockType, 0, 0, 0); this.nextPiece.paintPiece(g, nextX0, nextY0); //} } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_DOWN: if(this.movingPiece.down_shift()==false){ stopDown(); } repaint(); break; case KeyEvent.VK_UP: this.movingPiece.rotate(); repaint(); break; case KeyEvent.VK_RIGHT: this.movingPiece.r_shift(); repaint(); break; case KeyEvent.VK_LEFT: this.movingPiece.l_shift(); repaint(); break; case KeyEvent.VK_SPACE: while(this.movingPiece.down_shift()) { repaint(); } stopDown(); break; case KeyEvent.VK_SHIFT: if(this.change) { if(holdPiece==null) { holdPiece= movingPiece; holdPiece.setPos00(); repaint(); newPiece(); } else { { Piece tmp= holdPiece; holdPiece= movingPiece; movingPiece= tmp; } this.holdPiece.setPos00(); this.movingPiece.setPos40(); this.change= false; repaint(); } } break; } } void Sleep(int milliseconds) { try { Thread.sleep(milliseconds); } catch (InterruptedException e) { System.out.println("Unexcepted interrupt"); System.exit(0); } } void doClock(){ if(this.movingPiece.down_shift()==false){ stopDown(); } else{ repaint(); } } class TimerListener implements ActionListener { public void actionPerformed(ActionEvent e) { doClock(); } } }
5,560
0.514244
0.4958
184
28.76087
19.157454
88
false
false
0
0
0
0
0
0
0.798913
false
false
10
812ef059b715a18f2c4bff6ed258234cc598cc68
33,389,075,822,616
a96808c886debdbf2184d875b541d75d1497cee6
/morphia/src/test/java/com/github/jmkgreen/morphia/TestDatastore.java
07af6b9ae6a0df1b81e76e92cb5e1154042932c8
[ "Apache-2.0" ]
permissive
jmkgreen/morphia
https://github.com/jmkgreen/morphia
3010c1f9ae3293dab139d8d8cd51c3cec0e64954
cdb6f136c1ad0820954de8d2f40f40dc2c8cf71c
refs/heads/master
2023-07-31T13:12:18.485000
2013-10-13T10:17:49
2013-10-13T10:17:49
6,002,930
11
16
null
false
2021-11-11T22:31:22
2012-09-28T20:50:01
2020-03-20T21:52:46
2021-08-27T01:27:52
5,487
107
29
30
Java
false
false
/** * Copyright (C) 2010 Olafur Gauti Gudmundsson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jmkgreen.morphia; import com.github.jmkgreen.morphia.annotations.*; import com.github.jmkgreen.morphia.mapping.Mapper; import com.github.jmkgreen.morphia.testmodel.Address; import com.github.jmkgreen.morphia.testmodel.Hotel; import com.github.jmkgreen.morphia.testmodel.Rectangle; import com.github.jmkgreen.morphia.testutil.AssertedFailure; import com.mongodb.*; import org.bson.types.ObjectId; import org.junit.Test; import java.util.ArrayList; import java.util.Date; import java.util.List; import static org.junit.Assert.*; /** * * @author Scott Hernandez */ public class TestDatastore extends TestBase { @Entity("facebook_users") public static class FacebookUser { @Id long id; String username; public FacebookUser() {} public FacebookUser(long id, String name) { this(); this.id = id; this.username = name; } } public static class LifecycleListener { static boolean prePersist = false; static boolean prePersistWithEntity = false; @PrePersist void PrePersist() { prePersist = true; } @PrePersist void PrePersist(LifecycleTestObj obj) { if(obj == null) throw new RuntimeException(); prePersistWithEntity = true; } } @EntityListeners(LifecycleListener.class) public static class LifecycleTestObj { @Id ObjectId id; @Transient boolean prePersist, postPersist, preLoad, postLoad, postLoadWithParam; boolean prePersistWithParamAndReturn, prePersistWithParam; boolean postPersistWithParam; boolean preLoadWithParamAndReturn, preLoadWithParam; @PrePersist void PrePersist() { if (prePersist == true) throw new RuntimeException("already called"); prePersist = true; } @PrePersist protected void PrePersistWithParam(DBObject dbObj) { if (prePersistWithParam == true) throw new RuntimeException("already called"); prePersistWithParam = true; } @PrePersist public DBObject PrePersistWithParamAndReturn(DBObject dbObj) { if (prePersistWithParamAndReturn == true) throw new RuntimeException("already called"); prePersistWithParamAndReturn = true; return null; // DBObject retObj = new BasicDBObject((Map)dbObj); // retObj.put("prePersistWithParamAndReturn", true); // return retObj; } @SuppressWarnings("unused") @PostPersist private void PostPersistPersist() { if (postPersist == true) throw new RuntimeException("already called"); postPersist = true; } @PostPersist void PostPersistWithParam(DBObject dbObj) { // dbObj.put("postPersistWithParam", true); postPersistWithParam = true; if(!dbObj.containsField(Mapper.ID_KEY)) throw new RuntimeException("missing " + Mapper.ID_KEY); } @PreLoad void PreLoad() { if (preLoad == true) throw new RuntimeException("already called"); preLoad = true; } @PreLoad void PreLoadWithParam(DBObject dbObj) { dbObj.put("preLoadWithParam", true); } @SuppressWarnings("rawtypes") @PreLoad DBObject PreLoadWithParamAndReturn(DBObject dbObj) { BasicDBObject retObj = new BasicDBObject(); retObj.putAll(dbObj); retObj.put("preLoadWithParamAndReturn", true); return retObj; } @PostLoad void PostLoad() { if (postLoad == true) throw new RuntimeException("already called"); postLoad = true; } @PreLoad void PostLoadWithParam(DBObject dbObj) { if (postLoadWithParam == true) throw new RuntimeException("already called"); postLoadWithParam = true; // dbObj.put("postLoadWithParam", true); } } public static class KeysKeysKeys { @Id ObjectId id; List<Key<FacebookUser>> users; Key<Rectangle> rect; protected KeysKeysKeys() {} public KeysKeysKeys(Key<Rectangle> rectKey, List<Key<FacebookUser>> users) { this.rect = rectKey; this.users = users; } } @SuppressWarnings("unused") @Test public void testMorphiaDS() throws Exception { // Datastore ds = new Morphia().createDatastore(mongo); Datastore ds = new Morphia().createDatastore(mongo, "test"); } @Test public void testLifecycle() throws Exception { DBDecoderFactory oldFactory = ads.setDecoderFact(LazyWriteableDBDecoder.FACTORY); //only replace if using lazy decoder if (!(oldFactory instanceof LazyDBDecoder)) ads.setDecoderFact(oldFactory); try { LifecycleTestObj life1 = new LifecycleTestObj(); ds.getMapper().addMappedClass(LifecycleTestObj.class); ds.save(life1); assertTrue(life1.prePersist); assertTrue(life1.prePersistWithParam); assertTrue(life1.prePersistWithParamAndReturn); assertTrue(life1.postPersist); assertTrue(life1.postPersistWithParam); LifecycleTestObj loaded = ds.get(life1); assertTrue(loaded.preLoad); assertTrue(loaded.preLoadWithParam); assertTrue(loaded.preLoadWithParamAndReturn); assertTrue(loaded.postLoad); assertTrue(loaded.postLoadWithParam); } finally { ads.setDecoderFact(oldFactory); } } @Test public void testLifecycleListeners() throws Exception { DBDecoderFactory oldFactory = ads.setDecoderFact(LazyWriteableDBDecoder.FACTORY); //only replace if using lazy decoder if (!(oldFactory instanceof LazyDBDecoder)) ads.setDecoderFact(oldFactory); try { LifecycleTestObj life1 = new LifecycleTestObj(); ds.getMapper().addMappedClass(LifecycleTestObj.class); ds.save(life1); assertTrue(LifecycleListener.prePersist); assertTrue(LifecycleListener.prePersistWithEntity); } finally { ads.setDecoderFact(oldFactory); } } @Test public void testCollectionNames() throws Exception { assertEquals("facebook_users", morphia.getMapper().getCollectionName(FacebookUser.class)); } @Test public void testGet() throws Exception { morphia.map(FacebookUser.class); List<FacebookUser> fbUsers = new ArrayList<FacebookUser>(); fbUsers.add(new FacebookUser(1,"user 1")); fbUsers.add(new FacebookUser(2,"user 2")); fbUsers.add(new FacebookUser(3,"user 3")); fbUsers.add(new FacebookUser(4,"user 4")); ds.save(fbUsers); assertEquals(4, ds.getCount(FacebookUser.class)); assertNotNull(ds.get(FacebookUser.class, 1)); List<Long> ids = new ArrayList<Long>(2); ids.add(1L); ids.add(2L); List<FacebookUser> res = ds.get(FacebookUser.class, ids).asList(); assertEquals(res.size(), 2); assertNotNull(res.get(0)); assertNotNull(res.get(0).id); assertNotNull(res.get(1)); assertNotNull(res.get(1).username); } @Test public void testExists() throws Exception { Key<FacebookUser> k = ds.save(new FacebookUser(1,"user 1")); assertEquals(1, ds.getCount(FacebookUser.class)); assertNotNull(ds.get(FacebookUser.class, 1)); assertNotNull(ds.exists(k)); assertNotNull(ds.getByKey(FacebookUser.class, k)); ds.delete(ds.find(FacebookUser.class)); assertEquals(0, ds.getCount(FacebookUser.class)); assertNull(ds.exists(k)); } @Test public void testExistsWithEntity() throws Exception { FacebookUser facebookUser = new FacebookUser(1, "user one"); ds.save(facebookUser); assertEquals(1, ds.getCount(FacebookUser.class)); assertNotNull(ds.get(FacebookUser.class, 1)); assertNotNull(ds.exists(facebookUser)); ds.delete(ds.find(FacebookUser.class)); assertEquals(0, ds.getCount(FacebookUser.class)); assertNull(ds.exists(facebookUser)); } public void testIdUpdatedOnSave() throws Exception { Rectangle rect = new Rectangle(10, 10); ds.save(rect); assertNotNull(rect.getId()); } @Test public void testSaveAndDelete() throws Exception { Rectangle rect = new Rectangle(10, 10); rect.setId("1"); //test delete(entity) ds.save(rect); assertEquals(1, ds.getCount(rect)); ds.delete(rect); assertEquals(0, ds.getCount(rect)); //test delete(entity, id) ds.save(rect); assertEquals(1, ds.getCount(rect)); ds.delete(rect.getClass(), 1); assertEquals(1, ds.getCount(rect)); ds.delete(rect.getClass(), "1"); assertEquals(0, ds.getCount(rect)); //test delete(entity, {id}) ds.save(rect); assertEquals(1, ds.getCount(rect)); List<String> ids = new ArrayList<String>(); ids.add("1"); ds.delete(rect.getClass(), ids); assertEquals(0, ds.getCount(rect)); //test delete(entity, {id,id}) rect.setId("1"); ds.save(rect); rect.setId("2"); ds.save(rect); assertEquals(2, ds.getCount(rect)); ids.clear(); ids.add("1"); ids.add("2"); ds.delete(rect.getClass(), ids); assertEquals(0, ds.getCount(rect)); //test delete(entity, {id,id}) with autogenerated ids ids.clear(); rect.setId(new ObjectId().toString()); // rect1 ds.save(rect); ids.add(rect.getId()); rect.setId(new ObjectId().toString()); // rect2 ds.save(rect); ids.add(rect.getId()); assertEquals("datastore should have saved two entities with autogenerated ids", 2, ds.getCount(rect)); ds.delete(rect.getClass(), ids); assertEquals("datastore should have deleted two entities with autogenerated ids", 0, ds.getCount(rect)); //test delete(entity, {id}) with one left rect.setId("1"); ds.save(rect); rect.setId("2"); ds.save(rect); assertEquals(2, ds.getCount(rect)); ids.clear(); ids.add("1"); ds.delete(rect.getClass(), ids); assertEquals(1, ds.getCount(rect)); //test delete(Class, {id}) with one left rect.setId("1"); ds.save(rect); rect.setId("2"); ds.save(rect); assertEquals(2, ds.getCount(rect)); ids.clear(); ids.add("1"); ds.delete(Rectangle.class, ids); assertEquals(1, ds.getCount(rect)); } @Test public void testEmbedded() throws Exception { ds.delete(ds.createQuery(Hotel.class)); Hotel borg = Hotel.create(); borg.setName("Hotel Borg"); borg.setStars(4); borg.setTakesCreditCards(true); borg.setStartDate(new Date()); borg.setType(Hotel.Type.LEISURE); Address borgAddr = new Address(); borgAddr.setStreet("Posthusstraeti 11"); borgAddr.setPostCode("101"); borg.setAddress(borgAddr); ds.save(borg); assertEquals(1, ds.getCount(Hotel.class)); assertNotNull(borg.getId()); Hotel hotelLoaded = ds.get(Hotel.class, borg.getId()); assertEquals(borg.getName(), hotelLoaded.getName()); assertEquals(borg.getAddress().getPostCode(), hotelLoaded.getAddress().getPostCode()); } @Test public void testAuthentication() throws Exception { new AssertedFailure(AuthenticationException.class) { @Override protected void thisMustFail() throws Throwable { morphia.createDatastore(mongo, TestDatastore.this.db.getName(), "SomeWeirdUserName" + System.nanoTime(), ("SomeWeirdPassword" + System.nanoTime()).toCharArray()); } }; } }
UTF-8
Java
11,285
java
TestDatastore.java
Java
[ { "context": "/**\n * Copyright (C) 2010 Olafur Gauti Gudmundsson\n *\n * Licensed under the Apache License, Version ", "end": 50, "score": 0.9998927712440491, "start": 26, "tag": "NAME", "value": "Olafur Gauti Gudmundsson" }, { "context": "port static org.junit.Assert.*;\n\n/**\n *\n * @author Scott Hernandez\n */\npublic class TestDatastore extends TestBase ", "end": 1201, "score": 0.9998270869255066, "start": 1186, "tag": "NAME", "value": "Scott Hernandez" }, { "context": "otel borg = Hotel.create();\n borg.setName(\"Hotel Borg\");\n borg.setStars(4);\n borg.setTake", "end": 10244, "score": 0.9224788546562195, "start": 10234, "tag": "NAME", "value": "Hotel Borg" }, { "context": "ongo, TestDatastore.this.db.getName(),\n\t\t\t\t\t\t\"SomeWeirdUserName\" + System.nanoTime(),\n\t\t\t\t\t\t(\"SomeWeir", "end": 11172, "score": 0.506894052028656, "start": 11170, "tag": "USERNAME", "value": "We" } ]
null
[]
/** * Copyright (C) 2010 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jmkgreen.morphia; import com.github.jmkgreen.morphia.annotations.*; import com.github.jmkgreen.morphia.mapping.Mapper; import com.github.jmkgreen.morphia.testmodel.Address; import com.github.jmkgreen.morphia.testmodel.Hotel; import com.github.jmkgreen.morphia.testmodel.Rectangle; import com.github.jmkgreen.morphia.testutil.AssertedFailure; import com.mongodb.*; import org.bson.types.ObjectId; import org.junit.Test; import java.util.ArrayList; import java.util.Date; import java.util.List; import static org.junit.Assert.*; /** * * @author <NAME> */ public class TestDatastore extends TestBase { @Entity("facebook_users") public static class FacebookUser { @Id long id; String username; public FacebookUser() {} public FacebookUser(long id, String name) { this(); this.id = id; this.username = name; } } public static class LifecycleListener { static boolean prePersist = false; static boolean prePersistWithEntity = false; @PrePersist void PrePersist() { prePersist = true; } @PrePersist void PrePersist(LifecycleTestObj obj) { if(obj == null) throw new RuntimeException(); prePersistWithEntity = true; } } @EntityListeners(LifecycleListener.class) public static class LifecycleTestObj { @Id ObjectId id; @Transient boolean prePersist, postPersist, preLoad, postLoad, postLoadWithParam; boolean prePersistWithParamAndReturn, prePersistWithParam; boolean postPersistWithParam; boolean preLoadWithParamAndReturn, preLoadWithParam; @PrePersist void PrePersist() { if (prePersist == true) throw new RuntimeException("already called"); prePersist = true; } @PrePersist protected void PrePersistWithParam(DBObject dbObj) { if (prePersistWithParam == true) throw new RuntimeException("already called"); prePersistWithParam = true; } @PrePersist public DBObject PrePersistWithParamAndReturn(DBObject dbObj) { if (prePersistWithParamAndReturn == true) throw new RuntimeException("already called"); prePersistWithParamAndReturn = true; return null; // DBObject retObj = new BasicDBObject((Map)dbObj); // retObj.put("prePersistWithParamAndReturn", true); // return retObj; } @SuppressWarnings("unused") @PostPersist private void PostPersistPersist() { if (postPersist == true) throw new RuntimeException("already called"); postPersist = true; } @PostPersist void PostPersistWithParam(DBObject dbObj) { // dbObj.put("postPersistWithParam", true); postPersistWithParam = true; if(!dbObj.containsField(Mapper.ID_KEY)) throw new RuntimeException("missing " + Mapper.ID_KEY); } @PreLoad void PreLoad() { if (preLoad == true) throw new RuntimeException("already called"); preLoad = true; } @PreLoad void PreLoadWithParam(DBObject dbObj) { dbObj.put("preLoadWithParam", true); } @SuppressWarnings("rawtypes") @PreLoad DBObject PreLoadWithParamAndReturn(DBObject dbObj) { BasicDBObject retObj = new BasicDBObject(); retObj.putAll(dbObj); retObj.put("preLoadWithParamAndReturn", true); return retObj; } @PostLoad void PostLoad() { if (postLoad == true) throw new RuntimeException("already called"); postLoad = true; } @PreLoad void PostLoadWithParam(DBObject dbObj) { if (postLoadWithParam == true) throw new RuntimeException("already called"); postLoadWithParam = true; // dbObj.put("postLoadWithParam", true); } } public static class KeysKeysKeys { @Id ObjectId id; List<Key<FacebookUser>> users; Key<Rectangle> rect; protected KeysKeysKeys() {} public KeysKeysKeys(Key<Rectangle> rectKey, List<Key<FacebookUser>> users) { this.rect = rectKey; this.users = users; } } @SuppressWarnings("unused") @Test public void testMorphiaDS() throws Exception { // Datastore ds = new Morphia().createDatastore(mongo); Datastore ds = new Morphia().createDatastore(mongo, "test"); } @Test public void testLifecycle() throws Exception { DBDecoderFactory oldFactory = ads.setDecoderFact(LazyWriteableDBDecoder.FACTORY); //only replace if using lazy decoder if (!(oldFactory instanceof LazyDBDecoder)) ads.setDecoderFact(oldFactory); try { LifecycleTestObj life1 = new LifecycleTestObj(); ds.getMapper().addMappedClass(LifecycleTestObj.class); ds.save(life1); assertTrue(life1.prePersist); assertTrue(life1.prePersistWithParam); assertTrue(life1.prePersistWithParamAndReturn); assertTrue(life1.postPersist); assertTrue(life1.postPersistWithParam); LifecycleTestObj loaded = ds.get(life1); assertTrue(loaded.preLoad); assertTrue(loaded.preLoadWithParam); assertTrue(loaded.preLoadWithParamAndReturn); assertTrue(loaded.postLoad); assertTrue(loaded.postLoadWithParam); } finally { ads.setDecoderFact(oldFactory); } } @Test public void testLifecycleListeners() throws Exception { DBDecoderFactory oldFactory = ads.setDecoderFact(LazyWriteableDBDecoder.FACTORY); //only replace if using lazy decoder if (!(oldFactory instanceof LazyDBDecoder)) ads.setDecoderFact(oldFactory); try { LifecycleTestObj life1 = new LifecycleTestObj(); ds.getMapper().addMappedClass(LifecycleTestObj.class); ds.save(life1); assertTrue(LifecycleListener.prePersist); assertTrue(LifecycleListener.prePersistWithEntity); } finally { ads.setDecoderFact(oldFactory); } } @Test public void testCollectionNames() throws Exception { assertEquals("facebook_users", morphia.getMapper().getCollectionName(FacebookUser.class)); } @Test public void testGet() throws Exception { morphia.map(FacebookUser.class); List<FacebookUser> fbUsers = new ArrayList<FacebookUser>(); fbUsers.add(new FacebookUser(1,"user 1")); fbUsers.add(new FacebookUser(2,"user 2")); fbUsers.add(new FacebookUser(3,"user 3")); fbUsers.add(new FacebookUser(4,"user 4")); ds.save(fbUsers); assertEquals(4, ds.getCount(FacebookUser.class)); assertNotNull(ds.get(FacebookUser.class, 1)); List<Long> ids = new ArrayList<Long>(2); ids.add(1L); ids.add(2L); List<FacebookUser> res = ds.get(FacebookUser.class, ids).asList(); assertEquals(res.size(), 2); assertNotNull(res.get(0)); assertNotNull(res.get(0).id); assertNotNull(res.get(1)); assertNotNull(res.get(1).username); } @Test public void testExists() throws Exception { Key<FacebookUser> k = ds.save(new FacebookUser(1,"user 1")); assertEquals(1, ds.getCount(FacebookUser.class)); assertNotNull(ds.get(FacebookUser.class, 1)); assertNotNull(ds.exists(k)); assertNotNull(ds.getByKey(FacebookUser.class, k)); ds.delete(ds.find(FacebookUser.class)); assertEquals(0, ds.getCount(FacebookUser.class)); assertNull(ds.exists(k)); } @Test public void testExistsWithEntity() throws Exception { FacebookUser facebookUser = new FacebookUser(1, "user one"); ds.save(facebookUser); assertEquals(1, ds.getCount(FacebookUser.class)); assertNotNull(ds.get(FacebookUser.class, 1)); assertNotNull(ds.exists(facebookUser)); ds.delete(ds.find(FacebookUser.class)); assertEquals(0, ds.getCount(FacebookUser.class)); assertNull(ds.exists(facebookUser)); } public void testIdUpdatedOnSave() throws Exception { Rectangle rect = new Rectangle(10, 10); ds.save(rect); assertNotNull(rect.getId()); } @Test public void testSaveAndDelete() throws Exception { Rectangle rect = new Rectangle(10, 10); rect.setId("1"); //test delete(entity) ds.save(rect); assertEquals(1, ds.getCount(rect)); ds.delete(rect); assertEquals(0, ds.getCount(rect)); //test delete(entity, id) ds.save(rect); assertEquals(1, ds.getCount(rect)); ds.delete(rect.getClass(), 1); assertEquals(1, ds.getCount(rect)); ds.delete(rect.getClass(), "1"); assertEquals(0, ds.getCount(rect)); //test delete(entity, {id}) ds.save(rect); assertEquals(1, ds.getCount(rect)); List<String> ids = new ArrayList<String>(); ids.add("1"); ds.delete(rect.getClass(), ids); assertEquals(0, ds.getCount(rect)); //test delete(entity, {id,id}) rect.setId("1"); ds.save(rect); rect.setId("2"); ds.save(rect); assertEquals(2, ds.getCount(rect)); ids.clear(); ids.add("1"); ids.add("2"); ds.delete(rect.getClass(), ids); assertEquals(0, ds.getCount(rect)); //test delete(entity, {id,id}) with autogenerated ids ids.clear(); rect.setId(new ObjectId().toString()); // rect1 ds.save(rect); ids.add(rect.getId()); rect.setId(new ObjectId().toString()); // rect2 ds.save(rect); ids.add(rect.getId()); assertEquals("datastore should have saved two entities with autogenerated ids", 2, ds.getCount(rect)); ds.delete(rect.getClass(), ids); assertEquals("datastore should have deleted two entities with autogenerated ids", 0, ds.getCount(rect)); //test delete(entity, {id}) with one left rect.setId("1"); ds.save(rect); rect.setId("2"); ds.save(rect); assertEquals(2, ds.getCount(rect)); ids.clear(); ids.add("1"); ds.delete(rect.getClass(), ids); assertEquals(1, ds.getCount(rect)); //test delete(Class, {id}) with one left rect.setId("1"); ds.save(rect); rect.setId("2"); ds.save(rect); assertEquals(2, ds.getCount(rect)); ids.clear(); ids.add("1"); ds.delete(Rectangle.class, ids); assertEquals(1, ds.getCount(rect)); } @Test public void testEmbedded() throws Exception { ds.delete(ds.createQuery(Hotel.class)); Hotel borg = Hotel.create(); borg.setName("<NAME>"); borg.setStars(4); borg.setTakesCreditCards(true); borg.setStartDate(new Date()); borg.setType(Hotel.Type.LEISURE); Address borgAddr = new Address(); borgAddr.setStreet("Posthusstraeti 11"); borgAddr.setPostCode("101"); borg.setAddress(borgAddr); ds.save(borg); assertEquals(1, ds.getCount(Hotel.class)); assertNotNull(borg.getId()); Hotel hotelLoaded = ds.get(Hotel.class, borg.getId()); assertEquals(borg.getName(), hotelLoaded.getName()); assertEquals(borg.getAddress().getPostCode(), hotelLoaded.getAddress().getPostCode()); } @Test public void testAuthentication() throws Exception { new AssertedFailure(AuthenticationException.class) { @Override protected void thisMustFail() throws Throwable { morphia.createDatastore(mongo, TestDatastore.this.db.getName(), "SomeWeirdUserName" + System.nanoTime(), ("SomeWeirdPassword" + System.nanoTime()).toCharArray()); } }; } }
11,254
0.703677
0.695614
387
28.160206
22.01022
106
false
false
0
0
0
0
0
0
2.335917
false
false
10
1200cf2367627baa5e1d31a4aaf603c3c584fea3
68,719,538,617
ce3357b75ee4fea7186f4a50ce1540bc2267c1ac
/140921/task_5.1/Main.java
4208355d5bfd4764c88f52f98402fc40643b2b26
[]
no_license
kardan1984/1147_tasks
https://github.com/kardan1984/1147_tasks
010957f741e4794c89cc540dda4e5ae1582ff2d9
16494c95b1ecbb6ab2b510059126be7310bc0746
refs/heads/main
2023-08-18T05:23:17.332000
2021-09-27T18:48:24
2021-09-27T18:48:24
403,608,233
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Дана коллекция имён. * 1) удалить все повторяющиеся имена из коллекции * 2) вывести коллекцию на экран * */ import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); ArrayList<String> names = new ArrayList(); names.add("Анатолий"); names.add("Георгий"); names.add("Руслан"); names.add("Георгий"); names.add("Павел"); names.add("Руслан"); ArrayList<String> names1 = new ArrayList<String>(); for (String name:names) { if(!names1.contains(name)){ names1.add(name); } } System.out.println ("Коллекция после удаления дублей:"+names1); } }
UTF-8
Java
937
java
Main.java
Java
[ { "context": "ring> names = new ArrayList();\n names.add(\"Анатолий\");\n names.add(\"Георгий\");\n names.ad", "end": 366, "score": 0.9996450543403625, "start": 358, "tag": "NAME", "value": "Анатолий" }, { "context": " names.add(\"Анатолий\");\n names.add(\"Георгий\");\n names.add(\"Руслан\");\n names.add", "end": 396, "score": 0.9989252090454102, "start": 389, "tag": "NAME", "value": "Георгий" }, { "context": "\n names.add(\"Георгий\");\n names.add(\"Руслан\");\n names.add(\"Георгий\");\n names.ad", "end": 425, "score": 0.9998032450675964, "start": 419, "tag": "NAME", "value": "Руслан" }, { "context": ";\n names.add(\"Руслан\");\n names.add(\"Георгий\");\n names.add(\"Павел\");\n names.add(", "end": 455, "score": 0.9979285001754761, "start": 448, "tag": "NAME", "value": "Георгий" }, { "context": "\n names.add(\"Георгий\");\n names.add(\"Павел\");\n names.add(\"Руслан\");\n\n ArrayLis", "end": 483, "score": 0.9998016357421875, "start": 478, "tag": "NAME", "value": "Павел" }, { "context": ");\n names.add(\"Павел\");\n names.add(\"Руслан\");\n\n ArrayList<String> names1 = new Array", "end": 512, "score": 0.9998446106910706, "start": 506, "tag": "NAME", "value": "Руслан" } ]
null
[]
/* * Дана коллекция имён. * 1) удалить все повторяющиеся имена из коллекции * 2) вывести коллекцию на экран * */ import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); ArrayList<String> names = new ArrayList(); names.add("Анатолий"); names.add("Георгий"); names.add("Руслан"); names.add("Георгий"); names.add("Павел"); names.add("Руслан"); ArrayList<String> names1 = new ArrayList<String>(); for (String name:names) { if(!names1.contains(name)){ names1.add(name); } } System.out.println ("Коллекция после удаления дублей:"+names1); } }
937
0.582807
0.575221
30
25.366667
18.995584
71
false
false
0
0
0
0
0
0
0.433333
false
false
10
059a4dbc33439d473954e53ec90f89af13a130da
19,327,352,874,337
464b1dce3a973653ba9ba76c8fdd362108bc7431
/src/main/java/json/ConvertJson.java
b80e23abb122a2079eeb2f7e6d9d7e1cc3f4e1b1
[]
no_license
LischukNatali/Hometask_2_JSON
https://github.com/LischukNatali/Hometask_2_JSON
c12185364dd0eaab54e881835a5741b0d89fbc28
e20016a08007fcf458b32ec65387651ba4951caa
refs/heads/master
2021-01-02T08:22:34.577000
2017-08-01T12:11:04
2017-08-01T12:11:04
98,995,456
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package json; import json.annotations.CustomDateFormat; import json.annotations.JsonValue; import json.interfaces.IConvertJson; import java.lang.reflect.Field; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class ConvertJson implements IConvertJson { public String toJson(Object o) throws IllegalAccessException { String result = "{"; Class clazz = o.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); if (field.get(o) != null) { // если поле содержит аннотацию @JsonValue, то имя JSON элемента // должно соответствовать имени, указанному в аннотации. if (field.isAnnotationPresent(JsonValue.class)) { JsonValue jsonValue = field.getAnnotation(JsonValue.class); result += "\"" + jsonValue.name() + "\":\"" + field.get(o) + "\","; // аннотация @CustomDateFormat должна задавать форматированный вывод формата времени. Если есть поле даты, // но без указанного формата - использовать формат по умолчания (вывод через toString) } else if (field.isAnnotationPresent(CustomDateFormat.class)) { CustomDateFormat customDateFormat = field.getAnnotation(CustomDateFormat.class); LocalDate localDate = (LocalDate) field.get(o); result += "\"" + field.getName() + "\":\"" + localDate.format(DateTimeFormatter.ofPattern(customDateFormat.format())) + "\","; /// } else { result += "\"" + field.getName() + "\":\"" + field.get(o) + "\","; } field.setAccessible(false); } else { } } result += "}"; return result; } public Object fromJson(String json, Class clazz) throws IllegalAccessException, InstantiationException { Object result = clazz.newInstance(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); int startNameOfTheField = (json.indexOf(field.getName()) + field.getName().length() + 3); String findSymbol = "\""; String fieldValue = json.substring(startNameOfTheField, json.indexOf(findSymbol, startNameOfTheField)); if (json.contains(field.getName())) { if (field.getName().equals("birthDate")) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); LocalDate date = LocalDate.parse(fieldValue, formatter); field.set(result, date); } else { System.out.println(json.substring(startNameOfTheField, json.indexOf(findSymbol, startNameOfTheField))); field.set(result, fieldValue); } field.setAccessible(false); } } return result; } }
UTF-8
Java
3,273
java
ConvertJson.java
Java
[]
null
[]
package json; import json.annotations.CustomDateFormat; import json.annotations.JsonValue; import json.interfaces.IConvertJson; import java.lang.reflect.Field; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class ConvertJson implements IConvertJson { public String toJson(Object o) throws IllegalAccessException { String result = "{"; Class clazz = o.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); if (field.get(o) != null) { // если поле содержит аннотацию @JsonValue, то имя JSON элемента // должно соответствовать имени, указанному в аннотации. if (field.isAnnotationPresent(JsonValue.class)) { JsonValue jsonValue = field.getAnnotation(JsonValue.class); result += "\"" + jsonValue.name() + "\":\"" + field.get(o) + "\","; // аннотация @CustomDateFormat должна задавать форматированный вывод формата времени. Если есть поле даты, // но без указанного формата - использовать формат по умолчания (вывод через toString) } else if (field.isAnnotationPresent(CustomDateFormat.class)) { CustomDateFormat customDateFormat = field.getAnnotation(CustomDateFormat.class); LocalDate localDate = (LocalDate) field.get(o); result += "\"" + field.getName() + "\":\"" + localDate.format(DateTimeFormatter.ofPattern(customDateFormat.format())) + "\","; /// } else { result += "\"" + field.getName() + "\":\"" + field.get(o) + "\","; } field.setAccessible(false); } else { } } result += "}"; return result; } public Object fromJson(String json, Class clazz) throws IllegalAccessException, InstantiationException { Object result = clazz.newInstance(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); int startNameOfTheField = (json.indexOf(field.getName()) + field.getName().length() + 3); String findSymbol = "\""; String fieldValue = json.substring(startNameOfTheField, json.indexOf(findSymbol, startNameOfTheField)); if (json.contains(field.getName())) { if (field.getName().equals("birthDate")) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); LocalDate date = LocalDate.parse(fieldValue, formatter); field.set(result, date); } else { System.out.println(json.substring(startNameOfTheField, json.indexOf(findSymbol, startNameOfTheField))); field.set(result, fieldValue); } field.setAccessible(false); } } return result; } }
3,273
0.586252
0.585925
67
44.582088
35.689854
150
false
false
0
0
0
0
0
0
0.716418
false
false
10
417790db47506bb997b8a3da5b17acb74f59b0d7
19,533,511,272,344
66011b66790a1200a79e383c0c914686b83275a3
/src/game/gfx/Assets.java
91076d009fa695e74b48432fb492aebf74dc36b5
[ "Apache-2.0" ]
permissive
PhoenixVortex/WarpCorp
https://github.com/PhoenixVortex/WarpCorp
4c5789943e1dbd04de35142303abdc68d31e889d
bcbb9bead31fb1a6d38b677c777539940432b256
refs/heads/master
2021-08-26T06:39:54.168000
2017-11-21T22:37:30
2017-11-21T22:37:30
110,972,894
0
0
null
true
2017-11-16T13:10:28
2017-11-16T13:10:28
2017-11-15T19:25:21
2017-11-15T19:26:19
142
0
0
0
null
false
null
package game.gfx; import engine.gfx.Model; import engine.gfx.TextureSheet; public class Assets { private static Model model; //TextureSheets public static TextureSheet tiles; //Textures private static void initTextures() { tiles = new TextureSheet("tiles/tiles", 7); } public static Model getModel() { return model; } public static void initAssets() { float[] vertices = new float[] { -.5f, .5f, 0, // TOP LEFT .5f, .5f, 0, // TOP RIGHT 0.5f, -.5f, 0, // BOTTOM RIGHT -.5f, -.5f, 0, // Button LEFT };// Triangle float[] texture = new float[] { 0, 0, 1, 0, 1, 1, 0, 1, };// Texture int[] indices = new int[] { 0, 1, 2, // Draws first triangle 2, 3, 0// Draws second triangle }; model = new Model(vertices, texture, indices); initTextures(); } public static void deleteAsset() { model = null; } }
UTF-8
Java
902
java
Assets.java
Java
[]
null
[]
package game.gfx; import engine.gfx.Model; import engine.gfx.TextureSheet; public class Assets { private static Model model; //TextureSheets public static TextureSheet tiles; //Textures private static void initTextures() { tiles = new TextureSheet("tiles/tiles", 7); } public static Model getModel() { return model; } public static void initAssets() { float[] vertices = new float[] { -.5f, .5f, 0, // TOP LEFT .5f, .5f, 0, // TOP RIGHT 0.5f, -.5f, 0, // BOTTOM RIGHT -.5f, -.5f, 0, // Button LEFT };// Triangle float[] texture = new float[] { 0, 0, 1, 0, 1, 1, 0, 1, };// Texture int[] indices = new int[] { 0, 1, 2, // Draws first triangle 2, 3, 0// Draws second triangle }; model = new Model(vertices, texture, indices); initTextures(); } public static void deleteAsset() { model = null; } }
902
0.594235
0.563193
43
18.976744
19.243227
70
false
false
0
0
0
0
0
0
2.162791
false
false
10
f88445c1d91717748cbf0ffa0f61ea482fea5f69
23,948,737,684,925
bc312e7fe738b1a4918ef349e8420055f06b1d68
/learn/Solution8.java
1c05bcce7666a3b930c366d3488bb818f8a7f8f5
[]
no_license
11nitishparikh/learning-2-code
https://github.com/11nitishparikh/learning-2-code
d8247e3ff0a813e5470364d4e28c4edb5e34260e
22c28f67d3dca06ae41194a2810ef108aaa19bb7
refs/heads/main
2023-09-04T02:43:05.175000
2021-10-21T14:06:10
2021-10-21T14:06:10
324,217,870
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package learn; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; class Result8 { public static int getAnagram(String s) { int count = 0; String s1 = s.substring(0, (s.length()/2)); System.out.println(s1); String s2 = s.substring((s.length()/2), s.length()); System.out.println(s2); int letterCount[] = new int[10]; for (int i = 0; i < s1.length(); i++) letterCount[s1.charAt(i) - '0']++; for (int i = 0; i < s2.length(); i++) if (letterCount[s2.charAt(i) - '0']-- <= 0) count++; return count; } } public class Solution8 { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); String s = bufferedReader.readLine(); int result = Result8.getAnagram(s); bufferedWriter.write(String.valueOf(result)); bufferedWriter.newLine(); bufferedReader.close(); bufferedWriter.close(); } }
UTF-8
Java
1,294
java
Solution8.java
Java
[]
null
[]
package learn; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; class Result8 { public static int getAnagram(String s) { int count = 0; String s1 = s.substring(0, (s.length()/2)); System.out.println(s1); String s2 = s.substring((s.length()/2), s.length()); System.out.println(s2); int letterCount[] = new int[10]; for (int i = 0; i < s1.length(); i++) letterCount[s1.charAt(i) - '0']++; for (int i = 0; i < s2.length(); i++) if (letterCount[s2.charAt(i) - '0']-- <= 0) count++; return count; } } public class Solution8 { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); String s = bufferedReader.readLine(); int result = Result8.getAnagram(s); bufferedWriter.write(String.valueOf(result)); bufferedWriter.newLine(); bufferedReader.close(); bufferedWriter.close(); } }
1,294
0.602009
0.585008
43
28.093023
24.258121
105
false
false
0
0
0
0
0
0
0.953488
false
false
10
8336d9c4f0126d35957739e3b2e3ea5135cdb820
22,832,046,211,337
0fd13caeff68470e6fed05a020bab9040cca3fe7
/app/src/main/java/com/walker/cloud/sipadu/userinterface/LoginActivity.java
76ac13266a13a934bfe23ad9ae4e50f2a5b0a7c0
[]
no_license
SeptiawanAjiP/imk
https://github.com/SeptiawanAjiP/imk
bbbad7d274d0184943fe8e9e662ca6407f53af17
76ceec6d2241e24acbb046818ab4bbe7fc09c14f
refs/heads/master
2020-05-23T07:58:46.636000
2017-01-31T00:38:49
2017-01-31T00:38:49
80,478,281
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.walker.cloud.sipadu.userinterface; import android.app.ProgressDialog; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.walker.cloud.sipadu.R; import com.walker.cloud.sipadu.asset.SessionManager; import com.walker.cloud.sipadu.asset.Request; /** * A login screen that offers login via email/password. */ public class LoginActivity extends AppCompatActivity { private TextView message; private Button loginBtn; private EditText inputNIM, inputPassword; private LinearLayout loginHolder, label; private static final String d="LOGINCoba"; private SessionManager sessionManager; private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); sessionManager = new SessionManager(getApplicationContext()); sessionManager.firstInstall(); if (sessionManager.isLoggedIn()) { finish(); startActivity(new Intent(LoginActivity.this, HomeActivity .class)); } loginBtn = (Button) findViewById(R.id.masuk); inputNIM = (EditText) findViewById(R.id.nim_input); inputPassword = (EditText) findViewById(R.id.password_input); loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showProgress(); if(!inputNIM.getText().toString().isEmpty()){ if(!inputPassword.getText().toString().isEmpty()){ Request request = new Request(LoginActivity.this); request.verivyNim(inputNIM.getText().toString(),inputPassword.getText().toString(),0); progressDialog.dismiss(); // Intent intent = new Intent(getApplicationContext(),HomeActivity.class); // startActivity(intent); }else{ Toast.makeText(LoginActivity.this, "Password Kosong", Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); } }else{ Toast.makeText(LoginActivity.this, "Nim Kosong", Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); } } }); } private void showProgress() { progressDialog=null;// Initialize to null progressDialog = new ProgressDialog(this); progressDialog.setMessage("Loading..."); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressDialog.setCancelable(true); progressDialog.show(); } }
UTF-8
Java
2,970
java
LoginActivity.java
Java
[ { "context": " Toast.makeText(LoginActivity.this, \"Nim Kosong\", Toast.LENGTH_SHORT).show();\n ", "end": 2503, "score": 0.9975100159645081, "start": 2493, "tag": "NAME", "value": "Nim Kosong" } ]
null
[]
package com.walker.cloud.sipadu.userinterface; import android.app.ProgressDialog; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.walker.cloud.sipadu.R; import com.walker.cloud.sipadu.asset.SessionManager; import com.walker.cloud.sipadu.asset.Request; /** * A login screen that offers login via email/password. */ public class LoginActivity extends AppCompatActivity { private TextView message; private Button loginBtn; private EditText inputNIM, inputPassword; private LinearLayout loginHolder, label; private static final String d="LOGINCoba"; private SessionManager sessionManager; private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); sessionManager = new SessionManager(getApplicationContext()); sessionManager.firstInstall(); if (sessionManager.isLoggedIn()) { finish(); startActivity(new Intent(LoginActivity.this, HomeActivity .class)); } loginBtn = (Button) findViewById(R.id.masuk); inputNIM = (EditText) findViewById(R.id.nim_input); inputPassword = (EditText) findViewById(R.id.password_input); loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showProgress(); if(!inputNIM.getText().toString().isEmpty()){ if(!inputPassword.getText().toString().isEmpty()){ Request request = new Request(LoginActivity.this); request.verivyNim(inputNIM.getText().toString(),inputPassword.getText().toString(),0); progressDialog.dismiss(); // Intent intent = new Intent(getApplicationContext(),HomeActivity.class); // startActivity(intent); }else{ Toast.makeText(LoginActivity.this, "Password Kosong", Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); } }else{ Toast.makeText(LoginActivity.this, "<NAME>", Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); } } }); } private void showProgress() { progressDialog=null;// Initialize to null progressDialog = new ProgressDialog(this); progressDialog.setMessage("Loading..."); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressDialog.setCancelable(true); progressDialog.show(); } }
2,966
0.643098
0.642424
80
36.125
26.203709
110
false
false
0
0
0
0
0
0
0.7125
false
false
10
8282e449f0c213480c52bebd0cc3b1b269c22c17
26,250,840,162,534
df5974db8ce8f941f4dbe632048f8795e900dba4
/Vendor/SHFVendor/app/src/main/java/simplyhomefood/com/shfvendor/data_objects/JobListingTagBean.java
6683b778e50faea0d39f349ae48aa163adfdfe10
[]
no_license
bikramaditya/simplyhomefood
https://github.com/bikramaditya/simplyhomefood
13bf6aa3bb0d96d68d251c5c61d76285cb2294c2
9abfcda09d6c16f1f6279987301cefccd3401128
refs/heads/master
2016-09-17T20:17:49.669000
2016-05-26T12:34:13
2016-05-26T12:34:13
67,785,930
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package simplyhomefood.com.shfvendor.data_objects; /** * Created by User on 2/12/2016. */ public class JobListingTagBean { /* "id": 58, "slug": "organic", "title": "Organic", "description": "", "post_count": 7 */ String id; String slug; String title; String description; String post_count; public JobListingTagBean(String id, String slug, String title, String description, String post_count) { this.id=id; this.slug=slug; this.title=title; this.description=description; this.post_count=post_count; } public String getTitle() { return title; } public String getId() { return id; } public String getSlug() { return slug; } public String getDescription() { return description; } public String getPost_count() { return post_count; } }
UTF-8
Java
1,010
java
JobListingTagBean.java
Java
[]
null
[]
package simplyhomefood.com.shfvendor.data_objects; /** * Created by User on 2/12/2016. */ public class JobListingTagBean { /* "id": 58, "slug": "organic", "title": "Organic", "description": "", "post_count": 7 */ String id; String slug; String title; String description; String post_count; public JobListingTagBean(String id, String slug, String title, String description, String post_count) { this.id=id; this.slug=slug; this.title=title; this.description=description; this.post_count=post_count; } public String getTitle() { return title; } public String getId() { return id; } public String getSlug() { return slug; } public String getDescription() { return description; } public String getPost_count() { return post_count; } }
1,010
0.530693
0.520792
51
18.803921
19.054123
107
true
false
0
0
0
0
0
0
0.470588
false
false
10
a9c935397d9319e665961069f73cca3632cd27c2
17,617,955,910,473
7de15337fbf38cfce1c0a5260b5b6e61ca08bb13
/org.flowerplatform.codesync.wiki/src/com/crispico/flower/mp/codesync/wiki/dokuwiki/DokuWikiConfigurationProvider.java
cca9894279f74258b9a639cc4a12f2d9cc25db8d
[]
no_license
flower-platform/flower-platform-3
https://github.com/flower-platform/flower-platform-3
2a4efadf92c69d622dbd261d404d3fa4d08d0c29
e34ecdf967239bbd5e36015a2ce31e08bbe21041
refs/heads/master
2021-01-13T02:16:29.579000
2014-01-14T14:54:01
2014-01-14T14:54:01
10,144,151
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* license-start * * Copyright (C) 2008 - 2013 Crispico, <http://www.crispico.com/>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details, at <http://www.gnu.org/licenses/>. * * Contributors: * Crispico - Initial API and implementation * * license-end */ package com.crispico.flower.mp.codesync.wiki.dokuwiki; import java.util.List; import org.flowerplatform.common.regex.RegexWithAction; import org.flowerplatform.model.astcache.wiki.AstCacheWikiFactory; import org.flowerplatform.model.astcache.wiki.Page; import com.crispico.flower.mp.model.codesync.CodeSyncElement; import com.crispico.flower.mp.model.codesync.CodeSyncPackage; import com.crispico.flower.mp.model.codesync.CodeSyncRoot; import com.crispico.flower.mp.codesync.wiki.IConfigurationProvider; import com.crispico.flower.mp.codesync.wiki.WikiPlugin; import com.crispico.flower.mp.codesync.wiki.WikiRegexConfiguration; import com.crispico.flower.mp.codesync.wiki.WikiTextBuilder; import com.crispico.flower.mp.codesync.wiki.WikiTreeBuilder; import static com.crispico.flower.mp.codesync.wiki.WikiRegexConfiguration.*; /** * @author Mariana */ public class DokuWikiConfigurationProvider implements IConfigurationProvider { @Override public void buildConfiguration(WikiRegexConfiguration config, CodeSyncElement cse) { config .add(new RegexWithAction.IfFindThisAnnounceMatchCandidate(WikiPlugin.HEADING_LEVEL_1_CATEGORY, getHeading(1), WikiPlugin.HEADING_LEVEL_1_CATEGORY)) .add(new RegexWithAction.IfFindThisAnnounceMatchCandidate(WikiPlugin.HEADING_LEVEL_2_CATEGORY, getHeading(2), WikiPlugin.HEADING_LEVEL_2_CATEGORY)) .add(new RegexWithAction.IfFindThisAnnounceMatchCandidate(WikiPlugin.HEADING_LEVEL_3_CATEGORY, getHeading(3), WikiPlugin.HEADING_LEVEL_3_CATEGORY)) .add(new RegexWithAction.IfFindThisAnnounceMatchCandidate(WikiPlugin.HEADING_LEVEL_4_CATEGORY, getHeading(4), WikiPlugin.HEADING_LEVEL_4_CATEGORY)) .add(new RegexWithAction.IfFindThisAnnounceMatchCandidate(WikiPlugin.HEADING_LEVEL_5_CATEGORY, getHeading(5), WikiPlugin.HEADING_LEVEL_5_CATEGORY)) .add(new RegexWithAction.IfFindThisAnnounceMatchCandidate(WikiPlugin.PARAGRAPH_CATEGORY, PARAGRAPH_REGEX, WikiPlugin.PARAGRAPH_CATEGORY)) .setUseUntilFoundThisIgnoreAll(false); } @Override public Class<? extends WikiTreeBuilder> getWikiTreeBuilderClass() { return WikiTreeBuilder.class; } @Override public WikiTextBuilder getWikiTextBuilder(CodeSyncElement cse) { return new WikiTextBuilder(); } // TODO test private String getHeading(int level) { String delim = String.format("={%s}", 7 - level); return String.format(MULTILINE_MATCH_FORMAT, delim + CAPTURE_ANY + delim); // return String.format("^(={%s}", 7 - level) // + ".*?" // + String.format("={%s,}", 2) // at least 2 times // + "\\s*?" // + ")$"; } /** * @param wiki list of {@link DokuWikiPage}s */ @Override public CodeSyncRoot getWikiTree(Object wiki) { List<DokuWikiPage> pages = (List<DokuWikiPage>) wiki; CodeSyncRoot root = CodeSyncPackage.eINSTANCE.getCodeSyncFactory().createCodeSyncRoot(); root.setName(DokuWikiPlugin.getInstance().getWikiName()); root.setType(WikiPlugin.FOLDER_CATEGORY); if (pages != null) { for (DokuWikiPage page : pages) { CodeSyncElement crtNode = root; String[] fragments = page.getId().split(":"); for (int i = 0; i < fragments.length; i++) { String fragment = fragments[i]; CodeSyncElement child = getChild(crtNode, fragment); if (child == null) { child = CodeSyncPackage.eINSTANCE.getCodeSyncFactory().createCodeSyncElement(); child.setName(fragment); child.setType(WikiPlugin.FOLDER_CATEGORY); if (i == fragments.length - 1) { child.setType(WikiPlugin.PAGE_CATEGORY); Page wikiPage = AstCacheWikiFactory.eINSTANCE.createPage(); wikiPage.setInitialContent(page.getContent()); wikiPage.setLineDelimiter(WikiPlugin.getInstance().getLineDelimiter(page.getContent())); child.setAstCacheElement(wikiPage); } crtNode.getChildren().add(child); } crtNode = child; } } } return root; } private CodeSyncElement getChild(CodeSyncElement parent, String name) { for (CodeSyncElement child : parent.getChildren()) { if (child.getName().equals(name)) { return child; } } return null; } @Override public void savePage(Page page) { DokuWikiPlugin.getInstance().savePage(page); } }
UTF-8
Java
4,947
java
DokuWikiConfigurationProvider.java
Java
[ { "context": "* license-start\r\n * \r\n * Copyright (C) 2008 - 2013 Crispico, <http://www.crispico.com/>.\r\n * \r\n * This ", "end": 54, "score": 0.5484074354171753, "start": 52, "tag": "NAME", "value": "Cr" }, { "context": "icense-start\r\n * \r\n * Copyright (C) 2008 - 2013 Crispico, <http://www.crispico.com/>.\r\n * \r\n * This progra", "end": 60, "score": 0.6157094240188599, "start": 54, "tag": "USERNAME", "value": "ispico" }, { "context": "w.gnu.org/licenses/>.\r\n * \r\n * Contributors:\r\n * Crispico - Initial API and implementation\r\n *\r\n * license-", "end": 612, "score": 0.7861106395721436, "start": 604, "tag": "USERNAME", "value": "Crispico" }, { "context": ".wiki.WikiRegexConfiguration.*;\r\n\r\n/**\r\n * @author Mariana\r\n */\r\npublic class DokuWikiConfigurationProvider im", "end": 1546, "score": 0.995323657989502, "start": 1539, "tag": "NAME", "value": "Mariana" } ]
null
[]
/* license-start * * Copyright (C) 2008 - 2013 Crispico, <http://www.crispico.com/>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details, at <http://www.gnu.org/licenses/>. * * Contributors: * Crispico - Initial API and implementation * * license-end */ package com.crispico.flower.mp.codesync.wiki.dokuwiki; import java.util.List; import org.flowerplatform.common.regex.RegexWithAction; import org.flowerplatform.model.astcache.wiki.AstCacheWikiFactory; import org.flowerplatform.model.astcache.wiki.Page; import com.crispico.flower.mp.model.codesync.CodeSyncElement; import com.crispico.flower.mp.model.codesync.CodeSyncPackage; import com.crispico.flower.mp.model.codesync.CodeSyncRoot; import com.crispico.flower.mp.codesync.wiki.IConfigurationProvider; import com.crispico.flower.mp.codesync.wiki.WikiPlugin; import com.crispico.flower.mp.codesync.wiki.WikiRegexConfiguration; import com.crispico.flower.mp.codesync.wiki.WikiTextBuilder; import com.crispico.flower.mp.codesync.wiki.WikiTreeBuilder; import static com.crispico.flower.mp.codesync.wiki.WikiRegexConfiguration.*; /** * @author Mariana */ public class DokuWikiConfigurationProvider implements IConfigurationProvider { @Override public void buildConfiguration(WikiRegexConfiguration config, CodeSyncElement cse) { config .add(new RegexWithAction.IfFindThisAnnounceMatchCandidate(WikiPlugin.HEADING_LEVEL_1_CATEGORY, getHeading(1), WikiPlugin.HEADING_LEVEL_1_CATEGORY)) .add(new RegexWithAction.IfFindThisAnnounceMatchCandidate(WikiPlugin.HEADING_LEVEL_2_CATEGORY, getHeading(2), WikiPlugin.HEADING_LEVEL_2_CATEGORY)) .add(new RegexWithAction.IfFindThisAnnounceMatchCandidate(WikiPlugin.HEADING_LEVEL_3_CATEGORY, getHeading(3), WikiPlugin.HEADING_LEVEL_3_CATEGORY)) .add(new RegexWithAction.IfFindThisAnnounceMatchCandidate(WikiPlugin.HEADING_LEVEL_4_CATEGORY, getHeading(4), WikiPlugin.HEADING_LEVEL_4_CATEGORY)) .add(new RegexWithAction.IfFindThisAnnounceMatchCandidate(WikiPlugin.HEADING_LEVEL_5_CATEGORY, getHeading(5), WikiPlugin.HEADING_LEVEL_5_CATEGORY)) .add(new RegexWithAction.IfFindThisAnnounceMatchCandidate(WikiPlugin.PARAGRAPH_CATEGORY, PARAGRAPH_REGEX, WikiPlugin.PARAGRAPH_CATEGORY)) .setUseUntilFoundThisIgnoreAll(false); } @Override public Class<? extends WikiTreeBuilder> getWikiTreeBuilderClass() { return WikiTreeBuilder.class; } @Override public WikiTextBuilder getWikiTextBuilder(CodeSyncElement cse) { return new WikiTextBuilder(); } // TODO test private String getHeading(int level) { String delim = String.format("={%s}", 7 - level); return String.format(MULTILINE_MATCH_FORMAT, delim + CAPTURE_ANY + delim); // return String.format("^(={%s}", 7 - level) // + ".*?" // + String.format("={%s,}", 2) // at least 2 times // + "\\s*?" // + ")$"; } /** * @param wiki list of {@link DokuWikiPage}s */ @Override public CodeSyncRoot getWikiTree(Object wiki) { List<DokuWikiPage> pages = (List<DokuWikiPage>) wiki; CodeSyncRoot root = CodeSyncPackage.eINSTANCE.getCodeSyncFactory().createCodeSyncRoot(); root.setName(DokuWikiPlugin.getInstance().getWikiName()); root.setType(WikiPlugin.FOLDER_CATEGORY); if (pages != null) { for (DokuWikiPage page : pages) { CodeSyncElement crtNode = root; String[] fragments = page.getId().split(":"); for (int i = 0; i < fragments.length; i++) { String fragment = fragments[i]; CodeSyncElement child = getChild(crtNode, fragment); if (child == null) { child = CodeSyncPackage.eINSTANCE.getCodeSyncFactory().createCodeSyncElement(); child.setName(fragment); child.setType(WikiPlugin.FOLDER_CATEGORY); if (i == fragments.length - 1) { child.setType(WikiPlugin.PAGE_CATEGORY); Page wikiPage = AstCacheWikiFactory.eINSTANCE.createPage(); wikiPage.setInitialContent(page.getContent()); wikiPage.setLineDelimiter(WikiPlugin.getInstance().getLineDelimiter(page.getContent())); child.setAstCacheElement(wikiPage); } crtNode.getChildren().add(child); } crtNode = child; } } } return root; } private CodeSyncElement getChild(CodeSyncElement parent, String name) { for (CodeSyncElement child : parent.getChildren()) { if (child.getName().equals(name)) { return child; } } return null; } @Override public void savePage(Page page) { DokuWikiPlugin.getInstance().savePage(page); } }
4,947
0.72832
0.722256
126
37.277779
36.379097
149
false
false
0
0
0
0
0
0
2.301587
false
false
10
9020bd4eca53c981786ced8072e4452aa73d7a8f
6,116,033,436,658
228f7364081a22f24eb43446036dba7e37f2cb1b
/src/com/android/ckstudent/CallBTActivity.java
6f5a4e050bd67c994debc6adfd8383f8e0e6fef2
[]
no_license
noellin/NCKUproject
https://github.com/noellin/NCKUproject
b56cd2ca355e2ac7f2589cc2b52e4a7480785ae3
cb6796811cf7eedc9ae082efbd370d9590bee062
refs/heads/master
2020-04-05T20:08:27.904000
2018-11-12T06:42:29
2018-11-12T06:42:29
157,165,880
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.android.ckstudent; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.AlertDialog; import android.app.ListActivity; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; /* * This activity is to let teacher use bluetooth to check students' presentation. */ public class CallBTActivity extends ListActivity { StudentAdapter adapter; String courseNo; String url; ArrayList<Student> students; ArrayList<Student> uploadStudents; ArrayList<BTDevice> bluetoothDevices; static BluetoothAdapter bluetoothAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setDisplayHomeAsUpEnabled(true); //Add intent filter to catch action. IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); //Regist bluetooth receiver. registerReceiver(mReceiver, filter); students = new ArrayList<Student>(); uploadStudents = new ArrayList<Student>(); bluetoothDevices = new ArrayList<BTDevice>(); //Get bundle passed from SelectListActivity. Bundle course = CallBTActivity.this.getIntent().getExtras(); courseNo = course.getString("courseNo"); url = course.getString("Url"); adapter = new StudentAdapter(this, students, courseNo); this.setListAdapter(adapter); getListView().setBackgroundResource(R.drawable.custombg); //Get bluetooth instance. bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //Check bluetooth is supported or not. if (!bluetoothAdapter.isEnabled()) { bluetoothAdapter.enable(); } //If discovery already start, cancel it. if (bluetoothAdapter.isDiscovering()) { bluetoothAdapter.cancelDiscovery(); } AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Notice"); builder.setMessage("點名開始,請保持藍牙開啟"); builder.setPositiveButton("我知道了", null); builder.show(); //Get student list. getStudentData.execute(); } //Set up a broadcastreceiver to listen to bluetooth signal. private final BroadcastReceiver mReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); BTDevice bluetoothDevice = new BTDevice(); bluetoothDevice.macAddress = device.getAddress(); //Check in bluetoothDevices duplicate or not. if (!checkDuplicate(bluetoothDevice.macAddress)) { //Add into bluetooth devices list. bluetoothDevices.add(bluetoothDevice); //Match to the student list. matchList(bluetoothDevice.macAddress); } } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(intent.getAction())) { bluetoothAdapter.startDiscovery(); } } }; //Get student list by using webapi. AsyncTask<Void, Void, Void> getStudentData = new AsyncTask<Void, Void, Void>() { ProgressDialog mDialog; @Override protected void onPreExecute() { super.onPreExecute(); //Create progress dialog. mDialog = new ProgressDialog(CallBTActivity.this); mDialog.setMessage("Loading..."); //mDialog.setCancelable(false); mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mDialog.show(); } @Override protected Void doInBackground(Void... arg0) { try { //Set connection parameters. HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 5000); HttpConnectionParams.setSoTimeout(httpParameters, 5000); //Construct http client and http get request objects. DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpRequest = new HttpGet(url + "StudentList?CourseNo=" + courseNo); //Send request to web server. HttpResponse httpResponse = httpClient.execute(httpRequest); //Process the response. if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity httpEntity = httpResponse.getEntity(); InputStream content = httpEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } //Convert into JSONArray. JSONArray jsonArray = new JSONArray(builder.toString()); //Convert JSON to student list. for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Student student = new Student(); student.no = jsonObject.getString("StudentNo"); students.add(student); } } httpRequest = new HttpGet(url + "StudentData"); //Send request to web server. httpResponse = httpClient.execute(httpRequest); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity httpEntity = httpResponse.getEntity(); InputStream content = httpEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } //Convert into JSONArray. JSONArray jsonArray = new JSONArray(builder.toString()); //Convert JSON to student list. for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Student student = new Student(); student.no = jsonObject.getString("StudentNo"); student.mac = jsonObject.getString("MacAddress"); for (int j=0; j<students.size(); j++) { if (student.no.equals(students.get(j).no)) { students.get(j).name = jsonObject.getString("Name"); students.get(j).mac = jsonObject.getString("MacAddress"); } } } } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); mDialog.dismiss(); setListAdapter(getListAdapter()); //Start bluetooth discovery. bluetoothAdapter.startDiscovery(); } }; //Upload the presentation result by WebApi. AsyncTask<Void, Void, Void> postStudentData = new AsyncTask<Void, Void, Void>() { ProgressDialog mDialog; @Override protected void onPreExecute() { super.onPreExecute(); //Create dialog. Consider using horizontal progress bar. mDialog = new ProgressDialog(CallBTActivity.this); mDialog.setMessage("Loading..."); //mDialog.setCancelable(false); mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mDialog.show(); } @Override protected Void doInBackground(Void... arg0) { try { //Set connection parameters. HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 5000); HttpConnectionParams.setSoTimeout(httpParameters, 5000); //Construct http client and http get request objects. DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpRequest = new HttpPost(url + "RollCall"); JSONArray jsonArray = new JSONArray(); try { //Convert the result list into JSON. for(int i = 0; i < uploadStudents.size(); i++) { JSONObject jsonObject = new JSONObject(); jsonObject.put("CourseNo", courseNo); jsonObject.put("StudentNo", uploadStudents.get(i).no.toString()); jsonObject.put("Date", uploadStudents.get(i).date.toString()); jsonArray.put(jsonObject); } } catch (JSONException e) { e.printStackTrace(); } StringEntity stringEntity = new StringEntity(jsonArray.toString(), HTTP.UTF_8); stringEntity.setContentType("application/json"); httpRequest.setHeader("Content-type", "application/json"); httpRequest.setHeader("Accept", "application/json"); httpRequest.setEntity(stringEntity); //Send request to web server. //HttpResponse httpResponse = httpClient.execute(httpRequest); httpClient.execute(httpRequest); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); mDialog.dismiss(); Toast.makeText(CallBTActivity.this, "上傳成功!", Toast.LENGTH_LONG).show(); //End the activity. finish(); } }; //Check duplicate or not. private boolean checkDuplicate(String macAddress) { for (int i=0; i<bluetoothDevices.size(); i++) { if (macAddress.equals(bluetoothDevices.get(i).macAddress)) { return true; } } return false; } //Match the receive device to student. private void matchList(String macAddress) { for (int i=0; i<students.size(); i++) { if (macAddress.equals(students.get(i).mac)) { students.get(i).status = true; Toast.makeText(this, "Received!", Toast.LENGTH_LONG).show(); this.setListAdapter(getListAdapter()); } } } //Choose only absent student ready to upload. private void createUploadList() { for (int i=0; i<students.size(); i++) { if (students.get(i).status == false) { uploadStudents.add(students.get(i)); } } } private DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Close bluetooth discovery and prepare list to upload. bluetoothAdapter.cancelDiscovery(); createUploadList(); postStudentData.execute(); } }; @Override protected void onPause() { super.onPause(); bluetoothAdapter.cancelDiscovery(); unregisterReceiver(mReceiver); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.callbt, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { //Click the upload button on action bar. case R.id.uploadend: //Show alert to ensure. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Notice"); builder.setMessage("確定上傳嗎?該節課一天僅能上傳一次!"); builder.setPositiveButton("上傳", listener); builder.setNegativeButton("取消", null); builder.show(); break; case R.id.status: //check bluetooth discovery status. if (bluetoothAdapter.isDiscovering()) { Toast.makeText(CallBTActivity.this, "點名中..", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(CallBTActivity.this, "已停止..", Toast.LENGTH_SHORT).show(); } break; case android.R.id.home: onBackPressed(); break; } return true; } }
BIG5
Java
12,089
java
CallBTActivity.java
Java
[]
null
[]
package com.android.ckstudent; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.AlertDialog; import android.app.ListActivity; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; /* * This activity is to let teacher use bluetooth to check students' presentation. */ public class CallBTActivity extends ListActivity { StudentAdapter adapter; String courseNo; String url; ArrayList<Student> students; ArrayList<Student> uploadStudents; ArrayList<BTDevice> bluetoothDevices; static BluetoothAdapter bluetoothAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setDisplayHomeAsUpEnabled(true); //Add intent filter to catch action. IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); //Regist bluetooth receiver. registerReceiver(mReceiver, filter); students = new ArrayList<Student>(); uploadStudents = new ArrayList<Student>(); bluetoothDevices = new ArrayList<BTDevice>(); //Get bundle passed from SelectListActivity. Bundle course = CallBTActivity.this.getIntent().getExtras(); courseNo = course.getString("courseNo"); url = course.getString("Url"); adapter = new StudentAdapter(this, students, courseNo); this.setListAdapter(adapter); getListView().setBackgroundResource(R.drawable.custombg); //Get bluetooth instance. bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //Check bluetooth is supported or not. if (!bluetoothAdapter.isEnabled()) { bluetoothAdapter.enable(); } //If discovery already start, cancel it. if (bluetoothAdapter.isDiscovering()) { bluetoothAdapter.cancelDiscovery(); } AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Notice"); builder.setMessage("點名開始,請保持藍牙開啟"); builder.setPositiveButton("我知道了", null); builder.show(); //Get student list. getStudentData.execute(); } //Set up a broadcastreceiver to listen to bluetooth signal. private final BroadcastReceiver mReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); BTDevice bluetoothDevice = new BTDevice(); bluetoothDevice.macAddress = device.getAddress(); //Check in bluetoothDevices duplicate or not. if (!checkDuplicate(bluetoothDevice.macAddress)) { //Add into bluetooth devices list. bluetoothDevices.add(bluetoothDevice); //Match to the student list. matchList(bluetoothDevice.macAddress); } } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(intent.getAction())) { bluetoothAdapter.startDiscovery(); } } }; //Get student list by using webapi. AsyncTask<Void, Void, Void> getStudentData = new AsyncTask<Void, Void, Void>() { ProgressDialog mDialog; @Override protected void onPreExecute() { super.onPreExecute(); //Create progress dialog. mDialog = new ProgressDialog(CallBTActivity.this); mDialog.setMessage("Loading..."); //mDialog.setCancelable(false); mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mDialog.show(); } @Override protected Void doInBackground(Void... arg0) { try { //Set connection parameters. HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 5000); HttpConnectionParams.setSoTimeout(httpParameters, 5000); //Construct http client and http get request objects. DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpRequest = new HttpGet(url + "StudentList?CourseNo=" + courseNo); //Send request to web server. HttpResponse httpResponse = httpClient.execute(httpRequest); //Process the response. if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity httpEntity = httpResponse.getEntity(); InputStream content = httpEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } //Convert into JSONArray. JSONArray jsonArray = new JSONArray(builder.toString()); //Convert JSON to student list. for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Student student = new Student(); student.no = jsonObject.getString("StudentNo"); students.add(student); } } httpRequest = new HttpGet(url + "StudentData"); //Send request to web server. httpResponse = httpClient.execute(httpRequest); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity httpEntity = httpResponse.getEntity(); InputStream content = httpEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } //Convert into JSONArray. JSONArray jsonArray = new JSONArray(builder.toString()); //Convert JSON to student list. for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Student student = new Student(); student.no = jsonObject.getString("StudentNo"); student.mac = jsonObject.getString("MacAddress"); for (int j=0; j<students.size(); j++) { if (student.no.equals(students.get(j).no)) { students.get(j).name = jsonObject.getString("Name"); students.get(j).mac = jsonObject.getString("MacAddress"); } } } } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); mDialog.dismiss(); setListAdapter(getListAdapter()); //Start bluetooth discovery. bluetoothAdapter.startDiscovery(); } }; //Upload the presentation result by WebApi. AsyncTask<Void, Void, Void> postStudentData = new AsyncTask<Void, Void, Void>() { ProgressDialog mDialog; @Override protected void onPreExecute() { super.onPreExecute(); //Create dialog. Consider using horizontal progress bar. mDialog = new ProgressDialog(CallBTActivity.this); mDialog.setMessage("Loading..."); //mDialog.setCancelable(false); mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mDialog.show(); } @Override protected Void doInBackground(Void... arg0) { try { //Set connection parameters. HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 5000); HttpConnectionParams.setSoTimeout(httpParameters, 5000); //Construct http client and http get request objects. DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpRequest = new HttpPost(url + "RollCall"); JSONArray jsonArray = new JSONArray(); try { //Convert the result list into JSON. for(int i = 0; i < uploadStudents.size(); i++) { JSONObject jsonObject = new JSONObject(); jsonObject.put("CourseNo", courseNo); jsonObject.put("StudentNo", uploadStudents.get(i).no.toString()); jsonObject.put("Date", uploadStudents.get(i).date.toString()); jsonArray.put(jsonObject); } } catch (JSONException e) { e.printStackTrace(); } StringEntity stringEntity = new StringEntity(jsonArray.toString(), HTTP.UTF_8); stringEntity.setContentType("application/json"); httpRequest.setHeader("Content-type", "application/json"); httpRequest.setHeader("Accept", "application/json"); httpRequest.setEntity(stringEntity); //Send request to web server. //HttpResponse httpResponse = httpClient.execute(httpRequest); httpClient.execute(httpRequest); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); mDialog.dismiss(); Toast.makeText(CallBTActivity.this, "上傳成功!", Toast.LENGTH_LONG).show(); //End the activity. finish(); } }; //Check duplicate or not. private boolean checkDuplicate(String macAddress) { for (int i=0; i<bluetoothDevices.size(); i++) { if (macAddress.equals(bluetoothDevices.get(i).macAddress)) { return true; } } return false; } //Match the receive device to student. private void matchList(String macAddress) { for (int i=0; i<students.size(); i++) { if (macAddress.equals(students.get(i).mac)) { students.get(i).status = true; Toast.makeText(this, "Received!", Toast.LENGTH_LONG).show(); this.setListAdapter(getListAdapter()); } } } //Choose only absent student ready to upload. private void createUploadList() { for (int i=0; i<students.size(); i++) { if (students.get(i).status == false) { uploadStudents.add(students.get(i)); } } } private DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Close bluetooth discovery and prepare list to upload. bluetoothAdapter.cancelDiscovery(); createUploadList(); postStudentData.execute(); } }; @Override protected void onPause() { super.onPause(); bluetoothAdapter.cancelDiscovery(); unregisterReceiver(mReceiver); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.callbt, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { //Click the upload button on action bar. case R.id.uploadend: //Show alert to ensure. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Notice"); builder.setMessage("確定上傳嗎?該節課一天僅能上傳一次!"); builder.setPositiveButton("上傳", listener); builder.setNegativeButton("取消", null); builder.show(); break; case R.id.status: //check bluetooth discovery status. if (bluetoothAdapter.isDiscovering()) { Toast.makeText(CallBTActivity.this, "點名中..", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(CallBTActivity.this, "已停止..", Toast.LENGTH_SHORT).show(); } break; case android.R.id.home: onBackPressed(); break; } return true; } }
12,089
0.707677
0.70551
341
34.18475
21.599483
91
false
false
0
0
0
0
0
0
3.105572
false
false
10
0019a4faf2a47533a9307d996f88285e14d240fa
33,371,895,894,881
189241fd16a91d58f04432a32dbde91bdba410fd
/IbanValidation.java
851b641e64fb8cc2d871a11ccbfedbf865fab02c
[]
no_license
rysieko2/RegexValidation
https://github.com/rysieko2/RegexValidation
dfe613d23151672fa4e4710becf7fadbede48e28
af3a2003f831c5b7b80d96140a8003efd98f335b
refs/heads/master
2022-11-05T15:10:24.632000
2020-06-20T21:58:43
2020-06-20T21:58:43
273,749,082
0
0
null
false
2020-06-20T21:58:44
2020-06-20T16:57:19
2020-06-20T17:22:55
2020-06-20T21:58:43
1
0
0
0
Java
false
false
package lab2_03_regex; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class IbanValidation { public static void main(String[] args) { checkIban(); } private static void checkIban() { String iban_number; Scanner scanner = new Scanner(System.in); System.out.print("Enter nr IBAN: "); iban_number = scanner.nextLine(); String iban_regex = "^((NO)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{3}|(NO)[0-9A-Z]{13}|" + "(BE)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}|(BE)[0-9A-Z]{14}|" + "(DK|FO|FI|GL|NL)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{2}|" + "(DK|FO|FI|GL|NL)[0-9A-Z]{16}|(MK|SI)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{3}|" + "(MK|SI)[0-9A-Z]{17}|(BA|EE|KZ|LT|LU|AT)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}|" + "(BA|EE|KZ|LT|LU|AT)[0-9A-Z]{18}|(HR|LI|LV|CH)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{1}|" + "(HR|LI|LV|CH)[0-9A-Z]{19}|(BG|DE|IE|ME|RS|GB)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{2}|" + "(BG|DE|IE|ME|RS|GB)[0-9A-Z]{20}|(GI|IL)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{3}|" + "(GI|IL)[0-9A-Z]{21}|(AD|CZ|SA|RO|SK|ES|SE|TN)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}|" + "(AD|CZ|SA|RO|SK|ES|SE|TN)[0-9A-Z]{22}|(PT)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{1}|" + "(PT)[0-9A-Z]{23}|(IS|TR)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{2}|(IS|TR)[0-9A-Z]{24}|" + "(FR|GR|IT|MC|SM)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{3}|(FR|GR|IT|MC|SM)[0-9A-Z]{25}|" + "(AL|CY|HU|LB|PL)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}|(AL|CY|HU|LB|PL)[0-9A-Z]{26}|" + "(MU)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{2}|(MU)[0-9A-Z]{28}|" + "(MT)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{3}|(MT)[0-9A-Z]{29})$"; Pattern pattern = Pattern.compile(iban_regex); Matcher matcher = pattern.matcher(iban_number); if (matcher.matches()) { System.out.println("Account nr: " + iban_number + " is true"); } else { System.out.println("Account nr: " + iban_number + " is false"); } } }
UTF-8
Java
2,853
java
IbanValidation.java
Java
[]
null
[]
package lab2_03_regex; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class IbanValidation { public static void main(String[] args) { checkIban(); } private static void checkIban() { String iban_number; Scanner scanner = new Scanner(System.in); System.out.print("Enter nr IBAN: "); iban_number = scanner.nextLine(); String iban_regex = "^((NO)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{3}|(NO)[0-9A-Z]{13}|" + "(BE)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}|(BE)[0-9A-Z]{14}|" + "(DK|FO|FI|GL|NL)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{2}|" + "(DK|FO|FI|GL|NL)[0-9A-Z]{16}|(MK|SI)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{3}|" + "(MK|SI)[0-9A-Z]{17}|(BA|EE|KZ|LT|LU|AT)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}|" + "(BA|EE|KZ|LT|LU|AT)[0-9A-Z]{18}|(HR|LI|LV|CH)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{1}|" + "(HR|LI|LV|CH)[0-9A-Z]{19}|(BG|DE|IE|ME|RS|GB)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{2}|" + "(BG|DE|IE|ME|RS|GB)[0-9A-Z]{20}|(GI|IL)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{3}|" + "(GI|IL)[0-9A-Z]{21}|(AD|CZ|SA|RO|SK|ES|SE|TN)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}|" + "(AD|CZ|SA|RO|SK|ES|SE|TN)[0-9A-Z]{22}|(PT)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{1}|" + "(PT)[0-9A-Z]{23}|(IS|TR)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{2}|(IS|TR)[0-9A-Z]{24}|" + "(FR|GR|IT|MC|SM)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{3}|(FR|GR|IT|MC|SM)[0-9A-Z]{25}|" + "(AL|CY|HU|LB|PL)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}|(AL|CY|HU|LB|PL)[0-9A-Z]{26}|" + "(MU)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{2}|(MU)[0-9A-Z]{28}|" + "(MT)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{3}|(MT)[0-9A-Z]{29})$"; Pattern pattern = Pattern.compile(iban_regex); Matcher matcher = pattern.matcher(iban_number); if (matcher.matches()) { System.out.println("Account nr: " + iban_number + " is true"); } else { System.out.println("Account nr: " + iban_number + " is false"); } } }
2,853
0.426569
0.308798
44
63.840908
58.268948
161
false
false
0
0
0
0
0
0
2.568182
false
false
10
43ca3f6f670ba66f7979cd5aae6051ffd738d60d
2,138,893,714,670
3a010a701082a10bf9cd9f37b49d331f3a9f8ca4
/module18/src/main/java/org/zoltor/dao/ProjectDao.java
7e31f02d97097be1d55503ff08cd1b9ca19557f0
[]
no_license
niberius/jmp2016
https://github.com/niberius/jmp2016
9dc34ce056469207411ae58dde65864c71a10bc0
1817fb88bebe13fb983211ff88451992c188e3b5
refs/heads/master
2020-05-21T16:42:43.732000
2016-11-20T18:28:28
2016-11-20T18:28:28
62,722,665
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.zoltor.dao; import org.zoltor.db.entities.Project; /** * Created by Pavel Ordenko on 14/11/2016, 23:01. */ public interface ProjectDao extends GenericDao<Project> { }
UTF-8
Java
183
java
ProjectDao.java
Java
[ { "context": "org.zoltor.db.entities.Project;\n\n/**\n * Created by Pavel Ordenko on 14/11/2016, 23:01.\n */\npublic interface Projec", "end": 96, "score": 0.9998494386672974, "start": 83, "tag": "NAME", "value": "Pavel Ordenko" } ]
null
[]
package org.zoltor.dao; import org.zoltor.db.entities.Project; /** * Created by <NAME> on 14/11/2016, 23:01. */ public interface ProjectDao extends GenericDao<Project> { }
176
0.737705
0.672131
9
19.333334
21.802141
57
false
false
0
0
0
0
0
0
0.333333
false
false
10
91fb59de82d6b7117ce0b8e3c418691f48989c28
5,875,515,319,455
f1a9b228188f685ece5aaf0b872a7174fda5d90a
/src/com/maycontainsoftware/partition/MainScreen.java
7bc294d8a9b3d70343e8356f29afb39e3cec01ae
[]
no_license
cfmdobbie/Partition
https://github.com/cfmdobbie/Partition
08caf700450853f2fd827b09dabc94e9d413e024
c0d3a4e187ea3904bc1c61b92a62fb19f07ba0bf
refs/heads/master
2021-01-17T14:31:33.944000
2015-05-18T18:43:56
2015-05-18T18:44:24
27,093,637
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.maycontainsoftware.partition; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.utils.TiledDrawable; import com.maycontainsoftware.general.CScreen; /** * The main screen of the application. * * @author Charlie */ public class MainScreen extends CScreen<PartitionGame> { /** Tag for logging purposes. */ private static final String LOG = MainScreen.class.getName(); /** The card stack. */ final CardStack cardStack; /** * Construct a new MainScreen. * * @param game * The PartitionGame instance. */ public MainScreen(final PartitionGame game) { super(game); Gdx.app.debug(LOG, "MainScreen.<init>"); final TextureAtlas atlas = game.manager.get("atlas.atlas", TextureAtlas.class); // Static textures background root.setBackground(new TiledDrawable(atlas.findRegion("background"))); // UI spacing final float pad = 10.0f; final float topBarButtonSize = 40.0f; // Sound toggle button final Actor soundToggle = new SoundToggleButton(game, atlas); soundToggle.setX(game.virtualWidth - pad - topBarButtonSize); soundToggle.setY(game.virtualHeight - pad - topBarButtonSize); root.addActor(soundToggle); // Back button final BackButton back = new BackButton(game, atlas); back.setX(pad); back.setY(game.virtualHeight - pad - topBarButtonSize); root.addActor(back); // When the back button is pressed, go back one card in the stack back.addListener(new InputListener() { @Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { doBack(); return true; } }); // Inscribed line separating top menu buttons from main content final Image inscribed = new Image(atlas.findRegion("line")); // Fill width inscribed.setWidth(game.virtualWidth); // Graphic is 4px high inscribed.setHeight(4.0f); // 50% transparency inscribed.setColor(1.0f, 1.0f, 1.0f, 0.5f); // Position is below padding, menu buttons, and another padding inscribed.setY(game.virtualHeight - pad - topBarButtonSize - pad - inscribed.getHeight()); root.addActor(inscribed); // Area with interchangeable panels containing the actual screen content // Create the card stack cardStack = new CardStack(); // Set the back button to listen for stack changed events cardStack.addListener(back); // Set card stack size // Width is screen width final float panelAreaWidth = game.virtualWidth; // Height is screen height less height of sound toggle button, inscribed line and three bits of padding final float panelAreaHeight = game.virtualHeight - topBarButtonSize - inscribed.getHeight() - pad * 3; cardStack.setSize(panelAreaWidth, panelAreaHeight); // Add it to the root table root.addActor(cardStack); // Now the card stack is set up, set the initial card cardStack.setInitialCard(new MainPanel(game, cardStack)); } @Override protected boolean handleBack() { // Need to manually handle the back button on this screen. return true; } @Override protected void doBack() { if (cardStack.stackSize() <= 1) { Gdx.app.exit(); } else { cardStack.pop(); } } }
UTF-8
Java
3,401
java
MainScreen.java
Java
[ { "context": "The main screen of the application.\n * \n * @author Charlie\n */\npublic class MainScreen extends CScreen<Parti", "end": 496, "score": 0.9997091889381409, "start": 489, "tag": "NAME", "value": "Charlie" } ]
null
[]
package com.maycontainsoftware.partition; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.utils.TiledDrawable; import com.maycontainsoftware.general.CScreen; /** * The main screen of the application. * * @author Charlie */ public class MainScreen extends CScreen<PartitionGame> { /** Tag for logging purposes. */ private static final String LOG = MainScreen.class.getName(); /** The card stack. */ final CardStack cardStack; /** * Construct a new MainScreen. * * @param game * The PartitionGame instance. */ public MainScreen(final PartitionGame game) { super(game); Gdx.app.debug(LOG, "MainScreen.<init>"); final TextureAtlas atlas = game.manager.get("atlas.atlas", TextureAtlas.class); // Static textures background root.setBackground(new TiledDrawable(atlas.findRegion("background"))); // UI spacing final float pad = 10.0f; final float topBarButtonSize = 40.0f; // Sound toggle button final Actor soundToggle = new SoundToggleButton(game, atlas); soundToggle.setX(game.virtualWidth - pad - topBarButtonSize); soundToggle.setY(game.virtualHeight - pad - topBarButtonSize); root.addActor(soundToggle); // Back button final BackButton back = new BackButton(game, atlas); back.setX(pad); back.setY(game.virtualHeight - pad - topBarButtonSize); root.addActor(back); // When the back button is pressed, go back one card in the stack back.addListener(new InputListener() { @Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { doBack(); return true; } }); // Inscribed line separating top menu buttons from main content final Image inscribed = new Image(atlas.findRegion("line")); // Fill width inscribed.setWidth(game.virtualWidth); // Graphic is 4px high inscribed.setHeight(4.0f); // 50% transparency inscribed.setColor(1.0f, 1.0f, 1.0f, 0.5f); // Position is below padding, menu buttons, and another padding inscribed.setY(game.virtualHeight - pad - topBarButtonSize - pad - inscribed.getHeight()); root.addActor(inscribed); // Area with interchangeable panels containing the actual screen content // Create the card stack cardStack = new CardStack(); // Set the back button to listen for stack changed events cardStack.addListener(back); // Set card stack size // Width is screen width final float panelAreaWidth = game.virtualWidth; // Height is screen height less height of sound toggle button, inscribed line and three bits of padding final float panelAreaHeight = game.virtualHeight - topBarButtonSize - inscribed.getHeight() - pad * 3; cardStack.setSize(panelAreaWidth, panelAreaHeight); // Add it to the root table root.addActor(cardStack); // Now the card stack is set up, set the initial card cardStack.setInitialCard(new MainPanel(game, cardStack)); } @Override protected boolean handleBack() { // Need to manually handle the back button on this screen. return true; } @Override protected void doBack() { if (cardStack.stackSize() <= 1) { Gdx.app.exit(); } else { cardStack.pop(); } } }
3,401
0.728021
0.720082
114
28.833334
25.978371
105
false
false
0
0
0
0
0
0
1.815789
false
false
10
538e313beb8af57b172a882b899ec7fd86184d13
1,872,605,756,918
1945035ae091b6c8033e267695581a679ed449cc
/frontend/book-app-428/app/src/main/java/com/cs428/app/bookapp/model/Person.java
bb63301172e0255d7411ee1ca968865c76e86f2a
[]
no_license
lily514/book-app-428
https://github.com/lily514/book-app-428
792793ab134c1d4cce521df1a070d783b9b1af89
a899c459cc3661d3b3cdcc2f8fd776fe15af1b43
refs/heads/master
2021-05-09T19:21:41.787000
2018-05-23T16:40:30
2018-05-23T16:40:30
118,638,967
1
0
null
false
2018-04-07T22:05:33
2018-01-23T16:43:01
2018-03-23T17:10:55
2018-04-07T22:05:32
402
0
0
0
Java
false
null
package com.cs428.app.bookapp.model; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import com.amazonaws.auth.policy.Resource; import com.cs428.app.bookapp.R; import com.cs428.app.bookapp.interfaces.OnBitmapComplete; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; /** * Created by chees on 3/8/2018. */ public class Person { protected String name; protected String id; protected List<String> readingList = null; protected List<String> reviewedBooks = null; protected boolean isUser = false; protected String photoURL; protected Bitmap photoBitmap; protected String bio; public Person(){ } public Person(String name, String id) { this.name = name; this.id = id; this.photoBitmap = null; this.photoURL = null; } public boolean isUser() { return isUser; } public String getName() { return name; } public String getId() { return id; } public List<String> getReadingList() { return readingList; } public List<String> getReviewedBooks() { return reviewedBooks; } public void setReadingList(List<String> readingList) { this.readingList = readingList; } public void setReviewedBooks(List<String> reviewedBooks) { this.reviewedBooks = reviewedBooks; } public void setURL(String URL) { this.photoURL = URL; } public Bitmap getCover(OnBitmapComplete listener) { // may return null if there is exception when fetching from given URL if (photoBitmap == null) { if (photoURL != null){ Person.FetchCoverFromURL fetchCoverFromURL = new Person.FetchCoverFromURL(listener); fetchCoverFromURL.execute(photoURL); } return BitmapFactory.decodeResource(Resources.getSystem(), R.drawable.profile_pic_frame); } return photoBitmap; } public void setBio(String bio) { this.bio = bio; } public String getBio() { return bio; } public class FetchCoverFromURL extends AsyncTask<String, Void, Bitmap> { OnBitmapComplete listener; public FetchCoverFromURL(OnBitmapComplete listener){ this.listener = listener; } protected Bitmap doInBackground(String... strings) { try { URL url = new URL(strings[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap cover = BitmapFactory.decodeStream(input); return cover; } catch (IOException e) { return BitmapFactory.decodeResource(Resources.getSystem(), R.drawable.profile_pic_frame); // if exception occurs, return a null bitmap } } protected void onPostExecute(Bitmap cover) { photoBitmap = cover; listener.updateImages(); } } }
UTF-8
Java
3,298
java
Person.java
Java
[ { "context": "net.URL;\nimport java.util.List;\n\n/**\n * Created by chees on 3/8/2018.\n */\n\npublic class Person {\n prote", "end": 470, "score": 0.9808270931243896, "start": 465, "tag": "USERNAME", "value": "chees" } ]
null
[]
package com.cs428.app.bookapp.model; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import com.amazonaws.auth.policy.Resource; import com.cs428.app.bookapp.R; import com.cs428.app.bookapp.interfaces.OnBitmapComplete; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; /** * Created by chees on 3/8/2018. */ public class Person { protected String name; protected String id; protected List<String> readingList = null; protected List<String> reviewedBooks = null; protected boolean isUser = false; protected String photoURL; protected Bitmap photoBitmap; protected String bio; public Person(){ } public Person(String name, String id) { this.name = name; this.id = id; this.photoBitmap = null; this.photoURL = null; } public boolean isUser() { return isUser; } public String getName() { return name; } public String getId() { return id; } public List<String> getReadingList() { return readingList; } public List<String> getReviewedBooks() { return reviewedBooks; } public void setReadingList(List<String> readingList) { this.readingList = readingList; } public void setReviewedBooks(List<String> reviewedBooks) { this.reviewedBooks = reviewedBooks; } public void setURL(String URL) { this.photoURL = URL; } public Bitmap getCover(OnBitmapComplete listener) { // may return null if there is exception when fetching from given URL if (photoBitmap == null) { if (photoURL != null){ Person.FetchCoverFromURL fetchCoverFromURL = new Person.FetchCoverFromURL(listener); fetchCoverFromURL.execute(photoURL); } return BitmapFactory.decodeResource(Resources.getSystem(), R.drawable.profile_pic_frame); } return photoBitmap; } public void setBio(String bio) { this.bio = bio; } public String getBio() { return bio; } public class FetchCoverFromURL extends AsyncTask<String, Void, Bitmap> { OnBitmapComplete listener; public FetchCoverFromURL(OnBitmapComplete listener){ this.listener = listener; } protected Bitmap doInBackground(String... strings) { try { URL url = new URL(strings[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap cover = BitmapFactory.decodeStream(input); return cover; } catch (IOException e) { return BitmapFactory.decodeResource(Resources.getSystem(), R.drawable.profile_pic_frame); // if exception occurs, return a null bitmap } } protected void onPostExecute(Bitmap cover) { photoBitmap = cover; listener.updateImages(); } } }
3,298
0.629472
0.624621
119
26.714285
23.674311
102
false
false
0
0
0
0
0
0
0.478992
false
false
10
23e574c633c7ed5c24d6fe34d894e322ea2cfaef
2,705,829,415,965
73b850fad5f977483f05636912dfe5f661963450
/adad/src/main/java/com/dhcc/entity/SiteExcessHandleInfo.java
fb1054fe08e522ed0cf011b56041774c061d666e
[]
no_license
xuedie12369/data-transition
https://github.com/xuedie12369/data-transition
0712fe8b0b8a616d38069e198f36b8372ec5b09b
a7adf0075f24f58857a7553cb18fa200e282f3a8
refs/heads/master
2023-08-11T05:18:21.377000
2021-01-27T09:20:20
2021-01-27T09:20:20
241,546,935
0
1
null
false
2023-07-23T06:07:39
2020-02-19T06:12:45
2021-01-27T09:20:44
2023-07-23T06:07:38
961
0
1
4
Java
false
false
package com.dhcc.entity; import java.util.Date; import java.io.Serializable; /** * (SiteExcessHandleInfo)实体类 * * @author makejava * @since 2020-07-23 14:32:39 */ public class SiteExcessHandleInfo implements Serializable { private static final long serialVersionUID = 786316148918218847L; private Long id; /** * 创建时间 */ private Date gmtCreate; /** * 修改时间 */ private Date gmtModified; /** * 处理状态 */ private Integer status; /** * 处理时间 */ private Date collectTime; /** * 是否属实(1代表属实,-1代表不属实) */ private Integer isTrue; /** * 处罚类型 */ private String punishType; /** * 处罚内容 */ private String punishContent; /** * 处理照片 */ private String handleImage; /** * 超标原因 */ private String excessReason; /** * 备注 */ private String remark; /** * 处理用户(user表的username) */ private String username; /** * site_excess_census_infod 表的主键ID */ private Long siteExcessCensusId; private String backup1; private String backup2; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getCollectTime() { return collectTime; } public void setCollectTime(Date collectTime) { this.collectTime = collectTime; } public Integer getIsTrue() { return isTrue; } public void setIsTrue(Integer isTrue) { this.isTrue = isTrue; } public String getPunishType() { return punishType; } public void setPunishType(String punishType) { this.punishType = punishType; } public String getPunishContent() { return punishContent; } public void setPunishContent(String punishContent) { this.punishContent = punishContent; } public String getHandleImage() { return handleImage; } public void setHandleImage(String handleImage) { this.handleImage = handleImage; } public String getExcessReason() { return excessReason; } public void setExcessReason(String excessReason) { this.excessReason = excessReason; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Long getSiteExcessCensusId() { return siteExcessCensusId; } public void setSiteExcessCensusId(Long siteExcessCensusId) { this.siteExcessCensusId = siteExcessCensusId; } public String getBackup1() { return backup1; } public void setBackup1(String backup1) { this.backup1 = backup1; } public String getBackup2() { return backup2; } public void setBackup2(String backup2) { this.backup2 = backup2; } }
UTF-8
Java
3,655
java
SiteExcessHandleInfo.java
Java
[ { "context": "e;\n\n/**\n * (SiteExcessHandleInfo)实体类\n *\n * @author makejava\n * @since 2020-07-23 14:32:39\n */\npublic class Si", "end": 134, "score": 0.9993422031402588, "start": 126, "tag": "USERNAME", "value": "makejava" }, { "context": "\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String userna", "end": 2921, "score": 0.9600924849510193, "start": 2913, "tag": "USERNAME", "value": "username" }, { "context": "sername(String username) {\n this.username = username;\n }\n\n public Long getSiteExcessCensusId() {", "end": 3009, "score": 0.9798781275749207, "start": 3001, "tag": "USERNAME", "value": "username" } ]
null
[]
package com.dhcc.entity; import java.util.Date; import java.io.Serializable; /** * (SiteExcessHandleInfo)实体类 * * @author makejava * @since 2020-07-23 14:32:39 */ public class SiteExcessHandleInfo implements Serializable { private static final long serialVersionUID = 786316148918218847L; private Long id; /** * 创建时间 */ private Date gmtCreate; /** * 修改时间 */ private Date gmtModified; /** * 处理状态 */ private Integer status; /** * 处理时间 */ private Date collectTime; /** * 是否属实(1代表属实,-1代表不属实) */ private Integer isTrue; /** * 处罚类型 */ private String punishType; /** * 处罚内容 */ private String punishContent; /** * 处理照片 */ private String handleImage; /** * 超标原因 */ private String excessReason; /** * 备注 */ private String remark; /** * 处理用户(user表的username) */ private String username; /** * site_excess_census_infod 表的主键ID */ private Long siteExcessCensusId; private String backup1; private String backup2; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getCollectTime() { return collectTime; } public void setCollectTime(Date collectTime) { this.collectTime = collectTime; } public Integer getIsTrue() { return isTrue; } public void setIsTrue(Integer isTrue) { this.isTrue = isTrue; } public String getPunishType() { return punishType; } public void setPunishType(String punishType) { this.punishType = punishType; } public String getPunishContent() { return punishContent; } public void setPunishContent(String punishContent) { this.punishContent = punishContent; } public String getHandleImage() { return handleImage; } public void setHandleImage(String handleImage) { this.handleImage = handleImage; } public String getExcessReason() { return excessReason; } public void setExcessReason(String excessReason) { this.excessReason = excessReason; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Long getSiteExcessCensusId() { return siteExcessCensusId; } public void setSiteExcessCensusId(Long siteExcessCensusId) { this.siteExcessCensusId = siteExcessCensusId; } public String getBackup1() { return backup1; } public void setBackup1(String backup1) { this.backup1 = backup1; } public String getBackup2() { return backup2; } public void setBackup2(String backup2) { this.backup2 = backup2; } }
3,655
0.599149
0.585532
190
17.557896
16.62985
69
false
false
0
0
0
0
0
0
0.257895
false
false
10
a0fae80f684f7dca86d1ef73e1e21f8798ae6bc6
17,755,394,820,440
5ca3901b424539c2cf0d3dda52d8d7ba2ed91773
/src_procyon/y/e/i.java
56f4bdae15149cf09a6a3b9b9518bd29e4513ec9
[]
no_license
fjh658/bindiff
https://github.com/fjh658/bindiff
c98c9c24b0d904be852182ecbf4f81926ce67fb4
2a31859b4638404cdc915d7ed6be19937d762743
refs/heads/master
2021-01-20T06:43:12.134000
2016-06-29T17:09:03
2016-06-29T17:09:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package y.e; import y.h.*; import java.io.*; public interface i { void a(final bu p0, final Object p1, final ObjectOutputStream p2); }
UTF-8
Java
141
java
i.java
Java
[]
null
[]
package y.e; import y.h.*; import java.io.*; public interface i { void a(final bu p0, final Object p1, final ObjectOutputStream p2); }
141
0.687943
0.666667
9
14.666667
20.7953
70
false
false
0
0
0
0
0
0
0.666667
false
false
10
f246becc95f7efd606d1c9f71e94c0569971c6bb
12,369,505,816,579
807dabdf7b43b2315fa0e71cadb72c38300bb883
/src/main/java/com/service/RoleService.java
5d1da6265ed101a003f0f343d01727765e237f3f
[]
no_license
Hazrian/ProjetBackEnd
https://github.com/Hazrian/ProjetBackEnd
995b23c346fe84c005f11d40103e32604a4683b6
63c55bc2bfdc29f33494ab3219de3be94700ba44
refs/heads/master
2023-01-23T20:13:29.371000
2020-11-16T16:37:05
2020-11-16T16:37:05
313,345,704
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.service; import java.util.List; import com.entity.Role; public interface RoleService { public Role saveOrUpdateRole(Role pRole); public void deleteRole(Long pId); public Role findRoleById(Long pId); public List<Role> findRoles(); }
UTF-8
Java
253
java
RoleService.java
Java
[]
null
[]
package com.service; import java.util.List; import com.entity.Role; public interface RoleService { public Role saveOrUpdateRole(Role pRole); public void deleteRole(Long pId); public Role findRoleById(Long pId); public List<Role> findRoles(); }
253
0.766798
0.766798
14
17.071428
15.6089
42
false
false
0
0
0
0
0
0
0.785714
false
false
10
e4fc598e0beddaa30c056ef653947b9f4fd7c182
21,423,296,895,487
259dbaf8cde68d2339fb23c1215edd725ba27743
/app/src/main/java/net/damroo/androidprototype/events/DisplayOrderEvent.java
8375785b651cd471963497a01a8f18d660248300
[]
no_license
pshingala/android-prototype
https://github.com/pshingala/android-prototype
4730410cf7a999579265b3ebf8c5fe076d09c351
ce663eac8433e1a7f78d59397db4fbfd728316eb
refs/heads/master
2021-04-29T00:14:29.073000
2017-01-04T02:19:18
2017-01-04T02:19:18
77,712,743
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.damroo.androidprototype.events; /** * Created by damroo on 4/30/2016. */ public class DisplayOrderEvent { public DisplayEventType type; public DisplayOrderEvent(DisplayEventType type) { this.type = type; } }
UTF-8
Java
244
java
DisplayOrderEvent.java
Java
[ { "context": "damroo.androidprototype.events;\n\n/**\n * Created by damroo on 4/30/2016.\n */\npublic class DisplayOrderEvent ", "end": 69, "score": 0.9996633529663086, "start": 63, "tag": "USERNAME", "value": "damroo" } ]
null
[]
package net.damroo.androidprototype.events; /** * Created by damroo on 4/30/2016. */ public class DisplayOrderEvent { public DisplayEventType type; public DisplayOrderEvent(DisplayEventType type) { this.type = type; } }
244
0.70082
0.672131
12
19.333334
18.508257
53
false
false
0
0
0
0
0
0
0.25
false
false
10
eca93f7cdeaeb712bd034c930b0014742f98c403
14,010,183,324,637
9bcb6793622df58c6565e31f240a040cec7e3afc
/user-manage/src/main/java/com/cxtx/user_manage/web/rest/OaResource.java
fa448d8f6c65383732e36311f804ea93d070a5bc
[]
no_license
xeon-ye/cxtx_springCloud
https://github.com/xeon-ye/cxtx_springCloud
b2111b577e8dca65e0ed4cf64a3309c666e53c94
e45a8f27c5620dde82201a0949402126e01ce3d1
refs/heads/master
2023-07-04T19:11:52.947000
2021-08-25T06:53:59
2021-08-25T06:53:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cxtx.user_manage.web.rest; import com.cxtx.common.domain.JwtModel; import com.cxtx.common.unit.HttpServletUtils; import com.cxtx.common.unit.ResponseUtil; import com.cxtx.user_manage.domain.*; import com.cxtx.user_manage.service.*; import com.cxtx.user_manage.unit.GuavaUtil; import com.github.pagehelper.PageInfo; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import springfox.documentation.annotations.ApiIgnore; import javax.validation.Valid; import java.util.HashMap; import java.util.List; import java.util.Map; @Api(tags = "Oa") @RestController @RequestMapping("/api/oa") public class OaResource { private final Logger log = LoggerFactory.getLogger(OaResource.class); private static final String ENTITY_NAME = "oa"; @Autowired private OaFlowService oaFlowService; @Autowired private OaFormModelService oaFormModelService; @Autowired private OaFormProcessInstanceService oaFormProcessInstanceService; @Autowired private OaProcessRunService oaProcessRunService; @Autowired private OaProcessLogService oaProcessLogService; @Autowired private OaService oaService; @PostMapping("/submit") @ApiOperation(value = "流程发起", notes = "流程发起") public ResponseEntity<Map> submit(@RequestBody Map<String, Object> payload) { try { JwtModel curUser = HttpServletUtils.getUserInfo(); // 获取当前表单模块 Map<String, Object> module = (Map<String, Object>) payload.get("module"); Long formModId = Long.parseLong(module.get("id").toString()); if (null == oaFlowService.selectFlowByForm(formModId)) { // 表单没有绑定流程,直接填充数据 Long formId = oaFormModelService.insertFormData(payload, curUser); OaFormProcessInstance oaFormProcessInstance = new OaFormProcessInstance(); oaFormProcessInstance.setAppFormId(formId); oaFormProcessInstance.setFormModelId(formModId); oaFormProcessInstance.setUserId(Long.valueOf(curUser.getUserId())); oaFormProcessInstanceService.insertSelective(oaFormProcessInstance); return ResponseUtil.success("提交数据成功!"); } else { // 发起流程 Map result = oaService.submit(payload, curUser); if("1".equals(result.get("successStatus"))){ return ResponseUtil.success(result); }else if("2".equals(result.get("successStatus"))){ return ResponseUtil.success(2,"请选择审批人",result.get("data")); }else { return ResponseUtil.error("失败"); } } } catch (Exception e) { e.printStackTrace(); return ResponseUtil.error(e.getMessage()); } } @GetMapping("/listRunProcess") @ApiOperation(value = "待办事项", notes = "待办事项", response = ResponseUtil.Response.class) @ApiImplicitParams( value = { @ApiImplicitParam(name = "pageNum", value = "分页参数:第几页", required = true, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "pageSize", value = "分页参数:每页数量", required = true, paramType = "query", dataType = "int") } ) public ResponseEntity<Map> getRunProcessList(@ApiIgnore @RequestParam Map params) { try { JwtModel curUser = HttpServletUtils.getUserInfo(); params.put("userId",curUser.getUserId()); PageInfo<Map<String,Object>> result = oaProcessRunService.queryByPage(params); if (result != null) { return ResponseUtil.success(result); } else { return ResponseUtil.error("有错误"); } }catch (Exception e){ return ResponseUtil.error(e.getMessage()); } } @GetMapping("/getProcessDetail/{processId}") @ApiOperation(value = "待办详情", notes = "待办详情", response = ResponseUtil.Response.class) public ResponseEntity<Map> getProcessDetail(@PathVariable Long processId) { Map result = oaService.getProcessDetail(processId); if (result != null) { return ResponseUtil.success(result); } else { return ResponseUtil.error("获取失败!"); } } @GetMapping("/getHisProcessDetail/{processId}") @ApiOperation(value = "历史详情", notes = "历史详情", response = ResponseUtil.Response.class) public ResponseEntity<Map> getHisProcessDetail(@PathVariable Long processId) { Map result = oaService.getHisProcessDetail(processId); if (result != null) { return ResponseUtil.success(result); } else { return ResponseUtil.error("获取失败!"); } } @PostMapping("/handle") @ApiOperation(value = "流程审批-同意", notes = "流程审批-同意", response = ResponseUtil.Response.class) public ResponseEntity<Map> handle(@RequestBody Map<String, Object> payload) { try { JwtModel curUser = HttpServletUtils.getUserInfo(); Map result = oaService.approval(payload, curUser); if("1".equals(result.get("successStatus"))){ return ResponseUtil.success(result); }else if("2".equals(result.get("successStatus"))){ return ResponseUtil.success(2,"请选择审批人",result.get("data")); }else { return ResponseUtil.error("失败"); } } catch (Exception e) { e.printStackTrace(); return ResponseUtil.error(e.getMessage()); } } @PostMapping("/refuse") @ApiOperation(value = "流程审批-拒绝", notes = "流程审批-拒绝", response = ResponseUtil.Response.class) public ResponseEntity<Map> refuse(@RequestBody Map<String, Object> payload) { try { JwtModel curUser = HttpServletUtils.getUserInfo(); Map result = oaService.refuse(payload, curUser); if("1".equals(result.get("successStatus"))){ return ResponseUtil.success(result); }else if("2".equals(result.get("successStatus"))){ return ResponseUtil.success(2,result.get("message").toString(),result.get("data")); }else if("-2".equals(result.get("successStatus"))){ return ResponseUtil.error(result.get("message").toString()); } return ResponseUtil.error("失败"); } catch (Exception e) { e.printStackTrace(); return ResponseUtil.error(e.getMessage()); } } @PostMapping("/transfer") @ApiOperation(value = "流程审批-转交", notes = "流程审批-转交", response = ResponseUtil.Response.class) public ResponseEntity<Map> transfer(@RequestBody Map<String, Object> payload) { try { JwtModel curUser = HttpServletUtils.getUserInfo(); Map result = oaService.forward(payload, curUser); if("-2".equals(result.get("successStatus"))){ return ResponseUtil.error(result.get("message").toString()); }else if("-3".equals(result.get("successStatus"))){ return ResponseUtil.error(result.get("message").toString()); }else { return ResponseUtil.success("转交成功",result); } } catch (Exception e) { e.printStackTrace(); return ResponseUtil.error(e.getMessage()); } } @DeleteMapping("/deleteProcess/{processIds}") public ResponseEntity<Map> deleteProcessBatch(@PathVariable("processIds") String processIds) { try { List<String> processIdList = GuavaUtil.split2list(",", processIds); for (String id : processIdList) { oaService.deleteProcess(Long.parseLong(id)); } return ResponseUtil.success("流程删除成功"); } catch (Exception e) { e.printStackTrace(); return ResponseUtil.error(e.getMessage()); } } }
UTF-8
Java
8,599
java
OaResource.java
Java
[]
null
[]
package com.cxtx.user_manage.web.rest; import com.cxtx.common.domain.JwtModel; import com.cxtx.common.unit.HttpServletUtils; import com.cxtx.common.unit.ResponseUtil; import com.cxtx.user_manage.domain.*; import com.cxtx.user_manage.service.*; import com.cxtx.user_manage.unit.GuavaUtil; import com.github.pagehelper.PageInfo; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import springfox.documentation.annotations.ApiIgnore; import javax.validation.Valid; import java.util.HashMap; import java.util.List; import java.util.Map; @Api(tags = "Oa") @RestController @RequestMapping("/api/oa") public class OaResource { private final Logger log = LoggerFactory.getLogger(OaResource.class); private static final String ENTITY_NAME = "oa"; @Autowired private OaFlowService oaFlowService; @Autowired private OaFormModelService oaFormModelService; @Autowired private OaFormProcessInstanceService oaFormProcessInstanceService; @Autowired private OaProcessRunService oaProcessRunService; @Autowired private OaProcessLogService oaProcessLogService; @Autowired private OaService oaService; @PostMapping("/submit") @ApiOperation(value = "流程发起", notes = "流程发起") public ResponseEntity<Map> submit(@RequestBody Map<String, Object> payload) { try { JwtModel curUser = HttpServletUtils.getUserInfo(); // 获取当前表单模块 Map<String, Object> module = (Map<String, Object>) payload.get("module"); Long formModId = Long.parseLong(module.get("id").toString()); if (null == oaFlowService.selectFlowByForm(formModId)) { // 表单没有绑定流程,直接填充数据 Long formId = oaFormModelService.insertFormData(payload, curUser); OaFormProcessInstance oaFormProcessInstance = new OaFormProcessInstance(); oaFormProcessInstance.setAppFormId(formId); oaFormProcessInstance.setFormModelId(formModId); oaFormProcessInstance.setUserId(Long.valueOf(curUser.getUserId())); oaFormProcessInstanceService.insertSelective(oaFormProcessInstance); return ResponseUtil.success("提交数据成功!"); } else { // 发起流程 Map result = oaService.submit(payload, curUser); if("1".equals(result.get("successStatus"))){ return ResponseUtil.success(result); }else if("2".equals(result.get("successStatus"))){ return ResponseUtil.success(2,"请选择审批人",result.get("data")); }else { return ResponseUtil.error("失败"); } } } catch (Exception e) { e.printStackTrace(); return ResponseUtil.error(e.getMessage()); } } @GetMapping("/listRunProcess") @ApiOperation(value = "待办事项", notes = "待办事项", response = ResponseUtil.Response.class) @ApiImplicitParams( value = { @ApiImplicitParam(name = "pageNum", value = "分页参数:第几页", required = true, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "pageSize", value = "分页参数:每页数量", required = true, paramType = "query", dataType = "int") } ) public ResponseEntity<Map> getRunProcessList(@ApiIgnore @RequestParam Map params) { try { JwtModel curUser = HttpServletUtils.getUserInfo(); params.put("userId",curUser.getUserId()); PageInfo<Map<String,Object>> result = oaProcessRunService.queryByPage(params); if (result != null) { return ResponseUtil.success(result); } else { return ResponseUtil.error("有错误"); } }catch (Exception e){ return ResponseUtil.error(e.getMessage()); } } @GetMapping("/getProcessDetail/{processId}") @ApiOperation(value = "待办详情", notes = "待办详情", response = ResponseUtil.Response.class) public ResponseEntity<Map> getProcessDetail(@PathVariable Long processId) { Map result = oaService.getProcessDetail(processId); if (result != null) { return ResponseUtil.success(result); } else { return ResponseUtil.error("获取失败!"); } } @GetMapping("/getHisProcessDetail/{processId}") @ApiOperation(value = "历史详情", notes = "历史详情", response = ResponseUtil.Response.class) public ResponseEntity<Map> getHisProcessDetail(@PathVariable Long processId) { Map result = oaService.getHisProcessDetail(processId); if (result != null) { return ResponseUtil.success(result); } else { return ResponseUtil.error("获取失败!"); } } @PostMapping("/handle") @ApiOperation(value = "流程审批-同意", notes = "流程审批-同意", response = ResponseUtil.Response.class) public ResponseEntity<Map> handle(@RequestBody Map<String, Object> payload) { try { JwtModel curUser = HttpServletUtils.getUserInfo(); Map result = oaService.approval(payload, curUser); if("1".equals(result.get("successStatus"))){ return ResponseUtil.success(result); }else if("2".equals(result.get("successStatus"))){ return ResponseUtil.success(2,"请选择审批人",result.get("data")); }else { return ResponseUtil.error("失败"); } } catch (Exception e) { e.printStackTrace(); return ResponseUtil.error(e.getMessage()); } } @PostMapping("/refuse") @ApiOperation(value = "流程审批-拒绝", notes = "流程审批-拒绝", response = ResponseUtil.Response.class) public ResponseEntity<Map> refuse(@RequestBody Map<String, Object> payload) { try { JwtModel curUser = HttpServletUtils.getUserInfo(); Map result = oaService.refuse(payload, curUser); if("1".equals(result.get("successStatus"))){ return ResponseUtil.success(result); }else if("2".equals(result.get("successStatus"))){ return ResponseUtil.success(2,result.get("message").toString(),result.get("data")); }else if("-2".equals(result.get("successStatus"))){ return ResponseUtil.error(result.get("message").toString()); } return ResponseUtil.error("失败"); } catch (Exception e) { e.printStackTrace(); return ResponseUtil.error(e.getMessage()); } } @PostMapping("/transfer") @ApiOperation(value = "流程审批-转交", notes = "流程审批-转交", response = ResponseUtil.Response.class) public ResponseEntity<Map> transfer(@RequestBody Map<String, Object> payload) { try { JwtModel curUser = HttpServletUtils.getUserInfo(); Map result = oaService.forward(payload, curUser); if("-2".equals(result.get("successStatus"))){ return ResponseUtil.error(result.get("message").toString()); }else if("-3".equals(result.get("successStatus"))){ return ResponseUtil.error(result.get("message").toString()); }else { return ResponseUtil.success("转交成功",result); } } catch (Exception e) { e.printStackTrace(); return ResponseUtil.error(e.getMessage()); } } @DeleteMapping("/deleteProcess/{processIds}") public ResponseEntity<Map> deleteProcessBatch(@PathVariable("processIds") String processIds) { try { List<String> processIdList = GuavaUtil.split2list(",", processIds); for (String id : processIdList) { oaService.deleteProcess(Long.parseLong(id)); } return ResponseUtil.success("流程删除成功"); } catch (Exception e) { e.printStackTrace(); return ResponseUtil.error(e.getMessage()); } } }
8,599
0.624472
0.62266
209
38.612442
29.003845
133
false
false
0
0
0
0
0
0
0.617225
false
false
10
88124986e67d76fe785ae1cdff313aded2600b44
14,010,183,322,727
5160a134705e27eb2d1d2ab80655779479828317
/service/service-edu/src/main/java/com/danbro/edu/controller/vo/SecondSubjectVo.java
9ed421f66a2302e0274e3dd168193438c9739e67
[]
no_license
Danbro007/danbro-edu
https://github.com/Danbro007/danbro-edu
c3062fe71e4165731c4a9166a88af87062df3348
4b1af208e54df946d0d811c38603703069075575
refs/heads/main
2023-02-25T19:29:32.925000
2021-01-25T12:41:00
2021-01-25T12:41:00
321,248,859
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.danbro.edu.controller.vo; import java.io.Serializable; import java.util.Date; import com.danbro.edu.entity.EduSubject; import com.danbro.impl.VoConvert; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.experimental.Accessors; import org.springframework.beans.BeanUtils; /** * @Classname FirstSubject * @Description TODO 返回二级分类的数据 * @Date 2020/12/18 21:46 * @Author Danrbo */ @Data @ApiModel("返回给前端的二级课程分类") @Accessors(chain = true) public class SecondSubjectVo implements Serializable, VoConvert<SecondSubjectVo, EduSubject> { @ApiModelProperty("二级课程分类ID") private String id; @ApiModelProperty("课程名") private String title; @ApiModelProperty("一级课程名") private String parentId; @ApiModelProperty("排序") private Integer sort; @ApiModelProperty("创建时间") private Date gmtCreate; @ApiModelProperty("修改时间") private Date gmtModified; @Override public SecondSubjectVo convertFrom(EduSubject eduSubject) { BeanUtils.copyProperties(eduSubject, this); return this; } }
UTF-8
Java
1,218
java
SecondSubjectVo.java
Java
[ { "context": "ODO 返回二级分类的数据\n * @Date 2020/12/18 21:46\n * @Author Danrbo\n */\n\n@Data\n@ApiModel(\"返回给前端的二级课程分类\")\n@Accessors(c", "end": 462, "score": 0.999732255935669, "start": 456, "tag": "USERNAME", "value": "Danrbo" } ]
null
[]
package com.danbro.edu.controller.vo; import java.io.Serializable; import java.util.Date; import com.danbro.edu.entity.EduSubject; import com.danbro.impl.VoConvert; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.experimental.Accessors; import org.springframework.beans.BeanUtils; /** * @Classname FirstSubject * @Description TODO 返回二级分类的数据 * @Date 2020/12/18 21:46 * @Author Danrbo */ @Data @ApiModel("返回给前端的二级课程分类") @Accessors(chain = true) public class SecondSubjectVo implements Serializable, VoConvert<SecondSubjectVo, EduSubject> { @ApiModelProperty("二级课程分类ID") private String id; @ApiModelProperty("课程名") private String title; @ApiModelProperty("一级课程名") private String parentId; @ApiModelProperty("排序") private Integer sort; @ApiModelProperty("创建时间") private Date gmtCreate; @ApiModelProperty("修改时间") private Date gmtModified; @Override public SecondSubjectVo convertFrom(EduSubject eduSubject) { BeanUtils.copyProperties(eduSubject, this); return this; } }
1,218
0.742908
0.73227
47
23.021276
18.868515
94
false
false
0
0
0
0
0
0
0.446809
false
false
10
abd4e76180f9e44dd496762765d73099b4872bf5
25,477,746,017,602
aaaea2d199456d5232ccaa16045c60d92a9455da
/app/src/main/java/cmccwm/mobilemusic/receiver/NetStatusReceiver.java
cc0c934b2ed64eb6c75864d9421af9208d8c750d
[]
no_license
zhangphil/migu_musicplayer
https://github.com/zhangphil/migu_musicplayer
ae92864389e508c85780ab2124454e4ffc1c5fbb
cd79140d768af1504e9273e8161b41991f5f96eb
refs/heads/master
2016-04-11T17:58:15.652000
2016-04-01T10:00:51
2016-04-01T10:00:51
54,622,350
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * */ package cmccwm.mobilemusic.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.nostra13.universalimageloader.core.ImageLoader; import cmccwm.mobilemusic.CMCCMusicBusiness; import cmccwm.mobilemusic.GlobalController; import cmccwm.mobilemusic.GlobalSettingParameter; import cmccwm.mobilemusic.MobileMusicApplication; import cmccwm.mobilemusic.R; import cmccwm.mobilemusic.bean.Song; import cmccwm.mobilemusic.controller.HttpContentController; import cmccwm.mobilemusic.controller.IHttpCallBack; import cmccwm.mobilemusic.controller.PlayerController; import cmccwm.mobilemusic.controller.ReplaceableHttpAddress; import cmccwm.mobilemusic.controller.UIMessageCenter; import cmccwm.mobilemusic.db.MiguSharedPreferences; import cmccwm.mobilemusic.player.base.NotifyMessage; import cmccwm.mobilemusic.ui.DialogActivity; import cmccwm.mobilemusic.ui.SplashActivity; import cmccwm.mobilemusic.ui.WlanOnlyDialogActivity; import cmccwm.mobilemusic.ui.lrc.search.lrcManager; import cmccwm.mobilemusic.util.FlowStatistic; import cmccwm.mobilemusic.util.NetUtil; import cmccwm.mobilemusic.util.PlayerLog; import cmccwm.mobilemusic.util.UserLogin; import cmccwm.mobilemusic.util.Util; import cmccwm.mobilemusic.wimo.PlayWiMoController; /** * The Class NetStatusReceiver. * * @author liyi receiver the change of network */ public class NetStatusReceiver extends BroadcastReceiver { /** * The tag. */ private static final String TAG = "NetStatusReceiver"; /** * The current network state,which is one of -1(initial),NET_NO,NET_CMWAP,NET_CMNET,NET_WIFI. */ private int mCurNetState = -1; // 过滤第一次接收到的网络改变的广播(每次程序启动(广播刚注册),就会收到ConnectivityManager.CONNECTIVITY_ACTION的系统广播,需过滤掉) private boolean mIsFirstReceive = true; // 请求类 private HttpContentController mHttpController; @Override public final void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { if (mIsFirstReceive) { mIsFirstReceive = false; return; } localFunctionChange(); if ((MiguSharedPreferences.getLaunchNetworkNote() == false) && (SplashActivity.mIsAllowUseNet == false)) { // 用户还没同意联网,禁止网络操作 return; } netFunctionChange(context); } } /** * 非网络操作 * * @author xdp **/ private void localFunctionChange() { final int netType = NetUtil.checkNetWork(); if (netType == NetUtil.NET_CMWAP || netType == NetUtil.NET_CMNET) { // toast 流量提醒 // Operation when net change to NET_CMWAP & NET_CMNET FlowStatistic.staticWlanFlow(); } else if (netType == NetUtil.NET_WIFI) { // Operation when net change to WIFI FlowStatistic.staticWlanFlow(); FlowStatistic.initStaticWlanFlow(); } else { // Operation when net change to NO_NET // FlowStatistic.staticWlanFlow(); } } /** * 会引起联网的操作 * * @author xdp **/ private void netFunctionChange(Context context) { final int netType = NetUtil.checkNetWork(); UIMessageCenter.getIntance().notifyNetworkChanged(); PlayWiMoController.getInstance().networkChanged(); PlayerLog .w(getClass().toString(), "====before===[netType]" + netType + "========[mCurNetState]" + mCurNetState); // 断网后恢复,客户端在前台界面网络恢复,则继续播放 // from having no network to having network if ((mCurNetState == NetUtil.NET_NO || mCurNetState == -1) && netType != NetUtil.NET_NO) { // my app is running in foreground Song song = PlayerController.getUseSong(); if (song != null && !song.bLocal()) { if (!MobileMusicApplication.isApplicationBroughtToBackground(MobileMusicApplication.getInstance())) { PlayerLog.w(getClass().toString(), "===[enter]===isApplicationBroughtToBackground"); if (PlayerController.getPlayState() != NotifyMessage.USER_STATE_MSG_PLAYING && PlayerController.getPlayState() != NotifyMessage.USER_STATE_MSG_PAUSE) { PlayerLog.w(getClass().toString(), "===no network----->network,replaying"); PlayerController.play(); } else { if (MiguSharedPreferences.getIsWlanOnlyOn() == false || netType == NetUtil.NET_WIFI) { PlayerController.retryDownLoad(); } } PlayerLog.w(getClass().toString(), "===[leave]===isApplicationBroughtToBackground"); } } } if (netType != NetUtil.NET_NO) { // 网络恢复,需要搜索在线歌曲歌词 Song song = PlayerController.getUseSong(); if (song != null && !song.bLocal()) { lrcManager.getLrcIntance().songChange(); } } // 免流量地址请求 requestFreeAddress(netType); // 歌单同步 if (mCurNetState != netType && netType == NetUtil.NET_WIFI) { if (GlobalSettingParameter.LOGIN_SUCESS_INFO != null && !Util.checkIsShowWlanOnly()) { Intent serviceIntent = new Intent("cmccwm.mobilemusic.RemoteService").setPackage(MobileMusicApplication.getInstance().getApplicationContext().getPackageName()); serviceIntent.putExtra("SYNCDATATYPE", 0); MobileMusicApplication.getInstance().getApplicationContext().startService(serviceIntent); } } mCurNetState = netType; PlayerLog.w(getClass().toString(), "====after===[netType]" + netType + "========[mCurNetState]" + mCurNetState); // 网络切换时仅WLAN下联网判断 if (Util.checkIsShowWlanOnly()) { int startType = Util.checkCurrMediaType(); if (startType != WlanOnlyDialogActivity.DEFAULT_TYPE && !PlayerController.isBufferComplete()) { Intent dialogIntent = new Intent(context, WlanOnlyDialogActivity.class); dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); dialogIntent.putExtra("dialogType", startType); context.startActivity(dialogIntent); } } else { mediaIsPlaying(context); } // TODO 每次启动都会执行 if (netType != NetUtil.NET_NO && MiguSharedPreferences.getIsSkipUserlead()) { if (!UserLogin.sLoginOut && !Util.checkIsShowWlanOnly()) { UserLogin.getInstance().AutoLogin(); } } } /** * 若联网,则请求免流量地址 * * @param netType */ private void requestFreeAddress(int netType) { if (netType != NetUtil.NET_NO) { requestFreeHttpAddress(); } } /** * 获取免流量地址 */ public void requestFreeHttpAddress() { if (mHttpController == null) { mHttpController = new HttpContentController(mHttpCallBack); } mHttpController.requestFreeAddress(GlobalController.REQ_FREE_HTTP_ADDRESS, ReplaceableHttpAddress.class); } /** * 免流量地址请求结果的回调 */ private IHttpCallBack mHttpCallBack = new IHttpCallBack() { @Override public void onHttpFinish(int type, Object object) { if (type == GlobalController.REQ_FREE_HTTP_ADDRESS) { ReplaceableHttpAddress freeAddress = (ReplaceableHttpAddress) object; if (freeAddress != null && freeAddress.getCode() != null && CMCCMusicBusiness.TAG_CODE_SUCCESS.equals(freeAddress.getCode())) { MiguSharedPreferences.saveFreeHttpAddress(freeAddress); if (GlobalSettingParameter.B_FLOW_FREE) { try { Gson gson = new GsonBuilder().create(); ImageLoader.getInstance().sImgFreeAddress = ImageLoader.getInstance().new ImgFreeAddress(gson.toJson(freeAddress)); } catch (Exception e) { } } else { ImageLoader.getInstance().sImgFreeAddress = null; } } return; } } @Override public void onHttpFail(int type, Object object, Throwable e) { if (type == GlobalController.REQ_FREE_HTTP_ADDRESS) { // 请求失败则获取本地保存的免流量地址 ReplaceableHttpAddress freeAddress = MiguSharedPreferences.getFreeHttpAddress(); if (freeAddress != null && GlobalSettingParameter.B_FLOW_FREE) { // 若有数据并且免流量开关打开则对图片进行设置 try { Gson gson = new GsonBuilder().create(); ImageLoader.getInstance().sImgFreeAddress = ImageLoader.getInstance().new ImgFreeAddress(gson.toJson(freeAddress)); } catch (Exception ex) { } } else { // 将图片的免流量地址对象设置为null可返回非免流量的地址 ImageLoader.getInstance().sImgFreeAddress = null; } return; } } }; /** * 处理正在播放或下载的业务 * * @return * @author xdp **/ private void mediaIsPlaying(Context context) { if (Util.isShowNetWorkDialog()) { int startType = Util.checkCurrMediaType(); if (startType != DialogActivity.DEFAULT_TYPE && !PlayerController.isBufferComplete()) { Intent dialogIntent = new Intent(context, DialogActivity.class); dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); dialogIntent.putExtra("dialogType", startType); context.startActivity(dialogIntent); return; } } // 当网络切换到2G/3G网络时弹出Toast流量提示 if (GlobalSettingParameter.B_SHOW_NET_CAST_TOAST && GlobalSettingParameter.B_SHOW_NET_CAST_DIALOG && (NetUtil.checkNetWork() == NetUtil.NET_CMNET || NetUtil.checkNetWork() == NetUtil.NET_CMWAP)) { Toast.makeText(context, R.string.setting_gprs_warm_lunch_message, Toast.LENGTH_SHORT).show(); GlobalSettingParameter.B_SHOW_NET_CAST_TOAST = false; } } }
UTF-8
Java
11,170
java
NetStatusReceiver.java
Java
[ { "context": "\n/**\n * The Class NetStatusReceiver.\n *\n * @author liyi receiver the change of network\n */\n\npublic class ", "end": 1499, "score": 0.9260120391845703, "start": 1495, "tag": "USERNAME", "value": "liyi" }, { "context": "\n }\n\n /**\n * 非网络操作\n *\n * @author xdp\n **/\n private void localFunctionChange() {", "end": 2683, "score": 0.9996316432952881, "start": 2680, "tag": "USERNAME", "value": "xdp" }, { "context": " }\n\n /**\n * 会引起联网的操作\n *\n * @author xdp\n **/\n private void netFunctionChange(Conte", "end": 3372, "score": 0.9996303915977478, "start": 3369, "tag": "USERNAME", "value": "xdp" }, { "context": " 处理正在播放或下载的业务\n *\n * @return\n * @author xdp\n **/\n private void mediaIsPlaying(Context ", "end": 9606, "score": 0.9993572235107422, "start": 9603, "tag": "USERNAME", "value": "xdp" } ]
null
[]
/* * */ package cmccwm.mobilemusic.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.nostra13.universalimageloader.core.ImageLoader; import cmccwm.mobilemusic.CMCCMusicBusiness; import cmccwm.mobilemusic.GlobalController; import cmccwm.mobilemusic.GlobalSettingParameter; import cmccwm.mobilemusic.MobileMusicApplication; import cmccwm.mobilemusic.R; import cmccwm.mobilemusic.bean.Song; import cmccwm.mobilemusic.controller.HttpContentController; import cmccwm.mobilemusic.controller.IHttpCallBack; import cmccwm.mobilemusic.controller.PlayerController; import cmccwm.mobilemusic.controller.ReplaceableHttpAddress; import cmccwm.mobilemusic.controller.UIMessageCenter; import cmccwm.mobilemusic.db.MiguSharedPreferences; import cmccwm.mobilemusic.player.base.NotifyMessage; import cmccwm.mobilemusic.ui.DialogActivity; import cmccwm.mobilemusic.ui.SplashActivity; import cmccwm.mobilemusic.ui.WlanOnlyDialogActivity; import cmccwm.mobilemusic.ui.lrc.search.lrcManager; import cmccwm.mobilemusic.util.FlowStatistic; import cmccwm.mobilemusic.util.NetUtil; import cmccwm.mobilemusic.util.PlayerLog; import cmccwm.mobilemusic.util.UserLogin; import cmccwm.mobilemusic.util.Util; import cmccwm.mobilemusic.wimo.PlayWiMoController; /** * The Class NetStatusReceiver. * * @author liyi receiver the change of network */ public class NetStatusReceiver extends BroadcastReceiver { /** * The tag. */ private static final String TAG = "NetStatusReceiver"; /** * The current network state,which is one of -1(initial),NET_NO,NET_CMWAP,NET_CMNET,NET_WIFI. */ private int mCurNetState = -1; // 过滤第一次接收到的网络改变的广播(每次程序启动(广播刚注册),就会收到ConnectivityManager.CONNECTIVITY_ACTION的系统广播,需过滤掉) private boolean mIsFirstReceive = true; // 请求类 private HttpContentController mHttpController; @Override public final void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { if (mIsFirstReceive) { mIsFirstReceive = false; return; } localFunctionChange(); if ((MiguSharedPreferences.getLaunchNetworkNote() == false) && (SplashActivity.mIsAllowUseNet == false)) { // 用户还没同意联网,禁止网络操作 return; } netFunctionChange(context); } } /** * 非网络操作 * * @author xdp **/ private void localFunctionChange() { final int netType = NetUtil.checkNetWork(); if (netType == NetUtil.NET_CMWAP || netType == NetUtil.NET_CMNET) { // toast 流量提醒 // Operation when net change to NET_CMWAP & NET_CMNET FlowStatistic.staticWlanFlow(); } else if (netType == NetUtil.NET_WIFI) { // Operation when net change to WIFI FlowStatistic.staticWlanFlow(); FlowStatistic.initStaticWlanFlow(); } else { // Operation when net change to NO_NET // FlowStatistic.staticWlanFlow(); } } /** * 会引起联网的操作 * * @author xdp **/ private void netFunctionChange(Context context) { final int netType = NetUtil.checkNetWork(); UIMessageCenter.getIntance().notifyNetworkChanged(); PlayWiMoController.getInstance().networkChanged(); PlayerLog .w(getClass().toString(), "====before===[netType]" + netType + "========[mCurNetState]" + mCurNetState); // 断网后恢复,客户端在前台界面网络恢复,则继续播放 // from having no network to having network if ((mCurNetState == NetUtil.NET_NO || mCurNetState == -1) && netType != NetUtil.NET_NO) { // my app is running in foreground Song song = PlayerController.getUseSong(); if (song != null && !song.bLocal()) { if (!MobileMusicApplication.isApplicationBroughtToBackground(MobileMusicApplication.getInstance())) { PlayerLog.w(getClass().toString(), "===[enter]===isApplicationBroughtToBackground"); if (PlayerController.getPlayState() != NotifyMessage.USER_STATE_MSG_PLAYING && PlayerController.getPlayState() != NotifyMessage.USER_STATE_MSG_PAUSE) { PlayerLog.w(getClass().toString(), "===no network----->network,replaying"); PlayerController.play(); } else { if (MiguSharedPreferences.getIsWlanOnlyOn() == false || netType == NetUtil.NET_WIFI) { PlayerController.retryDownLoad(); } } PlayerLog.w(getClass().toString(), "===[leave]===isApplicationBroughtToBackground"); } } } if (netType != NetUtil.NET_NO) { // 网络恢复,需要搜索在线歌曲歌词 Song song = PlayerController.getUseSong(); if (song != null && !song.bLocal()) { lrcManager.getLrcIntance().songChange(); } } // 免流量地址请求 requestFreeAddress(netType); // 歌单同步 if (mCurNetState != netType && netType == NetUtil.NET_WIFI) { if (GlobalSettingParameter.LOGIN_SUCESS_INFO != null && !Util.checkIsShowWlanOnly()) { Intent serviceIntent = new Intent("cmccwm.mobilemusic.RemoteService").setPackage(MobileMusicApplication.getInstance().getApplicationContext().getPackageName()); serviceIntent.putExtra("SYNCDATATYPE", 0); MobileMusicApplication.getInstance().getApplicationContext().startService(serviceIntent); } } mCurNetState = netType; PlayerLog.w(getClass().toString(), "====after===[netType]" + netType + "========[mCurNetState]" + mCurNetState); // 网络切换时仅WLAN下联网判断 if (Util.checkIsShowWlanOnly()) { int startType = Util.checkCurrMediaType(); if (startType != WlanOnlyDialogActivity.DEFAULT_TYPE && !PlayerController.isBufferComplete()) { Intent dialogIntent = new Intent(context, WlanOnlyDialogActivity.class); dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); dialogIntent.putExtra("dialogType", startType); context.startActivity(dialogIntent); } } else { mediaIsPlaying(context); } // TODO 每次启动都会执行 if (netType != NetUtil.NET_NO && MiguSharedPreferences.getIsSkipUserlead()) { if (!UserLogin.sLoginOut && !Util.checkIsShowWlanOnly()) { UserLogin.getInstance().AutoLogin(); } } } /** * 若联网,则请求免流量地址 * * @param netType */ private void requestFreeAddress(int netType) { if (netType != NetUtil.NET_NO) { requestFreeHttpAddress(); } } /** * 获取免流量地址 */ public void requestFreeHttpAddress() { if (mHttpController == null) { mHttpController = new HttpContentController(mHttpCallBack); } mHttpController.requestFreeAddress(GlobalController.REQ_FREE_HTTP_ADDRESS, ReplaceableHttpAddress.class); } /** * 免流量地址请求结果的回调 */ private IHttpCallBack mHttpCallBack = new IHttpCallBack() { @Override public void onHttpFinish(int type, Object object) { if (type == GlobalController.REQ_FREE_HTTP_ADDRESS) { ReplaceableHttpAddress freeAddress = (ReplaceableHttpAddress) object; if (freeAddress != null && freeAddress.getCode() != null && CMCCMusicBusiness.TAG_CODE_SUCCESS.equals(freeAddress.getCode())) { MiguSharedPreferences.saveFreeHttpAddress(freeAddress); if (GlobalSettingParameter.B_FLOW_FREE) { try { Gson gson = new GsonBuilder().create(); ImageLoader.getInstance().sImgFreeAddress = ImageLoader.getInstance().new ImgFreeAddress(gson.toJson(freeAddress)); } catch (Exception e) { } } else { ImageLoader.getInstance().sImgFreeAddress = null; } } return; } } @Override public void onHttpFail(int type, Object object, Throwable e) { if (type == GlobalController.REQ_FREE_HTTP_ADDRESS) { // 请求失败则获取本地保存的免流量地址 ReplaceableHttpAddress freeAddress = MiguSharedPreferences.getFreeHttpAddress(); if (freeAddress != null && GlobalSettingParameter.B_FLOW_FREE) { // 若有数据并且免流量开关打开则对图片进行设置 try { Gson gson = new GsonBuilder().create(); ImageLoader.getInstance().sImgFreeAddress = ImageLoader.getInstance().new ImgFreeAddress(gson.toJson(freeAddress)); } catch (Exception ex) { } } else { // 将图片的免流量地址对象设置为null可返回非免流量的地址 ImageLoader.getInstance().sImgFreeAddress = null; } return; } } }; /** * 处理正在播放或下载的业务 * * @return * @author xdp **/ private void mediaIsPlaying(Context context) { if (Util.isShowNetWorkDialog()) { int startType = Util.checkCurrMediaType(); if (startType != DialogActivity.DEFAULT_TYPE && !PlayerController.isBufferComplete()) { Intent dialogIntent = new Intent(context, DialogActivity.class); dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); dialogIntent.putExtra("dialogType", startType); context.startActivity(dialogIntent); return; } } // 当网络切换到2G/3G网络时弹出Toast流量提示 if (GlobalSettingParameter.B_SHOW_NET_CAST_TOAST && GlobalSettingParameter.B_SHOW_NET_CAST_DIALOG && (NetUtil.checkNetWork() == NetUtil.NET_CMNET || NetUtil.checkNetWork() == NetUtil.NET_CMWAP)) { Toast.makeText(context, R.string.setting_gprs_warm_lunch_message, Toast.LENGTH_SHORT).show(); GlobalSettingParameter.B_SHOW_NET_CAST_TOAST = false; } } }
11,170
0.605362
0.60461
276
37.514492
32.815189
176
false
false
0
0
0
0
0
0
0.456522
false
false
10
9f8e26ac07c1e424833136967d2c4de70dc83345
26,671,746,973,668
ff11c130e5afc89811ace4cf70344e0aeba0476e
/src/main/java/com/zea7ot/leetcode/lvl4/lc0314/SolutionApproach0PreorderRecursive.java
ac6ba2fd25aea2b8eacb0041f1a6df2d6f3f205b
[]
no_license
IdiotLeon/lcidiot
https://github.com/IdiotLeon/lcidiot
38229f51278553decda9af6e24a48551ad45aecd
2ebdad68625815ebf54c7cd36dcf4d12d0674a32
refs/heads/master
2020-11-28T14:21:01.122000
2020-11-27T04:47:19
2020-11-27T04:47:19
229,832,217
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * https://leetcode.com/problems/binary-tree-vertical-order-traversal/ * * Time Complexity: O(W * lg(W) * N * lg(H)) + O(N) ~ O(W * H * lg(W * H)) * Space Complexity: O(N) + O(H) ~ O(N) */ package com.zea7ot.leetcode.lvl4.lc0314; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import com.zea7ot.utils.data_structure.tree.TreeNode; public class SolutionApproach0PreorderRecursive { public List<List<Integer>> verticalOrder(TreeNode root) { List<List<Integer>> ans = new ArrayList<>(); // sanity check if (root == null) return ans; TreeMap<Integer, TreeMap<Integer, List<Integer>>> map = new TreeMap<>(); preorder(0, 0, root, map); for (Map.Entry<Integer, TreeMap<Integer, List<Integer>>> entry : map.entrySet()) { List<Integer> level = new ArrayList<Integer>(); TreeMap<Integer, List<Integer>> mapY = entry.getValue(); for (Map.Entry<Integer, List<Integer>> entryY : mapY.entrySet()) { List<Integer> list = entryY.getValue(); level.addAll(list); } ans.add(level); } return ans; } private void preorder(int x, int y, TreeNode node, TreeMap<Integer, TreeMap<Integer, List<Integer>>> map) { if (node == null) return; map.putIfAbsent(x, new TreeMap<Integer, List<Integer>>()); map.get(x).putIfAbsent(y, new ArrayList<Integer>()); map.get(x).get(y).add(node.val); preorder(x - 1, y + 1, node.left, map); preorder(x + 1, y + 1, node.right, map); } }
UTF-8
Java
1,663
java
SolutionApproach0PreorderRecursive.java
Java
[]
null
[]
/** * https://leetcode.com/problems/binary-tree-vertical-order-traversal/ * * Time Complexity: O(W * lg(W) * N * lg(H)) + O(N) ~ O(W * H * lg(W * H)) * Space Complexity: O(N) + O(H) ~ O(N) */ package com.zea7ot.leetcode.lvl4.lc0314; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import com.zea7ot.utils.data_structure.tree.TreeNode; public class SolutionApproach0PreorderRecursive { public List<List<Integer>> verticalOrder(TreeNode root) { List<List<Integer>> ans = new ArrayList<>(); // sanity check if (root == null) return ans; TreeMap<Integer, TreeMap<Integer, List<Integer>>> map = new TreeMap<>(); preorder(0, 0, root, map); for (Map.Entry<Integer, TreeMap<Integer, List<Integer>>> entry : map.entrySet()) { List<Integer> level = new ArrayList<Integer>(); TreeMap<Integer, List<Integer>> mapY = entry.getValue(); for (Map.Entry<Integer, List<Integer>> entryY : mapY.entrySet()) { List<Integer> list = entryY.getValue(); level.addAll(list); } ans.add(level); } return ans; } private void preorder(int x, int y, TreeNode node, TreeMap<Integer, TreeMap<Integer, List<Integer>>> map) { if (node == null) return; map.putIfAbsent(x, new TreeMap<Integer, List<Integer>>()); map.get(x).putIfAbsent(y, new ArrayList<Integer>()); map.get(x).get(y).add(node.val); preorder(x - 1, y + 1, node.left, map); preorder(x + 1, y + 1, node.right, map); } }
1,663
0.589296
0.580878
50
32.279999
28.542627
111
false
false
0
0
0
0
0
0
0.9
false
false
10
5f01a5f589eef5ab79404eca3bd62b971b3e6a11
12,661,563,608,588
722a0bb4a6d6809e6537451742bb8f088c3ba1ad
/sentry-core/sentry-core-common/src/main/java/org/apache/sentry/core/common/utils/PubSub.java
eeb8f80a1d1f2e95649823abd321819b14ce4d76
[ "Apache-2.0", "BSD-3-Clause", "MIT", "EPL-1.0", "CDDL-1.0", "BSD-2-Clause", "MPL-1.0", "CDDL-1.1" ]
permissive
finalspy/sentry
https://github.com/finalspy/sentry
b7dc7a4686753d88f21d8085c45f83f15911d366
e2dd73d995be51f237cce3ae8240cc8c3407e820
refs/heads/master
2022-10-30T20:09:28.137000
2020-01-02T16:57:27
2020-01-02T16:57:27
234,554,607
0
0
Apache-2.0
true
2022-10-12T20:42:01
2020-01-17T13:32:18
2020-01-17T13:32:20
2022-10-12T20:41:58
9,426
0
0
8
null
false
false
/* * 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.sentry.core.common.utils; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import com.google.common.base.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is a simple publish-subscribe implementation for internal * communication between Sentry components. It's a singleton class. * <p> * For the initial set of use cases, publish events are expected to be * extremely rare, so no the data structures have been selected with no * consideration for high concurrency. */ public final class PubSub { private static final Logger LOGGER = LoggerFactory.getLogger(PubSub.class); private final Map<Topic,Set<Subscriber>> subscriberMap = new HashMap<>(); private static PubSub instance; /** * Subscriber callback interface. * The same subscriber can subscribe to multiple topics, * so callback API includes both topic and message. */ public interface Subscriber { void onMessage(Topic topic, String message); } /** * Enumerated topics one can subscribe to. * To be expanded as needed. */ public enum Topic { HDFS_SYNC_HMS("hdfs-sync-hms"), // upcoming feature, triggering HDFS sync between HMS and Sentry HDFS_SYNC_NN("hdfs-sync-nn"); // upcoming feature, triggering HDFS sync between Sentry and NameNode private final String name; private static final Map<String,Topic> map = new HashMap<>(); static { for (Topic t : Topic.values()) { map.put(t.name, t); } } public static Topic fromString(String name) { Preconditions.checkNotNull("Enum name cannot be null", name); name = name.trim().toLowerCase(); if (map.containsKey(name)) { return map.get(name); } throw new NoSuchElementException(name + " not found"); } private Topic(String name) { this.name = name.toLowerCase(); } public String getName() { return name; } } /** * Public factory method to guarantee singleton */ public static synchronized PubSub getInstance() { if (instance != null) { LOGGER.info(instance + " requested"); } else { instance = new PubSub(); LOGGER.info(instance + " created"); } return instance; } // declare private to prevent multiple class instantiation private PubSub() { } /** * Publish message on given topic. Message is optional. */ public synchronized void publish(Topic topic, String message) { Preconditions.checkNotNull(topic, "Topic cannot be null"); Set<Subscriber> subscribers = subscriberMap.get(topic); if (subscribers == null) { throw new IllegalArgumentException("cannot publish to unknown topic " + topic + ", existing topics " + subscriberMap.keySet()); } for (Subscriber subscriber : subscribers) { // Faulire of one subscriber to process message delivery should not affect // message delivery to other subscribers, therefore using try-catch. try { subscriber.onMessage(topic, message); } catch (Exception e) { LOGGER.error("Topic " + topic + ", message " + message + ", delivery error", e); } } LOGGER.info("Topic " + topic + ", message " + message + ": " + subscribers.size() + " subscribers called"); } /** * Subscribe to given topic. */ public synchronized void subscribe(Topic topic, Subscriber subscriber) { Preconditions.checkNotNull(topic, "Topic cannot be null"); Preconditions.checkNotNull(subscriber, "Topic %s: Subscriber cannot be null", topic); Set<Subscriber> subscribers = subscriberMap.get(topic); if (subscribers == null) { LOGGER.info("new topic " + topic); subscriberMap.put(topic, subscribers = new HashSet<Subscriber>()); } subscribers.add(subscriber); LOGGER.info("Topic " + topic + ", added subscriber " + subscriber + ", total topic subscribers: " + subscribers.size()); } /** * Unsubscribe from given topic. If the last subscriber, remove the topic. */ public synchronized void unsubscribe(Topic topic, Subscriber subscriber) { Preconditions.checkNotNull(topic, "Topic cannot be null"); Preconditions.checkNotNull(subscriber, "Topic %s: Subscriber cannot be null", topic); Set<Subscriber> subscribers = subscriberMap.get(topic); if (subscribers == null) { throw new IllegalArgumentException("cannot unsubscribe from unknown topic " + topic); } if (!subscribers.remove(subscriber)) { throw new IllegalArgumentException("cannot unsubscribe from topic " + topic + ", unknown subscriber"); } LOGGER.info("Topic " + topic + ", unsubscribing subscriber " + subscriber + ", total topic subscribers: " + subscribers.size()); if (subscribers.isEmpty()) { subscriberMap.remove(topic); } } /** * Get all existing topics. */ public synchronized Set<Topic> getTopics() { return subscriberMap.keySet(); } @Override public String toString() { return getClass().getSimpleName() + ":" + Integer.toHexString(hashCode()); } }
UTF-8
Java
5,967
java
PubSub.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.sentry.core.common.utils; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import com.google.common.base.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is a simple publish-subscribe implementation for internal * communication between Sentry components. It's a singleton class. * <p> * For the initial set of use cases, publish events are expected to be * extremely rare, so no the data structures have been selected with no * consideration for high concurrency. */ public final class PubSub { private static final Logger LOGGER = LoggerFactory.getLogger(PubSub.class); private final Map<Topic,Set<Subscriber>> subscriberMap = new HashMap<>(); private static PubSub instance; /** * Subscriber callback interface. * The same subscriber can subscribe to multiple topics, * so callback API includes both topic and message. */ public interface Subscriber { void onMessage(Topic topic, String message); } /** * Enumerated topics one can subscribe to. * To be expanded as needed. */ public enum Topic { HDFS_SYNC_HMS("hdfs-sync-hms"), // upcoming feature, triggering HDFS sync between HMS and Sentry HDFS_SYNC_NN("hdfs-sync-nn"); // upcoming feature, triggering HDFS sync between Sentry and NameNode private final String name; private static final Map<String,Topic> map = new HashMap<>(); static { for (Topic t : Topic.values()) { map.put(t.name, t); } } public static Topic fromString(String name) { Preconditions.checkNotNull("Enum name cannot be null", name); name = name.trim().toLowerCase(); if (map.containsKey(name)) { return map.get(name); } throw new NoSuchElementException(name + " not found"); } private Topic(String name) { this.name = name.toLowerCase(); } public String getName() { return name; } } /** * Public factory method to guarantee singleton */ public static synchronized PubSub getInstance() { if (instance != null) { LOGGER.info(instance + " requested"); } else { instance = new PubSub(); LOGGER.info(instance + " created"); } return instance; } // declare private to prevent multiple class instantiation private PubSub() { } /** * Publish message on given topic. Message is optional. */ public synchronized void publish(Topic topic, String message) { Preconditions.checkNotNull(topic, "Topic cannot be null"); Set<Subscriber> subscribers = subscriberMap.get(topic); if (subscribers == null) { throw new IllegalArgumentException("cannot publish to unknown topic " + topic + ", existing topics " + subscriberMap.keySet()); } for (Subscriber subscriber : subscribers) { // Faulire of one subscriber to process message delivery should not affect // message delivery to other subscribers, therefore using try-catch. try { subscriber.onMessage(topic, message); } catch (Exception e) { LOGGER.error("Topic " + topic + ", message " + message + ", delivery error", e); } } LOGGER.info("Topic " + topic + ", message " + message + ": " + subscribers.size() + " subscribers called"); } /** * Subscribe to given topic. */ public synchronized void subscribe(Topic topic, Subscriber subscriber) { Preconditions.checkNotNull(topic, "Topic cannot be null"); Preconditions.checkNotNull(subscriber, "Topic %s: Subscriber cannot be null", topic); Set<Subscriber> subscribers = subscriberMap.get(topic); if (subscribers == null) { LOGGER.info("new topic " + topic); subscriberMap.put(topic, subscribers = new HashSet<Subscriber>()); } subscribers.add(subscriber); LOGGER.info("Topic " + topic + ", added subscriber " + subscriber + ", total topic subscribers: " + subscribers.size()); } /** * Unsubscribe from given topic. If the last subscriber, remove the topic. */ public synchronized void unsubscribe(Topic topic, Subscriber subscriber) { Preconditions.checkNotNull(topic, "Topic cannot be null"); Preconditions.checkNotNull(subscriber, "Topic %s: Subscriber cannot be null", topic); Set<Subscriber> subscribers = subscriberMap.get(topic); if (subscribers == null) { throw new IllegalArgumentException("cannot unsubscribe from unknown topic " + topic); } if (!subscribers.remove(subscriber)) { throw new IllegalArgumentException("cannot unsubscribe from topic " + topic + ", unknown subscriber"); } LOGGER.info("Topic " + topic + ", unsubscribing subscriber " + subscriber + ", total topic subscribers: " + subscribers.size()); if (subscribers.isEmpty()) { subscriberMap.remove(topic); } } /** * Get all existing topics. */ public synchronized Set<Topic> getTopics() { return subscriberMap.keySet(); } @Override public String toString() { return getClass().getSimpleName() + ":" + Integer.toHexString(hashCode()); } }
5,967
0.685437
0.684431
178
32.522472
31.026304
132
false
false
0
0
0
0
0
0
0.5
false
false
10
1d6df9fcff0ea3a0c4ac9be1a561ba598d85326d
10,496,900,085,203
87a0a95e3345dc519ee4f34fcf1abb1e2eb287a5
/src/main/java/com/lbs/tedam/data/service/PropertyService.java
9f13a9fe873dd98ecbae0e8e0ebab9b0a81999b8
[ "Apache-2.0" ]
permissive
hakkisagdic/tedam-core
https://github.com/hakkisagdic/tedam-core
9c8aa6a3fa271b157796d724820271a7f0877b87
85ad1cb0341e1f53909e81148d72d928656b4bfd
refs/heads/master
2022-01-07T15:01:09.318000
2019-07-08T08:19:31
2019-07-08T08:19:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2014-2019 Logo Business Solutions * (a.k.a. LOGO YAZILIM SAN. VE TIC. A.S) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.lbs.tedam.data.service; import com.lbs.tedam.exception.localized.LocalizedException; import com.lbs.tedam.model.Property; import java.util.List; /** * @author Tarik.Mikyas * @since 11 January 2016 10:33:51 */ public interface PropertyService extends BaseService<Property, Integer> { /** * This method is an example of getSpecialList for param in this procedure. it is not used anywhere. * * @param param * @return * @throws LocalizedException * @author Tarik.Mikyas * @return_type List<String> * @since 11 January 2016 10:45:10 */ public List<Property> getPropertyListByValue(String value) throws LocalizedException; /** * Returns the Property object dependent on the parameters. * * @param name * @param parameter * @return * @throws LocalizedException * @author Tarik.Mikyas * @since 22 June 2016 10:33:44 */ public Property getPropertyByNameAndParameter(String name, String parameter) throws LocalizedException; /** * @param name * @param parameter * @param useLike If TRUE, it returns the parameter value (like "parameter%"). If FALSE is given, it is dialed with "=". * @return * @throws LocalizedException * @author Ahmet.Izgi */ public List<Property> getPropertyListByCriteria(String name, String parameter, boolean useLike) throws LocalizedException; /** * this method getPropertyListByName <br> * * @param name * @return <br> * @throws LocalizedException * @author Canberk.Erkmen */ public List<Property> getPropertyListByName(String name) throws LocalizedException; public String getTestcaseFolder(Integer testCaseId) throws LocalizedException; public List<Property> redefinePropertyList(List<Property> propertyList, List<Property> propertyListInDB); }
UTF-8
Java
2,539
java
PropertyService.java
Java
[ { "context": ".Property;\n\nimport java.util.List;\n\n/**\n * @author Tarik.Mikyas\n * @since 11 January 2016 10:33:51\n */\npublic int", "end": 838, "score": 0.9998893141746521, "start": 826, "tag": "NAME", "value": "Tarik.Mikyas" }, { "context": "n\n * @throws LocalizedException\n * @author Tarik.Mikyas\n * @return_type List<String>\n * @since 11", "end": 1169, "score": 0.9998899102210999, "start": 1157, "tag": "NAME", "value": "Tarik.Mikyas" }, { "context": "n\n * @throws LocalizedException\n * @author Tarik.Mikyas\n * @since 22 June 2016 10:33:44\n */\n p", "end": 1539, "score": 0.9998911619186401, "start": 1527, "tag": "NAME", "value": "Tarik.Mikyas" }, { "context": "n\n * @throws LocalizedException\n * @author Ahmet.Izgi\n */\n public List<Property> getPropertyList", "end": 1945, "score": 0.9999021291732788, "start": 1935, "tag": "NAME", "value": "Ahmet.Izgi" }, { "context": ">\n * @throws LocalizedException\n * @author Canberk.Erkmen\n */\n public List<Property> getPropertyList", "end": 2245, "score": 0.9999030828475952, "start": 2231, "tag": "NAME", "value": "Canberk.Erkmen" } ]
null
[]
/* * Copyright 2014-2019 Logo Business Solutions * (a.k.a. LOGO YAZILIM SAN. VE TIC. A.S) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.lbs.tedam.data.service; import com.lbs.tedam.exception.localized.LocalizedException; import com.lbs.tedam.model.Property; import java.util.List; /** * @author Tarik.Mikyas * @since 11 January 2016 10:33:51 */ public interface PropertyService extends BaseService<Property, Integer> { /** * This method is an example of getSpecialList for param in this procedure. it is not used anywhere. * * @param param * @return * @throws LocalizedException * @author Tarik.Mikyas * @return_type List<String> * @since 11 January 2016 10:45:10 */ public List<Property> getPropertyListByValue(String value) throws LocalizedException; /** * Returns the Property object dependent on the parameters. * * @param name * @param parameter * @return * @throws LocalizedException * @author Tarik.Mikyas * @since 22 June 2016 10:33:44 */ public Property getPropertyByNameAndParameter(String name, String parameter) throws LocalizedException; /** * @param name * @param parameter * @param useLike If TRUE, it returns the parameter value (like "parameter%"). If FALSE is given, it is dialed with "=". * @return * @throws LocalizedException * @author Ahmet.Izgi */ public List<Property> getPropertyListByCriteria(String name, String parameter, boolean useLike) throws LocalizedException; /** * this method getPropertyListByName <br> * * @param name * @return <br> * @throws LocalizedException * @author Canberk.Erkmen */ public List<Property> getPropertyListByName(String name) throws LocalizedException; public String getTestcaseFolder(Integer testCaseId) throws LocalizedException; public List<Property> redefinePropertyList(List<Property> propertyList, List<Property> propertyListInDB); }
2,539
0.702245
0.68334
78
31.551283
33.29266
126
false
false
0
0
0
0
0
0
0.282051
false
false
10
2aa9d4824985521f09e22f49eb6aeda452ef4f9e
10,496,900,085,455
58a61c6cc6542ad6ad1b4a0edbaedbf44b993885
/ex65.java
57be180fe12a734f120c77cd68801b08383c3b42
[]
no_license
lasemyung/java-Academy
https://github.com/lasemyung/java-Academy
5d0fc605e6ae785ce8fbbd409fb1543aaeffc623
0a28ecbfd1e15650c3dc1ed2f603138ef2034477
refs/heads/main
2023-06-03T05:30:59.211000
2021-07-02T12:01:32
2021-07-02T12:01:32
380,177,713
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package examples; public class ex65 { public static void main(String[] args) { // 함수 안에서 함수를 정의할 수 없다! // 함수의 4가지 패턴 // 1. 매개변수 X, 반환형 X func1(); // 2. 매개변수 O, 반환형 X func2(20); // 3. 매개변수 X, 반환형 O // int result = func3(); System.out.println("반환값:" + result); // 4. 매개변수 O, 반환형 O result = func4(20); System.out.println("반환값:" + result); } // static 예약어 : 정적 변수(함수)를 정의하고, // 램메모리에 적재될때, 일정한 메모리(static)에 올라가고, // 그 주소에 프로그램종료시까지 동일한 주소에 머문다. // static 함수에서 static함수만 호출가능하다. // void 반환형이 없다는 뜻 static void func1() { System.out.println("func1() 호출됨"); return; } static void func2(int param) { System.out.println("func2() 호출됨 : " + param); return; } static int func3() { System.out.println("func3() 호출됨"); return 10; } static int func4(int param) { System.out.println("func4() 호출됨 : " + param); return param; } }
UHC
Java
1,205
java
ex65.java
Java
[]
null
[]
package examples; public class ex65 { public static void main(String[] args) { // 함수 안에서 함수를 정의할 수 없다! // 함수의 4가지 패턴 // 1. 매개변수 X, 반환형 X func1(); // 2. 매개변수 O, 반환형 X func2(20); // 3. 매개변수 X, 반환형 O // int result = func3(); System.out.println("반환값:" + result); // 4. 매개변수 O, 반환형 O result = func4(20); System.out.println("반환값:" + result); } // static 예약어 : 정적 변수(함수)를 정의하고, // 램메모리에 적재될때, 일정한 메모리(static)에 올라가고, // 그 주소에 프로그램종료시까지 동일한 주소에 머문다. // static 함수에서 static함수만 호출가능하다. // void 반환형이 없다는 뜻 static void func1() { System.out.println("func1() 호출됨"); return; } static void func2(int param) { System.out.println("func2() 호출됨 : " + param); return; } static int func3() { System.out.println("func3() 호출됨"); return 10; } static int func4(int param) { System.out.println("func4() 호출됨 : " + param); return param; } }
1,205
0.5747
0.547437
45
18.422222
14.322459
47
false
false
0
0
0
0
0
0
1.777778
false
false
10
3e3e1279845ca21522d57d31b22a375ccfe1ee4d
8,735,963,481,240
ff52bbb9a1b0a35887f9b92ba4988b4686ac783d
/src/test/java/com/kakao/minsub/spring/jpa/SpringJdbcTest.java
c635c7d68f8555369196c8acf7f0593749cca836
[]
no_license
Minsub/SpringStudy
https://github.com/Minsub/SpringStudy
22226941b83db8fe89047af28704779b26e02877
6d50aea2711352870498207ac5231ae25a624236
refs/heads/master
2021-01-01T17:46:05.776000
2019-01-21T01:45:00
2019-01-21T01:45:00
98,152,412
0
0
null
false
2019-01-09T08:05:37
2017-07-24T05:33:03
2019-01-09T07:42:44
2019-01-09T08:05:37
4,409
0
0
0
JavaScript
false
null
package com.kakao.minsub.spring.jpa; import com.kakao.minsub.spring.config.db.LocalMysqlConfig; import com.kakao.minsub.spring.model.Profile; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.JdbcTest; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @JdbcTest @ContextConfiguration(classes = {LocalMysqlConfig.class}) @ActiveProfiles("development") public class SpringJdbcTest { @Autowired private JdbcTemplate jdbcTemplate; @Test public void jdbcTest() { Profile profile = jdbcTemplate.queryForObject("select * from profiles where id=1", Profile.class); System.err.println(profile); } }
UTF-8
Java
967
java
SpringJdbcTest.java
Java
[]
null
[]
package com.kakao.minsub.spring.jpa; import com.kakao.minsub.spring.config.db.LocalMysqlConfig; import com.kakao.minsub.spring.model.Profile; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.JdbcTest; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @JdbcTest @ContextConfiguration(classes = {LocalMysqlConfig.class}) @ActiveProfiles("development") public class SpringJdbcTest { @Autowired private JdbcTemplate jdbcTemplate; @Test public void jdbcTest() { Profile profile = jdbcTemplate.queryForObject("select * from profiles where id=1", Profile.class); System.err.println(profile); } }
967
0.795243
0.793175
27
34.814816
25.324614
106
false
false
0
0
0
0
0
0
0.555556
false
false
10
3ad9a3f8f9be97a55e0fcbe1359ce2fdecaa6cd2
1,640,677,531,741
32e6ba2a34acf6ab16f36d15e3181d4a6af552a4
/czy-mall/src/main/java/clouddev/com/czy/mall/ui/main/search/SearchFragment.java
b141f9a304f18a7fa96b8c4a4c73ebf3e23dd603
[]
no_license
ToadKing1926/mall
https://github.com/ToadKing1926/mall
45417beb7778a9420fee7bb57722115f8db12d52
4b66f78f5c39a4d98505e08b25187d7d75a0ad98
refs/heads/master
2021-04-25T04:07:33.748000
2018-06-19T12:58:29
2018-06-19T12:58:29
114,882,906
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package clouddev.com.czy.mall.ui.main.search; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.EditText; import com.alibaba.fastjson.JSON; import com.blankj.utilcode.util.StringUtils; import com.choices.divider.Divider; import com.choices.divider.DividerItemDecoration; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.OnClick; import clouddev.com.czy.fragment.CoreFragment; import clouddev.com.czy.mall.R; import clouddev.com.czy.mall.R2; import clouddev.com.czy.mall.converter.SearchDataConverter; import clouddev.com.czy.storage.appPreference; import clouddev.com.czy.ui.recycler.DividerLookupImpl; import clouddev.com.czy.ui.recycler.MultipleItemEntity; import clouddev.com.czy.util.callback.CallBackManager; import clouddev.com.czy.util.callback.CallBackType; import clouddev.com.czy.util.callback.iGlobalCallback; /** * Created by 29737 */ public class SearchFragment extends CoreFragment { @BindView(R2.id.rv_search) RecyclerView mRecyclerView = null; @BindView(R2.id.et_search_view) EditText mEditText = null; private boolean isSearched = false; @OnClick(R2.id.tv_top_search) void onClickSearch() { //TODO:请求服务器 final String searchItemText = mEditText.getText().toString(); if(!isSearched) { saveItem(searchItemText); } isSearched = false; getSupportDelegate().pop(); } @OnClick(R2.id.icon_top_search_back) void onClickBack() { getSupportDelegate().pop(); } private void saveItem(String item) { if(!StringUtils.isEmpty(item) && !StringUtils.isSpace(item)) { List<String> history; final String historyItem = appPreference.getCustomAppProfile("search_history"); if(StringUtils.isEmpty(historyItem)) { history = new ArrayList<>(); } else { history = JSON.parseObject(historyItem,ArrayList.class); } history.add(item); final String json = JSON.toJSONString(history); appPreference.addCustomAppProfile("search_history",json); } } @Override public Object setLayout() { return R.layout.search_fragment; } @Override public void onBindView(@Nullable Bundle savedInstanceState, View rootView) { final LinearLayoutManager manager = new LinearLayoutManager(getContext()); mRecyclerView.setLayoutManager(manager); final List<MultipleItemEntity> data = new SearchDataConverter().convert(); final SearchAdapter adapter = new SearchAdapter(data); mRecyclerView.setAdapter(adapter); mRecyclerView.addOnItemTouchListener(new SearchClickListener()); CallBackManager.getInstance().addCallback(CallBackType.SEARCH, new iGlobalCallback<String>() { @Override public void executeCallback(String args) { mEditText.setText(args); mRecyclerView.setVisibility(View.INVISIBLE); isSearched = true; } }); final DividerItemDecoration itemDecoration = new DividerItemDecoration(); itemDecoration.setDividerLookup(new DividerItemDecoration.DividerLookup() { @Override public Divider getVerticalDivider(int position) { return null; } @Override public Divider getHorizontalDivider(int position) { return new Divider.Builder() .size(2) .margin(20,20) .color(Color.GRAY) .build(); } }); mRecyclerView.addItemDecoration(itemDecoration); } }
UTF-8
Java
4,142
java
SearchFragment.java
Java
[]
null
[]
package clouddev.com.czy.mall.ui.main.search; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.EditText; import com.alibaba.fastjson.JSON; import com.blankj.utilcode.util.StringUtils; import com.choices.divider.Divider; import com.choices.divider.DividerItemDecoration; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.OnClick; import clouddev.com.czy.fragment.CoreFragment; import clouddev.com.czy.mall.R; import clouddev.com.czy.mall.R2; import clouddev.com.czy.mall.converter.SearchDataConverter; import clouddev.com.czy.storage.appPreference; import clouddev.com.czy.ui.recycler.DividerLookupImpl; import clouddev.com.czy.ui.recycler.MultipleItemEntity; import clouddev.com.czy.util.callback.CallBackManager; import clouddev.com.czy.util.callback.CallBackType; import clouddev.com.czy.util.callback.iGlobalCallback; /** * Created by 29737 */ public class SearchFragment extends CoreFragment { @BindView(R2.id.rv_search) RecyclerView mRecyclerView = null; @BindView(R2.id.et_search_view) EditText mEditText = null; private boolean isSearched = false; @OnClick(R2.id.tv_top_search) void onClickSearch() { //TODO:请求服务器 final String searchItemText = mEditText.getText().toString(); if(!isSearched) { saveItem(searchItemText); } isSearched = false; getSupportDelegate().pop(); } @OnClick(R2.id.icon_top_search_back) void onClickBack() { getSupportDelegate().pop(); } private void saveItem(String item) { if(!StringUtils.isEmpty(item) && !StringUtils.isSpace(item)) { List<String> history; final String historyItem = appPreference.getCustomAppProfile("search_history"); if(StringUtils.isEmpty(historyItem)) { history = new ArrayList<>(); } else { history = JSON.parseObject(historyItem,ArrayList.class); } history.add(item); final String json = JSON.toJSONString(history); appPreference.addCustomAppProfile("search_history",json); } } @Override public Object setLayout() { return R.layout.search_fragment; } @Override public void onBindView(@Nullable Bundle savedInstanceState, View rootView) { final LinearLayoutManager manager = new LinearLayoutManager(getContext()); mRecyclerView.setLayoutManager(manager); final List<MultipleItemEntity> data = new SearchDataConverter().convert(); final SearchAdapter adapter = new SearchAdapter(data); mRecyclerView.setAdapter(adapter); mRecyclerView.addOnItemTouchListener(new SearchClickListener()); CallBackManager.getInstance().addCallback(CallBackType.SEARCH, new iGlobalCallback<String>() { @Override public void executeCallback(String args) { mEditText.setText(args); mRecyclerView.setVisibility(View.INVISIBLE); isSearched = true; } }); final DividerItemDecoration itemDecoration = new DividerItemDecoration(); itemDecoration.setDividerLookup(new DividerItemDecoration.DividerLookup() { @Override public Divider getVerticalDivider(int position) { return null; } @Override public Divider getHorizontalDivider(int position) { return new Divider.Builder() .size(2) .margin(20,20) .color(Color.GRAY) .build(); } }); mRecyclerView.addItemDecoration(itemDecoration); } }
4,142
0.637464
0.633349
134
29.835821
24.04945
100
false
false
0
0
0
0
0
0
0.462687
false
false
10
0a53a53e36abc27926eeb77cb6602660ed809eba
20,907,900,797,110
2f5741a4d185dd5164f8605baad395783e20f1a2
/main/java/com/gildedgames/aether/common/entities/living/EntityAerbunny.java
ddb1c0f0db355bf28bb123371f7d981a6f83b446
[]
no_license
liuminghao233/Aether2-Rewrite
https://github.com/liuminghao233/Aether2-Rewrite
3d0265be504d9de92d63905b4f65e5244d544ac6
d4d74123e3fb04f333be081f3522b9882e6b5d27
refs/heads/master
2016-09-18T10:09:43.119000
2016-08-29T04:25:20
2016-08-29T04:25:20
66,775,774
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gildedgames.aether.common.entities.living; import com.gildedgames.aether.common.AetherCore; import com.gildedgames.aether.common.SoundsAether; import com.gildedgames.aether.common.blocks.BlocksAether; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityAgeable; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.*; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.pathfinding.PathNavigate; import net.minecraft.pathfinding.PathNavigateGround; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class EntityAerbunny extends EntityAetherAnimal { @SideOnly(Side.CLIENT) private double prevMotionY; @SideOnly(Side.CLIENT) private int puffiness; public EntityAerbunny(World world) { super(world); this.tasks.addTask(1, new EntityAISwimming(this)); this.tasks.addTask(3, new EntityAIMate(this, 1.0D)); this.tasks.addTask(4, new EntityAIAvoidEntity<>(this, EntityPlayer.class, 12.0F, 1.2F, 1.8F)); this.tasks.addTask(5, new EntityAIWander(this, 1.0D)); this.tasks.addTask(11, new EntityAIWatchClosest(this, EntityPlayer.class, 10.0F)); this.jumpHelper = new AerbunnyJumpHelper(this); this.spawnableBlock = BlocksAether.aether_grass; this.setSize(0.65F, 0.65F); } @Override protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(0.3D); this.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(5); } @Override public void onUpdate() { super.onUpdate(); if (this.worldObj.isRemote) { if (this.puffiness > 0) { this.puffiness--; } if (this.prevMotionY <= 0 && this.motionY > 0) { BlockPos pos = this.getPosition(); // Make sure we only spawn particles when it's jumping off a block if (this.worldObj.isBlockFullCube(pos.down())) { AetherCore.PROXY.spawnJumpParticles(this.worldObj, this.posX, pos.getY() + 0.1D, this.posZ, 0.6D, 6); } this.puffiness = 10; } this.prevMotionY = this.motionY; } if (this.isRiding()) { Entity entity = this.getRidingEntity(); if (entity.isSneaking() && entity.onGround) { this.dismountRidingEntity(); } if (entity.motionY < 0) { entity.motionY *= entity.isSneaking() ? 0.9D : 0.7D; entity.fallDistance = 0; } this.setRotation(entity.rotationYaw, entity.rotationPitch); } if (this.motionY < -0.1D) { this.motionY = -0.1D; } this.fallDistance = 0.0F; } @Override public EnumActionResult applyPlayerInteraction(EntityPlayer player, Vec3d vec, ItemStack stack, EnumHand hand) { this.worldObj.playSound(player, player.getPosition(), SoundsAether.aerbunny_lift, SoundCategory.NEUTRAL, 1.0F, 0.8F + (this.rand.nextFloat() * 0.5F)); if (!this.isRiding()) { this.startRiding(player, true); AetherCore.PROXY.displayDismountMessage(); return EnumActionResult.SUCCESS; } return super.applyPlayerInteraction(player, vec, stack, hand); } @Override public double getYOffset() { return this.getRidingEntity() != null ? 0.45D : 0.0D; } @Override public Item getDropItem() { return Items.STRING; } @Override protected SoundEvent getAmbientSound() { return SoundsAether.aerbunny_ambient; } @Override protected SoundEvent getHurtSound() { return SoundsAether.aerbunny_hurt; } @Override protected SoundEvent getDeathSound() { return SoundsAether.aerbunny_death; } @Override protected PathNavigate getNewNavigator(World worldIn) { return new AerbunnyNavigator(this, worldIn); } @Override public EntityAgeable createChild(EntityAgeable ageable) { return new EntityAerbunny(this.worldObj); } private class AerbunnyJumpHelper extends EntityJumpHelper { private EntityLiving entity; public AerbunnyJumpHelper(EntityAerbunny entity) { super(entity); this.entity = entity; } public void doJump() { this.entity.setJumping(true); } } private class AerbunnyNavigator extends PathNavigateGround { public AerbunnyNavigator(EntityLiving entity, World world) { super(entity, world); } @Override protected boolean canNavigate() { return !this.theEntity.isRiding(); } } @SideOnly(Side.CLIENT) public int getPuffiness() { return this.puffiness; } @Override public boolean canRiderInteract() { return true; } }
UTF-8
Java
4,879
java
EntityAerbunny.java
Java
[]
null
[]
package com.gildedgames.aether.common.entities.living; import com.gildedgames.aether.common.AetherCore; import com.gildedgames.aether.common.SoundsAether; import com.gildedgames.aether.common.blocks.BlocksAether; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityAgeable; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.*; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.pathfinding.PathNavigate; import net.minecraft.pathfinding.PathNavigateGround; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class EntityAerbunny extends EntityAetherAnimal { @SideOnly(Side.CLIENT) private double prevMotionY; @SideOnly(Side.CLIENT) private int puffiness; public EntityAerbunny(World world) { super(world); this.tasks.addTask(1, new EntityAISwimming(this)); this.tasks.addTask(3, new EntityAIMate(this, 1.0D)); this.tasks.addTask(4, new EntityAIAvoidEntity<>(this, EntityPlayer.class, 12.0F, 1.2F, 1.8F)); this.tasks.addTask(5, new EntityAIWander(this, 1.0D)); this.tasks.addTask(11, new EntityAIWatchClosest(this, EntityPlayer.class, 10.0F)); this.jumpHelper = new AerbunnyJumpHelper(this); this.spawnableBlock = BlocksAether.aether_grass; this.setSize(0.65F, 0.65F); } @Override protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(0.3D); this.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(5); } @Override public void onUpdate() { super.onUpdate(); if (this.worldObj.isRemote) { if (this.puffiness > 0) { this.puffiness--; } if (this.prevMotionY <= 0 && this.motionY > 0) { BlockPos pos = this.getPosition(); // Make sure we only spawn particles when it's jumping off a block if (this.worldObj.isBlockFullCube(pos.down())) { AetherCore.PROXY.spawnJumpParticles(this.worldObj, this.posX, pos.getY() + 0.1D, this.posZ, 0.6D, 6); } this.puffiness = 10; } this.prevMotionY = this.motionY; } if (this.isRiding()) { Entity entity = this.getRidingEntity(); if (entity.isSneaking() && entity.onGround) { this.dismountRidingEntity(); } if (entity.motionY < 0) { entity.motionY *= entity.isSneaking() ? 0.9D : 0.7D; entity.fallDistance = 0; } this.setRotation(entity.rotationYaw, entity.rotationPitch); } if (this.motionY < -0.1D) { this.motionY = -0.1D; } this.fallDistance = 0.0F; } @Override public EnumActionResult applyPlayerInteraction(EntityPlayer player, Vec3d vec, ItemStack stack, EnumHand hand) { this.worldObj.playSound(player, player.getPosition(), SoundsAether.aerbunny_lift, SoundCategory.NEUTRAL, 1.0F, 0.8F + (this.rand.nextFloat() * 0.5F)); if (!this.isRiding()) { this.startRiding(player, true); AetherCore.PROXY.displayDismountMessage(); return EnumActionResult.SUCCESS; } return super.applyPlayerInteraction(player, vec, stack, hand); } @Override public double getYOffset() { return this.getRidingEntity() != null ? 0.45D : 0.0D; } @Override public Item getDropItem() { return Items.STRING; } @Override protected SoundEvent getAmbientSound() { return SoundsAether.aerbunny_ambient; } @Override protected SoundEvent getHurtSound() { return SoundsAether.aerbunny_hurt; } @Override protected SoundEvent getDeathSound() { return SoundsAether.aerbunny_death; } @Override protected PathNavigate getNewNavigator(World worldIn) { return new AerbunnyNavigator(this, worldIn); } @Override public EntityAgeable createChild(EntityAgeable ageable) { return new EntityAerbunny(this.worldObj); } private class AerbunnyJumpHelper extends EntityJumpHelper { private EntityLiving entity; public AerbunnyJumpHelper(EntityAerbunny entity) { super(entity); this.entity = entity; } public void doJump() { this.entity.setJumping(true); } } private class AerbunnyNavigator extends PathNavigateGround { public AerbunnyNavigator(EntityLiving entity, World world) { super(entity, world); } @Override protected boolean canNavigate() { return !this.theEntity.isRiding(); } } @SideOnly(Side.CLIENT) public int getPuffiness() { return this.puffiness; } @Override public boolean canRiderInteract() { return true; } }
4,879
0.738061
0.724944
217
21.483871
24.715729
152
false
false
0
0
0
0
0
0
1.778802
false
false
10
b7c8db0bf5a081e96b35f15e50f5897244537295
13,116,830,148,818
3a5985651d77a31437cfdac25e594087c27e93d6
/driver-tests/bpelse/scalability/ScalabilityStandAloneTestClient/src/driver/Worker.java
89c6ff644010f006c3e5a683edc0a58a66ea4dff
[]
no_license
vitalif/openesb-components
https://github.com/vitalif/openesb-components
a37d62133d81edb3fdc091abd5c1d72dbe2fc736
560910d2a1fdf31879e3d76825edf079f76812c7
refs/heads/master
2023-09-04T14:40:55.665000
2016-01-25T13:12:22
2016-01-25T13:12:33
48,222,841
0
5
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * BEGIN_HEADER - DO NOT EDIT * * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. * If applicable add the following below this CDDL HEADER, * with the fields enclosed by brackets "[]" replaced with * your own identifying information: Portions Copyright * [year] [name of copyright owner] */ /* * @(#)EngineChannel.java * * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved. * * END_HEADER - DO NOT EDIT */ package driver; /** * @author mbhasin * */ class Worker implements Runnable { private MessageSender sender = null; int threadId = 1; /** * @param driver * @param iterations */ public Worker(MessageSender driver, int threadId) { this.sender = driver; this.threadId = threadId; } public void run() { int i = 0; try { sender.runTest(threadId); } catch (Exception e) { System.out.println("Ran into exceptions at count " + i); e.printStackTrace(); } } }
UTF-8
Java
1,575
java
Worker.java
Java
[ { "context": "- DO NOT EDIT\n */\n\npackage driver;\n\n/**\n * @author mbhasin\n *\n */\nclass Worker implements Runnable {\n \n ", "end": 1019, "score": 0.9871414303779602, "start": 1012, "tag": "USERNAME", "value": "mbhasin" } ]
null
[]
/* * BEGIN_HEADER - DO NOT EDIT * * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. * If applicable add the following below this CDDL HEADER, * with the fields enclosed by brackets "[]" replaced with * your own identifying information: Portions Copyright * [year] [name of copyright owner] */ /* * @(#)EngineChannel.java * * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved. * * END_HEADER - DO NOT EDIT */ package driver; /** * @author mbhasin * */ class Worker implements Runnable { private MessageSender sender = null; int threadId = 1; /** * @param driver * @param iterations */ public Worker(MessageSender driver, int threadId) { this.sender = driver; this.threadId = threadId; } public void run() { int i = 0; try { sender.runTest(threadId); } catch (Exception e) { System.out.println("Ran into exceptions at count " + i); e.printStackTrace(); } } }
1,575
0.650794
0.641905
60
25.25
22.020161
68
false
false
0
0
0
0
0
0
0.216667
false
false
10
83d0d7af9e0f422249d8c66d04be7dd99692af25
22,617,297,801,879
08adfaadba127826f75c560234744f85df00258c
/songsir-bean/src/java/com/songsir/bean/TestBean.java
0a9060b1d97ad069770b5436b3b0d4b2a14082e8
[]
no_license
songsir01/songsir-demoboot
https://github.com/songsir01/songsir-demoboot
89af677d5b30ebcfe16759d781228f0740f936a6
eac2191d8743b830d283aedf973b9784ada43065
refs/heads/master
2022-12-10T04:34:31.894000
2022-12-08T01:00:26
2022-12-08T01:00:26
159,476,932
10
3
null
false
2022-12-08T01:00:28
2018-11-28T09:31:37
2022-04-15T07:37:43
2022-12-08T01:00:27
3,271
8
3
0
Java
false
false
package com.songsir.bean; /** * @PackageName com.songsir.bean * @ProjectName songsir-demoboot * @Author: SongYapeng * @Date: Create in 10:39 2018/12/17 * @Description: * @Copyright Copyright (c) 2018, songyapeng@shopin.cn All Rights Reserved. */ public class TestBean { private String $name; private String $age; public String get$name() { return $name; } public void set$name(String $name) { this.$name = $name; } public String get$age() { return $age; } public void set$age(String $age) { this.$age = $age; } @Override public String toString() { return "TestBean{" + "$name='" + $name + '\'' + ", $age='" + $age + '\'' + '}'; } }
UTF-8
Java
787
java
TestBean.java
Java
[ { "context": ".bean\n * @ProjectName songsir-demoboot\n * @Author: SongYapeng\n * @Date: Create in 10:39 2018/12/17\n * @Descript", "end": 119, "score": 0.9998427629470825, "start": 109, "tag": "NAME", "value": "SongYapeng" }, { "context": " * @Description:\n * @Copyright Copyright (c) 2018, songyapeng@shopin.cn All Rights Reserved.\n */\npublic class TestBean {\n", "end": 228, "score": 0.9999319911003113, "start": 208, "tag": "EMAIL", "value": "songyapeng@shopin.cn" } ]
null
[]
package com.songsir.bean; /** * @PackageName com.songsir.bean * @ProjectName songsir-demoboot * @Author: SongYapeng * @Date: Create in 10:39 2018/12/17 * @Description: * @Copyright Copyright (c) 2018, <EMAIL> All Rights Reserved. */ public class TestBean { private String $name; private String $age; public String get$name() { return $name; } public void set$name(String $name) { this.$name = $name; } public String get$age() { return $age; } public void set$age(String $age) { this.$age = $age; } @Override public String toString() { return "TestBean{" + "$name='" + $name + '\'' + ", $age='" + $age + '\'' + '}'; } }
774
0.532402
0.512071
40
18.674999
16.597271
75
false
false
0
0
0
0
0
0
0.25
false
false
10
0543ad20d8a97ba3cbb07c4d9091d172f95296b2
25,254,407,719,585
9eb28641834a745d4f83ab2cbe78ce87b4319641
/src/concurrent/ReentrantLockTest.java
8180746fbed147f6d55a4667029b6c890c19e104
[]
no_license
s12345sk/testJava
https://github.com/s12345sk/testJava
a6499396ad0e57fc189e8b49d959dffc9635445d
a6b82199c8a7488e32f84d6a249e692f957c3b09
refs/heads/master
2021-01-18T18:25:28.772000
2015-05-11T03:26:47
2015-05-11T03:26:47
35,085,741
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * @Title: ReentrantLockTest.java * @Package concurrent * @Description: TODO(用一句话描述该文件做什么) * @author:kang.sun1@renren-inc.com * @date 2014-9-23 下午8:23:06 * @version V1.0 */ package concurrent; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.ReentrantLock; /** * @author renren * */ public class ReentrantLockTest extends Thread { private Lock chicken; private String userName; public ReentrantLockTest(String userName,Lock chicken){ this.userName = userName; this.chicken = chicken; } public void run(){ chicken.print(userName); } public static void main(String[] args) { // TODO Auto-generated method stub ExecutorService es = Executors.newFixedThreadPool(3); Lock chicken = new Lock(); for(int i=0;i<10;i++) es.execute(new ReentrantLockTest("pk:"+i,chicken)); es.shutdown(); } } /** * 这其实相当于是一个互斥类,一个上完以后,才能第二个上。 * 噗- -我邪恶了。 * 一次只能一个人用。所以可以用传参的方式,来获取每个使用者的特色。 * @author renren * */ class Lock{ private ReentrantLock lock = new ReentrantLock() ; // private int id; // public Lock(int id,ReentrantLock lock){ // this.id = id; // this.lock = lock; // } public void print(String userName){ System.out.println(userName+"before :the chicken is fu?"+lock.isLocked()+" "+lock.getHoldCount()); lock.lock(); // lock.lock(); System.out.println(userName+"after :the chicken is fu?"+lock.isLocked()+" "+lock.getHoldCount()); try{ System.out.println(userName+" fu happy now!"); Thread.sleep(1000); }catch(Exception e){ e.printStackTrace(); }finally{ lock.unlock(); } } }
UTF-8
Java
1,822
java
ReentrantLockTest.java
Java
[ { "context": "nt \n* @Description: TODO(用一句话描述该文件做什么) \n* @author:kang.sun1@renren-inc.com \n* @date 2014-9-23 下午8:23:06 \n* @version V1.0 ", "end": 134, "score": 0.9999169707298279, "start": 110, "tag": "EMAIL", "value": "kang.sun1@renren-inc.com" }, { "context": "il.concurrent.locks.ReentrantLock;\n\n/**\n * @author renren\n *\n */\npublic class ReentrantLockTest extends Thr", "end": 404, "score": 0.9995146989822388, "start": 398, "tag": "USERNAME", "value": "renren" }, { "context": "t(String userName,Lock chicken){\n\t\tthis.userName = userName;\n\t\tthis.chicken = chicken;\n\t}\n\tpublic void run(){", "end": 592, "score": 0.9787113070487976, "start": 584, "tag": "USERNAME", "value": "userName" }, { "context": "恶了。\n * 一次只能一个人用。所以可以用传参的方式,来获取每个使用者的特色。\n * @author renren\n *\n */\nclass Lock{\n\tprivate ReentrantLock lock = ", "end": 1047, "score": 0.9994688034057617, "start": 1041, "tag": "USERNAME", "value": "renren" }, { "context": "ock.lock();\n//\t\tlock.lock();\n\t\tSystem.out.println(userName+\"after :the chicken is fu?\"+lock.isLocked()+\" \"+l", "end": 1425, "score": 0.5399324893951416, "start": 1417, "tag": "USERNAME", "value": "userName" } ]
null
[]
/** * @Title: ReentrantLockTest.java * @Package concurrent * @Description: TODO(用一句话描述该文件做什么) * @author:<EMAIL> * @date 2014-9-23 下午8:23:06 * @version V1.0 */ package concurrent; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.ReentrantLock; /** * @author renren * */ public class ReentrantLockTest extends Thread { private Lock chicken; private String userName; public ReentrantLockTest(String userName,Lock chicken){ this.userName = userName; this.chicken = chicken; } public void run(){ chicken.print(userName); } public static void main(String[] args) { // TODO Auto-generated method stub ExecutorService es = Executors.newFixedThreadPool(3); Lock chicken = new Lock(); for(int i=0;i<10;i++) es.execute(new ReentrantLockTest("pk:"+i,chicken)); es.shutdown(); } } /** * 这其实相当于是一个互斥类,一个上完以后,才能第二个上。 * 噗- -我邪恶了。 * 一次只能一个人用。所以可以用传参的方式,来获取每个使用者的特色。 * @author renren * */ class Lock{ private ReentrantLock lock = new ReentrantLock() ; // private int id; // public Lock(int id,ReentrantLock lock){ // this.id = id; // this.lock = lock; // } public void print(String userName){ System.out.println(userName+"before :the chicken is fu?"+lock.isLocked()+" "+lock.getHoldCount()); lock.lock(); // lock.lock(); System.out.println(userName+"after :the chicken is fu?"+lock.isLocked()+" "+lock.getHoldCount()); try{ System.out.println(userName+" fu happy now!"); Thread.sleep(1000); }catch(Exception e){ e.printStackTrace(); }finally{ lock.unlock(); } } }
1,805
0.691106
0.677284
73
21.794521
20.858925
100
false
false
0
0
0
0
0
0
1.369863
false
false
10
d7e614dc2ebe128296153ffa57ee4de59ca811c5
5,927,054,896,126
ec2ce86c99924c14b5a6a3d9b082fbb82ea6e670
/src/main/java/solution/ImplemPolynomial.java
74defddf15390c8e2cc57c27b539bc5e1a18c9a0
[]
no_license
Disteonne/The-zeroes-of-the-function_v1.2
https://github.com/Disteonne/The-zeroes-of-the-function_v1.2
7c3e7bcaeda734fadf046a88f170a9ad37b7a41b
0225beadac529d11a57d2b78a34e67b9d2e050d3
refs/heads/master
2022-12-02T11:31:41.421000
2020-08-23T19:42:27
2020-08-23T19:42:27
289,553,901
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package solution; import javax.swing.plaf.synth.SynthLookAndFeel; import java.util.Scanner; public class ImplemPolynomial implements polynomial { private double left_a, right_b; private int n; private int[] c = new int[11]; //max-10 степень, следовательно,11 коэфф.+1 на запас // double res1,res; /* * КОНСТРУКТОР */ void getNumbers () throws ArrayIndexOutOfBoundsException{ System.out.println("Инициализация полинома..."); System.out.println("Введите интервал рассмотрения функции."); Scanner scanner = new Scanner(System.in); this.left_a = scanner.nextDouble(); this.right_b = scanner.nextDouble(); System.out.println("Введите наибольшую степень многочлена из max-возможной величины." + "Максимальная степень многочлена равна 10."); this.n = scanner.nextInt(); System.out.println("Замечательно! Правда сказать,мы еще не проверили введенные Вами данные,но " + "нам необходимо,чтобы вы заполнили следующие коээфициэнты..."); System.out.println("Введите коэффициенты многочлена." + "К примеру, c[0]-коэффициент,стоящий перед x в степени 0."); for (int i = 0; i <= n; i++) { System.out.print("c[" + i + "] = "); c[i] = scanner.nextInt(); System.out.println(); } } /* ImplemPolynomial() { System.out.println("Инициализация полинома..."); System.out.println("Введите интервал рассмотрения функции."); Scanner scanner = new Scanner(System.in); this.left_a = scanner.nextDouble(); this.right_b = scanner.nextDouble(); System.out.println("Введите наибольшую степень многочлена из max-возможной величины." + "Максимальная степень многочлена равна 10."); this.n = scanner.nextInt(); System.out.println("Замечательно! Правда сказать,мы еще не проверили введенные Вами данные,но " + "нам необходимо,чтобы вы заполнили следующие коээфициэнты..."); System.out.println("Введите коэффициенты многочлена." + "К примеру, c[0]-коэффициент,стоящий перед x в степени 0."); try { for (int i = 0; i <= n; i++) { System.out.print("c[" + i + "] = "); c[i] = scanner.nextInt(); System.out.println(); } } catch (ArrayIndexOutOfBoundsException ex) { System.out.println("Проггер этой проги-даунич! :("); } } */ /* ImplemPolynomial(double left_a,double right_b){ this.left_a=left_a; this.right_b=right_b; this.n=5; c[0]=4; c[1]=2; c[2]=-4; c[3]=-3; c[4]=0; c[5]=1; } /* * * ГЕТТЕРЫ/СЕТТЕРЫ * */ public void setLeft_a(double left_a) { this.left_a = left_a; } public double getLeft_a() { return left_a; } public double getRight_b() { return right_b; } public void setRight_b(double right_b) { this.right_b = right_b; } public void setC(int[] c) { this.c = c; } public int[] getC() { return c; } public void setN(int n) { this.n = n; } public int getN() { return n; } /* * Проверка гранчных значений интерв. и введенной степени */ public void checkBorder() { try { double tmp = 0; if (left_a > right_b) { tmp = left_a; left_a = right_b; right_b = tmp; } else if (left_a == right_b) { throw new ExEqualityBorders(); } } catch (ExEqualityBorders ex) { System.out.println("- - -"); } } public boolean checkPower() { if(n<0 && n>10){ System.out.println("Упс! Но максимально значение меньше 10...и больше 0!"); return false; } return true; } public void printBored() { System.out.println("Проверка пройдена." + "Введенный Вами интервал:" + "[" + left_a + " : " + right_b + "]"); } public double getPolynomial(double approx) { double res = 0; for (int i = 0; i <= n; i++) { res += c[i] * Math.pow(approx, i); } return res; } public double getOneDiffPolynomial(double approx) { double res1=0; for (int i = 1; i <= n; i++) { res1 += c[i] *i* Math.pow(approx, i-1); } return res1; } public double getTwoDiffPolynomial(double approx) { double res2=0; for (int i = 2; i <= n; i++) { res2 += c[i] *i*(i-1)*Math.pow(approx, i-2); } return res2; } }
UTF-8
Java
5,752
java
ImplemPolynomial.java
Java
[]
null
[]
package solution; import javax.swing.plaf.synth.SynthLookAndFeel; import java.util.Scanner; public class ImplemPolynomial implements polynomial { private double left_a, right_b; private int n; private int[] c = new int[11]; //max-10 степень, следовательно,11 коэфф.+1 на запас // double res1,res; /* * КОНСТРУКТОР */ void getNumbers () throws ArrayIndexOutOfBoundsException{ System.out.println("Инициализация полинома..."); System.out.println("Введите интервал рассмотрения функции."); Scanner scanner = new Scanner(System.in); this.left_a = scanner.nextDouble(); this.right_b = scanner.nextDouble(); System.out.println("Введите наибольшую степень многочлена из max-возможной величины." + "Максимальная степень многочлена равна 10."); this.n = scanner.nextInt(); System.out.println("Замечательно! Правда сказать,мы еще не проверили введенные Вами данные,но " + "нам необходимо,чтобы вы заполнили следующие коээфициэнты..."); System.out.println("Введите коэффициенты многочлена." + "К примеру, c[0]-коэффициент,стоящий перед x в степени 0."); for (int i = 0; i <= n; i++) { System.out.print("c[" + i + "] = "); c[i] = scanner.nextInt(); System.out.println(); } } /* ImplemPolynomial() { System.out.println("Инициализация полинома..."); System.out.println("Введите интервал рассмотрения функции."); Scanner scanner = new Scanner(System.in); this.left_a = scanner.nextDouble(); this.right_b = scanner.nextDouble(); System.out.println("Введите наибольшую степень многочлена из max-возможной величины." + "Максимальная степень многочлена равна 10."); this.n = scanner.nextInt(); System.out.println("Замечательно! Правда сказать,мы еще не проверили введенные Вами данные,но " + "нам необходимо,чтобы вы заполнили следующие коээфициэнты..."); System.out.println("Введите коэффициенты многочлена." + "К примеру, c[0]-коэффициент,стоящий перед x в степени 0."); try { for (int i = 0; i <= n; i++) { System.out.print("c[" + i + "] = "); c[i] = scanner.nextInt(); System.out.println(); } } catch (ArrayIndexOutOfBoundsException ex) { System.out.println("Проггер этой проги-даунич! :("); } } */ /* ImplemPolynomial(double left_a,double right_b){ this.left_a=left_a; this.right_b=right_b; this.n=5; c[0]=4; c[1]=2; c[2]=-4; c[3]=-3; c[4]=0; c[5]=1; } /* * * ГЕТТЕРЫ/СЕТТЕРЫ * */ public void setLeft_a(double left_a) { this.left_a = left_a; } public double getLeft_a() { return left_a; } public double getRight_b() { return right_b; } public void setRight_b(double right_b) { this.right_b = right_b; } public void setC(int[] c) { this.c = c; } public int[] getC() { return c; } public void setN(int n) { this.n = n; } public int getN() { return n; } /* * Проверка гранчных значений интерв. и введенной степени */ public void checkBorder() { try { double tmp = 0; if (left_a > right_b) { tmp = left_a; left_a = right_b; right_b = tmp; } else if (left_a == right_b) { throw new ExEqualityBorders(); } } catch (ExEqualityBorders ex) { System.out.println("- - -"); } } public boolean checkPower() { if(n<0 && n>10){ System.out.println("Упс! Но максимально значение меньше 10...и больше 0!"); return false; } return true; } public void printBored() { System.out.println("Проверка пройдена." + "Введенный Вами интервал:" + "[" + left_a + " : " + right_b + "]"); } public double getPolynomial(double approx) { double res = 0; for (int i = 0; i <= n; i++) { res += c[i] * Math.pow(approx, i); } return res; } public double getOneDiffPolynomial(double approx) { double res1=0; for (int i = 1; i <= n; i++) { res1 += c[i] *i* Math.pow(approx, i-1); } return res1; } public double getTwoDiffPolynomial(double approx) { double res2=0; for (int i = 2; i <= n; i++) { res2 += c[i] *i*(i-1)*Math.pow(approx, i-2); } return res2; } }
5,752
0.522005
0.511206
180
26.26111
24.716698
105
false
false
0
0
0
0
0
0
0.533333
false
false
10
b423448307410951e58e12d3114193b84de29ce2
21,002,390,104,246
0c3dc3c60fdcfa62d7a30cf1b7394629a5305beb
/decorator/src/test/java/com/zero/DecoratorTest.java
7794832548b333b95f9a248dca11df5184064ac3
[]
no_license
iguilty/design-patterns
https://github.com/iguilty/design-patterns
e86827de579ddb30abdfea979b1854fb9cd28580
ff64e9c8df6c464f0108fe51af58f38e5b051c60
refs/heads/master
2020-05-20T00:54:37.080000
2019-05-09T02:16:07
2019-05-09T02:16:07
185,297,108
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zero; import com.zero.decorator.RedShapeDecorator; import com.zero.decorator.ShapeDecorator; import com.zero.shape.Circle; import com.zero.shape.Rectangle; import com.zero.shape.Shape; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class DecoratorTest { @Test public void testDecorator() { Shape rectangle=new Rectangle(); ShapeDecorator shapeDecorator1=new RedShapeDecorator(rectangle); shapeDecorator1.draw(); Shape circle=new Circle(); ShapeDecorator shapeDecorator2=new RedShapeDecorator(circle); shapeDecorator2.draw(); } }
UTF-8
Java
796
java
DecoratorTest.java
Java
[]
null
[]
package com.zero; import com.zero.decorator.RedShapeDecorator; import com.zero.decorator.ShapeDecorator; import com.zero.shape.Circle; import com.zero.shape.Rectangle; import com.zero.shape.Shape; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class DecoratorTest { @Test public void testDecorator() { Shape rectangle=new Rectangle(); ShapeDecorator shapeDecorator1=new RedShapeDecorator(rectangle); shapeDecorator1.draw(); Shape circle=new Circle(); ShapeDecorator shapeDecorator2=new RedShapeDecorator(circle); shapeDecorator2.draw(); } }
796
0.753769
0.747487
34
22.411764
21.600813
72
false
false
0
0
0
0
0
0
0.470588
false
false
10
ccc9120e0ef5b3b36273c4d063c155b4ac2a8ab7
39,444,979,675,193
43e5daf2f8838267a5ddb447e90f45b6e0c970a6
/trade/src/main/java/co/bitsquared/btceparser/trade/callbacks/CreateCouponCallback.java
c113ed20b411c350b36963d50ce625daf8a116fe
[]
no_license
rdadkins/BTCeParser
https://github.com/rdadkins/BTCeParser
3b5404206cc7812215d135b5c1f3ff9a70c214c4
c50b6a26efebc4e03ee4c181ceed4d7f3e146bcb
refs/heads/master
2021-01-21T04:50:36.850000
2016-06-23T23:42:01
2016-06-23T23:42:01
47,581,191
1
0
null
false
2016-05-21T22:28:25
2015-12-07T21:45:47
2016-03-04T14:01:56
2016-05-21T22:28:25
409
1
0
0
Java
null
null
package co.bitsquared.btceparser.trade.callbacks; import co.bitsquared.btceparser.trade.data.Funds; public interface CreateCouponCallback extends AccountCallback { void onSuccess(String coupon, long transactionID, Funds[] funds); }
UTF-8
Java
240
java
CreateCouponCallback.java
Java
[]
null
[]
package co.bitsquared.btceparser.trade.callbacks; import co.bitsquared.btceparser.trade.data.Funds; public interface CreateCouponCallback extends AccountCallback { void onSuccess(String coupon, long transactionID, Funds[] funds); }
240
0.808333
0.808333
9
25.666666
29.066973
69
false
false
0
0
0
0
0
0
0.555556
false
false
10
1c31ff84e1468f8d6d111383cd6180226e4423ad
38,465,727,121,811
416f954e0b3dedc2820866c8bda9f62cc73a92be
/backUser/src/main/java/study/cjj/eloan/base/controller/BorrowInfoController.java
55c5c726a3b3e1e7731fa2772ef38ac836c75a27
[]
no_license
Gaga17/graduationDsign
https://github.com/Gaga17/graduationDsign
f9f184d8e827e5aba95cae2600c7bec1eaf63a8e
b226fa52085810ea66643346353d0d36fb182817
refs/heads/master
2020-04-26T22:13:47.902000
2019-04-24T05:38:13
2019-04-24T05:38:13
173,865,723
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package study.cjj.eloan.base.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import study.cjj.eloan.base.domain.BidRequest; import study.cjj.eloan.base.domain.UserFile; import study.cjj.eloan.base.domain.UserInfo; import study.cjj.eloan.base.query.UserFileQueryObject; import study.cjj.eloan.base.service.IBidRequestService; import study.cjj.eloan.base.service.IRealAuthService; import study.cjj.eloan.base.service.IUserFileService; import study.cjj.eloan.base.service.IUserInfoService; import study.cjj.eloan.base.service.impl.RealAuthServiceImpl; @Controller public class BorrowInfoController extends BaseController { @Autowired private IBidRequestService bidRequestService; @Autowired private IUserInfoService userInfoService; @Autowired private IUserFileService userFileService; @Autowired private IRealAuthService realAuthService; /** * 查看标的明细 */ @RequestMapping("/borrow_info") public String borrowInfo(Long id, Model model) { BidRequest bidRequest = this.bidRequestService.getBidRequest(id); //获得当前的借款人 UserInfo userinfo = this.userInfoService.getUserInfo(bidRequest.getCreateUser().getId()); model.addAttribute("bidRequest",bidRequest ); model.addAttribute("userInfo",userinfo); //查询当前标的 历史审核对象 model.addAttribute("audits", this.bidRequestService.listAuditHistorayByBidRequest(bidRequest.getId())); //用户的实名认证信息 model.addAttribute("realAuth", this.realAuthService.getRealAuth(userinfo.getRealAuthenticationId())); //借款人所有的相关的风控材料(已经审核通过) UserFileQueryObject qo = new UserFileQueryObject() ; qo.setStatus(UserFile.STATE_PASS); qo.setApplierId(userinfo.getId()); qo.setPageSize(-1); model.addAttribute("userFiles", this.userFileService.getUserFileBy(qo)); return "bidrequest/borrow_info"; } }
UTF-8
Java
2,109
java
BorrowInfoController.java
Java
[]
null
[]
package study.cjj.eloan.base.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import study.cjj.eloan.base.domain.BidRequest; import study.cjj.eloan.base.domain.UserFile; import study.cjj.eloan.base.domain.UserInfo; import study.cjj.eloan.base.query.UserFileQueryObject; import study.cjj.eloan.base.service.IBidRequestService; import study.cjj.eloan.base.service.IRealAuthService; import study.cjj.eloan.base.service.IUserFileService; import study.cjj.eloan.base.service.IUserInfoService; import study.cjj.eloan.base.service.impl.RealAuthServiceImpl; @Controller public class BorrowInfoController extends BaseController { @Autowired private IBidRequestService bidRequestService; @Autowired private IUserInfoService userInfoService; @Autowired private IUserFileService userFileService; @Autowired private IRealAuthService realAuthService; /** * 查看标的明细 */ @RequestMapping("/borrow_info") public String borrowInfo(Long id, Model model) { BidRequest bidRequest = this.bidRequestService.getBidRequest(id); //获得当前的借款人 UserInfo userinfo = this.userInfoService.getUserInfo(bidRequest.getCreateUser().getId()); model.addAttribute("bidRequest",bidRequest ); model.addAttribute("userInfo",userinfo); //查询当前标的 历史审核对象 model.addAttribute("audits", this.bidRequestService.listAuditHistorayByBidRequest(bidRequest.getId())); //用户的实名认证信息 model.addAttribute("realAuth", this.realAuthService.getRealAuth(userinfo.getRealAuthenticationId())); //借款人所有的相关的风控材料(已经审核通过) UserFileQueryObject qo = new UserFileQueryObject() ; qo.setStatus(UserFile.STATE_PASS); qo.setApplierId(userinfo.getId()); qo.setPageSize(-1); model.addAttribute("userFiles", this.userFileService.getUserFileBy(qo)); return "bidrequest/borrow_info"; } }
2,109
0.77961
0.77911
58
32.5
27.264509
105
false
false
0
0
0
0
0
0
1.534483
false
false
10
90530872dd75430d473081f6781375fd7e202c75
34,840,774,752,092
13f2768814f8ffb7bcd7cd7f9d11c9b9dd99e820
/RZrtcPaasdemo/app/src/main/java/com/rzrtc/paasdemo/recycleview/CommonHolder.java
f58d1ac626fdc479b4564589c21695209db33bb5
[]
no_license
rzrtc/RzRTCPaaSDemo-Android
https://github.com/rzrtc/RzRTCPaaSDemo-Android
45884edcc25f0f30a1620f902412258ea74cacd7
ba02a2f26f9a930ce29e928d3874e68bb69c2dc9
refs/heads/master
2023-09-02T21:57:24.698000
2021-11-25T09:42:59
2021-11-25T09:42:59
327,569,603
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rzrtc.paasdemo.recycleview; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class CommonHolder extends RecyclerView.ViewHolder { private Resources resources; public SparseArray<View> viewMap = new SparseArray<>(); public CommonHolder(View itemView) { super(itemView); resources = itemView.getResources(); } public <V extends View> V findView(int resId) { View view = viewMap.get(resId); if (view == null) { View findView = itemView.findViewById(resId); view = findView; viewMap.put(resId, view); } return (V) view; } public CommonHolder setText(int resId, String text) { TextView view = findView(resId); view.setText(text); return this; } public CommonHolder setVisible(int resId, int visible) { View view = findView(resId); view.setVisibility(visible); return this; } public CommonHolder setBackGround(int resId, ChangeBackground background) { View view = findView(resId); background.change(view); return this; } public CommonHolder setBackGroundColor(int resId, int color) { View view = findView(resId); view.setBackgroundColor(color); return this; } public CommonHolder setImage(int viewId, int resId) { ImageView view = findView(viewId); view.setImageResource(resId); return this; } public CommonHolder setTextColor(int viewId, int color) { TextView view = findView(viewId); view.setTextColor(resources.getColor(color)); return this; } public CommonHolder setTextDrawable(int viewId, int drawable) { TextView view = findView(viewId); Drawable leftDrawable = resources.getDrawable(drawable); leftDrawable.setBounds(0, 0, leftDrawable.getMinimumWidth(), leftDrawable.getMinimumHeight()); view.setCompoundDrawablesRelative(leftDrawable, null, null, null); return this; } public CommonHolder setOnClickListener(int viewId, View.OnClickListener l) { View view = findView(viewId); view.setOnClickListener(l); return this; } public void addView(int iconContainer, @Nullable View view) { ViewGroup container = ((ViewGroup) findView(iconContainer)); if (view != null && view.getParent() == null) container.addView(view); } public void removeView(int iconContainer, @NotNull View view) { ViewGroup container = ((ViewGroup) findView(iconContainer)); if (view.getParent() != null) { container.removeView(view); } } public void removeAllView(int iconContainer) { ViewGroup container = ((ViewGroup) findView(iconContainer)); container.removeAllViews(); } }
UTF-8
Java
3,209
java
CommonHolder.java
Java
[]
null
[]
package com.rzrtc.paasdemo.recycleview; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class CommonHolder extends RecyclerView.ViewHolder { private Resources resources; public SparseArray<View> viewMap = new SparseArray<>(); public CommonHolder(View itemView) { super(itemView); resources = itemView.getResources(); } public <V extends View> V findView(int resId) { View view = viewMap.get(resId); if (view == null) { View findView = itemView.findViewById(resId); view = findView; viewMap.put(resId, view); } return (V) view; } public CommonHolder setText(int resId, String text) { TextView view = findView(resId); view.setText(text); return this; } public CommonHolder setVisible(int resId, int visible) { View view = findView(resId); view.setVisibility(visible); return this; } public CommonHolder setBackGround(int resId, ChangeBackground background) { View view = findView(resId); background.change(view); return this; } public CommonHolder setBackGroundColor(int resId, int color) { View view = findView(resId); view.setBackgroundColor(color); return this; } public CommonHolder setImage(int viewId, int resId) { ImageView view = findView(viewId); view.setImageResource(resId); return this; } public CommonHolder setTextColor(int viewId, int color) { TextView view = findView(viewId); view.setTextColor(resources.getColor(color)); return this; } public CommonHolder setTextDrawable(int viewId, int drawable) { TextView view = findView(viewId); Drawable leftDrawable = resources.getDrawable(drawable); leftDrawable.setBounds(0, 0, leftDrawable.getMinimumWidth(), leftDrawable.getMinimumHeight()); view.setCompoundDrawablesRelative(leftDrawable, null, null, null); return this; } public CommonHolder setOnClickListener(int viewId, View.OnClickListener l) { View view = findView(viewId); view.setOnClickListener(l); return this; } public void addView(int iconContainer, @Nullable View view) { ViewGroup container = ((ViewGroup) findView(iconContainer)); if (view != null && view.getParent() == null) container.addView(view); } public void removeView(int iconContainer, @NotNull View view) { ViewGroup container = ((ViewGroup) findView(iconContainer)); if (view.getParent() != null) { container.removeView(view); } } public void removeAllView(int iconContainer) { ViewGroup container = ((ViewGroup) findView(iconContainer)); container.removeAllViews(); } }
3,209
0.660642
0.660019
102
30.460785
23.140522
80
false
false
0
0
0
0
0
0
0.676471
false
false
10
3ecd966d1aa41c3a2c1510f217a483ebedf51d26
35,991,825,981,004
0fe00d8ff44c50d5b17c29e1a526a7601b4d65d1
/command/src/main/java/com/abel/commend/DeletePageCommand.java
e7c91ba0fc923081f460eb5cdacb9d2ca75f0197
[]
no_license
527515025/Design_pattern
https://github.com/527515025/Design_pattern
01ac63616a9ba6ade43fbbfe11118616d3a729f1
b56223d43f49405e52e5e6a906726a122fa01b8c
refs/heads/master
2021-05-23T05:24:07.484000
2020-11-18T05:04:59
2020-11-18T05:04:59
95,179,865
17
7
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.abel.commend; /** * Created by yangyibo on 17/10/18. */ public class DeletePageCommand extends Command { public void execute() { // 找到美工组 super.pg.find(); //删除一个页面 super.pg.delete(); // 给出计划 super.pg.plan(); } }
UTF-8
Java
314
java
DeletePageCommand.java
Java
[ { "context": "package com.abel.commend;\n\n/**\n * Created by yangyibo on 17/10/18.\n */\npublic class DeletePageCommand e", "end": 53, "score": 0.9992297291755676, "start": 45, "tag": "USERNAME", "value": "yangyibo" } ]
null
[]
package com.abel.commend; /** * Created by yangyibo on 17/10/18. */ public class DeletePageCommand extends Command { public void execute() { // 找到美工组 super.pg.find(); //删除一个页面 super.pg.delete(); // 给出计划 super.pg.plan(); } }
314
0.545775
0.524648
16
16.75
13.699909
48
false
false
0
0
0
0
0
0
0.25
false
false
10
f89fdcf6852cf3507016afda9339a4521777c8dd
39,075,612,495,883
533ed51ace7f4d10016ddb966499b8178ca7034a
/src/main/java/com/thesis/webspajz/controller/UserIngredientController.java
928dde106ff326edeaf60744585d87847cad7d84
[]
no_license
Bunyi5/Webspajz
https://github.com/Bunyi5/Webspajz
f233cc2887b050885268416449955a8e09af2afb
7a12767827f1f424244f6e5eea8e21326713bcc2
refs/heads/master
2023-03-26T13:02:02.417000
2021-03-28T17:06:36
2021-03-28T17:06:36
301,658,675
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.thesis.webspajz.controller; import com.thesis.webspajz.dto.UserIngredientResponseDTO; import com.thesis.webspajz.dto.UserIngredientRequestDTO; import com.thesis.webspajz.service.UserAuthenticationService; import com.thesis.webspajz.service.UserIngredientService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; @Slf4j @RestController @RequiredArgsConstructor public class UserIngredientController { private final UserIngredientService userIngredientService; private final UserAuthenticationService userAuthenticationService; @GetMapping("/ingredients") public ResponseEntity<List<UserIngredientResponseDTO>> getIngredients() { return ResponseEntity.ok(userIngredientService.getLoggedUserIngredients()); } @PostMapping("/modifyQuantities") public ResponseEntity<Void> modifyUserIngredientQuantities(@RequestBody List<UserIngredientRequestDTO> requestDTOS) { try { userIngredientService.modifyUserIngredients(requestDTOS); log.info("User: " + userAuthenticationService.getLoggedInUser().getUsername() + " modified quantities."); return ResponseEntity.ok().build(); } catch (Exception e) { log.info("Error saving quantities for user: " + userAuthenticationService.getLoggedInUser().getUsername()); return ResponseEntity.status(404).build(); } } }
UTF-8
Java
1,724
java
UserIngredientController.java
Java
[]
null
[]
package com.thesis.webspajz.controller; import com.thesis.webspajz.dto.UserIngredientResponseDTO; import com.thesis.webspajz.dto.UserIngredientRequestDTO; import com.thesis.webspajz.service.UserAuthenticationService; import com.thesis.webspajz.service.UserIngredientService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; @Slf4j @RestController @RequiredArgsConstructor public class UserIngredientController { private final UserIngredientService userIngredientService; private final UserAuthenticationService userAuthenticationService; @GetMapping("/ingredients") public ResponseEntity<List<UserIngredientResponseDTO>> getIngredients() { return ResponseEntity.ok(userIngredientService.getLoggedUserIngredients()); } @PostMapping("/modifyQuantities") public ResponseEntity<Void> modifyUserIngredientQuantities(@RequestBody List<UserIngredientRequestDTO> requestDTOS) { try { userIngredientService.modifyUserIngredients(requestDTOS); log.info("User: " + userAuthenticationService.getLoggedInUser().getUsername() + " modified quantities."); return ResponseEntity.ok().build(); } catch (Exception e) { log.info("Error saving quantities for user: " + userAuthenticationService.getLoggedInUser().getUsername()); return ResponseEntity.status(404).build(); } } }
1,724
0.781322
0.777842
41
41.048782
33.157387
121
false
false
0
0
0
0
0
0
0.512195
false
false
10
29d5abd777d851ee9ac1a9418745c9a645a75ff0
39,152,921,885,909
a82e629fa7490f9df67a5a2ca15d426ace779af4
/src/main/java/com/epam/shop/dao/item/ItemDao.java
bff77b4a4ad4aa84ee3e0664994c6e88d66034f0
[]
no_license
batik/courseWork
https://github.com/batik/courseWork
62ffdd0ce07a79494858d8d3bfab5da0912dc21c
b78f40a9cc616fd0196310ff4a712de5321a47cf
refs/heads/master
2016-09-02T03:04:31.332000
2015-06-07T22:07:31
2015-06-07T22:07:31
37,033,769
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.epam.shop.dao.item; import com.epam.shop.dao.CRUDDao; import com.epam.shop.domain.Category; import com.epam.shop.domain.Item; import com.epam.shop.entity.FilterCriteria; import org.springframework.data.mongodb.core.query.Query; import java.util.List; /** * @Author Oleh_Osyka on 10.02.2015 for Spring-shop.com.epam.shop.dao.item. */ public interface ItemDao extends CRUDDao<Item> { /** * Find item by name * * @param name of item * @return founded item or null if nothing found. */ public Item findItem(String name); public List<Item> findItemsByCategory(Category category); /** * Find total items count for using filter * * @param preparedQuery - filter params * @return count items, or 0 if nothing found */ public int getTotalListCount(FilterCriteria criteria); /** * Filter and get items * * @param preparedQuery - filtering params * @return item list for shown. */ public List<Item> getFilterItems(FilterCriteria criteria); }
UTF-8
Java
1,055
java
ItemDao.java
Java
[ { "context": "ery.Query;\n\nimport java.util.List;\n\n/**\n * @Author Oleh_Osyka on 10.02.2015 for Spring-shop.com.epam.sho", "end": 284, "score": 0.77588951587677, "start": 281, "tag": "USERNAME", "value": "Ole" }, { "context": "Query;\n\nimport java.util.List;\n\n/**\n * @Author Oleh_Osyka on 10.02.2015 for Spring-shop.com.epam.shop.dao.i", "end": 291, "score": 0.8154980540275574, "start": 284, "tag": "NAME", "value": "h_Osyka" } ]
null
[]
package com.epam.shop.dao.item; import com.epam.shop.dao.CRUDDao; import com.epam.shop.domain.Category; import com.epam.shop.domain.Item; import com.epam.shop.entity.FilterCriteria; import org.springframework.data.mongodb.core.query.Query; import java.util.List; /** * @Author Oleh_Osyka on 10.02.2015 for Spring-shop.com.epam.shop.dao.item. */ public interface ItemDao extends CRUDDao<Item> { /** * Find item by name * * @param name of item * @return founded item or null if nothing found. */ public Item findItem(String name); public List<Item> findItemsByCategory(Category category); /** * Find total items count for using filter * * @param preparedQuery - filter params * @return count items, or 0 if nothing found */ public int getTotalListCount(FilterCriteria criteria); /** * Filter and get items * * @param preparedQuery - filtering params * @return item list for shown. */ public List<Item> getFilterItems(FilterCriteria criteria); }
1,055
0.681517
0.672986
41
24.731707
22.214064
75
false
false
0
0
0
0
0
0
0.292683
false
false
10
3254a41b74800b5926f676f7702cf28ba2aba501
5,901,285,113,131
5b7a0a98264f24b2534521c2a94992b749cc42a1
/game/src/us/asciiroth/client/ui/MessageList.java
ec1c6723005afa847bd0aa11be21b316b8e3c42b
[]
no_license
alxdark/asciiroth
https://github.com/alxdark/asciiroth
19177f878ed9d9fc4c21ab476b89b15d3d2474ed
744a0dc413418aa8f038942c2043e29ce3f095d6
refs/heads/master
2021-01-22T07:27:09.443000
2014-01-25T18:51:32
2014-01-25T18:51:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright 2008 Alx Dark * * 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 us.asciiroth.client.ui; import java.util.ArrayList; public class MessageList extends ArrayList<String> { private static final long serialVersionUID = 1L; public String toBreakList() { StringBuilder sb = new StringBuilder(); for (int i=0, len = size(); i < len; i++) { sb.append(get(i)); if (i < (len-1)) { sb.append("<br/>"); } } return sb.toString(); } public String toBreakListWithEnterPrompt() { add("<small>ESC/ENTER to continue&#8230;</small>"); return toBreakList(); } }
UTF-8
Java
1,245
java
MessageList.java
Java
[ { "context": "/**\r\n * Copyright 2008 Alx Dark\r\n * \r\n * Licensed under the Apache License, Versi", "end": 31, "score": 0.9997584223747253, "start": 23, "tag": "NAME", "value": "Alx Dark" } ]
null
[]
/** * Copyright 2008 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package us.asciiroth.client.ui; import java.util.ArrayList; public class MessageList extends ArrayList<String> { private static final long serialVersionUID = 1L; public String toBreakList() { StringBuilder sb = new StringBuilder(); for (int i=0, len = size(); i < len; i++) { sb.append(get(i)); if (i < (len-1)) { sb.append("<br/>"); } } return sb.toString(); } public String toBreakListWithEnterPrompt() { add("<small>ESC/ENTER to continue&#8230;</small>"); return toBreakList(); } }
1,243
0.6249
0.612851
37
31.648649
24.098017
75
false
false
0
0
0
0
0
0
0.567568
false
false
10
5f5648fd2b88f4e24f2ffab147daf0153dc42988
31,997,506,398,530
7c455ce3ea9d94ac77a552c8387c90ae04c99166
/spacebook/controllers/Home.java
97ac703ed4eac6d2af42fbca57009623537a2be8
[]
no_license
jowijoke/assignment-3-spacebook
https://github.com/jowijoke/assignment-3-spacebook
056b3dbad8a673d0231f7d7e2ca6be3771a48732
927a9f50894c83d6ed2b089b19b80d48cf657986
refs/heads/master
2021-01-01T05:04:54.322000
2016-05-15T19:07:31
2016-05-15T19:07:31
56,597,700
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package controllers; import java.util.ArrayList; import java.util.Collections; import models.Friendship; import models.Message; import models.User; import utils.MessageDateComparator; import utils.MessageFromComparator; import views.HomeView; public class Home { /** * Dispatches a list of messages in the user's inbox to HomeView for rendering * This method simulates the Play version of spaceboook Home page responding * to BY DATE button press Note that the method HomeView.index(User, ArrayList * <Message>) could have been condensed to HomeView.index(User) since the * reference to outbox is available from within the User object. The more * verbose version of the method has been chosen to preserve similarity with * the equivalent Play method. A similar approach has been adopted with other * view methods. * * @param user * simulates the logged-in user */ public static void index(User user) { HomeView.index(user, user.inbox); } /** * Sort a copy of a specific user's inbox. Render sorted list of messages in * HomeView. * * @param user * the user whose message inbox will be displayed grouped by user. * */ public static void byUser(User user) { /* * Copy the user's inbox to a new list of messages Sort the copy of the * inbox by sender name (name = firstname + lastname)) Render the inbox in * the home view */ ArrayList<Message> inbox = user.inbox; Collections.sort(inbox, new MessageFromComparator()); HomeView.byUser(user, inbox); } /** * This method creates and renders a list of conversations between a user and * all its friends A single conversation between 2 users comprises a list of * messages ordered by date-time. A user has a list of friendships (friends). * Thus a conversation comprises a list of date-time-sorted messages. The * conversations, therefore, comprise a list of a list of messages. This can * represent a conversation: ArrayList<Message> This can represent a list of * conversations: ArrayList<ArrayList<Message>> * * @param user * the user that initiates the conversation */ public static void byConversation(User user) { /* * Create a list of list of messages Each list of messages is a single * conversation A conversation takes place between 2 users * * loop for all of param user friends create list of messages comprising * conversation with this friend add list of messages (conversation) to list * of conversations end loop render conversations in view */ ArrayList<ArrayList<Message>> conversations = new ArrayList<ArrayList<Message>>(); { ArrayList<User> friends = new ArrayList<User>(); for (Friendship f : user.friendships) { User source = f.sourceUser; if (!source.equals(user) && !friends.contains(source)) { friends.add(source); } User target = f.targetUser; if (!target.equals(user) && !friends.contains(target)) { friends.add(target); } } for (User friend : friends) { conversations.add(getConversation(user, friend)); } } HomeView.byConversation(user, conversations); } /** * Generates a conversation comprising a list of messages between two users. * The list is sorted by reference to date and time. Recall that a message * object contains an instance of Date object * * @param user * the user who initiates the conversation * @param friend * the user with whom the initiator is having a conversation * @return the list of messages which makes up the conversation */ static ArrayList<Message> getConversation(User user, User friend) { /* * Create a list of messages to represent a conversation loop through user's * outbox if the user to whom message sent is a friend then add the message * to the conversation endif loop through user's inbox if the message is * from a friend add the message to the conversation endif Sort the * conversation by date return the conversation */ ArrayList<Message> conversation = new ArrayList<Message>(); ArrayList<Message> inbox = user.inbox; for (Message msg1 : inbox) { if (msg1.from.equals(friend)) { conversation.add(msg1); } } ArrayList<Message> outbox = user.outbox; for (Message msg2 : outbox) { if (msg2.to.equals(friend)) { conversation.add(msg2); } } Collections.sort(conversation, new MessageDateComparator()); return conversation; } }
UTF-8
Java
4,721
java
Home.java
Java
[]
null
[]
package controllers; import java.util.ArrayList; import java.util.Collections; import models.Friendship; import models.Message; import models.User; import utils.MessageDateComparator; import utils.MessageFromComparator; import views.HomeView; public class Home { /** * Dispatches a list of messages in the user's inbox to HomeView for rendering * This method simulates the Play version of spaceboook Home page responding * to BY DATE button press Note that the method HomeView.index(User, ArrayList * <Message>) could have been condensed to HomeView.index(User) since the * reference to outbox is available from within the User object. The more * verbose version of the method has been chosen to preserve similarity with * the equivalent Play method. A similar approach has been adopted with other * view methods. * * @param user * simulates the logged-in user */ public static void index(User user) { HomeView.index(user, user.inbox); } /** * Sort a copy of a specific user's inbox. Render sorted list of messages in * HomeView. * * @param user * the user whose message inbox will be displayed grouped by user. * */ public static void byUser(User user) { /* * Copy the user's inbox to a new list of messages Sort the copy of the * inbox by sender name (name = firstname + lastname)) Render the inbox in * the home view */ ArrayList<Message> inbox = user.inbox; Collections.sort(inbox, new MessageFromComparator()); HomeView.byUser(user, inbox); } /** * This method creates and renders a list of conversations between a user and * all its friends A single conversation between 2 users comprises a list of * messages ordered by date-time. A user has a list of friendships (friends). * Thus a conversation comprises a list of date-time-sorted messages. The * conversations, therefore, comprise a list of a list of messages. This can * represent a conversation: ArrayList<Message> This can represent a list of * conversations: ArrayList<ArrayList<Message>> * * @param user * the user that initiates the conversation */ public static void byConversation(User user) { /* * Create a list of list of messages Each list of messages is a single * conversation A conversation takes place between 2 users * * loop for all of param user friends create list of messages comprising * conversation with this friend add list of messages (conversation) to list * of conversations end loop render conversations in view */ ArrayList<ArrayList<Message>> conversations = new ArrayList<ArrayList<Message>>(); { ArrayList<User> friends = new ArrayList<User>(); for (Friendship f : user.friendships) { User source = f.sourceUser; if (!source.equals(user) && !friends.contains(source)) { friends.add(source); } User target = f.targetUser; if (!target.equals(user) && !friends.contains(target)) { friends.add(target); } } for (User friend : friends) { conversations.add(getConversation(user, friend)); } } HomeView.byConversation(user, conversations); } /** * Generates a conversation comprising a list of messages between two users. * The list is sorted by reference to date and time. Recall that a message * object contains an instance of Date object * * @param user * the user who initiates the conversation * @param friend * the user with whom the initiator is having a conversation * @return the list of messages which makes up the conversation */ static ArrayList<Message> getConversation(User user, User friend) { /* * Create a list of messages to represent a conversation loop through user's * outbox if the user to whom message sent is a friend then add the message * to the conversation endif loop through user's inbox if the message is * from a friend add the message to the conversation endif Sort the * conversation by date return the conversation */ ArrayList<Message> conversation = new ArrayList<Message>(); ArrayList<Message> inbox = user.inbox; for (Message msg1 : inbox) { if (msg1.from.equals(friend)) { conversation.add(msg1); } } ArrayList<Message> outbox = user.outbox; for (Message msg2 : outbox) { if (msg2.to.equals(friend)) { conversation.add(msg2); } } Collections.sort(conversation, new MessageDateComparator()); return conversation; } }
4,721
0.672315
0.670621
151
30.2649
28.817236
86
false
false
0
0
0
0
0
0
0.251656
false
false
10
73701c3508d7925be2a332d67c5ea2f8410247ec
2,113,123,931,496
e070d1075621d4c46a5521d0a99dd549a94eebe3
/app/src/main/java/thinktechsol/msquare/model/Item.java
0e3cede16a1a070e04b274619e768921e113734f
[]
no_license
EhtishamShami/mSquare
https://github.com/EhtishamShami/mSquare
9b2a0d4c00ac18ab123869fcc0d7355159160220
c06263b3cd104310f0b7b0a27f820d909d63ba31
refs/heads/master
2021-01-11T20:55:58.746000
2017-01-17T10:21:35
2017-01-17T10:21:35
79,215,639
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package thinktechsol.msquare.model; /** * Created by Arshad.Iqbal on 5/16/2016. */ public class Item { public String label; public int counter, counter3, counter4, counter5; public int icon; public int bgColor; public int subItemIcon1; public int subItemIcon2; public int subItemIcon3; public int subItemIcon4; public boolean FourStats; public Item(String label, int counter, int icon, int bgColor, int subItemIcon1, int subItemIcon2) { this.label = label; this.counter = counter; this.icon = icon; this.bgColor = bgColor; this.subItemIcon1 = subItemIcon1; this.subItemIcon2 = subItemIcon2; } public Item(String label, int counter, int icon, int bgColor, int subItemIcon1, int subItemIcon2, int subItemIcon3, int subItemIcon4) { this.label = label; this.counter = counter; this.icon = icon; this.bgColor = bgColor; this.subItemIcon1 = subItemIcon1; this.subItemIcon2 = subItemIcon2; this.subItemIcon3 = subItemIcon3; this.subItemIcon4 = subItemIcon4; } public Item(String label, int counter, int counter3, int counter4, int counter5, int icon, int bgColor, int subItemIcon1, int subItemIcon2, boolean FourStats) { this.label = label; this.counter = counter; this.counter3 = counter3; this.counter4 = counter4; this.counter5 = counter5; this.icon = icon; this.bgColor = bgColor; this.subItemIcon1 = subItemIcon1; this.subItemIcon2 = subItemIcon2; this.FourStats = FourStats; } public Item(String label, int counter, int counter3, int counter4, int counter5, int icon, int bgColor, int subItemIcon1, int subItemIcon2, int subItemIcon3, int subItemIcon4) { this.label = label; this.counter = counter; this.counter3 = counter3; this.counter4 = counter4; this.counter5 = counter5; this.icon = icon; this.bgColor = bgColor; this.subItemIcon1 = subItemIcon1; this.subItemIcon2 = subItemIcon2; this.subItemIcon3 = subItemIcon3; this.subItemIcon4 = subItemIcon4; } }
UTF-8
Java
2,213
java
Item.java
Java
[ { "context": "age thinktechsol.msquare.model;\n\n/**\n * Created by Arshad.Iqbal on 5/16/2016.\n */\npublic class Item {\n public ", "end": 67, "score": 0.9998314380645752, "start": 55, "tag": "NAME", "value": "Arshad.Iqbal" } ]
null
[]
package thinktechsol.msquare.model; /** * Created by Arshad.Iqbal on 5/16/2016. */ public class Item { public String label; public int counter, counter3, counter4, counter5; public int icon; public int bgColor; public int subItemIcon1; public int subItemIcon2; public int subItemIcon3; public int subItemIcon4; public boolean FourStats; public Item(String label, int counter, int icon, int bgColor, int subItemIcon1, int subItemIcon2) { this.label = label; this.counter = counter; this.icon = icon; this.bgColor = bgColor; this.subItemIcon1 = subItemIcon1; this.subItemIcon2 = subItemIcon2; } public Item(String label, int counter, int icon, int bgColor, int subItemIcon1, int subItemIcon2, int subItemIcon3, int subItemIcon4) { this.label = label; this.counter = counter; this.icon = icon; this.bgColor = bgColor; this.subItemIcon1 = subItemIcon1; this.subItemIcon2 = subItemIcon2; this.subItemIcon3 = subItemIcon3; this.subItemIcon4 = subItemIcon4; } public Item(String label, int counter, int counter3, int counter4, int counter5, int icon, int bgColor, int subItemIcon1, int subItemIcon2, boolean FourStats) { this.label = label; this.counter = counter; this.counter3 = counter3; this.counter4 = counter4; this.counter5 = counter5; this.icon = icon; this.bgColor = bgColor; this.subItemIcon1 = subItemIcon1; this.subItemIcon2 = subItemIcon2; this.FourStats = FourStats; } public Item(String label, int counter, int counter3, int counter4, int counter5, int icon, int bgColor, int subItemIcon1, int subItemIcon2, int subItemIcon3, int subItemIcon4) { this.label = label; this.counter = counter; this.counter3 = counter3; this.counter4 = counter4; this.counter5 = counter5; this.icon = icon; this.bgColor = bgColor; this.subItemIcon1 = subItemIcon1; this.subItemIcon2 = subItemIcon2; this.subItemIcon3 = subItemIcon3; this.subItemIcon4 = subItemIcon4; } }
2,213
0.653864
0.623136
63
34.126984
33.057186
181
false
false
0
0
0
0
0
0
1.253968
false
false
10
352df275799fab1bac0183f6b2cdde2fd949a88e
22,342,419,923,126
74b8dea52308ecebb2ad403d397d915f68ce9a53
/PumpAndJump/src/com/musicgame/PumpAndJump/game/sound/MP3Decoder.java
62ce51ec720a3ff0ab01e810c4ee7237ef6b3a02
[]
no_license
dtracers/PumpAndJump
https://github.com/dtracers/PumpAndJump
3c344f32903a4b65156affc5c37aebf41b8dcb22
a6be20e678e61fd7c66a1855d67895f179d7e126
refs/heads/master
2020-04-06T03:33:59.303000
2013-05-12T23:02:04
2013-05-12T23:02:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.musicgame.PumpAndJump.game.sound; import java.io.File; import com.badlogic.gdx.audio.io.Decoder; import com.badlogic.gdx.files.FileHandle; public abstract class MP3Decoder extends Decoder { protected String absolutePath = null; /** * It is empty and does absolutely nothing for right now * @param file */ public MP3Decoder(FileHandle file) { if(file!=null) { File f = file.file(); if(f!=null) { absolutePath = f.getAbsolutePath(); } } } /** * Will create a specific instance of the MP3 decoder with the given file * @param file * @return */ public abstract MP3Decoder getInstance(FileHandle file); /** * @param samples this is the short array that the values are copied into * @param offset this is the offest * @param numsamples the number samples that will be read */ public abstract int readSamples(short[] samples, int offset, int numSamples); }
UTF-8
Java
924
java
MP3Decoder.java
Java
[]
null
[]
package com.musicgame.PumpAndJump.game.sound; import java.io.File; import com.badlogic.gdx.audio.io.Decoder; import com.badlogic.gdx.files.FileHandle; public abstract class MP3Decoder extends Decoder { protected String absolutePath = null; /** * It is empty and does absolutely nothing for right now * @param file */ public MP3Decoder(FileHandle file) { if(file!=null) { File f = file.file(); if(f!=null) { absolutePath = f.getAbsolutePath(); } } } /** * Will create a specific instance of the MP3 decoder with the given file * @param file * @return */ public abstract MP3Decoder getInstance(FileHandle file); /** * @param samples this is the short array that the values are copied into * @param offset this is the offest * @param numsamples the number samples that will be read */ public abstract int readSamples(short[] samples, int offset, int numSamples); }
924
0.704545
0.700216
42
21
23.869686
78
false
false
0
0
0
0
0
0
1.380952
false
false
10
0819ed1bd9b7310895ef2f383e4c3776a3dd7cd1
7,825,430,428,110
d39b9bf67ef40784ea62885e7f1067e7e2845d9b
/src/main/java/org/dev/metier/BookingMetier.java
ae4ab0026731f66135b0a842f2e3b1e1a799091a
[]
no_license
ThranduilUrM0m/CarDoc
https://github.com/ThranduilUrM0m/CarDoc
95af128bba0e703824dbd517f720013116fad388
edda3f93a9365b5bd60b5588a881852d7e2eaffd
refs/heads/master
2021-10-11T17:52:50.081000
2019-01-28T22:23:57
2019-01-28T22:23:57
100,618,080
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.dev.metier; import java.util.Collection; import java.util.Date; import org.dev.entities.Account; import org.dev.entities.Booking; import org.dev.entities.Consultation; import org.dev.entities.Control; import org.dev.entities.Tvg; import org.dev.entities.Vehicle; public interface BookingMetier { public void createBooking(Date bookingDate, Date bookingCreationdate, boolean bookingIsCanceled, Account account, Vehicle vehicle, Control control, Collection<Consultation> consultation, Tvg tvg); public Collection<Booking> getAllBooking(); public Booking getBookingByBookingDate(java.util.Date bookingDate); public void deleteBooking(Date bookingDate); }
UTF-8
Java
674
java
BookingMetier.java
Java
[]
null
[]
package org.dev.metier; import java.util.Collection; import java.util.Date; import org.dev.entities.Account; import org.dev.entities.Booking; import org.dev.entities.Consultation; import org.dev.entities.Control; import org.dev.entities.Tvg; import org.dev.entities.Vehicle; public interface BookingMetier { public void createBooking(Date bookingDate, Date bookingCreationdate, boolean bookingIsCanceled, Account account, Vehicle vehicle, Control control, Collection<Consultation> consultation, Tvg tvg); public Collection<Booking> getAllBooking(); public Booking getBookingByBookingDate(java.util.Date bookingDate); public void deleteBooking(Date bookingDate); }
674
0.818991
0.818991
19
34.473682
27.993174
102
false
false
0
0
0
0
0
0
1.421053
false
false
10
ca0186a0cb41e757279ccbb5873ded1f50cf4079
22,179,211,177,559
afdd2270f79b4afd275253a9a759412070fb5ae2
/src/main/java/com/pirate/router/UserRouter.java
1a8f987779889afe1f591574986d2171bd5bcba2
[]
no_license
renowarrior97/pirate-backend
https://github.com/renowarrior97/pirate-backend
964a43b779a16bc893e6aac059f4629f7b98a2c0
ce069834ed4d53e319c2d551b95c1831561d6c35
refs/heads/master
2022-11-30T10:02:32.842000
2020-07-16T07:20:06
2020-07-16T07:20:06
280,078,744
0
0
null
false
2020-08-14T22:55:58
2020-07-16T06:59:03
2020-07-21T22:23:50
2020-08-14T22:55:58
60
0
0
0
TSQL
false
false
package com.pirate.router; public class UserRouter { }
UTF-8
Java
57
java
UserRouter.java
Java
[]
null
[]
package com.pirate.router; public class UserRouter { }
57
0.754386
0.754386
5
10.4
12.338557
26
false
false
0
0
0
0
0
0
0.2
false
false
10
b08b74cbb3cda11f2a21a71a274dbdc57db2a81e
18,794,776,952,323
bc1e0597c42dc15c86d491b0c56e92d3b24bf4bb
/40.LessonFourty-PcShop/backend/src/main/java/pcShop/service/ComponentService.java
aac9f2b87e1e9685e68288f77aa431942fd78c6f
[]
no_license
Anno008/JavaTraining
https://github.com/Anno008/JavaTraining
705a38d4ec05244e221a27165eaa762d4ae1c874
4fb8cc38c561a792e22ab62880623d8f56a41248
refs/heads/master
2021-01-19T08:25:14.230000
2017-12-29T19:39:17
2017-12-29T19:39:17
87,628,209
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package pcShop.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import pcShop.model.Component; import pcShop.repository.ComponentRepository; @org.springframework.stereotype.Component public class ComponentService { @Autowired private ComponentRepository componentRepository; public List<Component> findAll() { return componentRepository.findAll(); } public Page<Component> findAll(Pageable page) { return componentRepository.findAll(page); } public Component findOne(Long id) { return componentRepository.findOne(id); } public Component save(Component comp) { return componentRepository.save(comp); } public void remove(Long id) { componentRepository.delete(id); } }
UTF-8
Java
878
java
ComponentService.java
Java
[]
null
[]
package pcShop.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import pcShop.model.Component; import pcShop.repository.ComponentRepository; @org.springframework.stereotype.Component public class ComponentService { @Autowired private ComponentRepository componentRepository; public List<Component> findAll() { return componentRepository.findAll(); } public Page<Component> findAll(Pageable page) { return componentRepository.findAll(page); } public Component findOne(Long id) { return componentRepository.findOne(id); } public Component save(Component comp) { return componentRepository.save(comp); } public void remove(Long id) { componentRepository.delete(id); } }
878
0.758542
0.758542
37
21.729731
20.002228
62
false
false
0
0
0
0
0
0
1
false
false
10
c7cd2e6250e982c9c1502154da734c9651bafd17
20,615,843,038,986
f3b80fe8eb692047f31ee130a5246cf02c028f3d
/app/src/main/java/com/example/nebalbarhoome/home3/DataBase.java
4deacca646617abaa0b4b8d3e9d52c231da769b3
[]
no_license
firecodering/webpages
https://github.com/firecodering/webpages
178faedeb11dd8a633d07990daeb3435195edd0f
864e9cd67d61a543c46fc0eb49c910e0d24b9665
refs/heads/master
2020-03-14T03:49:23.796000
2018-04-28T17:00:04
2018-04-28T17:00:04
131,428,133
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.nebalbarhoome.home3; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class DataBase implements Serializable { public final static String fName = "database.serialized"; private static DataBase ourInstance = new DataBase(); public static void createSampleData(){ DataBase dataBase=new DataBase(); dataBase.addPage(new FavoritePage("Google","https://www.google.com/",0)); dataBase.addPage(new FavoritePage("Yahoo","https://www.yahoo.com/",0)); dataBase.addPage(new FavoritePage("Msn","https://www.msn.com/",0)); dataBase.addPage(new FavoritePage("westminster","http://www.westminster.edu/index.cfm",0)); dataBase.addPage(new FavoritePage("developer.android","https://developer.android.com/index.html",0)); dataBase.addPage(new FavoritePage("cplusplus","http://www.cplusplus.com/",0)); dataBase.addPage(new FavoritePage("Geeksforgeeks","https://www.geeksforgeeks.org/",0)); dataBase.addPage(new FavoritePage("GitHub","https://github.com/",0)); ourInstance =dataBase; } public static DataBase getInstance() { if (ourInstance == null) ourInstance = new DataBase(); return ourInstance; } private DataBase() { pages = new ArrayList<>(); } private List<FavoritePage> pages; //load the database (into the singleton variable) from the specified file public static void load(File f) throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f)); ourInstance = (DataBase) ois.readObject(); ois.close(); } //save this database to the specified file public void save(File f) throws IOException{ ObjectOutputStream oout = new ObjectOutputStream(new FileOutputStream(f)); oout.writeObject(this); oout.close(); } //return the site at the specified index public int getPageCount() { return pages.size(); } //return the list of sites, wrapped to be “unmodifiable” public FavoritePage getPage(int index) { return pages.get(index); } public List<FavoritePage> getPages() { return pages; } public void addPage(FavoritePage p){ pages.add(p); } }
UTF-8
Java
2,554
java
DataBase.java
Java
[]
null
[]
package com.example.nebalbarhoome.home3; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class DataBase implements Serializable { public final static String fName = "database.serialized"; private static DataBase ourInstance = new DataBase(); public static void createSampleData(){ DataBase dataBase=new DataBase(); dataBase.addPage(new FavoritePage("Google","https://www.google.com/",0)); dataBase.addPage(new FavoritePage("Yahoo","https://www.yahoo.com/",0)); dataBase.addPage(new FavoritePage("Msn","https://www.msn.com/",0)); dataBase.addPage(new FavoritePage("westminster","http://www.westminster.edu/index.cfm",0)); dataBase.addPage(new FavoritePage("developer.android","https://developer.android.com/index.html",0)); dataBase.addPage(new FavoritePage("cplusplus","http://www.cplusplus.com/",0)); dataBase.addPage(new FavoritePage("Geeksforgeeks","https://www.geeksforgeeks.org/",0)); dataBase.addPage(new FavoritePage("GitHub","https://github.com/",0)); ourInstance =dataBase; } public static DataBase getInstance() { if (ourInstance == null) ourInstance = new DataBase(); return ourInstance; } private DataBase() { pages = new ArrayList<>(); } private List<FavoritePage> pages; //load the database (into the singleton variable) from the specified file public static void load(File f) throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f)); ourInstance = (DataBase) ois.readObject(); ois.close(); } //save this database to the specified file public void save(File f) throws IOException{ ObjectOutputStream oout = new ObjectOutputStream(new FileOutputStream(f)); oout.writeObject(this); oout.close(); } //return the site at the specified index public int getPageCount() { return pages.size(); } //return the list of sites, wrapped to be “unmodifiable” public FavoritePage getPage(int index) { return pages.get(index); } public List<FavoritePage> getPages() { return pages; } public void addPage(FavoritePage p){ pages.add(p); } }
2,554
0.681961
0.678431
89
27.662922
28.566479
109
false
false
0
0
0
0
0
0
0.617977
false
false
10
e8b64fe36f508c9bc8d1029e490609dac51c5831
14,903,536,555,050
c06c597f3a9341a4c046adf3935131195ff65291
/ConsoleGame/src/com/baeseokjae/Monster.java
5015108112886bf8c74f2e800c9714e0d95a4ccb
[]
no_license
bsjp400/-Java-Console-Game
https://github.com/bsjp400/-Java-Console-Game
e0d48924aaeef54863a183b134a2b3a65d899923
37681f1e1aeea473dc9ccd9b63b70b093e675833
refs/heads/master
2023-01-04T04:35:05.126000
2020-11-02T16:35:27
2020-11-02T16:35:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.baeseokjae; public class Monster extends Character { public int monexp; public int buff; public int Getbuff() { return buff; } public void Setbuff(int buff) { this.buff = buff; } public int Getmonexp() { return monexp; } public void Setmonexp(int monexp) { this.monexp = monexp; } public Monster(String name, int level, int hp, int mp, int atk, int atkSpeed, int armor, int monexp, int money, int buff) { super(name, level, hp, mp, atk, atkSpeed, armor, money); this.buff = buff; this.monexp = monexp; } public String toString() { return " " + Getname() + " 스탯\n" + " HP : " + Gethp() + "\n" + " 공격력 : " + Getatk() + "\n" + " 방어력 : " + Getdefense() + "\n" + " ----------------------------------------------------------------------"; } }
UTF-8
Java
829
java
Monster.java
Java
[]
null
[]
package com.baeseokjae; public class Monster extends Character { public int monexp; public int buff; public int Getbuff() { return buff; } public void Setbuff(int buff) { this.buff = buff; } public int Getmonexp() { return monexp; } public void Setmonexp(int monexp) { this.monexp = monexp; } public Monster(String name, int level, int hp, int mp, int atk, int atkSpeed, int armor, int monexp, int money, int buff) { super(name, level, hp, mp, atk, atkSpeed, armor, money); this.buff = buff; this.monexp = monexp; } public String toString() { return " " + Getname() + " 스탯\n" + " HP : " + Gethp() + "\n" + " 공격력 : " + Getatk() + "\n" + " 방어력 : " + Getdefense() + "\n" + " ----------------------------------------------------------------------"; } }
829
0.544895
0.544895
37
20.972973
24.733702
124
false
false
0
0
0
0
0
0
2
false
false
10
a11910e4ac951c83d3f11c4001130fda5aa7e4c5
2,224,793,119,589
4ac3b6c021421dfd75bfd0f8e7012fa71d1f241a
/src/main/java/lab3/templateMethod/Field.java
12af9f0f528a75ec5c7417dd8fa4106e3c4eff94
[]
no_license
MegaOmegaAlpha/patterns
https://github.com/MegaOmegaAlpha/patterns
60ac361f726426f5f28986be2e0cae2db6dbead6
cb3c80b8ec7f4e4f55d5649380415d62671ffbbf
refs/heads/master
2021-01-01T21:42:03.894000
2020-03-27T18:04:36
2020-03-27T18:04:36
239,353,114
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Created by JFormDesigner on Thu Mar 12 23:44:17 GMT+04:00 2020 */ package lab3.templateMethod; import java.awt.*; import java.awt.event.*; import java.util.Arrays; import javax.swing.*; import javax.swing.GroupLayout; /** * @author Vladimir */ public class Field extends JFrame { private AnimatedLayer screen; private String[] arguments = { "RECTANGLE", "CIRCLE", "STAR" }; public Field() { initComponents(); screen = new AnimatedLayer(); panel1.add(screen); Arrays.stream(arguments).forEach(comboBox1::addItem); } private void button1ActionPerformed(ActionEvent e) { String selectedName = (String) comboBox1.getSelectedItem(); if (selectedName != null && !selectedName.isEmpty()) { screen.run(selectedName); } } private void initComponents() { // JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents // Generated using JFormDesigner Evaluation license - Vladimir button1 = new JButton(); panel1 = new JPanel(); comboBox1 = new JComboBox(); //======== this ======== Container contentPane = getContentPane(); //---- button1 ---- button1.setText("text"); button1.addActionListener(e -> button1ActionPerformed(e)); //======== panel1 ======== { panel1.setBorder ( new javax . swing. border .CompoundBorder ( new javax . swing. border .TitledBorder ( new javax . swing. border .EmptyBorder ( 0, 0 ,0 , 0) , "JFor\u006dDesi\u0067ner \u0045valu\u0061tion" , javax. swing .border . TitledBorder. CENTER ,javax . swing. border .TitledBorder . BOTTOM , new java. awt .Font ( "Dia\u006cog", java .awt . Font. BOLD ,12 ) ,java . awt. Color .red ) ,panel1. getBorder () ) ); panel1. addPropertyChangeListener( new java. beans .PropertyChangeListener ( ){ @Override public void propertyChange (java . beans. PropertyChangeEvent e ) { if( "bord\u0065r" .equals ( e. getPropertyName () ) )throw new RuntimeException( ) ;} } ); panel1.setLayout(new GridLayout()); } GroupLayout contentPaneLayout = new GroupLayout(contentPane); contentPane.setLayout(contentPaneLayout); contentPaneLayout.setHorizontalGroup( contentPaneLayout.createParallelGroup() .addGroup(contentPaneLayout.createSequentialGroup() .addContainerGap() .addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false) .addComponent(button1, GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE) .addComponent(comboBox1, GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(panel1, GroupLayout.DEFAULT_SIZE, 714, Short.MAX_VALUE)) ); contentPaneLayout.setVerticalGroup( contentPaneLayout.createParallelGroup() .addGroup(contentPaneLayout.createSequentialGroup() .addContainerGap() .addComponent(button1, GroupLayout.PREFERRED_SIZE, 77, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(comboBox1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGap(0, 348, Short.MAX_VALUE)) .addComponent(panel1, GroupLayout.DEFAULT_SIZE, 461, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(getOwner()); // JFormDesigner - End of component initialization //GEN-END:initComponents } // JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables // Generated using JFormDesigner Evaluation license - Vladimir private JButton button1; private JPanel panel1; private JComboBox comboBox1; // JFormDesigner - End of variables declaration //GEN-END:variables }
UTF-8
Java
4,154
java
Field.java
Java
[ { "context": "*;\nimport javax.swing.GroupLayout;\n\n/**\n * @author Vladimir\n */\npublic class Field extends JFrame {\n\n priv", "end": 251, "score": 0.9998328685760498, "start": 243, "tag": "NAME", "value": "Vladimir" } ]
null
[]
/* * Created by JFormDesigner on Thu Mar 12 23:44:17 GMT+04:00 2020 */ package lab3.templateMethod; import java.awt.*; import java.awt.event.*; import java.util.Arrays; import javax.swing.*; import javax.swing.GroupLayout; /** * @author Vladimir */ public class Field extends JFrame { private AnimatedLayer screen; private String[] arguments = { "RECTANGLE", "CIRCLE", "STAR" }; public Field() { initComponents(); screen = new AnimatedLayer(); panel1.add(screen); Arrays.stream(arguments).forEach(comboBox1::addItem); } private void button1ActionPerformed(ActionEvent e) { String selectedName = (String) comboBox1.getSelectedItem(); if (selectedName != null && !selectedName.isEmpty()) { screen.run(selectedName); } } private void initComponents() { // JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents // Generated using JFormDesigner Evaluation license - Vladimir button1 = new JButton(); panel1 = new JPanel(); comboBox1 = new JComboBox(); //======== this ======== Container contentPane = getContentPane(); //---- button1 ---- button1.setText("text"); button1.addActionListener(e -> button1ActionPerformed(e)); //======== panel1 ======== { panel1.setBorder ( new javax . swing. border .CompoundBorder ( new javax . swing. border .TitledBorder ( new javax . swing. border .EmptyBorder ( 0, 0 ,0 , 0) , "JFor\u006dDesi\u0067ner \u0045valu\u0061tion" , javax. swing .border . TitledBorder. CENTER ,javax . swing. border .TitledBorder . BOTTOM , new java. awt .Font ( "Dia\u006cog", java .awt . Font. BOLD ,12 ) ,java . awt. Color .red ) ,panel1. getBorder () ) ); panel1. addPropertyChangeListener( new java. beans .PropertyChangeListener ( ){ @Override public void propertyChange (java . beans. PropertyChangeEvent e ) { if( "bord\u0065r" .equals ( e. getPropertyName () ) )throw new RuntimeException( ) ;} } ); panel1.setLayout(new GridLayout()); } GroupLayout contentPaneLayout = new GroupLayout(contentPane); contentPane.setLayout(contentPaneLayout); contentPaneLayout.setHorizontalGroup( contentPaneLayout.createParallelGroup() .addGroup(contentPaneLayout.createSequentialGroup() .addContainerGap() .addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false) .addComponent(button1, GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE) .addComponent(comboBox1, GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(panel1, GroupLayout.DEFAULT_SIZE, 714, Short.MAX_VALUE)) ); contentPaneLayout.setVerticalGroup( contentPaneLayout.createParallelGroup() .addGroup(contentPaneLayout.createSequentialGroup() .addContainerGap() .addComponent(button1, GroupLayout.PREFERRED_SIZE, 77, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(comboBox1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGap(0, 348, Short.MAX_VALUE)) .addComponent(panel1, GroupLayout.DEFAULT_SIZE, 461, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(getOwner()); // JFormDesigner - End of component initialization //GEN-END:initComponents } // JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables // Generated using JFormDesigner Evaluation license - Vladimir private JButton button1; private JPanel panel1; private JComboBox comboBox1; // JFormDesigner - End of variables declaration //GEN-END:variables }
4,154
0.630717
0.609533
97
41.824741
34.668983
130
false
false
0
0
0
0
0
0
0.690722
false
false
10
e2d65220bd1baa0a9040cf8a2bc9b814199404a0
20,796,231,685,499
b3bfb78ae533af108abf1ed187ba13da5b2e33ed
/hrm-commons/src/main/java/com/sgic/hrm/commons/repository/privilege/PermissionRepository.java
174599e8f627b8929517443689cb6cc4f8e71f06
[]
no_license
Suwarnan91/hrm_backend
https://github.com/Suwarnan91/hrm_backend
fee7f1dbc785276ec4a548ee1e6cdef92fd9744a
6e7bf5baffacfd2d902d5fcf9ca7abcc3e5c5129
refs/heads/master
2020-04-12T20:35:43.890000
2018-12-21T17:37:22
2018-12-21T17:37:22
162,741,123
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//package com.sgic.hrm.commons.repository.privilege; // //import org.springframework.data.jpa.repository.JpaRepository; // //import com.sgic.hrm.commons.entity.privilege.Permission; // //public interface PermissionRepository extends JpaRepository<Permission, Integer> { // //}
UTF-8
Java
277
java
PermissionRepository.java
Java
[]
null
[]
//package com.sgic.hrm.commons.repository.privilege; // //import org.springframework.data.jpa.repository.JpaRepository; // //import com.sgic.hrm.commons.entity.privilege.Permission; // //public interface PermissionRepository extends JpaRepository<Permission, Integer> { // //}
277
0.783394
0.783394
9
29.777779
31.863522
84
false
false
0
0
0
0
0
0
0.444444
false
false
10
2f655bf42aad4b5f9a2d8fcce7e0d3ed4f200835
51,539,651,359
983cd6fa19b5b69bc9406d446657f5fc6a8790e1
/src/main/java/com/interviewcity/interview/configuration/SwaggerConfiguration.java
1f080729f4d368239ab1eca5769e1de4920582cf
[]
no_license
trainningjava/spring-boot-interview
https://github.com/trainningjava/spring-boot-interview
fb5ff6493942585a8eafe95f730e07f0d4d88535
6f08d36c7e87d446594943e2fc956a95a21d2e0a
refs/heads/main
2023-01-21T04:46:54.701000
2020-11-12T22:53:50
2020-11-12T22:53:50
306,023,962
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.interviewcity.interview.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.service.VendorExtension; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.ArrayList; import static springfox.documentation.builders.PathSelectors.regex; @Configuration @EnableSwagger2 public class SwaggerConfiguration extends WebMvcConfigurationSupport { @Bean public Docket grettingApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.interviewcity.interview")) .paths(PathSelectors.any()) .build() .apiInfo(metaData()); } private ApiInfo metaData(){ return new ApiInfoBuilder() .title("Interview") .description("API Interview") .version("1.0.0") .license("MIT License") .licenseUrl("") .build(); } @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addRedirectViewController("/v2/api-docs", "/v2/api-docs"); registry.addRedirectViewController("/swagger-resources/configuration/ui", "/swagger-resources/configuration/ui"); registry.addRedirectViewController("/swagger-resources/configuration/security", "/swagger-resources/configuration/security"); registry.addRedirectViewController("/swagger-resources", "/swagger-resources"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //enabling swagger-ui part for visual documentation registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
UTF-8
Java
2,637
java
SwaggerConfiguration.java
Java
[]
null
[]
package com.interviewcity.interview.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.service.VendorExtension; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.ArrayList; import static springfox.documentation.builders.PathSelectors.regex; @Configuration @EnableSwagger2 public class SwaggerConfiguration extends WebMvcConfigurationSupport { @Bean public Docket grettingApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.interviewcity.interview")) .paths(PathSelectors.any()) .build() .apiInfo(metaData()); } private ApiInfo metaData(){ return new ApiInfoBuilder() .title("Interview") .description("API Interview") .version("1.0.0") .license("MIT License") .licenseUrl("") .build(); } @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addRedirectViewController("/v2/api-docs", "/v2/api-docs"); registry.addRedirectViewController("/swagger-resources/configuration/ui", "/swagger-resources/configuration/ui"); registry.addRedirectViewController("/swagger-resources/configuration/security", "/swagger-resources/configuration/security"); registry.addRedirectViewController("/swagger-resources", "/swagger-resources"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //enabling swagger-ui part for visual documentation registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
2,637
0.741373
0.73796
62
41.532257
33.716904
133
false
false
0
0
0
0
0
0
0.467742
false
false
10
a920f7983adb44b5e335a43d5b834521d7dcc7c3
6,451,040,939,577
027fd4a4af2993a078c5a74d92bfe47529a2a6ca
/geode-dunit/src/main/java/org/apache/geode/management/internal/cli/commands/QueryCommandDUnitTestBase.java
52f27f2ccce237fd2e7d1f503044f8812f614c8f
[ "Apache-2.0", "LicenseRef-scancode-unknown", "BSD-3-Clause", "MIT", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
gmstrbytes/geode
https://github.com/gmstrbytes/geode
e03a814d11482d0ea64de3d665f6a4e643eb0d74
265d00c4e03b013a54266675ed51309722b76b07
refs/heads/develop
2022-01-12T14:20:29.133000
2021-06-02T15:05:58
2021-06-02T15:05:58
125,238,887
1
0
Apache-2.0
true
2021-06-02T15:08:12
2018-03-14T16:04:23
2020-02-02T12:09:52
2021-06-02T15:08:12
185,529
0
0
0
Java
false
false
/* * 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.geode.management.internal.cli.commands; import static org.apache.geode.cache.Region.SEPARATOR; import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL; import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT; import static org.apache.geode.distributed.ConfigurationProperties.SERIALIZABLE_OBJECT_FILTER; import static org.apache.geode.management.internal.i18n.CliStrings.MEMBER; import static org.apache.geode.management.internal.i18n.CliStrings.QUERY; import static org.apache.geode.test.dunit.IgnoredException.addIgnoredException; import static org.apache.geode.test.junit.rules.GfshCommandRule.PortType.jmxManager; import static org.assertj.core.api.Java6Assertions.assertThat; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.UUID; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.apache.geode.cache.EvictionAction; import org.apache.geode.cache.EvictionAlgorithm; import org.apache.geode.cache.PartitionAttributes; import org.apache.geode.cache.PartitionAttributesFactory; import org.apache.geode.cache.Region; import org.apache.geode.cache.RegionFactory; import org.apache.geode.cache.RegionShortcut; import org.apache.geode.cache.query.QueryInvalidException; import org.apache.geode.cache.query.data.Portfolio; import org.apache.geode.distributed.ConfigurationProperties; import org.apache.geode.internal.AvailablePortHelper; import org.apache.geode.internal.cache.EvictionAttributesImpl; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.management.ManagementService; import org.apache.geode.management.MemberMXBean; import org.apache.geode.management.internal.cli.domain.DataCommandResult; import org.apache.geode.management.internal.cli.dto.Value1; import org.apache.geode.management.internal.cli.result.CommandResult; import org.apache.geode.management.internal.cli.result.model.ResultModel; import org.apache.geode.management.internal.cli.util.CommandStringBuilder; import org.apache.geode.test.dunit.rules.ClusterStartupRule; import org.apache.geode.test.dunit.rules.MemberVM; import org.apache.geode.test.junit.rules.GfshCommandRule; @SuppressWarnings("serial") public class QueryCommandDUnitTestBase { private static final String DATA_REGION_NAME = "GemfireDataCommandsTestRegion"; private static final String DATA_REGION_NAME_PATH = SEPARATOR + DATA_REGION_NAME; private static final String DATA_REGION_WITH_EVICTION_NAME = "GemfireDataCommandsTestRegionWithEviction"; private static final String DATA_REGION_WITH_EVICTION_NAME_PATH = SEPARATOR + DATA_REGION_WITH_EVICTION_NAME; private static final String DATA_PAR_REGION_NAME = "GemfireDataCommandsTestParRegion"; private static final String DATA_PAR_REGION_NAME_PATH = SEPARATOR + DATA_PAR_REGION_NAME; private static final String DATA_REGION_WITH_PROXY_NAME = "GemfireDataCommandsTestRegionWithProxy"; private static final String DATA_REGION_WITH_PROXY_NAME_PATH = SEPARATOR + DATA_REGION_WITH_PROXY_NAME; private static final String SERIALIZATION_FILTER = "org.apache.geode.management.internal.cli.dto.**"; static final int COUNT = 5; @Rule public GfshCommandRule gfsh = new GfshCommandRule(); @Rule public ClusterStartupRule cluster = new ClusterStartupRule(); protected MemberVM locator, server1, server2; @Before public void before() throws Exception { Properties locatorProps = locatorProperties(); locator = cluster.startLocatorVM(0, l -> l.withHttpService().withProperties(locatorProps)); server1 = cluster.startServerVM(1, serverProperties(), locator.getPort()); server2 = cluster.startServerVM(2, serverProperties(), locator.getPort()); server1.invoke(() -> setupReplicatedRegion(DATA_REGION_NAME)); server2.invoke(() -> setupReplicatedRegion(DATA_REGION_NAME)); server1.invoke(() -> setupPartitionedRegion(DATA_PAR_REGION_NAME)); locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_PATH, 2); locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_PAR_REGION_NAME_PATH, 1); connectToLocator(); } public void connectToLocator() throws Exception { gfsh.connectAndVerify(locator.getJmxPort(), jmxManager); } @Test public void testWithGfshEnvironmentVariables() { String query = "query --query=\"select ID , status , createTime , pk, floatMinValue from ${DATA_REGION} where ID <= ${PORTFOLIO_ID}" + " and status=${STATUS}" + "\" --interactive=false"; gfsh.executeAndAssertThat("set variable --name=DATA_REGION --value=" + DATA_REGION_NAME_PATH) .statusIsSuccess(); gfsh.executeAndAssertThat("set variable --name=PORTFOLIO_ID --value=3").statusIsSuccess(); gfsh.executeAndAssertThat("set variable --name=STATUS --value=inactive").statusIsSuccess(); gfsh.executeAndAssertThat(query).statusIsSuccess(); } @Test public void testWithUnsetGfshEnvironmentVariables() { addIgnoredException(QueryInvalidException.class.getSimpleName(), locator.getVM()); String query = "query --query=\"select ID , status , createTime , pk, floatMinValue from ${UNSET_REGION} " + "where ID <= ${UNSET_PORTFOLIO_ID}" + " and status=${UNSET_STATUS}" + "\" --interactive=false"; gfsh.executeAndAssertThat(query).statusIsError() .containsOutput(String.format("Syntax error in query: %s", "")); } @Test public void testSimpleQuery() { server1.invoke(() -> prepareDataForRegion(DATA_PAR_REGION_NAME_PATH)); Random random = new Random(System.nanoTime()); int randomInteger = random.nextInt(COUNT); String query = "query --query=\"select ID , status , createTime , pk, floatMinValue from " + DATA_PAR_REGION_NAME_PATH + " where ID <= " + randomInteger + "\" --interactive=false"; CommandResult commandResult = gfsh.executeCommand(query); validateSelectResult(commandResult, true, (randomInteger + 1), new String[] {"ID", "status", "createTime", "pk", "floatMinValue"}); } @Test public void testSimpleQueryWithEscapingCharacter() { server1.invoke(() -> prepareDataForRegionWithSpecialCharacters(DATA_PAR_REGION_NAME_PATH)); String query = "query --query=\"select * from " + DATA_PAR_REGION_NAME_PATH + " e where e LIKE 'value\\$'\""; String query1 = "query --query=\"select * from " + DATA_PAR_REGION_NAME_PATH + " e where e LIKE 'value\\%'\""; gfsh.executeAndAssertThat(query).statusIsSuccess().containsOutput("value$"); gfsh.executeAndAssertThat(query1).statusIsSuccess().containsOutput("value%"); } @Test public void testSimpleQueryOnLocator() { server1.invoke(() -> prepareDataForRegion(DATA_PAR_REGION_NAME_PATH)); locator.invoke(() -> { String query = "query --query=\"select ID , status , createTime , pk, floatMinValue from " + DATA_PAR_REGION_NAME_PATH + " where ID <= 4" + "\" --interactive=false"; ManagementService service = ManagementService.getExistingManagementService(ClusterStartupRule.getCache()); MemberMXBean member = service.getMemberMXBean(); String cmdResult = member.processCommand(query); assertThat(cmdResult).contains("ID"); assertThat(cmdResult).contains("status"); assertThat(cmdResult).contains("createTime"); assertThat(cmdResult).contains("pk"); assertThat(cmdResult).contains("floatMinValue"); assertThat(cmdResult).contains("\"Rows\":\"5\""); }); } @Test public void testSimpleQueryWithUUID() { server1.invoke(() -> prepareDataForRegionWithUUID(DATA_PAR_REGION_NAME_PATH)); String uuidKey = String.valueOf(new UUID(1, 1)); String query = "query --query=\"select key from " + DATA_PAR_REGION_NAME_PATH + ".entries\""; String query1 = "query --query=\"select key,value from " + DATA_PAR_REGION_NAME_PATH + ".entries\""; gfsh.executeAndAssertThat(query).statusIsSuccess() .containsOutput(uuidKey); gfsh.executeAndAssertThat(query1).statusIsSuccess() .containsOutput(uuidKey, "value"); } @Test public void testQueryEvictedDataDeserializable() { server1.invoke(() -> setupReplicatedRegionWithEviction(DATA_REGION_WITH_EVICTION_NAME)); locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_WITH_EVICTION_NAME_PATH, 1); server1.invoke(() -> prepareDeserializableDataForRegion(DATA_REGION_WITH_EVICTION_NAME_PATH)); String query = "query --query=\"select Value from " + DATA_REGION_WITH_EVICTION_NAME_PATH + "\" --interactive=false"; CommandResult commandResult = gfsh.executeCommand(query); validateSelectResult(commandResult, Boolean.TRUE, 10, new String[] {"Value"}); } @Test public void testQueryEvictedDataNotDeserializable() { addIgnoredException(Exception.class.getSimpleName(), server1.getVM()); server1.invoke(() -> setupReplicatedRegionWithEviction(DATA_REGION_WITH_EVICTION_NAME)); locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_WITH_EVICTION_NAME_PATH, 1); server1 .invoke(() -> prepareNotDeserializableDataForRegion(DATA_REGION_WITH_EVICTION_NAME_PATH)); String query = "query --query=\"select Value from " + DATA_REGION_WITH_EVICTION_NAME_PATH + "\" --interactive=false"; CommandResult commandResult = gfsh.executeCommand(query); validateSelectResult(commandResult, Boolean.FALSE, -1, new String[] {"Value"}); assertThat(commandResult.asString()) .contains("An IOException was thrown while deserializing"); } private static void prepareDataForRegion(String regionPath) { InternalCache cache = ClusterStartupRule.getCache(); Region dataRegion = cache.getRegion(regionPath); for (int j = 0; j < 10; j++) { dataRegion.put(new Integer(j), new Portfolio(j)); } } private static void prepareDataForRegionWithSpecialCharacters(String regionPath) { InternalCache cache = ClusterStartupRule.getCache(); Region<Integer, String> dataRegion = cache.getRegion(regionPath); dataRegion.put(1, "value$"); dataRegion.put(2, "value%"); } private static void prepareDataForRegionWithUUID(String regionPath) { InternalCache cache = ClusterStartupRule.getCache(); Region<UUID, String> dataRegion = cache.getRegion(regionPath); dataRegion.put(new UUID(1, 1), "value"); } private static void prepareNotDeserializableDataForRegion(String regionPath) { InternalCache cache = ClusterStartupRule.getCache(); Region dataRegion = cache.getRegion(regionPath); for (int j = 0; j < 10; j++) { dataRegion.put(new Integer(j), new shouldFailSerializationFilter(j)); } } private static void prepareDeserializableDataForRegion(String regionPath) { InternalCache cache = ClusterStartupRule.getCache(); Region dataRegion = cache.getRegion(regionPath); for (int j = 0; j < 10; j++) { dataRegion.put(new Integer(j), new Value1(j)); } } private static void setupReplicatedRegionWithEviction(String regionName) { InternalCache cache = ClusterStartupRule.getCache(); EvictionAttributesImpl evictionAttributes = new EvictionAttributesImpl(); evictionAttributes.setMaximum(1).setAction(EvictionAction.OVERFLOW_TO_DISK) .setAlgorithm(EvictionAlgorithm.LRU_ENTRY); RegionFactory regionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE) .setEvictionAttributes(evictionAttributes); Region dataRegion = regionFactory.create(regionName); assertThat(dataRegion).isNotNull(); assertThat(dataRegion.getFullPath()).contains(regionName); } private static void setupPartitionedRegion(String regionName) { InternalCache cache = ClusterStartupRule.getCache(); PartitionAttributes partitionAttrs = new PartitionAttributesFactory().setRedundantCopies(2).create(); RegionFactory<Object, Object> partitionRegionFactory = cache.createRegionFactory(RegionShortcut.PARTITION); partitionRegionFactory.setPartitionAttributes(partitionAttrs); Region dataParRegion = partitionRegionFactory.create(regionName); assertThat(dataParRegion).isNotNull(); assertThat(dataParRegion.getFullPath()).contains(regionName); } private static void setupReplicatedRegion(String regionName) { InternalCache cache = ClusterStartupRule.getCache(); RegionFactory regionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE); Region dataRegion = regionFactory.create(regionName); assertThat(dataRegion).isNotNull(); assertThat(dataRegion.getFullPath()).contains(regionName); } private static void setupReplicatedProxyRegion(String regionName) { InternalCache cache = ClusterStartupRule.getCache(); RegionFactory<Integer, Portfolio> regionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE_PROXY); Region<Integer, Portfolio> proxyRegion = regionFactory.create(regionName); assertThat(proxyRegion).isNotNull(); assertThat(proxyRegion.getFullPath()).contains(regionName); } private void validateSelectResult(CommandResult cmdResult, Boolean expectSuccess, Integer expectedRows, String[] cols) { ResultModel rd = cmdResult.getResultData(); Map<String, String> data = rd.getDataSection(DataCommandResult.DATA_INFO_SECTION).getContent(); assertThat(data.get("Result")).isEqualTo(expectSuccess.toString()); if (expectSuccess && expectedRows != -1) { assertThat(data.get("Rows")).isEqualTo(expectedRows.toString()); if (expectedRows > 0 && cols != null) { Map<String, List<String>> table = rd.getTableSection(DataCommandResult.QUERY_SECTION).getContent(); assertThat(table.keySet()).contains(cols); } } } private Properties locatorProperties() { int jmxPort = AvailablePortHelper.getRandomAvailableTCPPort(); Properties props = new Properties(); props.setProperty(MCAST_PORT, "0"); props.setProperty(LOG_LEVEL, "fine"); props.setProperty(SERIALIZABLE_OBJECT_FILTER, SERIALIZATION_FILTER); props.setProperty(ConfigurationProperties.JMX_MANAGER_HOSTNAME_FOR_CLIENTS, "localhost"); props.setProperty(ConfigurationProperties.JMX_MANAGER_PORT, "" + jmxPort); return props; } private Properties serverProperties() { Properties props = new Properties(); props.setProperty(SERIALIZABLE_OBJECT_FILTER, SERIALIZATION_FILTER); return props; } public static class shouldFailSerializationFilter extends Value1 { private Value1 value1 = null; public shouldFailSerializationFilter(int i) { super(i); } public Value1 getValue1() { return value1; } public void setValue1(Value1 value1) { this.value1 = value1; } } @Test public void testSimpleQueryWithProxyRegion() { server1.invoke(() -> setupReplicatedProxyRegion(DATA_REGION_WITH_PROXY_NAME)); server2.invoke(() -> setupReplicatedRegion(DATA_REGION_WITH_PROXY_NAME)); locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_WITH_PROXY_NAME_PATH, 2); server1.invoke(() -> prepareDataForRegion(DATA_REGION_WITH_PROXY_NAME_PATH)); String member = "server-2"; Random random = new Random(System.nanoTime()); int randomInteger = random.nextInt(COUNT); String queryString = new StringBuilder() .append("\"select ID , status , createTime , pk, floatMinValue from ") .append(DATA_REGION_WITH_PROXY_NAME_PATH).append(" where ID <= ") .append(randomInteger).append("\"").toString(); String command = new CommandStringBuilder(QUERY) .addOption(MEMBER, member) .addOption(QUERY, queryString).getCommandString(); CommandResult commandResult = gfsh.executeAndAssertThat(command).getCommandResult(); validateSelectResult(commandResult, true, (randomInteger + 1), new String[] {"ID", "status", "createTime", "pk", "floatMinValue"}); } }
UTF-8
Java
16,812
java
QueryCommandDUnitTestBase.java
Java
[ { "context": "R_REGION_NAME_PATH));\n String uuidKey = String.valueOf(new UUID(1, 1));\n String query = \"query --quer", "end": 8542, "score": 0.7702423930168152, "start": 8535, "tag": "KEY", "value": "valueOf" }, { "context": "ION_WITH_PROXY_NAME_PATH));\n\n String member = \"server-2\";\n Random random = new Random(System.nanoTime(", "end": 16069, "score": 0.9219962954521179, "start": 16061, "tag": "USERNAME", "value": "server-2" } ]
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.geode.management.internal.cli.commands; import static org.apache.geode.cache.Region.SEPARATOR; import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL; import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT; import static org.apache.geode.distributed.ConfigurationProperties.SERIALIZABLE_OBJECT_FILTER; import static org.apache.geode.management.internal.i18n.CliStrings.MEMBER; import static org.apache.geode.management.internal.i18n.CliStrings.QUERY; import static org.apache.geode.test.dunit.IgnoredException.addIgnoredException; import static org.apache.geode.test.junit.rules.GfshCommandRule.PortType.jmxManager; import static org.assertj.core.api.Java6Assertions.assertThat; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.UUID; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.apache.geode.cache.EvictionAction; import org.apache.geode.cache.EvictionAlgorithm; import org.apache.geode.cache.PartitionAttributes; import org.apache.geode.cache.PartitionAttributesFactory; import org.apache.geode.cache.Region; import org.apache.geode.cache.RegionFactory; import org.apache.geode.cache.RegionShortcut; import org.apache.geode.cache.query.QueryInvalidException; import org.apache.geode.cache.query.data.Portfolio; import org.apache.geode.distributed.ConfigurationProperties; import org.apache.geode.internal.AvailablePortHelper; import org.apache.geode.internal.cache.EvictionAttributesImpl; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.management.ManagementService; import org.apache.geode.management.MemberMXBean; import org.apache.geode.management.internal.cli.domain.DataCommandResult; import org.apache.geode.management.internal.cli.dto.Value1; import org.apache.geode.management.internal.cli.result.CommandResult; import org.apache.geode.management.internal.cli.result.model.ResultModel; import org.apache.geode.management.internal.cli.util.CommandStringBuilder; import org.apache.geode.test.dunit.rules.ClusterStartupRule; import org.apache.geode.test.dunit.rules.MemberVM; import org.apache.geode.test.junit.rules.GfshCommandRule; @SuppressWarnings("serial") public class QueryCommandDUnitTestBase { private static final String DATA_REGION_NAME = "GemfireDataCommandsTestRegion"; private static final String DATA_REGION_NAME_PATH = SEPARATOR + DATA_REGION_NAME; private static final String DATA_REGION_WITH_EVICTION_NAME = "GemfireDataCommandsTestRegionWithEviction"; private static final String DATA_REGION_WITH_EVICTION_NAME_PATH = SEPARATOR + DATA_REGION_WITH_EVICTION_NAME; private static final String DATA_PAR_REGION_NAME = "GemfireDataCommandsTestParRegion"; private static final String DATA_PAR_REGION_NAME_PATH = SEPARATOR + DATA_PAR_REGION_NAME; private static final String DATA_REGION_WITH_PROXY_NAME = "GemfireDataCommandsTestRegionWithProxy"; private static final String DATA_REGION_WITH_PROXY_NAME_PATH = SEPARATOR + DATA_REGION_WITH_PROXY_NAME; private static final String SERIALIZATION_FILTER = "org.apache.geode.management.internal.cli.dto.**"; static final int COUNT = 5; @Rule public GfshCommandRule gfsh = new GfshCommandRule(); @Rule public ClusterStartupRule cluster = new ClusterStartupRule(); protected MemberVM locator, server1, server2; @Before public void before() throws Exception { Properties locatorProps = locatorProperties(); locator = cluster.startLocatorVM(0, l -> l.withHttpService().withProperties(locatorProps)); server1 = cluster.startServerVM(1, serverProperties(), locator.getPort()); server2 = cluster.startServerVM(2, serverProperties(), locator.getPort()); server1.invoke(() -> setupReplicatedRegion(DATA_REGION_NAME)); server2.invoke(() -> setupReplicatedRegion(DATA_REGION_NAME)); server1.invoke(() -> setupPartitionedRegion(DATA_PAR_REGION_NAME)); locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_PATH, 2); locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_PAR_REGION_NAME_PATH, 1); connectToLocator(); } public void connectToLocator() throws Exception { gfsh.connectAndVerify(locator.getJmxPort(), jmxManager); } @Test public void testWithGfshEnvironmentVariables() { String query = "query --query=\"select ID , status , createTime , pk, floatMinValue from ${DATA_REGION} where ID <= ${PORTFOLIO_ID}" + " and status=${STATUS}" + "\" --interactive=false"; gfsh.executeAndAssertThat("set variable --name=DATA_REGION --value=" + DATA_REGION_NAME_PATH) .statusIsSuccess(); gfsh.executeAndAssertThat("set variable --name=PORTFOLIO_ID --value=3").statusIsSuccess(); gfsh.executeAndAssertThat("set variable --name=STATUS --value=inactive").statusIsSuccess(); gfsh.executeAndAssertThat(query).statusIsSuccess(); } @Test public void testWithUnsetGfshEnvironmentVariables() { addIgnoredException(QueryInvalidException.class.getSimpleName(), locator.getVM()); String query = "query --query=\"select ID , status , createTime , pk, floatMinValue from ${UNSET_REGION} " + "where ID <= ${UNSET_PORTFOLIO_ID}" + " and status=${UNSET_STATUS}" + "\" --interactive=false"; gfsh.executeAndAssertThat(query).statusIsError() .containsOutput(String.format("Syntax error in query: %s", "")); } @Test public void testSimpleQuery() { server1.invoke(() -> prepareDataForRegion(DATA_PAR_REGION_NAME_PATH)); Random random = new Random(System.nanoTime()); int randomInteger = random.nextInt(COUNT); String query = "query --query=\"select ID , status , createTime , pk, floatMinValue from " + DATA_PAR_REGION_NAME_PATH + " where ID <= " + randomInteger + "\" --interactive=false"; CommandResult commandResult = gfsh.executeCommand(query); validateSelectResult(commandResult, true, (randomInteger + 1), new String[] {"ID", "status", "createTime", "pk", "floatMinValue"}); } @Test public void testSimpleQueryWithEscapingCharacter() { server1.invoke(() -> prepareDataForRegionWithSpecialCharacters(DATA_PAR_REGION_NAME_PATH)); String query = "query --query=\"select * from " + DATA_PAR_REGION_NAME_PATH + " e where e LIKE 'value\\$'\""; String query1 = "query --query=\"select * from " + DATA_PAR_REGION_NAME_PATH + " e where e LIKE 'value\\%'\""; gfsh.executeAndAssertThat(query).statusIsSuccess().containsOutput("value$"); gfsh.executeAndAssertThat(query1).statusIsSuccess().containsOutput("value%"); } @Test public void testSimpleQueryOnLocator() { server1.invoke(() -> prepareDataForRegion(DATA_PAR_REGION_NAME_PATH)); locator.invoke(() -> { String query = "query --query=\"select ID , status , createTime , pk, floatMinValue from " + DATA_PAR_REGION_NAME_PATH + " where ID <= 4" + "\" --interactive=false"; ManagementService service = ManagementService.getExistingManagementService(ClusterStartupRule.getCache()); MemberMXBean member = service.getMemberMXBean(); String cmdResult = member.processCommand(query); assertThat(cmdResult).contains("ID"); assertThat(cmdResult).contains("status"); assertThat(cmdResult).contains("createTime"); assertThat(cmdResult).contains("pk"); assertThat(cmdResult).contains("floatMinValue"); assertThat(cmdResult).contains("\"Rows\":\"5\""); }); } @Test public void testSimpleQueryWithUUID() { server1.invoke(() -> prepareDataForRegionWithUUID(DATA_PAR_REGION_NAME_PATH)); String uuidKey = String.valueOf(new UUID(1, 1)); String query = "query --query=\"select key from " + DATA_PAR_REGION_NAME_PATH + ".entries\""; String query1 = "query --query=\"select key,value from " + DATA_PAR_REGION_NAME_PATH + ".entries\""; gfsh.executeAndAssertThat(query).statusIsSuccess() .containsOutput(uuidKey); gfsh.executeAndAssertThat(query1).statusIsSuccess() .containsOutput(uuidKey, "value"); } @Test public void testQueryEvictedDataDeserializable() { server1.invoke(() -> setupReplicatedRegionWithEviction(DATA_REGION_WITH_EVICTION_NAME)); locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_WITH_EVICTION_NAME_PATH, 1); server1.invoke(() -> prepareDeserializableDataForRegion(DATA_REGION_WITH_EVICTION_NAME_PATH)); String query = "query --query=\"select Value from " + DATA_REGION_WITH_EVICTION_NAME_PATH + "\" --interactive=false"; CommandResult commandResult = gfsh.executeCommand(query); validateSelectResult(commandResult, Boolean.TRUE, 10, new String[] {"Value"}); } @Test public void testQueryEvictedDataNotDeserializable() { addIgnoredException(Exception.class.getSimpleName(), server1.getVM()); server1.invoke(() -> setupReplicatedRegionWithEviction(DATA_REGION_WITH_EVICTION_NAME)); locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_WITH_EVICTION_NAME_PATH, 1); server1 .invoke(() -> prepareNotDeserializableDataForRegion(DATA_REGION_WITH_EVICTION_NAME_PATH)); String query = "query --query=\"select Value from " + DATA_REGION_WITH_EVICTION_NAME_PATH + "\" --interactive=false"; CommandResult commandResult = gfsh.executeCommand(query); validateSelectResult(commandResult, Boolean.FALSE, -1, new String[] {"Value"}); assertThat(commandResult.asString()) .contains("An IOException was thrown while deserializing"); } private static void prepareDataForRegion(String regionPath) { InternalCache cache = ClusterStartupRule.getCache(); Region dataRegion = cache.getRegion(regionPath); for (int j = 0; j < 10; j++) { dataRegion.put(new Integer(j), new Portfolio(j)); } } private static void prepareDataForRegionWithSpecialCharacters(String regionPath) { InternalCache cache = ClusterStartupRule.getCache(); Region<Integer, String> dataRegion = cache.getRegion(regionPath); dataRegion.put(1, "value$"); dataRegion.put(2, "value%"); } private static void prepareDataForRegionWithUUID(String regionPath) { InternalCache cache = ClusterStartupRule.getCache(); Region<UUID, String> dataRegion = cache.getRegion(regionPath); dataRegion.put(new UUID(1, 1), "value"); } private static void prepareNotDeserializableDataForRegion(String regionPath) { InternalCache cache = ClusterStartupRule.getCache(); Region dataRegion = cache.getRegion(regionPath); for (int j = 0; j < 10; j++) { dataRegion.put(new Integer(j), new shouldFailSerializationFilter(j)); } } private static void prepareDeserializableDataForRegion(String regionPath) { InternalCache cache = ClusterStartupRule.getCache(); Region dataRegion = cache.getRegion(regionPath); for (int j = 0; j < 10; j++) { dataRegion.put(new Integer(j), new Value1(j)); } } private static void setupReplicatedRegionWithEviction(String regionName) { InternalCache cache = ClusterStartupRule.getCache(); EvictionAttributesImpl evictionAttributes = new EvictionAttributesImpl(); evictionAttributes.setMaximum(1).setAction(EvictionAction.OVERFLOW_TO_DISK) .setAlgorithm(EvictionAlgorithm.LRU_ENTRY); RegionFactory regionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE) .setEvictionAttributes(evictionAttributes); Region dataRegion = regionFactory.create(regionName); assertThat(dataRegion).isNotNull(); assertThat(dataRegion.getFullPath()).contains(regionName); } private static void setupPartitionedRegion(String regionName) { InternalCache cache = ClusterStartupRule.getCache(); PartitionAttributes partitionAttrs = new PartitionAttributesFactory().setRedundantCopies(2).create(); RegionFactory<Object, Object> partitionRegionFactory = cache.createRegionFactory(RegionShortcut.PARTITION); partitionRegionFactory.setPartitionAttributes(partitionAttrs); Region dataParRegion = partitionRegionFactory.create(regionName); assertThat(dataParRegion).isNotNull(); assertThat(dataParRegion.getFullPath()).contains(regionName); } private static void setupReplicatedRegion(String regionName) { InternalCache cache = ClusterStartupRule.getCache(); RegionFactory regionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE); Region dataRegion = regionFactory.create(regionName); assertThat(dataRegion).isNotNull(); assertThat(dataRegion.getFullPath()).contains(regionName); } private static void setupReplicatedProxyRegion(String regionName) { InternalCache cache = ClusterStartupRule.getCache(); RegionFactory<Integer, Portfolio> regionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE_PROXY); Region<Integer, Portfolio> proxyRegion = regionFactory.create(regionName); assertThat(proxyRegion).isNotNull(); assertThat(proxyRegion.getFullPath()).contains(regionName); } private void validateSelectResult(CommandResult cmdResult, Boolean expectSuccess, Integer expectedRows, String[] cols) { ResultModel rd = cmdResult.getResultData(); Map<String, String> data = rd.getDataSection(DataCommandResult.DATA_INFO_SECTION).getContent(); assertThat(data.get("Result")).isEqualTo(expectSuccess.toString()); if (expectSuccess && expectedRows != -1) { assertThat(data.get("Rows")).isEqualTo(expectedRows.toString()); if (expectedRows > 0 && cols != null) { Map<String, List<String>> table = rd.getTableSection(DataCommandResult.QUERY_SECTION).getContent(); assertThat(table.keySet()).contains(cols); } } } private Properties locatorProperties() { int jmxPort = AvailablePortHelper.getRandomAvailableTCPPort(); Properties props = new Properties(); props.setProperty(MCAST_PORT, "0"); props.setProperty(LOG_LEVEL, "fine"); props.setProperty(SERIALIZABLE_OBJECT_FILTER, SERIALIZATION_FILTER); props.setProperty(ConfigurationProperties.JMX_MANAGER_HOSTNAME_FOR_CLIENTS, "localhost"); props.setProperty(ConfigurationProperties.JMX_MANAGER_PORT, "" + jmxPort); return props; } private Properties serverProperties() { Properties props = new Properties(); props.setProperty(SERIALIZABLE_OBJECT_FILTER, SERIALIZATION_FILTER); return props; } public static class shouldFailSerializationFilter extends Value1 { private Value1 value1 = null; public shouldFailSerializationFilter(int i) { super(i); } public Value1 getValue1() { return value1; } public void setValue1(Value1 value1) { this.value1 = value1; } } @Test public void testSimpleQueryWithProxyRegion() { server1.invoke(() -> setupReplicatedProxyRegion(DATA_REGION_WITH_PROXY_NAME)); server2.invoke(() -> setupReplicatedRegion(DATA_REGION_WITH_PROXY_NAME)); locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_WITH_PROXY_NAME_PATH, 2); server1.invoke(() -> prepareDataForRegion(DATA_REGION_WITH_PROXY_NAME_PATH)); String member = "server-2"; Random random = new Random(System.nanoTime()); int randomInteger = random.nextInt(COUNT); String queryString = new StringBuilder() .append("\"select ID , status , createTime , pk, floatMinValue from ") .append(DATA_REGION_WITH_PROXY_NAME_PATH).append(" where ID <= ") .append(randomInteger).append("\"").toString(); String command = new CommandStringBuilder(QUERY) .addOption(MEMBER, member) .addOption(QUERY, queryString).getCommandString(); CommandResult commandResult = gfsh.executeAndAssertThat(command).getCommandResult(); validateSelectResult(commandResult, true, (randomInteger + 1), new String[] {"ID", "status", "createTime", "pk", "floatMinValue"}); } }
16,812
0.737985
0.733048
389
42.21851
31.965214
125
false
false
0
0
0
0
0
0
0.727506
false
false
10
b7253974a3ebcaac197296bee48f7789a8f0c997
25,606,595,028,323
4777a0c394979a3786fb1d255ec4d815b2a1d2f3
/retail-goods/src/main/java/com/morning/star/retail/entity/BrandWaterEntity.java
562d024c22b660c2dfa09d3e8dc2044fe61a89f4
[]
no_license
chaoren007/big-middle
https://github.com/chaoren007/big-middle
0d98ea0ce7b2c892eb249dbbd116b4e0767686c5
29952ea01f0af89847286fa7d910640b1c83e3db
refs/heads/master
2022-12-15T13:29:44.555000
2019-07-29T08:47:03
2019-07-29T08:47:03
199,414,109
0
3
null
false
2022-12-10T03:18:29
2019-07-29T08:45:13
2019-07-29T08:50:11
2022-12-10T03:18:27
1,275
0
3
7
Java
false
false
package com.morning.star.retail.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.hibernate.annotations.Where; @Table(name = "retail_brand_water") @Where(clause = "delete_flag <> 1") @Entity public class BrandWaterEntity extends WaterEntity { private static final long serialVersionUID = 1111320370190733556L; private Long id; /** * 品牌名称 */ @Column(length=64) private String brandName; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } }
UTF-8
Java
711
java
BrandWaterEntity.java
Java
[]
null
[]
package com.morning.star.retail.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.hibernate.annotations.Where; @Table(name = "retail_brand_water") @Where(clause = "delete_flag <> 1") @Entity public class BrandWaterEntity extends WaterEntity { private static final long serialVersionUID = 1111320370190733556L; private Long id; /** * 品牌名称 */ @Column(length=64) private String brandName; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } }
711
0.72404
0.692745
40
16.575001
17.468382
67
false
false
0
0
0
0
0
0
0.825
false
false
10
a5554b57470d04b6b8e5c25968d27640859de802
33,277,406,649,022
181a54c01414ecedf2127bc62c01578fc828b9c5
/src/test/java/org/launchcode/techjobs/oo/TestTaskFour.java
3015fb394b061cf715ef90c3723b120858bed2a5
[]
no_license
LC101-May-2021-Java-Unit2/assignment-2-techjobs-object-oriented-edition-shanthipriyaram
https://github.com/LC101-May-2021-Java-Unit2/assignment-2-techjobs-object-oriented-edition-shanthipriyaram
075e4ecd626c0fedfc72d8f7b05bc6c107b21348
60f3d5c0146313d136c91d9378617a276aab444e
refs/heads/master
2023-08-28T10:51:10.438000
2021-11-08T00:44:12
2021-11-08T00:44:12
409,404,158
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.launchcode.techjobs.oo; import mockit.Expectations; import mockit.Mocked; import mockit.Tested; import org.junit.Assert; import org.junit.Test; import org.launchcode.techjobs.oo.test.JobTest; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import static org.junit.Assert.*; /** * Created by LaunchCode */ public class TestTaskFour extends AbstractTest { @Tested JobTest jobTest; @Test public void testTestSettingJobIdExists () throws ClassNotFoundException { Class jobTestClass = getClassByName("test.JobTest"); Method testSettingJobIdMethod = null; try { testSettingJobIdMethod = jobTestClass.getMethod("testSettingJobId"); } catch (NoSuchMethodException e) { fail("JobTest does not have a testSettingId method"); } } @Test public void testTestSettingJobIdCallsJobConstructorTwice (@Mocked Job job) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { Class jobTestClass = getClassByName("test.JobTest"); JobTest jobTest = (JobTest) jobTestClass.getConstructor().newInstance(); Method testSettingJobIdMethod = jobTestClass.getMethod("testSettingJobId"); new Expectations() {{ new Job(); minTimes = 2; maxTimes = 2; }}; try { testSettingJobIdMethod.invoke(jobTest); } catch (InvocationTargetException e) { // do nothing: this is expected when using a mocked Job instance } } // TODO - this test isn't matching the expectation properly. // @Test // public void testTestSettingJobIdCallsProperAssertion (@Mocked Assert mockedAssert) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { // Class jobTestClass = getClassByName("test.JobTest"); // JobTest jobTest = (JobTest) jobTestClass.getConstructor().newInstance(); // Method testSettingJobIdMethod = jobTestClass.getMethod("testSettingJobId"); // // new Expectations() {{ // assertNotEquals(anyInt, anyInt); // }}; // // testSettingJobIdMethod.invoke(jobTest); // } @Test public void testTestJobConstructorSetsAllFieldsExists () throws ClassNotFoundException { Class jobTestClass = getClassByName("test.JobTest"); Method testSettingJobIdMethod = null; try { testSettingJobIdMethod = jobTestClass.getMethod("testJobConstructorSetsAllFields"); } catch (NoSuchMethodException e) { fail("JobTest does not have a testJobConstructorSetsAllFields method"); } } @Test public void testTestJobConstructorSetsAllFieldsCallsAsserts (@Mocked Assert mockedAssert) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class jobTestClass = getClassByName("test.JobTest"); Method testJobConstructorSetsAllFieldsMethod = jobTestClass.getMethod("testJobConstructorSetsAllFields"); new Expectations() {{ Assert.assertTrue(anyBoolean); minTimes = 5; Assert.assertEquals(anyString, anyString); minTimes = 5; }}; testJobConstructorSetsAllFieldsMethod.invoke(jobTest); } @Test public void testTestJobsForEqualityExists () throws ClassNotFoundException { Class jobTestClass = getClassByName("test.JobTest"); try { jobTestClass.getMethod("testJobsForEquality"); } catch (NoSuchMethodException e) { fail("JobTest does not have a testJobsForEquality method"); } } @Test public void testTestJobsForEqualityCallsAssertion(@Mocked Assert mockedAssert) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class jobTestClass = getClassByName("test.JobTest"); Method testJobsForEqualityMethod = jobTestClass.getMethod("testJobsForEquality"); new Expectations() {{ assertFalse(anyBoolean); }}; testJobsForEqualityMethod.invoke(jobTest); } }
UTF-8
Java
4,238
java
TestTaskFour.java
Java
[ { "context": "port static org.junit.Assert.*;\n\n/**\n * Created by LaunchCode\n */\npublic class TestTaskFour extends AbstractTes", "end": 355, "score": 0.9988383054733276, "start": 345, "tag": "USERNAME", "value": "LaunchCode" } ]
null
[]
package org.launchcode.techjobs.oo; import mockit.Expectations; import mockit.Mocked; import mockit.Tested; import org.junit.Assert; import org.junit.Test; import org.launchcode.techjobs.oo.test.JobTest; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import static org.junit.Assert.*; /** * Created by LaunchCode */ public class TestTaskFour extends AbstractTest { @Tested JobTest jobTest; @Test public void testTestSettingJobIdExists () throws ClassNotFoundException { Class jobTestClass = getClassByName("test.JobTest"); Method testSettingJobIdMethod = null; try { testSettingJobIdMethod = jobTestClass.getMethod("testSettingJobId"); } catch (NoSuchMethodException e) { fail("JobTest does not have a testSettingId method"); } } @Test public void testTestSettingJobIdCallsJobConstructorTwice (@Mocked Job job) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { Class jobTestClass = getClassByName("test.JobTest"); JobTest jobTest = (JobTest) jobTestClass.getConstructor().newInstance(); Method testSettingJobIdMethod = jobTestClass.getMethod("testSettingJobId"); new Expectations() {{ new Job(); minTimes = 2; maxTimes = 2; }}; try { testSettingJobIdMethod.invoke(jobTest); } catch (InvocationTargetException e) { // do nothing: this is expected when using a mocked Job instance } } // TODO - this test isn't matching the expectation properly. // @Test // public void testTestSettingJobIdCallsProperAssertion (@Mocked Assert mockedAssert) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { // Class jobTestClass = getClassByName("test.JobTest"); // JobTest jobTest = (JobTest) jobTestClass.getConstructor().newInstance(); // Method testSettingJobIdMethod = jobTestClass.getMethod("testSettingJobId"); // // new Expectations() {{ // assertNotEquals(anyInt, anyInt); // }}; // // testSettingJobIdMethod.invoke(jobTest); // } @Test public void testTestJobConstructorSetsAllFieldsExists () throws ClassNotFoundException { Class jobTestClass = getClassByName("test.JobTest"); Method testSettingJobIdMethod = null; try { testSettingJobIdMethod = jobTestClass.getMethod("testJobConstructorSetsAllFields"); } catch (NoSuchMethodException e) { fail("JobTest does not have a testJobConstructorSetsAllFields method"); } } @Test public void testTestJobConstructorSetsAllFieldsCallsAsserts (@Mocked Assert mockedAssert) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class jobTestClass = getClassByName("test.JobTest"); Method testJobConstructorSetsAllFieldsMethod = jobTestClass.getMethod("testJobConstructorSetsAllFields"); new Expectations() {{ Assert.assertTrue(anyBoolean); minTimes = 5; Assert.assertEquals(anyString, anyString); minTimes = 5; }}; testJobConstructorSetsAllFieldsMethod.invoke(jobTest); } @Test public void testTestJobsForEqualityExists () throws ClassNotFoundException { Class jobTestClass = getClassByName("test.JobTest"); try { jobTestClass.getMethod("testJobsForEquality"); } catch (NoSuchMethodException e) { fail("JobTest does not have a testJobsForEquality method"); } } @Test public void testTestJobsForEqualityCallsAssertion(@Mocked Assert mockedAssert) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class jobTestClass = getClassByName("test.JobTest"); Method testJobsForEqualityMethod = jobTestClass.getMethod("testJobsForEquality"); new Expectations() {{ assertFalse(anyBoolean); }}; testJobsForEqualityMethod.invoke(jobTest); } }
4,238
0.705285
0.704342
115
35.852173
43.116474
218
false
false
0
0
0
0
0
0
0.565217
false
false
10
04c0febf7b21839f3161bcb5bcafe5deaf0a9722
25,769,807,681
40665051fadf3fb75e5a8f655362126c1a2a3af6
/CesarValiente-quitesleep/97cb4dcabd1c6c267ff65f52bd419884d4c61226/157/DDBBValues.java
10037935284048beb490cb5d76f1f458e76690dc
[]
no_license
fermadeiral/StyleErrors
https://github.com/fermadeiral/StyleErrors
6f44379207e8490ba618365c54bdfef554fc4fde
d1a6149d9526eb757cf053bc971dbd92b2bfcdf1
refs/heads/master
2020-07-15T12:55:10.564000
2019-10-24T02:30:45
2019-10-24T02:30:45
205,546,543
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.staticValues; public class DDBBValues { //------ Contact -------------------------------// public static final String CONTACT_ID = "contactId"; public static final String CONTACT_NAME = "contactName"; public static final String BANNED = "banned"; //-------- Phone -----------------------------------// public static final String CONTACT = "contact"; public static final String CONTACT_PHONE = "contactPhone"; public static final String USED_TO_SEND = "usedToSend"; //-------- Mail --------------------------------// public static final String CONTACT_MAIL = "contactMail"; //Also used here: CONTACT and USED_TO_SEND //-------- Schedule --------------------------------// public static final String START_SCHEDULE = "startSchedule"; public static final String END_SCHEDULE = "endSchedule"; public static final String START_FORMAT_SCHEDULE = "startFormatSchedule"; public static final String END_FORMAT_SCHEDULE = "endFormatSchedule"; //-------- Banned --------------------------------------// public static final String SCHEDULE = "schedule"; //Also used here: CONTACT //-------- CallLog ---------------------------------// public static final String PHONE = "phone"; public static final String NUM_ORDER = "numOrder"; public static final String NUM_SEND_SMS = "numSendSms"; public static final String NUM_SEND_MAIL = "numSendMail"; }
UTF-8
Java
2,138
java
DDBBValues.java
Java
[ { "context": "/* \n \tCopyright 2010 Cesar Valiente Gordo\n \n \tThis file is part of QuiteSleep.\n\n QuiteSl", "end": 41, "score": 0.9998524188995361, "start": 21, "tag": "NAME", "value": "Cesar Valiente Gordo" } ]
null
[]
/* Copyright 2010 <NAME> This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.staticValues; public class DDBBValues { //------ Contact -------------------------------// public static final String CONTACT_ID = "contactId"; public static final String CONTACT_NAME = "contactName"; public static final String BANNED = "banned"; //-------- Phone -----------------------------------// public static final String CONTACT = "contact"; public static final String CONTACT_PHONE = "contactPhone"; public static final String USED_TO_SEND = "usedToSend"; //-------- Mail --------------------------------// public static final String CONTACT_MAIL = "contactMail"; //Also used here: CONTACT and USED_TO_SEND //-------- Schedule --------------------------------// public static final String START_SCHEDULE = "startSchedule"; public static final String END_SCHEDULE = "endSchedule"; public static final String START_FORMAT_SCHEDULE = "startFormatSchedule"; public static final String END_FORMAT_SCHEDULE = "endFormatSchedule"; //-------- Banned --------------------------------------// public static final String SCHEDULE = "schedule"; //Also used here: CONTACT //-------- CallLog ---------------------------------// public static final String PHONE = "phone"; public static final String NUM_ORDER = "numOrder"; public static final String NUM_SEND_SMS = "numSendSms"; public static final String NUM_SEND_MAIL = "numSendMail"; }
2,124
0.649673
0.647334
56
37.17857
26.947109
74
false
false
0
0
0
0
0
0
1.267857
false
false
10
37bb0f43c14286cb6f4f22c65a2ccea3b996909b
25,769,808,618
254a9b34356712383b7a69d568b97fc135993664
/jcertif-dao/src/test/java/com/jcertif/dao/hibernate/comite/ComiteOrganisationDAOHibernateTest.java
c9d36fca61914cd4136cd620d1034d2a25a97c59
[]
no_license
albu77/jcertif-backend-2012
https://github.com/albu77/jcertif-backend-2012
c9920f30a80e757a51372d09798a39e7ed84ddcb
f25c71db9c2704e24b5e8e5eb20578bd299c09be
refs/heads/master
2018-12-30T08:48:26.982000
2013-02-10T01:22:23
2013-02-10T01:22:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jcertif.dao.hibernate.comite; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import com.jcertif.bo.comite.ComiteOrganisation; import com.jcertif.dao.api.comite.ComiteOrganisationDAO; import com.jcertif.dao.hibernate.AbstractDAOTestCase; /** * Test de la classe ComiteOrganisationDAOHibernate. * * @author rossi.oddet * */ @ContextConfiguration(locations = { "classpath:jcertif-dao-test-beans.xml" }) public class ComiteOrganisationDAOHibernateTest extends AbstractDAOTestCase { /** * DAO ComiteOrganisation. */ @Autowired private ComiteOrganisationDAO comiteOrganisationDAO; /** * Test de la methode getReference(). */ @Test public void testGetReference() { ComiteOrganisation comite = comiteOrganisationDAO.getReference(Long .valueOf(1)); assertEquals("nom 1", comite.getNom()); assertEquals("prenom 1", comite.getPrenom()); assertEquals("1@jcertif.com", comite.getEmail()); assertEquals("details 1", comite.getDetails()); assertEquals(Character.valueOf('M'), comite.getSexeMf()); assertEquals("111111", comite.getTelephone()); } /** * Test de la methode findById(). */ @Test public void testFindById() { ComiteOrganisation comite = comiteOrganisationDAO.findById(Long .valueOf(1)); assertEquals("nom 1", comite.getNom()); assertEquals("prenom 1", comite.getPrenom()); assertEquals("1@jcertif.com", comite.getEmail()); assertEquals("details 1", comite.getDetails()); assertEquals(Character.valueOf('M'), comite.getSexeMf()); assertEquals("111111", comite.getTelephone()); } /** * Test de la methode findAll(). */ @Test public void testFindAll() { assertEquals(4, comiteOrganisationDAO.findAll().size()); } /** * Test de la methode findAllWithSort(). */ @Test public void testFindAllWithSort() { assertEquals("nom 4", comiteOrganisationDAO.findAllWithSort("nom", false).iterator() .next().getNom()); } /** * Test de la methode persist(). */ @Test public void testPersist() { ComiteOrganisation comite = new ComiteOrganisation(); comite.setNom("nom 100"); comite.setPrenom("prenom 100"); comiteOrganisationDAO.persist(comite); ComiteOrganisation comiteRecup = comiteOrganisationDAO.findById(comite .getId()); assertEquals("nom 100", comiteRecup.getNom()); assertEquals("prenom 100", comiteRecup.getPrenom()); } /** * Test de la methode merge(). */ @Test public void testMerge() { ComiteOrganisation comite = new ComiteOrganisation(); comite.setNom("nom 1000"); comite.setPrenom("prenom 1000"); ComiteOrganisation persistedComiteOrganisation = comiteOrganisationDAO .merge(comite); ComiteOrganisation comiteRecup = comiteOrganisationDAO .findById(persistedComiteOrganisation.getId()); assertEquals("nom 1000", comiteRecup.getNom()); assertEquals("prenom 1000", comiteRecup.getPrenom()); } /** * Test de la methode remove(). */ @Test public void testRemove() { ComiteOrganisation entity = comiteOrganisationDAO.findById(Long .valueOf(1l)); comiteOrganisationDAO.remove(entity); assertEquals(3, comiteOrganisationDAO.findAll().size()); } }
UTF-8
Java
3,395
java
ComiteOrganisationDAOHibernateTest.java
Java
[ { "context": "e ComiteOrganisationDAOHibernate.\r\n * \r\n * @author rossi.oddet\r\n * \r\n */\r\n@ContextConfiguration(locations = { \"c", "end": 497, "score": 0.971142590045929, "start": 486, "tag": "USERNAME", "value": "rossi.oddet" }, { "context": "\"prenom 1\", comite.getPrenom());\r\n\t\tassertEquals(\"1@jcertif.com\", comite.getEmail());\r\n\t\tassertEquals(\"details 1\"", "end": 1086, "score": 0.9999306797981262, "start": 1073, "tag": "EMAIL", "value": "1@jcertif.com" }, { "context": "\"prenom 1\", comite.getPrenom());\r\n\t\tassertEquals(\"1@jcertif.com\", comite.getEmail());\r\n\t\tassertEquals(\"details 1\"", "end": 1572, "score": 0.9999306797981262, "start": 1559, "tag": "EMAIL", "value": "1@jcertif.com" } ]
null
[]
package com.jcertif.dao.hibernate.comite; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import com.jcertif.bo.comite.ComiteOrganisation; import com.jcertif.dao.api.comite.ComiteOrganisationDAO; import com.jcertif.dao.hibernate.AbstractDAOTestCase; /** * Test de la classe ComiteOrganisationDAOHibernate. * * @author rossi.oddet * */ @ContextConfiguration(locations = { "classpath:jcertif-dao-test-beans.xml" }) public class ComiteOrganisationDAOHibernateTest extends AbstractDAOTestCase { /** * DAO ComiteOrganisation. */ @Autowired private ComiteOrganisationDAO comiteOrganisationDAO; /** * Test de la methode getReference(). */ @Test public void testGetReference() { ComiteOrganisation comite = comiteOrganisationDAO.getReference(Long .valueOf(1)); assertEquals("nom 1", comite.getNom()); assertEquals("prenom 1", comite.getPrenom()); assertEquals("<EMAIL>", comite.getEmail()); assertEquals("details 1", comite.getDetails()); assertEquals(Character.valueOf('M'), comite.getSexeMf()); assertEquals("111111", comite.getTelephone()); } /** * Test de la methode findById(). */ @Test public void testFindById() { ComiteOrganisation comite = comiteOrganisationDAO.findById(Long .valueOf(1)); assertEquals("nom 1", comite.getNom()); assertEquals("prenom 1", comite.getPrenom()); assertEquals("<EMAIL>", comite.getEmail()); assertEquals("details 1", comite.getDetails()); assertEquals(Character.valueOf('M'), comite.getSexeMf()); assertEquals("111111", comite.getTelephone()); } /** * Test de la methode findAll(). */ @Test public void testFindAll() { assertEquals(4, comiteOrganisationDAO.findAll().size()); } /** * Test de la methode findAllWithSort(). */ @Test public void testFindAllWithSort() { assertEquals("nom 4", comiteOrganisationDAO.findAllWithSort("nom", false).iterator() .next().getNom()); } /** * Test de la methode persist(). */ @Test public void testPersist() { ComiteOrganisation comite = new ComiteOrganisation(); comite.setNom("nom 100"); comite.setPrenom("prenom 100"); comiteOrganisationDAO.persist(comite); ComiteOrganisation comiteRecup = comiteOrganisationDAO.findById(comite .getId()); assertEquals("nom 100", comiteRecup.getNom()); assertEquals("prenom 100", comiteRecup.getPrenom()); } /** * Test de la methode merge(). */ @Test public void testMerge() { ComiteOrganisation comite = new ComiteOrganisation(); comite.setNom("nom 1000"); comite.setPrenom("prenom 1000"); ComiteOrganisation persistedComiteOrganisation = comiteOrganisationDAO .merge(comite); ComiteOrganisation comiteRecup = comiteOrganisationDAO .findById(persistedComiteOrganisation.getId()); assertEquals("nom 1000", comiteRecup.getNom()); assertEquals("prenom 1000", comiteRecup.getPrenom()); } /** * Test de la methode remove(). */ @Test public void testRemove() { ComiteOrganisation entity = comiteOrganisationDAO.findById(Long .valueOf(1l)); comiteOrganisationDAO.remove(entity); assertEquals(3, comiteOrganisationDAO.findAll().size()); } }
3,383
0.704271
0.688365
119
26.546219
23.527115
77
false
false
0
0
0
0
0
0
1.756302
false
false
10
d10317447fbecbbb0d0d388593d6ae89605cb747
34,548,716,988,162
cc2eb646f43c983e3c4be9abc9b7d6380ad34560
/src/main/java/com/grantcs/usermanagementsystem/GroupOrder/ValidGroup2.java
3c5cf3ccc06c0918aceaa8ffd93d890cdff94d1f
[]
no_license
MikhailPalagashvili/User-Management-System
https://github.com/MikhailPalagashvili/User-Management-System
f3f72f65f207eb0a9589a00f0454935bfef8b6f6
efd683f0434eddab0331b0e1c7ab66dd007a10ee
refs/heads/master
2023-06-05T11:02:51.204000
2021-07-04T18:12:16
2021-07-04T18:12:16
382,919,327
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.grantcs.usermanagementsystem.GroupOrder; public interface ValidGroup2 { }
UTF-8
Java
87
java
ValidGroup2.java
Java
[]
null
[]
package com.grantcs.usermanagementsystem.GroupOrder; public interface ValidGroup2 { }
87
0.83908
0.827586
4
20.75
21.695333
52
false
false
0
0
0
0
0
0
0.25
false
false
10
cb5a168d1e6242ef12189c367aec8b03176db190
35,914,516,576,971
814be8730785ec55cc4fc13631a35cb43c24b3fb
/1.JavaSyntax/src/com/javarush/task/task08/task0817/Solution.java
c6591e051c83b7839f50d6f41ed9e391dcfab0b4
[]
no_license
efesenko/JavaRushTasks
https://github.com/efesenko/JavaRushTasks
ad12f88b1cf9497f087671551232e4a07d096f75
1a753d9468340d2843866bfeb3fa78861f47f747
refs/heads/master
2021-05-13T11:32:05.237000
2018-04-23T15:50:15
2018-04-23T15:50:15
117,128,494
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.javarush.task.task08.task0817; import java.util.*; /* Нам повторы не нужны */ public class Solution { public static HashMap<String, String> createMap() { //напишите тут ваш код Map<String, String> map = new HashMap<String, String>(); map.put("Фесенко", "Mama12313"); map.put("фесенко1", "Mila"); map.put("фесенко2", "Ramu1"); map.put("Фесенко3", "Mama1"); map.put("фесенко12", "Mila"); map.put("фесенко23", "Ramu1"); map.put("Фесенко213", "Mama2"); map.put("фесенко11", "Mila"); map.put("фесенко2322", "Ramu"); map.put("фесенко23221", "Ramu2323"); return (HashMap<String, String>)map; } public static void removeTheFirstNameDuplicates(HashMap<String, String> map) { //напишите тут ваш код List<String> list = new LinkedList<>(map.values()); for (String s : list) { if (Collections.frequency(map.values(), s) > 1) { removeItemFromMapByValue(map, s); } } } public static void removeItemFromMapByValue(HashMap<String, String> map, String value) { HashMap<String, String> copy = new HashMap<String, String>(map); for (Map.Entry<String, String> pair : copy.entrySet()) { if (pair.getValue().equals(value)) map.remove(pair.getKey()); } } public static void main(String[] args) { } }
UTF-8
Java
1,586
java
Solution.java
Java
[ { "context": "= new HashMap<String, String>();\n map.put(\"Фесенко\", \"Mama12313\");\n map.put(\"фесенко1\", \"Mila", "end": 294, "score": 0.9899653792381287, "start": 287, "tag": "NAME", "value": "Фесенко" }, { "context": "ap<String, String>();\n map.put(\"Фесенко\", \"Mama12313\");\n map.put(\"фесенко1\", \"Mila\");\n m", "end": 307, "score": 0.9505094885826111, "start": 298, "tag": "NAME", "value": "Mama12313" }, { "context": "енко\", \"Mama12313\");\n map.put(\"фесенко1\", \"Mila\");\n map.put(\"фесенко2\", \"Ramu1\");\n ", "end": 344, "score": 0.9827144742012024, "start": 340, "tag": "NAME", "value": "Mila" }, { "context": "\"фесенко1\", \"Mila\");\n map.put(\"фесенко2\", \"Ramu1\");\n map.put(\"Фесенко3\", \"Mama1\");\n ", "end": 382, "score": 0.9316036701202393, "start": 377, "tag": "NAME", "value": "Ramu1" }, { "context": " map.put(\"фесенко2\", \"Ramu1\");\n map.put(\"Фесенко3\", \"Mama1\");\n map.put(\"фесенко12\", \"Mila\")", "end": 410, "score": 0.8886222839355469, "start": 404, "tag": "NAME", "value": "есенко" }, { "context": "фесенко2\", \"Ramu1\");\n map.put(\"Фесенко3\", \"Mama1\");\n map.put(\"фесенко12\", \"Mila\");\n ", "end": 420, "score": 0.8594300150871277, "start": 415, "tag": "NAME", "value": "Mama1" }, { "context": "есенко3\", \"Mama1\");\n map.put(\"фесенко12\", \"Mila\");\n map.put(\"фесенко23\", \"Ramu1\");\n ", "end": 458, "score": 0.9528615474700928, "start": 454, "tag": "NAME", "value": "Mila" }, { "context": "есенко12\", \"Mila\");\n map.put(\"фесенко23\", \"Ramu1\");\n map.put(\"Фесенко213\", \"Mama2\");\n ", "end": 497, "score": 0.8798763155937195, "start": 492, "tag": "NAME", "value": "Ramu1" }, { "context": " map.put(\"фесенко23\", \"Ramu1\");\n map.put(\"Фесенко213\", \"Mama2\");\n map.put(\"фесенко11\", \"Mila", "end": 525, "score": 0.8864789009094238, "start": 518, "tag": "NAME", "value": "Фесенко" }, { "context": "енко23\", \"Ramu1\");\n map.put(\"Фесенко213\", \"Mama2\");\n map.put(\"фесенко11\", \"Mila\");\n ", "end": 537, "score": 0.8597039580345154, "start": 532, "tag": "NAME", "value": "Mama2" }, { "context": "map.put(\"Фесенко213\", \"Mama2\");\n map.put(\"фесенко11\", \"Mila\");\n map.put(\"фесенко2322\", \"Ra", "end": 563, "score": 0.6490256786346436, "start": 559, "tag": "NAME", "value": "есен" }, { "context": "енко213\", \"Mama2\");\n map.put(\"фесенко11\", \"Mila\");\n map.put(\"фесенко2322\", \"Ramu\");\n ", "end": 575, "score": 0.9697556495666504, "start": 571, "tag": "NAME", "value": "Mila" }, { "context": "енко11\", \"Mila\");\n map.put(\"фесенко2322\", \"Ramu\");\n map.put(\"фесенко23221\", \"Ramu2323\");\n\n", "end": 615, "score": 0.884191632270813, "start": 611, "tag": "NAME", "value": "Ramu" }, { "context": "о2322\", \"Ramu\");\n map.put(\"фесенко23221\", \"Ramu2323\");\n\n return (HashMap<String, String>)map;\n\n ", "end": 660, "score": 0.8539347648620605, "start": 652, "tag": "NAME", "value": "Ramu2323" } ]
null
[]
package com.javarush.task.task08.task0817; import java.util.*; /* Нам повторы не нужны */ public class Solution { public static HashMap<String, String> createMap() { //напишите тут ваш код Map<String, String> map = new HashMap<String, String>(); map.put("Фесенко", "Mama12313"); map.put("фесенко1", "Mila"); map.put("фесенко2", "Ramu1"); map.put("Фесенко3", "Mama1"); map.put("фесенко12", "Mila"); map.put("фесенко23", "Ramu1"); map.put("Фесенко213", "Mama2"); map.put("фесенко11", "Mila"); map.put("фесенко2322", "Ramu"); map.put("фесенко23221", "Ramu2323"); return (HashMap<String, String>)map; } public static void removeTheFirstNameDuplicates(HashMap<String, String> map) { //напишите тут ваш код List<String> list = new LinkedList<>(map.values()); for (String s : list) { if (Collections.frequency(map.values(), s) > 1) { removeItemFromMapByValue(map, s); } } } public static void removeItemFromMapByValue(HashMap<String, String> map, String value) { HashMap<String, String> copy = new HashMap<String, String>(map); for (Map.Entry<String, String> pair : copy.entrySet()) { if (pair.getValue().equals(value)) map.remove(pair.getKey()); } } public static void main(String[] args) { } }
1,586
0.575427
0.54744
51
27.725491
24.839151
92
false
false
0
0
0
0
0
0
0.784314
false
false
10
17cc7aad03b30ba33c160c1cb849daea997df568
38,362,647,914,443
fc5fe6c26a4f0fe3fd3f1d8dcaa3f7404d4e53a4
/app/src/main/java/com/zsh/shopclient/model/Luck.java
c4c79d5f6d7b311f0856c4c9c7100b75e5c5f366
[]
no_license
xxxloli123/ShopClient
https://github.com/xxxloli123/ShopClient
35f0f4fbf70a45de601f87caaa05be26d633c847
1d857f05b4da8be543a8e15b5252b7efa827849c
refs/heads/master
2021-09-03T10:17:49.976000
2018-01-08T10:04:41
2018-01-08T10:04:46
115,705,060
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zsh.shopclient.model; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2017/12/18. */ public class Luck extends Struct { private List<CharSequence[]> list; public Luck(String imagePath,JSONArray jsonArray)throws JSONException{ list = new ArrayList<>(); for(int index = 0;index< jsonArray.length();index++){ JSONObject jsonObject = jsonArray.getJSONObject(index); list.add(new CharSequence[]{imagePath + jsonObject.getString("productSmallImg"),jsonObject.getString("productName"), jsonObject.getString("bargainPrice"), jsonObject.getString("id"),"0",jsonObject.getString("originalPrice")}); } } public List<CharSequence[]> getList() { return list; } }
UTF-8
Java
888
java
Luck.java
Java
[]
null
[]
package com.zsh.shopclient.model; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2017/12/18. */ public class Luck extends Struct { private List<CharSequence[]> list; public Luck(String imagePath,JSONArray jsonArray)throws JSONException{ list = new ArrayList<>(); for(int index = 0;index< jsonArray.length();index++){ JSONObject jsonObject = jsonArray.getJSONObject(index); list.add(new CharSequence[]{imagePath + jsonObject.getString("productSmallImg"),jsonObject.getString("productName"), jsonObject.getString("bargainPrice"), jsonObject.getString("id"),"0",jsonObject.getString("originalPrice")}); } } public List<CharSequence[]> getList() { return list; } }
888
0.684685
0.673423
28
30.714285
34.203026
129
false
false
0
0
0
0
0
0
0.678571
false
false
10
fa7bb4f733d741dcd51c3d62eb581f02e1dac6cc
20,340,965,142,725
cb30f68e27b226b9d6dccd36d373fe45db18b0d9
/ais2/src/com/xbwl/flow/dao/impl/FormfieldHibernateDaoImpl.java
f912b982695032c0493b32f4fce797c0ed970787
[]
no_license
czltx224/ais2
https://github.com/czltx224/ais2
81ab0b92073ae7fa22923c7be104446b4c39cc23
348e5f8d8aee735b2fe9a3d81d1d73ab02672675
refs/heads/master
2021-01-10T12:42:10.015000
2016-01-07T01:32:57
2016-01-07T01:32:57
49,176,839
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xbwl.flow.dao.impl; import org.springframework.stereotype.Repository; import com.xbwl.common.orm.hibernate.BaseDAOHibernateImpl; import com.xbwl.entity.FlowFormfield; import com.xbwl.flow.dao.IFormfieldDao; /** * 流程管理-表单字段数据访问层实现类 *@author LiuHao *@time Feb 14, 2012 4:18:47 PM */ @Repository("formfieldHibernateDaoImpl") public class FormfieldHibernateDaoImpl extends BaseDAOHibernateImpl<FlowFormfield,Long> implements IFormfieldDao { }
GB18030
Java
511
java
FormfieldHibernateDaoImpl.java
Java
[ { "context": "mfieldDao;\r\n\r\n/**\r\n * 流程管理-表单字段数据访问层实现类\r\n *@author LiuHao\r\n *@time Feb 14, 2012 4:18:47 PM\r\n */\r\n@Repositor", "end": 273, "score": 0.980354905128479, "start": 267, "tag": "NAME", "value": "LiuHao" } ]
null
[]
package com.xbwl.flow.dao.impl; import org.springframework.stereotype.Repository; import com.xbwl.common.orm.hibernate.BaseDAOHibernateImpl; import com.xbwl.entity.FlowFormfield; import com.xbwl.flow.dao.IFormfieldDao; /** * 流程管理-表单字段数据访问层实现类 *@author LiuHao *@time Feb 14, 2012 4:18:47 PM */ @Repository("formfieldHibernateDaoImpl") public class FormfieldHibernateDaoImpl extends BaseDAOHibernateImpl<FlowFormfield,Long> implements IFormfieldDao { }
511
0.77453
0.751566
18
24.611111
25.649645
98
false
false
0
0
0
0
0
0
0.5
false
false
10
0d672e1dd0b0ae3a8d5f829080947a70513b33eb
2,542,620,668,018
7f91cdaa4b93e0900dff65eac1b4babbf5b338ae
/src/main/java/com/runqing/spring/scope/ThreadScope.java
9a023a3fe6b69c99c0219733fb2b5820156137ca
[]
no_license
wanghaord/spring-demo
https://github.com/wanghaord/spring-demo
597e92da956da44cf6b4f53e1022000bba3bc6e5
ca8663056631306c1bc2ca80513309f13b9da8a8
refs/heads/master
2022-05-30T06:47:28.830000
2020-05-01T08:53:59
2020-05-01T08:53:59
257,230,804
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.runqing.spring.scope; import com.sun.corba.se.spi.ior.ObjectKey; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.config.Scope; import java.util.HashMap; import java.util.Map; /** * 自定义bean作用域 */ public class ThreadScope implements Scope { ThreadLocal<Object> local = new ThreadLocal<Object>() { @Override protected Object initialValue() { return new HashMap<String, Object>(); } }; @Override public Object get(String name, ObjectFactory<?> objectFactory) { HashMap map = (HashMap) local.get(); Object object = null; if ((object = map.get(name)) == null) { object = objectFactory.getObject(); map.put(name, object); local.set(map); } return object; } @Override public Object remove(String name) { Map map = (Map) local.get(); if (map.get(name) != null) { local.remove(); return map.get(name); } return null; } @Override public void registerDestructionCallback(String s, Runnable runnable) { } @Override public Object resolveContextualObject(String s) { return null; } @Override public String getConversationId() { return null; } }
UTF-8
Java
1,368
java
ThreadScope.java
Java
[]
null
[]
package com.runqing.spring.scope; import com.sun.corba.se.spi.ior.ObjectKey; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.config.Scope; import java.util.HashMap; import java.util.Map; /** * 自定义bean作用域 */ public class ThreadScope implements Scope { ThreadLocal<Object> local = new ThreadLocal<Object>() { @Override protected Object initialValue() { return new HashMap<String, Object>(); } }; @Override public Object get(String name, ObjectFactory<?> objectFactory) { HashMap map = (HashMap) local.get(); Object object = null; if ((object = map.get(name)) == null) { object = objectFactory.getObject(); map.put(name, object); local.set(map); } return object; } @Override public Object remove(String name) { Map map = (Map) local.get(); if (map.get(name) != null) { local.remove(); return map.get(name); } return null; } @Override public void registerDestructionCallback(String s, Runnable runnable) { } @Override public Object resolveContextualObject(String s) { return null; } @Override public String getConversationId() { return null; } }
1,368
0.603245
0.603245
59
21.983051
20.004654
74
false
false
0
0
0
0
0
0
0.40678
false
false
10
6dc2076947f23ff74ed80fd35badecd7862b16cd
37,958,920,978,526
209e3de7d3ed97b081e63e55a78cedbe1a5852e7
/src/main/java/com/techmahindra/smartparking/service/reports/impl/SPSReportsServiceImpl.java
cd7a9e2a2c2e3c5bc3b839042527b5e3c5e4d53e
[]
no_license
happy6eve/smartparking
https://github.com/happy6eve/smartparking
7af1541eed4b473c3d783d332905cb6615d66dc4
4a4cdd11df7951b544bd3b7b046cf804bb8161ec
refs/heads/master
2018-04-08T07:44:45.906000
2017-04-28T12:07:46
2017-04-28T12:07:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.techmahindra.smartparking.service.reports.impl; import java.math.BigDecimal; import java.math.BigInteger; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import com.techmahindra.smartparking.common.exception.application.GenericDBException; import com.techmahindra.smartparking.constant.BookingStatus; import com.techmahindra.smartparking.dao.jpa.booking.ISpBookingCRUDRepository; import com.techmahindra.smartparking.dao.jpa.device.ISpDeviceCRUDRepository; import com.techmahindra.smartparking.dao.jpa.zone.ISpZoneCRUDRepository; import com.techmahindra.smartparking.pojo.dbentity.device.SpDevice; import com.techmahindra.smartparking.pojo.dbentity.zone.SpZone; import com.techmahindra.smartparking.pojo.dto.response.device.SpSensorReportListResponseDTO; import com.techmahindra.smartparking.pojo.dto.response.reports.SpBookingReportResponseDTO; import com.techmahindra.smartparking.pojo.dto.response.reports.SpBookingReportResponseListDTO; import com.techmahindra.smartparking.pojo.dto.response.reports.SpReportResponseDTO; import com.techmahindra.smartparking.pojo.dto.response.reports.SpReportResponseListDTO; import com.techmahindra.smartparking.pojo.dto.response.zone.FloorBooking; import com.techmahindra.smartparking.pojo.dto.response.zone.SpZoneDto; import com.techmahindra.smartparking.security.SecurityUser; import com.techmahindra.smartparking.service.device.SPSDeviceService; import com.techmahindra.smartparking.service.device.SPSSensorService; import com.techmahindra.smartparking.service.reports.SPSReportsService; import com.techmahindra.smartparking.utility.CommonUtility; @Service public class SPSReportsServiceImpl implements SPSReportsService { final static Logger LOGGER = LoggerFactory.getLogger(SPSDeviceService.class); @Autowired private ISpBookingCRUDRepository bookingRepo; @Autowired private ISpDeviceCRUDRepository deviceRepo; @Autowired private ISpZoneCRUDRepository zoneRepo; @Autowired private SPSSensorService sensorService; @Override public SpReportResponseListDTO getRevenueReport(Integer zoneId, String fromTime, String toTime) { SpReportResponseListDTO result = new SpReportResponseListDTO(); List<SpReportResponseDTO> list = new ArrayList<>(); List<Object[]> objList = bookingRepo.getPaymentReport(zoneId, fromTime, toTime); if (objList == null || objList.isEmpty()) { return null; } else { for (Object[] obj : objList) { SpReportResponseDTO dto = new SpReportResponseDTO(); dto.setPaymentAmount(new BigDecimal(obj[0].toString())); dto.setZoneName(obj[1].toString()); dto.setPaymentTime(obj[2].toString()); dto.setPaymentInfo(obj[3] + ""); dto.setZoneId((int) obj[4]); dto.setCustomer(obj[5].toString()); dto.setMobile(obj[6].toString()); list.add(dto); } result.setReport(list); } SpZone zone = zoneRepo.findOne(zoneId); result.setCurrency(zone.getCurrency().getCurrency()); return result; } @Override public SpBookingReportResponseListDTO getBookingRevenueReport(Integer zoneId, String fromTime, String toTime, int bookingStatus) { SpBookingReportResponseListDTO result = new SpBookingReportResponseListDTO(); List<SpBookingReportResponseDTO> list = new ArrayList<>(); List<Object[]> objList = null; if(bookingStatus == 0) { objList = bookingRepo.getAllBookingRecords(zoneId, fromTime, toTime); } else { objList = bookingRepo.getBookingReport(zoneId, fromTime, toTime, bookingStatus); } if (objList == null || objList.isEmpty()) { return null; } else { for (Object[] obj : objList) { SpBookingReportResponseDTO dto = new SpBookingReportResponseDTO(); System.out.println("Before object to time for from time"+ obj[3]); System.out.println("Before object to time for to time"+ obj[4]); String timezone=(obj[13].toString()); String fromTime1=CommonUtility.convertGMTToTimeZone(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(obj[3]),timezone); String toTime1=CommonUtility.convertGMTToTimeZone(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(obj[4]),timezone); System.out.println("From time here is "+ fromTime1); System.out.println("to time here is "+ toTime1); System.out.println("time zone is "+ timezone); dto.setZoneId((int) obj[9]); dto.setZoneName(obj[10].toString()); dto.setBookingId((int) obj[0]); dto.setBookingTime(obj[11].toString()); dto.setFromTime(fromTime1); dto.setToTime(toTime1); dto.setFloor((int) obj[6]); dto.setVehicle(obj[7].toString()); dto.setSlot(obj[8].toString()); dto.setCustomer(obj[2].toString()); dto.setMobile(obj[5].toString()); dto.setBookingStatus(BookingStatus.findStatus((int) obj[12])); dto.setBookingNumber(CommonUtility.formatBookingId((int) obj[0])); list.add(dto); } result.setReport(list); } return result; } @Override public SpReportResponseListDTO getConsolidatedRevenueReport() { SpReportResponseListDTO result = new SpReportResponseListDTO(); List<SpReportResponseDTO> list = new ArrayList<>(); SecurityUser user = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); List<SpZoneDto> authList = user.getAuthorizedParkingZones(); Date today = new Date(); String fromTime = (today.getYear() + 1900) + "-" + (today.getMonth() + 1) + "-01 00:00:00"; Calendar calendar = Calendar.getInstance(); calendar.setTime(today); calendar.add(Calendar.MONTH, 1); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.add(Calendar.DATE, -1); Date lastDayOfMonth = calendar.getTime(); DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String toTime = sdf.format(lastDayOfMonth) + " 00:00:00"; for (SpZoneDto zone : authList) { List<Object[]> objList = bookingRepo.getPaymentReport(zone.getZoneId(), fromTime, toTime); if (objList == null || objList.size() == 0) { continue; } else { for (Object[] obj : objList) { SpReportResponseDTO dto = new SpReportResponseDTO(); dto.setPaymentAmount(new BigDecimal(obj[0].toString())); dto.setZoneName(obj[1].toString()); dto.setPaymentTime(obj[2].toString()); dto.setPaymentInfo(obj[3] + ""); dto.setZoneId((int) obj[4]); dto.setCustomer(obj[5].toString()); dto.setMobile(obj[6].toString()); list.add(dto); } result.setReport(list); } } return result; } @Override public SpBookingReportResponseListDTO getConsolidatedBookingRevenueReport() { SpBookingReportResponseListDTO result = new SpBookingReportResponseListDTO(); List<SpBookingReportResponseDTO> list = new ArrayList<>(); SecurityUser user = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); List<SpZoneDto> authList = user.getAuthorizedParkingZones(); Date today = new Date(); String fromTime = (today.getYear() + 1900) + "-" + (today.getMonth() + 1) + "-01 00:00:00"; Calendar calendar = Calendar.getInstance(); calendar.setTime(today); calendar.add(Calendar.MONTH, 1); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.add(Calendar.DATE, -1); Date lastDayOfMonth = calendar.getTime(); DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String toTime = sdf.format(lastDayOfMonth) + " 00:00:00"; for (SpZoneDto zone : authList) { List<Object[]> objList = bookingRepo.getAllBookingRecords(zone.getZoneId(), fromTime, toTime); if (objList == null || objList.size() == 0) { continue; } else { for (Object[] obj : objList) { SpBookingReportResponseDTO dto = new SpBookingReportResponseDTO(); dto.setZoneId((int) obj[9]); dto.setZoneName(obj[10].toString()); dto.setBookingId((int) obj[0]); dto.setBookingTime(obj[11].toString()); dto.setFromTime(obj[3].toString()); dto.setToTime(obj[4].toString()); dto.setFloor((int) obj[6]); dto.setVehicle(obj[7].toString()); dto.setSlot(obj[8].toString()); dto.setCustomer(obj[2].toString()); dto.setMobile(obj[5].toString()); dto.setBookingStatus(BookingStatus.findStatus((int) obj[12])); dto.setBookingNumber(CommonUtility.formatBookingId((int) obj[0])); list.add(dto); } result.setReport(list); } } return result; } @Override public SpSensorReportListResponseDTO getParkingOccupancy(SpZone zone){ List<SpDevice> devices = deviceRepo.findSpDeviceByZone(zone); List<String> deviceIds = new ArrayList<String>(); SpSensorReportListResponseDTO sensorReportListResponseDTO; for (SpDevice d : devices) { deviceIds.add(d.getDeviceId().toString()); } try { sensorReportListResponseDTO = sensorService.findOccupancyByDeviceIds(deviceIds); } catch (GenericDBException e) { e.printStackTrace(); return null; } return sensorReportListResponseDTO; } @Override public SpSensorReportListResponseDTO getConsolidatedParkingOccupancy(Iterable<SpZone> zones){ List<SpDevice> devices = deviceRepo.findSpDeviceByZoneIn(zones); List<String> deviceIds = new ArrayList<String>(); SpSensorReportListResponseDTO sensorReportListResponseDTO; for (SpDevice d : devices) { deviceIds.add(d.getDeviceId().toString()); } try { sensorReportListResponseDTO = sensorService.findOccupancyByDeviceIds(deviceIds); } catch (GenericDBException e) { e.printStackTrace(); return null; } return sensorReportListResponseDTO; } @Override public SpBookingReportResponseDTO getBookingDetailReport(Integer bookingId) { Object[] rec = bookingRepo.getBookingDetail(bookingId); if (rec == null) { return null; } else { SpBookingReportResponseDTO dto = new SpBookingReportResponseDTO(); Object[] obj = (Object[]) rec[0]; System.out.println("Before object to time for from time"+ obj[3]); System.out.println("Before object to time for to time"+ obj[4]); String timezone=(obj[15].toString()); String fromTime1=CommonUtility.convertGMTToTimeZone(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(obj[3]),timezone); String toTime1=CommonUtility.convertGMTToTimeZone(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(obj[4]),timezone); System.out.println("From time here is "+ fromTime1); dto.setZoneId((int) obj[9]); dto.setZoneName(obj[10].toString()); dto.setBookingId((int) obj[0]); dto.setBookingTime(obj[11].toString()); dto.setFromTime(fromTime1); dto.setToTime(toTime1); dto.setFloor((int) obj[6]); dto.setVehicle(obj[7].toString()); dto.setSlot(obj[8].toString()); dto.setCustomer(obj[2].toString()); dto.setMobile(obj[5].toString()); dto.setPrice(new BigDecimal(obj[12].toString())); dto.setAmount(new BigDecimal(obj[13].toString())); dto.setBookingStatus(BookingStatus.findStatus((int) obj[14])); dto.setBookingNumber(CommonUtility.formatBookingId((int) obj[0])); return dto; } } @Override public List<FloorBooking> getFloorBooking(SpZone zone) { List<FloorBooking> list = new ArrayList<FloorBooking>(); Date today = new Date(); String fromTime = (today.getYear() + 1900) + "-" + (today.getMonth() + 1) + "-" + today.getDate() + " 00:00:00"; String toTime = (today.getYear() + 1900) + "-" + (today.getMonth() + 1) + "-" + today.getDate() + " 23:59:59"; List<Object[]> objList = bookingRepo.getCurrentBookingReport(zone.getZoneId(), fromTime, toTime); for (Object[] obj : objList) { FloorBooking fb = new FloorBooking(); fb.setBooking(new BigInteger(obj[0].toString())); fb.setFloor(new BigInteger(obj[1].toString())); list.add(fb); } return list; } @Override public List<FloorBooking> getAllFloorBooking(Iterable<SpZone> zones) { List<FloorBooking> list = new ArrayList<FloorBooking>(); Date today = new Date(); String fromTime = (today.getYear() + 1900) + "-" + (today.getMonth() + 1) + "-" + today.getDate() + " 00:00:00"; String toTime = (today.getYear() + 1900) + "-" + (today.getMonth() + 1) + "-" + today.getDate() + " 23:59:59"; String zoneIds=""; for(SpZone z: zones) { if(zoneIds=="") { zoneIds = zoneIds +z.getZoneId(); } else { zoneIds = zoneIds +","+z.getZoneId(); } } List<Object[]> objList = bookingRepo.getCurrentConsolidatedBookingReport(zoneIds, fromTime, toTime); for (Object[] obj : objList) { FloorBooking fb = new FloorBooking(); fb.setBooking(new BigInteger(obj[0].toString())); fb.setFloor(new BigInteger(obj[1].toString())); String zoneName = zoneRepo.findOne((int)obj[2]).getZoneName(); fb.setZone(zoneName); list.add(fb); } return list; } }
UTF-8
Java
12,960
java
SPSReportsServiceImpl.java
Java
[]
null
[]
package com.techmahindra.smartparking.service.reports.impl; import java.math.BigDecimal; import java.math.BigInteger; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import com.techmahindra.smartparking.common.exception.application.GenericDBException; import com.techmahindra.smartparking.constant.BookingStatus; import com.techmahindra.smartparking.dao.jpa.booking.ISpBookingCRUDRepository; import com.techmahindra.smartparking.dao.jpa.device.ISpDeviceCRUDRepository; import com.techmahindra.smartparking.dao.jpa.zone.ISpZoneCRUDRepository; import com.techmahindra.smartparking.pojo.dbentity.device.SpDevice; import com.techmahindra.smartparking.pojo.dbentity.zone.SpZone; import com.techmahindra.smartparking.pojo.dto.response.device.SpSensorReportListResponseDTO; import com.techmahindra.smartparking.pojo.dto.response.reports.SpBookingReportResponseDTO; import com.techmahindra.smartparking.pojo.dto.response.reports.SpBookingReportResponseListDTO; import com.techmahindra.smartparking.pojo.dto.response.reports.SpReportResponseDTO; import com.techmahindra.smartparking.pojo.dto.response.reports.SpReportResponseListDTO; import com.techmahindra.smartparking.pojo.dto.response.zone.FloorBooking; import com.techmahindra.smartparking.pojo.dto.response.zone.SpZoneDto; import com.techmahindra.smartparking.security.SecurityUser; import com.techmahindra.smartparking.service.device.SPSDeviceService; import com.techmahindra.smartparking.service.device.SPSSensorService; import com.techmahindra.smartparking.service.reports.SPSReportsService; import com.techmahindra.smartparking.utility.CommonUtility; @Service public class SPSReportsServiceImpl implements SPSReportsService { final static Logger LOGGER = LoggerFactory.getLogger(SPSDeviceService.class); @Autowired private ISpBookingCRUDRepository bookingRepo; @Autowired private ISpDeviceCRUDRepository deviceRepo; @Autowired private ISpZoneCRUDRepository zoneRepo; @Autowired private SPSSensorService sensorService; @Override public SpReportResponseListDTO getRevenueReport(Integer zoneId, String fromTime, String toTime) { SpReportResponseListDTO result = new SpReportResponseListDTO(); List<SpReportResponseDTO> list = new ArrayList<>(); List<Object[]> objList = bookingRepo.getPaymentReport(zoneId, fromTime, toTime); if (objList == null || objList.isEmpty()) { return null; } else { for (Object[] obj : objList) { SpReportResponseDTO dto = new SpReportResponseDTO(); dto.setPaymentAmount(new BigDecimal(obj[0].toString())); dto.setZoneName(obj[1].toString()); dto.setPaymentTime(obj[2].toString()); dto.setPaymentInfo(obj[3] + ""); dto.setZoneId((int) obj[4]); dto.setCustomer(obj[5].toString()); dto.setMobile(obj[6].toString()); list.add(dto); } result.setReport(list); } SpZone zone = zoneRepo.findOne(zoneId); result.setCurrency(zone.getCurrency().getCurrency()); return result; } @Override public SpBookingReportResponseListDTO getBookingRevenueReport(Integer zoneId, String fromTime, String toTime, int bookingStatus) { SpBookingReportResponseListDTO result = new SpBookingReportResponseListDTO(); List<SpBookingReportResponseDTO> list = new ArrayList<>(); List<Object[]> objList = null; if(bookingStatus == 0) { objList = bookingRepo.getAllBookingRecords(zoneId, fromTime, toTime); } else { objList = bookingRepo.getBookingReport(zoneId, fromTime, toTime, bookingStatus); } if (objList == null || objList.isEmpty()) { return null; } else { for (Object[] obj : objList) { SpBookingReportResponseDTO dto = new SpBookingReportResponseDTO(); System.out.println("Before object to time for from time"+ obj[3]); System.out.println("Before object to time for to time"+ obj[4]); String timezone=(obj[13].toString()); String fromTime1=CommonUtility.convertGMTToTimeZone(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(obj[3]),timezone); String toTime1=CommonUtility.convertGMTToTimeZone(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(obj[4]),timezone); System.out.println("From time here is "+ fromTime1); System.out.println("to time here is "+ toTime1); System.out.println("time zone is "+ timezone); dto.setZoneId((int) obj[9]); dto.setZoneName(obj[10].toString()); dto.setBookingId((int) obj[0]); dto.setBookingTime(obj[11].toString()); dto.setFromTime(fromTime1); dto.setToTime(toTime1); dto.setFloor((int) obj[6]); dto.setVehicle(obj[7].toString()); dto.setSlot(obj[8].toString()); dto.setCustomer(obj[2].toString()); dto.setMobile(obj[5].toString()); dto.setBookingStatus(BookingStatus.findStatus((int) obj[12])); dto.setBookingNumber(CommonUtility.formatBookingId((int) obj[0])); list.add(dto); } result.setReport(list); } return result; } @Override public SpReportResponseListDTO getConsolidatedRevenueReport() { SpReportResponseListDTO result = new SpReportResponseListDTO(); List<SpReportResponseDTO> list = new ArrayList<>(); SecurityUser user = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); List<SpZoneDto> authList = user.getAuthorizedParkingZones(); Date today = new Date(); String fromTime = (today.getYear() + 1900) + "-" + (today.getMonth() + 1) + "-01 00:00:00"; Calendar calendar = Calendar.getInstance(); calendar.setTime(today); calendar.add(Calendar.MONTH, 1); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.add(Calendar.DATE, -1); Date lastDayOfMonth = calendar.getTime(); DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String toTime = sdf.format(lastDayOfMonth) + " 00:00:00"; for (SpZoneDto zone : authList) { List<Object[]> objList = bookingRepo.getPaymentReport(zone.getZoneId(), fromTime, toTime); if (objList == null || objList.size() == 0) { continue; } else { for (Object[] obj : objList) { SpReportResponseDTO dto = new SpReportResponseDTO(); dto.setPaymentAmount(new BigDecimal(obj[0].toString())); dto.setZoneName(obj[1].toString()); dto.setPaymentTime(obj[2].toString()); dto.setPaymentInfo(obj[3] + ""); dto.setZoneId((int) obj[4]); dto.setCustomer(obj[5].toString()); dto.setMobile(obj[6].toString()); list.add(dto); } result.setReport(list); } } return result; } @Override public SpBookingReportResponseListDTO getConsolidatedBookingRevenueReport() { SpBookingReportResponseListDTO result = new SpBookingReportResponseListDTO(); List<SpBookingReportResponseDTO> list = new ArrayList<>(); SecurityUser user = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); List<SpZoneDto> authList = user.getAuthorizedParkingZones(); Date today = new Date(); String fromTime = (today.getYear() + 1900) + "-" + (today.getMonth() + 1) + "-01 00:00:00"; Calendar calendar = Calendar.getInstance(); calendar.setTime(today); calendar.add(Calendar.MONTH, 1); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.add(Calendar.DATE, -1); Date lastDayOfMonth = calendar.getTime(); DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String toTime = sdf.format(lastDayOfMonth) + " 00:00:00"; for (SpZoneDto zone : authList) { List<Object[]> objList = bookingRepo.getAllBookingRecords(zone.getZoneId(), fromTime, toTime); if (objList == null || objList.size() == 0) { continue; } else { for (Object[] obj : objList) { SpBookingReportResponseDTO dto = new SpBookingReportResponseDTO(); dto.setZoneId((int) obj[9]); dto.setZoneName(obj[10].toString()); dto.setBookingId((int) obj[0]); dto.setBookingTime(obj[11].toString()); dto.setFromTime(obj[3].toString()); dto.setToTime(obj[4].toString()); dto.setFloor((int) obj[6]); dto.setVehicle(obj[7].toString()); dto.setSlot(obj[8].toString()); dto.setCustomer(obj[2].toString()); dto.setMobile(obj[5].toString()); dto.setBookingStatus(BookingStatus.findStatus((int) obj[12])); dto.setBookingNumber(CommonUtility.formatBookingId((int) obj[0])); list.add(dto); } result.setReport(list); } } return result; } @Override public SpSensorReportListResponseDTO getParkingOccupancy(SpZone zone){ List<SpDevice> devices = deviceRepo.findSpDeviceByZone(zone); List<String> deviceIds = new ArrayList<String>(); SpSensorReportListResponseDTO sensorReportListResponseDTO; for (SpDevice d : devices) { deviceIds.add(d.getDeviceId().toString()); } try { sensorReportListResponseDTO = sensorService.findOccupancyByDeviceIds(deviceIds); } catch (GenericDBException e) { e.printStackTrace(); return null; } return sensorReportListResponseDTO; } @Override public SpSensorReportListResponseDTO getConsolidatedParkingOccupancy(Iterable<SpZone> zones){ List<SpDevice> devices = deviceRepo.findSpDeviceByZoneIn(zones); List<String> deviceIds = new ArrayList<String>(); SpSensorReportListResponseDTO sensorReportListResponseDTO; for (SpDevice d : devices) { deviceIds.add(d.getDeviceId().toString()); } try { sensorReportListResponseDTO = sensorService.findOccupancyByDeviceIds(deviceIds); } catch (GenericDBException e) { e.printStackTrace(); return null; } return sensorReportListResponseDTO; } @Override public SpBookingReportResponseDTO getBookingDetailReport(Integer bookingId) { Object[] rec = bookingRepo.getBookingDetail(bookingId); if (rec == null) { return null; } else { SpBookingReportResponseDTO dto = new SpBookingReportResponseDTO(); Object[] obj = (Object[]) rec[0]; System.out.println("Before object to time for from time"+ obj[3]); System.out.println("Before object to time for to time"+ obj[4]); String timezone=(obj[15].toString()); String fromTime1=CommonUtility.convertGMTToTimeZone(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(obj[3]),timezone); String toTime1=CommonUtility.convertGMTToTimeZone(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(obj[4]),timezone); System.out.println("From time here is "+ fromTime1); dto.setZoneId((int) obj[9]); dto.setZoneName(obj[10].toString()); dto.setBookingId((int) obj[0]); dto.setBookingTime(obj[11].toString()); dto.setFromTime(fromTime1); dto.setToTime(toTime1); dto.setFloor((int) obj[6]); dto.setVehicle(obj[7].toString()); dto.setSlot(obj[8].toString()); dto.setCustomer(obj[2].toString()); dto.setMobile(obj[5].toString()); dto.setPrice(new BigDecimal(obj[12].toString())); dto.setAmount(new BigDecimal(obj[13].toString())); dto.setBookingStatus(BookingStatus.findStatus((int) obj[14])); dto.setBookingNumber(CommonUtility.formatBookingId((int) obj[0])); return dto; } } @Override public List<FloorBooking> getFloorBooking(SpZone zone) { List<FloorBooking> list = new ArrayList<FloorBooking>(); Date today = new Date(); String fromTime = (today.getYear() + 1900) + "-" + (today.getMonth() + 1) + "-" + today.getDate() + " 00:00:00"; String toTime = (today.getYear() + 1900) + "-" + (today.getMonth() + 1) + "-" + today.getDate() + " 23:59:59"; List<Object[]> objList = bookingRepo.getCurrentBookingReport(zone.getZoneId(), fromTime, toTime); for (Object[] obj : objList) { FloorBooking fb = new FloorBooking(); fb.setBooking(new BigInteger(obj[0].toString())); fb.setFloor(new BigInteger(obj[1].toString())); list.add(fb); } return list; } @Override public List<FloorBooking> getAllFloorBooking(Iterable<SpZone> zones) { List<FloorBooking> list = new ArrayList<FloorBooking>(); Date today = new Date(); String fromTime = (today.getYear() + 1900) + "-" + (today.getMonth() + 1) + "-" + today.getDate() + " 00:00:00"; String toTime = (today.getYear() + 1900) + "-" + (today.getMonth() + 1) + "-" + today.getDate() + " 23:59:59"; String zoneIds=""; for(SpZone z: zones) { if(zoneIds=="") { zoneIds = zoneIds +z.getZoneId(); } else { zoneIds = zoneIds +","+z.getZoneId(); } } List<Object[]> objList = bookingRepo.getCurrentConsolidatedBookingReport(zoneIds, fromTime, toTime); for (Object[] obj : objList) { FloorBooking fb = new FloorBooking(); fb.setBooking(new BigInteger(obj[0].toString())); fb.setFloor(new BigInteger(obj[1].toString())); String zoneName = zoneRepo.findOne((int)obj[2]).getZoneName(); fb.setZone(zoneName); list.add(fb); } return list; } }
12,960
0.719367
0.70517
398
31.562815
30.563631
131
false
false
0
0
0
0
0
0
2.635678
false
false
10
191bd8b6a1165bcb874235c833465b74f2bfb95c
28,544,352,717,276
6884500b1976dff17aa571c4d6851970f3b077c5
/src/main/java/f1/notice/board/SearchProvider.java
3a81e1e19238286189054babb2ffe17a91f62abf
[]
no_license
FireDevil/notice
https://github.com/FireDevil/notice
c9bbf37a63c6f49ad22966f3744e799673b6f15c
422dbec83d55d8a779e005f7cbd5cab78f4adcce
refs/heads/master
2020-05-18T07:46:12.692000
2014-10-26T18:20:20
2014-10-26T18:20:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package f1.notice.board; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.MatrixCursor; import android.net.Uri; import android.provider.BaseColumns; /** * Created by Antec on 18.01.14. */ public class SearchProvider extends ContentProvider { private Context ctx; @Override public boolean onCreate() { return false; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { ctx = ACP.getContext(); MatrixCursor mc = new MatrixCursor(new String[]{BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_TEXT_2, SearchManager.SUGGEST_COLUMN_ICON_1, SearchManager.SUGGEST_COLUMN_INTENT_DATA, SearchManager.SUGGEST_COLUMN_INTENT_ACTION}); if(selectionArgs[0].length() < 3){ mc.addRow(new Object[]{"0",ctx.getString(R.string.littleMore),ctx.getString(R.string.getSuggestions),R.drawable.ic_action_search,"hallo","NOTHING"}); return mc; } DBHelper db = new DBHelper(); Cursor c1 = db.select("SELECT * FROM Content WHERE text LIKE '%"+selectionArgs[0]+"%' ORDER BY clicked DESC"); Cursor c2 = db.select("SELECT * FROM TableOfContent WHERE name LIKE '%"+selectionArgs[0]+"%' LIMIT 5"); Cursor recent = db.select("SELECT * FROM RecentSearch WHERE query LIKE '%"+selectionArgs[0]+"%' ORDER BY count DESC"); int n = 0; String section =""; while(recent.moveToNext() && n < 6){ mc.addRow(new Object[]{""+n,recent.getString(1),ctx.getString(R.string.searchedBefore)+recent.getString(2)+ctx.getString(R.string.time_s),R.drawable.ic_action_search,recent.getString(1),"android.intent.action.ANSWER"}); n++; } n = 0; while(c2.moveToNext() && n < 6){ if(c2.getString(1).equals("S")){ section = ctx.getString(R.string.Sporting); }else{ section = ctx.getString(R.string.Technical); } mc.addRow(new Object[]{""+n,c2.getString(3),c2.getString(2)+" - "+section,R.drawable.ic_drawer," TableOfContent WHERE _id ="+c2.getInt(0),"android.intent.action.VIEW"}); n++; } while(c1.moveToNext() && n < 10){ if(c1.getString(1).equals("S")){ section = ctx.getString(R.string.Sporting); }else{ section = ctx.getString(R.string.Technical); } mc.addRow(new Object[]{""+n,c1.getString(4),c1.getString(2)+"."+c1.getString(3)+" - "+section,R.drawable.ic_drawer," Content WHERE _id ="+c1.getInt(0),"android.intent.action.VIEW"}); n++; } if(mc.getCount() == 0){ //mc.addRow(new Object[]{""+n,"no results","try a more common wording",R.drawable.ic_action_search,"hallo","NOTHING"}); } recent.close(); c1.close(); c2.close(); db.close(); return mc; } @Override public String getType(Uri uri) { return null; } @Override public Uri insert(Uri uri, ContentValues values) { return null; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { return 0; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { return 0; } }
UTF-8
Java
3,696
java
SearchProvider.java
Java
[ { "context": "t android.provider.BaseColumns;\n\n/**\n * Created by Antec on 18.01.14.\n */\npublic class SearchProvider exte", "end": 325, "score": 0.9972743988037109, "start": 320, "tag": "USERNAME", "value": "Antec" } ]
null
[]
package f1.notice.board; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.MatrixCursor; import android.net.Uri; import android.provider.BaseColumns; /** * Created by Antec on 18.01.14. */ public class SearchProvider extends ContentProvider { private Context ctx; @Override public boolean onCreate() { return false; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { ctx = ACP.getContext(); MatrixCursor mc = new MatrixCursor(new String[]{BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_TEXT_2, SearchManager.SUGGEST_COLUMN_ICON_1, SearchManager.SUGGEST_COLUMN_INTENT_DATA, SearchManager.SUGGEST_COLUMN_INTENT_ACTION}); if(selectionArgs[0].length() < 3){ mc.addRow(new Object[]{"0",ctx.getString(R.string.littleMore),ctx.getString(R.string.getSuggestions),R.drawable.ic_action_search,"hallo","NOTHING"}); return mc; } DBHelper db = new DBHelper(); Cursor c1 = db.select("SELECT * FROM Content WHERE text LIKE '%"+selectionArgs[0]+"%' ORDER BY clicked DESC"); Cursor c2 = db.select("SELECT * FROM TableOfContent WHERE name LIKE '%"+selectionArgs[0]+"%' LIMIT 5"); Cursor recent = db.select("SELECT * FROM RecentSearch WHERE query LIKE '%"+selectionArgs[0]+"%' ORDER BY count DESC"); int n = 0; String section =""; while(recent.moveToNext() && n < 6){ mc.addRow(new Object[]{""+n,recent.getString(1),ctx.getString(R.string.searchedBefore)+recent.getString(2)+ctx.getString(R.string.time_s),R.drawable.ic_action_search,recent.getString(1),"android.intent.action.ANSWER"}); n++; } n = 0; while(c2.moveToNext() && n < 6){ if(c2.getString(1).equals("S")){ section = ctx.getString(R.string.Sporting); }else{ section = ctx.getString(R.string.Technical); } mc.addRow(new Object[]{""+n,c2.getString(3),c2.getString(2)+" - "+section,R.drawable.ic_drawer," TableOfContent WHERE _id ="+c2.getInt(0),"android.intent.action.VIEW"}); n++; } while(c1.moveToNext() && n < 10){ if(c1.getString(1).equals("S")){ section = ctx.getString(R.string.Sporting); }else{ section = ctx.getString(R.string.Technical); } mc.addRow(new Object[]{""+n,c1.getString(4),c1.getString(2)+"."+c1.getString(3)+" - "+section,R.drawable.ic_drawer," Content WHERE _id ="+c1.getInt(0),"android.intent.action.VIEW"}); n++; } if(mc.getCount() == 0){ //mc.addRow(new Object[]{""+n,"no results","try a more common wording",R.drawable.ic_action_search,"hallo","NOTHING"}); } recent.close(); c1.close(); c2.close(); db.close(); return mc; } @Override public String getType(Uri uri) { return null; } @Override public Uri insert(Uri uri, ContentValues values) { return null; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { return 0; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { return 0; } }
3,696
0.594697
0.580357
113
31.707964
42.455322
231
false
false
0
0
0
0
0
0
0.725664
false
false
10
60892898161559d841e67d108e237774ad08a4ea
35,046,933,181,192
0945f772cc8ace3c1cda86ee11cd2e158b46422c
/Credicorp/src/com/mega/credicorp/riesgos/reportes/TablePresentationExport.java
08c7ee95b5ec14b5e4c134a94697b0b48a00e6d7
[]
no_license
sergiorjuela/credicorpOneClick
https://github.com/sergiorjuela/credicorpOneClick
630a570e7855fa555d519b91d3abe7ddb6537175
7027245e9a43577d0cd2735726a9ddf7c935a522
refs/heads/master
2020-03-15T07:01:07.431000
2018-05-08T13:44:37
2018-05-08T13:44:37
132,020,374
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mega.credicorp.riesgos.reportes; import java.util.ArrayList; import java.util.Map; import com.mega.modeling.analysis.content.Dataset; import com.mega.modeling.analysis.content.Dimension; import com.mega.modeling.analysis.content.ReportContent; import com.mega.modeling.analysis.content.Text; import com.mega.modeling.analysis.content.View; import com.mega.modeling.api.MegaObject; import com.mega.modeling.api.MegaRoot; import com.mega.soho.grcu.GRCDataProcessing; import com.mega.soho.grcu.GRCReportViewUtility; /* * Esta clase en escencia realiza la misma labor que la clase * TablaPresentation sin emabrgo algunas caracteristicas del como lo hace * son diferentes. */ public class TablePresentationExport { private MegaRoot mgRoot; private Dataset heatMapDataset; private Dimension dimFirstMaAttribute; private Dimension dimSecondMaAttribute; private ReportContent rContent; private Hmap hMap; public View createReportTable(MegaRoot root, ReportContent reportContent, Hmap heatMap) { this.mgRoot = root; this.rContent = reportContent; this.hMap = heatMap; this.heatMapDataset = new Dataset(""); this.dimFirstMaAttribute = new Dimension(""); this.dimSecondMaAttribute = new Dimension(""); this.dimFirstMaAttribute.setSize(this.hMap.getMavFirstMaAttribute().size() + 2); this.dimSecondMaAttribute.setSize(this.hMap.getMavSecondMaAttribute().size() + 2); this.heatMapDataset.addDimension(this.dimFirstMaAttribute); this.heatMapDataset.addDimension(this.dimSecondMaAttribute); fillHeatMap(); View vTable = new View(reportContent.addDataset(this.heatMapDataset)); vTable.addRenderer("~WCgdfMQqBzc1[table]"); vTable.getItemRenderer().addParameter("class", "charttable"); return vTable; } private void fillHeatMap() { //Obtiene el map de celdas vinculado al hmap Map<String, HCell> mavsMap = this.hMap.getMavsMap(); /* * Define las variables ligne, column y total value contexts con 1,1 y 0 * y setTitles con false */ int ligne = 2; int column = 2; int totalValueContexts = 0; boolean setTitles = false; //Almacena en el objeto de tipo text el nombre de la tabla del hmap Text tableName = getTitlesTexts(this.hMap.getTableName()); //Agrega al dataset el item tablename en la posición 1,1 this.heatMapDataset.addItem(tableName, "1,1"); for (MegaObject mavFirstMetAttribute : this.hMap.getMavFirstMaAttribute()) { //Obtiene por cada matv un titulo y lo agrega en la coordenada X. Text tex_mavName = getTitlesTexts(mavFirstMetAttribute.getProp("~H3l5fU1F3n80[Value Name]")); //Agrega al data set el titulo obtenido this.heatMapDataset.addItem(tex_mavName, ligne + ",1"); /* * La variable total line se inicializa en 0 y se va incrementando a medida * que se llenan la celdas de la fila */ int totalLine = 0; for (MegaObject mavSecondMetAttribute : this.hMap.getMavSecondMaAttribute()) { if (!setTitles) { //Obtiene por cada matv un titulo y lo agrega en la coordenada Y del data set. tex_mavName = getTitlesTexts(mavSecondMetAttribute.getProp("~H3l5fU1F3n80[Value Name]")); this.heatMapDataset.addItem(tex_mavName, "1," + column); } //Arma el valor de la llave de la celda String heatMapCellKey = Double.valueOf(mavFirstMetAttribute.getProp("~L20000000L50[Internal Value]")).toString() + "," + Double.valueOf(mavSecondMetAttribute.getProp("~L20000000L50[Internal Value]")).toString(); /* * Define un objeto de tipo celca y le asigna el objeto celda almacenado * en el map vinculado a la llave previamente estructurada */ HCell hcell = (HCell)mavsMap.get(heatMapCellKey); /* * Incrementa el valor de la linea de acuerdo al tamaño del valores * de contexto de la celda */ totalLine += hcell.getValueContexts().size(); /* * Genera un objeto de tipo texto en donde le pasa el tamaño del arreglo * este tamaño representa en nuero de coincidencias por nodo. */ Text value = new Text("<b><center>" + hcell.getValueContexts().size() + "</center></b>", false); value.isHtml(true); /* * Le pone el color a la celda y le agrega la propiedad * drilldown que genera un evento cuando se selecciona la casilla */ value.getItemRenderer().addParameter("color", hcell.getColor()); value.getItemRenderer().addParameter("drilldown", getDrillDown(hcell.getValueContexts()).toString()); /* * Agrega al data set el objeto text en la posición ligne (2) y column (2) * y posteriormente aumenta el contador de columna. */ this.heatMapDataset.addItem(value, ligne + "," + column); column++; } /* * Genera un titulo con el valor del totalline el cual es el acumulado * de toda la linea y lo coloca en la ultima posición en la cual se * totaliza */ Text ittotal = getTitlesTexts(String.valueOf(totalLine)); this.heatMapDataset.addItem(ittotal, ligne + "," + column++); /* * a la variable totalValueContexts se suma el valor de la linea * para obtener un acumulado del valor total. */ totalValueContexts += totalLine; /* * Incrementa la linea y la columna la inicializa en 2 para reiniciar * el recorrido de izquierda a derecha en la segunda fila. */ column = 2; ligne++; //Cambia el valor de setTitles a true para que los titulos ya no se generen setTitles = true; } //Agrega un texto vacio que se ubica en la parte superior derecha this.heatMapDataset.addItem(getTitlesTexts(" "), "1," + (this.hMap.getMavSecondMaAttribute().size() + 2)); //Agrega un texto que se ubica en la parte inferior izquierda "Total" Text totalTitle = getTitlesTexts(GRCDataProcessing.getCodeTemplate("~5ARhLtwZGr5Q[total]", this.mgRoot)); this.heatMapDataset.addItem(totalTitle, this.hMap.getMavFirstMaAttribute().size() + 2 + ",1"); //Calcula el total de la columnas y lo agrega a la tabla setTotalColumns(); //Genera un objeto text con el total calculado y lo agrega a la tabla Text totalAll = getTitlesTexts(" " + String.valueOf(totalValueContexts)); this.heatMapDataset.addItem(totalAll, this.hMap.getMavFirstMaAttribute().size() + 2 + "," + (this.hMap.getMavSecondMaAttribute().size() + 2)); //GEnera la vista con el data set y la renderiza View heatMapView = new View(this.rContent.addDataset(this.heatMapDataset)); heatMapView.addRenderer("~WCgdfMQqBzc1[table]"); heatMapView.getItemRenderer().addParameter("class", "charttable"); } private void setTotalColumns() { /* * Inicializa el objeto ligne en el tamaño mas dos para que la linea * sea la ultima de la tabla. */ int ligne = this.hMap.getMavSecondMaAttribute().size() + 2; int column = 2; //Inicializa la columna en dos for (MegaObject mavSecondMetAttribute : this.hMap.getMavSecondMaAttribute()) { //Define contador de total por columna int totalColumn = 0; for (MegaObject mavFirstMetAttribute : this.hMap.getMavFirstMaAttribute()) { //Arma la llave de la celda String heatMapCellKey = Double.valueOf(mavFirstMetAttribute.getProp("~L20000000L50[Internal Value]")).toString() + "," + Double.valueOf(mavSecondMetAttribute.getProp("~L20000000L50[Internal Value]")).toString(); //Obtiene el objeto celda con la llave generada HCell hcell = (HCell)this.hMap.getMavsMap().get(heatMapCellKey); //Aumenta el valor total con el valor del tamaño del arreglo de la celda totalColumn += hcell.getValueContexts().size(); // define el objeto text y lo adiciona al final de la columna Text ittotal = getTitlesTexts(String.valueOf(totalColumn)); this.heatMapDataset.addItem(ittotal, ligne + "," + column); } column++; } } /* * Recibe un string, el cual a traves de un objeto Text lo convierte en un titulo * y le asigna un color predeterminado. */ private Text getTitlesTexts(String str) { String html_str = "<b><center>" + str + "</center></b>"; Text tex_str = new Text(html_str, false); tex_str.isHtml(true); tex_str.getItemRenderer().addParameter("color", "E8E6DE"); return tex_str; } /* *Recibe una lista de string que representa los nodos almacenados en esa posicion *genera un stringbuffer el cual llena de forma consecuente con cada string nodo de *la lista */ private StringBuffer getDrillDown(ArrayList<String> nodes) { StringBuffer objectsId = new StringBuffer("~)0Gb81(DEL3o[Assessment Value Context]:"); for (String nodeMegaField : nodes) { objectsId.append(nodeMegaField + ","); } GRCReportViewUtility.deleteSemiColon(objectsId); return objectsId; } }
ISO-8859-1
Java
9,161
java
TablePresentationExport.java
Java
[]
null
[]
package com.mega.credicorp.riesgos.reportes; import java.util.ArrayList; import java.util.Map; import com.mega.modeling.analysis.content.Dataset; import com.mega.modeling.analysis.content.Dimension; import com.mega.modeling.analysis.content.ReportContent; import com.mega.modeling.analysis.content.Text; import com.mega.modeling.analysis.content.View; import com.mega.modeling.api.MegaObject; import com.mega.modeling.api.MegaRoot; import com.mega.soho.grcu.GRCDataProcessing; import com.mega.soho.grcu.GRCReportViewUtility; /* * Esta clase en escencia realiza la misma labor que la clase * TablaPresentation sin emabrgo algunas caracteristicas del como lo hace * son diferentes. */ public class TablePresentationExport { private MegaRoot mgRoot; private Dataset heatMapDataset; private Dimension dimFirstMaAttribute; private Dimension dimSecondMaAttribute; private ReportContent rContent; private Hmap hMap; public View createReportTable(MegaRoot root, ReportContent reportContent, Hmap heatMap) { this.mgRoot = root; this.rContent = reportContent; this.hMap = heatMap; this.heatMapDataset = new Dataset(""); this.dimFirstMaAttribute = new Dimension(""); this.dimSecondMaAttribute = new Dimension(""); this.dimFirstMaAttribute.setSize(this.hMap.getMavFirstMaAttribute().size() + 2); this.dimSecondMaAttribute.setSize(this.hMap.getMavSecondMaAttribute().size() + 2); this.heatMapDataset.addDimension(this.dimFirstMaAttribute); this.heatMapDataset.addDimension(this.dimSecondMaAttribute); fillHeatMap(); View vTable = new View(reportContent.addDataset(this.heatMapDataset)); vTable.addRenderer("~WCgdfMQqBzc1[table]"); vTable.getItemRenderer().addParameter("class", "charttable"); return vTable; } private void fillHeatMap() { //Obtiene el map de celdas vinculado al hmap Map<String, HCell> mavsMap = this.hMap.getMavsMap(); /* * Define las variables ligne, column y total value contexts con 1,1 y 0 * y setTitles con false */ int ligne = 2; int column = 2; int totalValueContexts = 0; boolean setTitles = false; //Almacena en el objeto de tipo text el nombre de la tabla del hmap Text tableName = getTitlesTexts(this.hMap.getTableName()); //Agrega al dataset el item tablename en la posición 1,1 this.heatMapDataset.addItem(tableName, "1,1"); for (MegaObject mavFirstMetAttribute : this.hMap.getMavFirstMaAttribute()) { //Obtiene por cada matv un titulo y lo agrega en la coordenada X. Text tex_mavName = getTitlesTexts(mavFirstMetAttribute.getProp("~H3l5fU1F3n80[Value Name]")); //Agrega al data set el titulo obtenido this.heatMapDataset.addItem(tex_mavName, ligne + ",1"); /* * La variable total line se inicializa en 0 y se va incrementando a medida * que se llenan la celdas de la fila */ int totalLine = 0; for (MegaObject mavSecondMetAttribute : this.hMap.getMavSecondMaAttribute()) { if (!setTitles) { //Obtiene por cada matv un titulo y lo agrega en la coordenada Y del data set. tex_mavName = getTitlesTexts(mavSecondMetAttribute.getProp("~H3l5fU1F3n80[Value Name]")); this.heatMapDataset.addItem(tex_mavName, "1," + column); } //Arma el valor de la llave de la celda String heatMapCellKey = Double.valueOf(mavFirstMetAttribute.getProp("~L20000000L50[Internal Value]")).toString() + "," + Double.valueOf(mavSecondMetAttribute.getProp("~L20000000L50[Internal Value]")).toString(); /* * Define un objeto de tipo celca y le asigna el objeto celda almacenado * en el map vinculado a la llave previamente estructurada */ HCell hcell = (HCell)mavsMap.get(heatMapCellKey); /* * Incrementa el valor de la linea de acuerdo al tamaño del valores * de contexto de la celda */ totalLine += hcell.getValueContexts().size(); /* * Genera un objeto de tipo texto en donde le pasa el tamaño del arreglo * este tamaño representa en nuero de coincidencias por nodo. */ Text value = new Text("<b><center>" + hcell.getValueContexts().size() + "</center></b>", false); value.isHtml(true); /* * Le pone el color a la celda y le agrega la propiedad * drilldown que genera un evento cuando se selecciona la casilla */ value.getItemRenderer().addParameter("color", hcell.getColor()); value.getItemRenderer().addParameter("drilldown", getDrillDown(hcell.getValueContexts()).toString()); /* * Agrega al data set el objeto text en la posición ligne (2) y column (2) * y posteriormente aumenta el contador de columna. */ this.heatMapDataset.addItem(value, ligne + "," + column); column++; } /* * Genera un titulo con el valor del totalline el cual es el acumulado * de toda la linea y lo coloca en la ultima posición en la cual se * totaliza */ Text ittotal = getTitlesTexts(String.valueOf(totalLine)); this.heatMapDataset.addItem(ittotal, ligne + "," + column++); /* * a la variable totalValueContexts se suma el valor de la linea * para obtener un acumulado del valor total. */ totalValueContexts += totalLine; /* * Incrementa la linea y la columna la inicializa en 2 para reiniciar * el recorrido de izquierda a derecha en la segunda fila. */ column = 2; ligne++; //Cambia el valor de setTitles a true para que los titulos ya no se generen setTitles = true; } //Agrega un texto vacio que se ubica en la parte superior derecha this.heatMapDataset.addItem(getTitlesTexts(" "), "1," + (this.hMap.getMavSecondMaAttribute().size() + 2)); //Agrega un texto que se ubica en la parte inferior izquierda "Total" Text totalTitle = getTitlesTexts(GRCDataProcessing.getCodeTemplate("~5ARhLtwZGr5Q[total]", this.mgRoot)); this.heatMapDataset.addItem(totalTitle, this.hMap.getMavFirstMaAttribute().size() + 2 + ",1"); //Calcula el total de la columnas y lo agrega a la tabla setTotalColumns(); //Genera un objeto text con el total calculado y lo agrega a la tabla Text totalAll = getTitlesTexts(" " + String.valueOf(totalValueContexts)); this.heatMapDataset.addItem(totalAll, this.hMap.getMavFirstMaAttribute().size() + 2 + "," + (this.hMap.getMavSecondMaAttribute().size() + 2)); //GEnera la vista con el data set y la renderiza View heatMapView = new View(this.rContent.addDataset(this.heatMapDataset)); heatMapView.addRenderer("~WCgdfMQqBzc1[table]"); heatMapView.getItemRenderer().addParameter("class", "charttable"); } private void setTotalColumns() { /* * Inicializa el objeto ligne en el tamaño mas dos para que la linea * sea la ultima de la tabla. */ int ligne = this.hMap.getMavSecondMaAttribute().size() + 2; int column = 2; //Inicializa la columna en dos for (MegaObject mavSecondMetAttribute : this.hMap.getMavSecondMaAttribute()) { //Define contador de total por columna int totalColumn = 0; for (MegaObject mavFirstMetAttribute : this.hMap.getMavFirstMaAttribute()) { //Arma la llave de la celda String heatMapCellKey = Double.valueOf(mavFirstMetAttribute.getProp("~L20000000L50[Internal Value]")).toString() + "," + Double.valueOf(mavSecondMetAttribute.getProp("~L20000000L50[Internal Value]")).toString(); //Obtiene el objeto celda con la llave generada HCell hcell = (HCell)this.hMap.getMavsMap().get(heatMapCellKey); //Aumenta el valor total con el valor del tamaño del arreglo de la celda totalColumn += hcell.getValueContexts().size(); // define el objeto text y lo adiciona al final de la columna Text ittotal = getTitlesTexts(String.valueOf(totalColumn)); this.heatMapDataset.addItem(ittotal, ligne + "," + column); } column++; } } /* * Recibe un string, el cual a traves de un objeto Text lo convierte en un titulo * y le asigna un color predeterminado. */ private Text getTitlesTexts(String str) { String html_str = "<b><center>" + str + "</center></b>"; Text tex_str = new Text(html_str, false); tex_str.isHtml(true); tex_str.getItemRenderer().addParameter("color", "E8E6DE"); return tex_str; } /* *Recibe una lista de string que representa los nodos almacenados en esa posicion *genera un stringbuffer el cual llena de forma consecuente con cada string nodo de *la lista */ private StringBuffer getDrillDown(ArrayList<String> nodes) { StringBuffer objectsId = new StringBuffer("~)0Gb81(DEL3o[Assessment Value Context]:"); for (String nodeMegaField : nodes) { objectsId.append(nodeMegaField + ","); } GRCReportViewUtility.deleteSemiColon(objectsId); return objectsId; } }
9,161
0.677811
0.667868
223
40.044842
32.354645
146
false
false
0
0
0
0
0
0
0.600897
false
false
10
f886a49a0d4b668720e0c323b79c2d39a21b6bf3
30,288,109,432,304
3e6132abe7b2416e515cc9ec989d9f368b4914db
/src/control/servlet/CodificaUTF8.java
3f85ffc0986f8bbc1bd9fffb9dbdebe3b83fdcb4
[]
no_license
samito123/viewmaster_optometria
https://github.com/samito123/viewmaster_optometria
7933d5c0d36a31ee3909bbf58af7806840e54959
88ac4bf4af9143514f6c8f574536abc96e3d2dcc
refs/heads/master
2021-01-20T05:52:16.391000
2017-05-30T11:56:13
2017-05-30T11:56:13
89,814,037
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package control.servlet; import java.io.UnsupportedEncodingException; public class CodificaUTF8 { public String CodificaString(String string) throws UnsupportedEncodingException{ return new String(string.getBytes("UTF-8"), "ISO-8859-1"); } }
UTF-8
Java
249
java
CodificaUTF8.java
Java
[]
null
[]
package control.servlet; import java.io.UnsupportedEncodingException; public class CodificaUTF8 { public String CodificaString(String string) throws UnsupportedEncodingException{ return new String(string.getBytes("UTF-8"), "ISO-8859-1"); } }
249
0.791165
0.763052
10
23.9
27.739683
81
false
false
0
0
0
0
0
0
0.8
false
false
10
78c4b45c18a9e554743bfb360817e1cdb1ef0ef7
37,048,387,923,602
4ac93e5d04218ee27d4264c189d33a3f49c50877
/src/main/java/com/nativeslang/view/EditUserPage.java
39e5e32680ab19755ed8ea7fac80fa72eed44943
[]
no_license
snordgren/nativeslang
https://github.com/snordgren/nativeslang
3650f6436bf815f89dfcaf4c840d9a925b28b956
b84aef2a288e82cba9f3689db1ca331b56964753
refs/heads/master
2021-03-27T10:16:37.428000
2019-02-18T10:00:11
2019-02-18T10:00:11
120,191,909
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nativeslang.view; import j2html.tags.ContainerTag; import java.util.Optional; import static j2html.TagCreator.*; public class EditUserPage extends AbstractHeadedPage { private final String description, username; public EditUserPage(Optional<String> user, String description) { super("edit-user", user); this.description = description; if (user.isPresent()) { this.username = user.get(); } else { throw new UnsupportedOperationException(); } } @Override protected ContainerTag mainTag() { TopicSection topicSection = new TopicSection("Edit Profile", "Update your profile here."); ContainerTag descriptionArea = textarea(description) .withName("description") .withPlaceholder("Enter description here..."); ContainerTag submitButton = button("Submit") .withType("submit"); ContainerTag form = form(descriptionArea, submitButton) .withAction("/user/update/" + username) .withMethod("post"); return main(topicSection.render(), form); } }
UTF-8
Java
1,007
java
EditUserPage.java
Java
[]
null
[]
package com.nativeslang.view; import j2html.tags.ContainerTag; import java.util.Optional; import static j2html.TagCreator.*; public class EditUserPage extends AbstractHeadedPage { private final String description, username; public EditUserPage(Optional<String> user, String description) { super("edit-user", user); this.description = description; if (user.isPresent()) { this.username = user.get(); } else { throw new UnsupportedOperationException(); } } @Override protected ContainerTag mainTag() { TopicSection topicSection = new TopicSection("Edit Profile", "Update your profile here."); ContainerTag descriptionArea = textarea(description) .withName("description") .withPlaceholder("Enter description here..."); ContainerTag submitButton = button("Submit") .withType("submit"); ContainerTag form = form(descriptionArea, submitButton) .withAction("/user/update/" + username) .withMethod("post"); return main(topicSection.render(), form); } }
1,007
0.731877
0.729891
36
26.972221
20.236774
65
false
false
0
0
0
0
0
0
2.111111
false
false
10
cb3012954f1598c6dc5a71dd1f3e498cd4cd3f39
37,495,064,525,923
2ec905b5b130bed2aa6f1f37591317d80b7ce70d
/ihmc-humanoid-behaviors/src/main/java/us/ihmc/humanoidBehaviors/behaviors/primitives/TimingBehaviorHelper.java
e48bea6c90c23db2b7e4f6b4c269ace8beb546a1
[ "Apache-2.0" ]
permissive
ihmcrobotics/ihmc-open-robotics-software
https://github.com/ihmcrobotics/ihmc-open-robotics-software
dbb1f9d7a4eaf01c08068b7233d1b01d25c5d037
42a4e385af75e8e13291d6156a5c7bebebbecbfd
refs/heads/develop
2023-09-01T18:18:14.623000
2023-09-01T14:16:26
2023-09-01T14:16:26
50,613,360
227
91
null
false
2023-01-25T21:39:35
2016-01-28T21:00:16
2023-01-23T10:08:40
2023-01-25T21:39:32
980,849
195
77
30
Java
false
false
package us.ihmc.humanoidBehaviors.behaviors.primitives; import java.util.concurrent.atomic.AtomicReference; import controller_msgs.msg.dds.ArmTrajectoryMessage; import perception_msgs.msg.dds.DoorLocationPacket; import controller_msgs.msg.dds.FootstepDataListMessage; import toolbox_msgs.msg.dds.FootstepPlanningRequestPacket; import toolbox_msgs.msg.dds.FootstepPlanningToolboxOutputStatus; import controller_msgs.msg.dds.FootstepStatusMessage; import controller_msgs.msg.dds.HandTrajectoryMessage; import controller_msgs.msg.dds.WalkOverTerrainGoalPacket; import controller_msgs.msg.dds.WalkingStatusMessage; import us.ihmc.humanoidBehaviors.behaviors.AbstractBehavior; import us.ihmc.humanoidBehaviors.behaviors.diagnostic.RunEvent; import us.ihmc.humanoidBehaviors.behaviors.diagnostic.SQLBehaviorDatabaseManager; import us.ihmc.ros2.ROS2Node; public class TimingBehaviorHelper extends AbstractBehavior { public final AtomicReference<FootstepPlanningToolboxOutputStatus> plannerResult = new AtomicReference<>(null); public final AtomicReference<FootstepStatusMessage> footstepStatusMessage = new AtomicReference<>(null); public final AtomicReference<DoorLocationPacket> doorLocationMessage = new AtomicReference<>(null); public final AtomicReference<WalkOverTerrainGoalPacket> walkOverTerrainGoalMessage = new AtomicReference<>(null); public final AtomicReference<HandTrajectoryMessage> handTrajectoryMessage = new AtomicReference<>(null); public final AtomicReference<ArmTrajectoryMessage> armTrajectoryMessage = new AtomicReference<>(null); public final AtomicReference<FootstepDataListMessage> footstepDataListMessage = new AtomicReference<>(null); public final AtomicReference<WalkingStatusMessage> walkingStatusMessage = new AtomicReference<>(null); public final AtomicReference<FootstepPlanningRequestPacket> footstepPlanningRequestPacket = new AtomicReference<>(null); public SQLBehaviorDatabaseManager dataBase; public TimingBehaviorHelper(String robotName, ROS2Node ros2Node) { super(robotName, ros2Node); createSubscriber(FootstepPlanningToolboxOutputStatus.class, footstepPlannerOutputTopic, plannerResult::set); createSubscriber(FootstepPlanningRequestPacket.class, footstepPlannerInputTopic, footstepPlanningRequestPacket::set); createSubscriber(FootstepStatusMessage.class, controllerInputTopic, footstepStatusMessage::set); createSubscriber(HandTrajectoryMessage.class, controllerInputTopic, handTrajectoryMessage::set); createSubscriber(ArmTrajectoryMessage.class, controllerInputTopic, armTrajectoryMessage::set); createSubscriber(FootstepDataListMessage.class, controllerInputTopic, footstepDataListMessage::set); createSubscriber(WalkingStatusMessage.class, controllerInputTopic, walkingStatusMessage::set); createSubscriber(FootstepStatusMessage.class, controllerOutputTopic, footstepStatusMessage::set); createSubscriber(HandTrajectoryMessage.class, controllerOutputTopic, handTrajectoryMessage::set); createSubscriber(ArmTrajectoryMessage.class, controllerOutputTopic, armTrajectoryMessage::set); createSubscriber(FootstepDataListMessage.class, controllerOutputTopic, footstepDataListMessage::set); createSubscriber(WalkingStatusMessage.class, controllerOutputTopic, walkingStatusMessage::set); createBehaviorInputSubscriber(DoorLocationPacket.class, doorLocationMessage::set); createBehaviorInputSubscriber(WalkOverTerrainGoalPacket.class, walkOverTerrainGoalMessage::set); dataBase = new SQLBehaviorDatabaseManager(); } public void clean() { plannerResult.set(null); footstepStatusMessage.set(null); doorLocationMessage.set(null); walkOverTerrainGoalMessage.set(null); handTrajectoryMessage.set(null); armTrajectoryMessage.set(null); footstepDataListMessage.set(null); walkingStatusMessage.set(null); } @Override public void doControl() { if (plannerResult.get() != null) { publishTextToSpeech("timer received plannerResultMessage"); plannerResult.set(null); } if (footstepStatusMessage.get() != null) { publishTextToSpeech("timer received footstepStatusMessage"); footstepStatusMessage.set(null); } if (handTrajectoryMessage.get() != null) { publishTextToSpeech("timer received handTrajectoryMessage"); handTrajectoryMessage.set(null); } if (armTrajectoryMessage.get() != null) { publishTextToSpeech("timer received armTrajectoryMessage"); armTrajectoryMessage.set(null); } if (footstepDataListMessage.get() != null) { publishTextToSpeech("timer received footstepDataListMessage"); footstepDataListMessage.set(null); } if (walkingStatusMessage.get() != null) { publishTextToSpeech("timer received walkingStatusMessage"); walkingStatusMessage.set(null); } if (doorLocationMessage.get() != null) { publishTextToSpeech("timer received doorLocationMessage"); doorLocationMessage.set(null); } if (walkOverTerrainGoalMessage.get() != null) { publishTextToSpeech("timer received walkOverTerrainGoalMessage"); walkOverTerrainGoalMessage.set(null); } } @Override public void onBehaviorEntered() { } @Override public void onBehaviorAborted() { } @Override public void onBehaviorPaused() { } @Override public void onBehaviorResumed() { } @Override public void onBehaviorExited() { } @Override public boolean isDone() { return false; } public void saveEvent(int runID, String eventName, double eventTime) { dataBase.saveRunEvent(new RunEvent(runID, eventName, (float) eventTime, true)); } }
UTF-8
Java
5,918
java
TimingBehaviorHelper.java
Java
[]
null
[]
package us.ihmc.humanoidBehaviors.behaviors.primitives; import java.util.concurrent.atomic.AtomicReference; import controller_msgs.msg.dds.ArmTrajectoryMessage; import perception_msgs.msg.dds.DoorLocationPacket; import controller_msgs.msg.dds.FootstepDataListMessage; import toolbox_msgs.msg.dds.FootstepPlanningRequestPacket; import toolbox_msgs.msg.dds.FootstepPlanningToolboxOutputStatus; import controller_msgs.msg.dds.FootstepStatusMessage; import controller_msgs.msg.dds.HandTrajectoryMessage; import controller_msgs.msg.dds.WalkOverTerrainGoalPacket; import controller_msgs.msg.dds.WalkingStatusMessage; import us.ihmc.humanoidBehaviors.behaviors.AbstractBehavior; import us.ihmc.humanoidBehaviors.behaviors.diagnostic.RunEvent; import us.ihmc.humanoidBehaviors.behaviors.diagnostic.SQLBehaviorDatabaseManager; import us.ihmc.ros2.ROS2Node; public class TimingBehaviorHelper extends AbstractBehavior { public final AtomicReference<FootstepPlanningToolboxOutputStatus> plannerResult = new AtomicReference<>(null); public final AtomicReference<FootstepStatusMessage> footstepStatusMessage = new AtomicReference<>(null); public final AtomicReference<DoorLocationPacket> doorLocationMessage = new AtomicReference<>(null); public final AtomicReference<WalkOverTerrainGoalPacket> walkOverTerrainGoalMessage = new AtomicReference<>(null); public final AtomicReference<HandTrajectoryMessage> handTrajectoryMessage = new AtomicReference<>(null); public final AtomicReference<ArmTrajectoryMessage> armTrajectoryMessage = new AtomicReference<>(null); public final AtomicReference<FootstepDataListMessage> footstepDataListMessage = new AtomicReference<>(null); public final AtomicReference<WalkingStatusMessage> walkingStatusMessage = new AtomicReference<>(null); public final AtomicReference<FootstepPlanningRequestPacket> footstepPlanningRequestPacket = new AtomicReference<>(null); public SQLBehaviorDatabaseManager dataBase; public TimingBehaviorHelper(String robotName, ROS2Node ros2Node) { super(robotName, ros2Node); createSubscriber(FootstepPlanningToolboxOutputStatus.class, footstepPlannerOutputTopic, plannerResult::set); createSubscriber(FootstepPlanningRequestPacket.class, footstepPlannerInputTopic, footstepPlanningRequestPacket::set); createSubscriber(FootstepStatusMessage.class, controllerInputTopic, footstepStatusMessage::set); createSubscriber(HandTrajectoryMessage.class, controllerInputTopic, handTrajectoryMessage::set); createSubscriber(ArmTrajectoryMessage.class, controllerInputTopic, armTrajectoryMessage::set); createSubscriber(FootstepDataListMessage.class, controllerInputTopic, footstepDataListMessage::set); createSubscriber(WalkingStatusMessage.class, controllerInputTopic, walkingStatusMessage::set); createSubscriber(FootstepStatusMessage.class, controllerOutputTopic, footstepStatusMessage::set); createSubscriber(HandTrajectoryMessage.class, controllerOutputTopic, handTrajectoryMessage::set); createSubscriber(ArmTrajectoryMessage.class, controllerOutputTopic, armTrajectoryMessage::set); createSubscriber(FootstepDataListMessage.class, controllerOutputTopic, footstepDataListMessage::set); createSubscriber(WalkingStatusMessage.class, controllerOutputTopic, walkingStatusMessage::set); createBehaviorInputSubscriber(DoorLocationPacket.class, doorLocationMessage::set); createBehaviorInputSubscriber(WalkOverTerrainGoalPacket.class, walkOverTerrainGoalMessage::set); dataBase = new SQLBehaviorDatabaseManager(); } public void clean() { plannerResult.set(null); footstepStatusMessage.set(null); doorLocationMessage.set(null); walkOverTerrainGoalMessage.set(null); handTrajectoryMessage.set(null); armTrajectoryMessage.set(null); footstepDataListMessage.set(null); walkingStatusMessage.set(null); } @Override public void doControl() { if (plannerResult.get() != null) { publishTextToSpeech("timer received plannerResultMessage"); plannerResult.set(null); } if (footstepStatusMessage.get() != null) { publishTextToSpeech("timer received footstepStatusMessage"); footstepStatusMessage.set(null); } if (handTrajectoryMessage.get() != null) { publishTextToSpeech("timer received handTrajectoryMessage"); handTrajectoryMessage.set(null); } if (armTrajectoryMessage.get() != null) { publishTextToSpeech("timer received armTrajectoryMessage"); armTrajectoryMessage.set(null); } if (footstepDataListMessage.get() != null) { publishTextToSpeech("timer received footstepDataListMessage"); footstepDataListMessage.set(null); } if (walkingStatusMessage.get() != null) { publishTextToSpeech("timer received walkingStatusMessage"); walkingStatusMessage.set(null); } if (doorLocationMessage.get() != null) { publishTextToSpeech("timer received doorLocationMessage"); doorLocationMessage.set(null); } if (walkOverTerrainGoalMessage.get() != null) { publishTextToSpeech("timer received walkOverTerrainGoalMessage"); walkOverTerrainGoalMessage.set(null); } } @Override public void onBehaviorEntered() { } @Override public void onBehaviorAborted() { } @Override public void onBehaviorPaused() { } @Override public void onBehaviorResumed() { } @Override public void onBehaviorExited() { } @Override public boolean isDone() { return false; } public void saveEvent(int runID, String eventName, double eventTime) { dataBase.saveRunEvent(new RunEvent(runID, eventName, (float) eventTime, true)); } }
5,918
0.75904
0.758195
156
36.935898
36.742466
123
false
false
0
0
0
0
0
0
0.641026
false
false
10
181d3c5ecb65af02cc0c7b5c71abd3f697bcd3a5
37,495,064,522,594
f651b1ad007dfc249e8986187f606890ad525046
/GestionAuxiliares/src/java/Entities/SolicitudAuxiliares.java
26db756e5dda72c718f38c1292ea14e42388f39e
[]
no_license
admont28/Proyecto-Final-BD
https://github.com/admont28/Proyecto-Final-BD
ae3f782d6a2f826e5e3ee50ace690e0cf7898935
24a6082ebd495c4095148147a2917a6540ed01b6
refs/heads/master
2020-12-24T14:36:59.561000
2014-06-04T08:23:28
2014-06-04T08:23:28
null
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 Entities; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author DavidMontoya */ @Entity @Table(name = "SOLICITUD_AUXILIARES", catalog = "", schema = "PROYECTO_FINAL") @XmlRootElement @NamedQueries({ @NamedQuery(name = "SolicitudAuxiliares.findAll", query = "SELECT s FROM SolicitudAuxiliares s"), @NamedQuery(name = "SolicitudAuxiliares.findBySolicitudAuxiliaresId", query = "SELECT s FROM SolicitudAuxiliares s WHERE s.solicitudAuxiliaresId = :solicitudAuxiliaresId"), @NamedQuery(name = "SolicitudAuxiliares.findByCantidadAuxiliares", query = "SELECT s FROM SolicitudAuxiliares s WHERE s.cantidadAuxiliares = :cantidadAuxiliares"), @NamedQuery(name = "SolicitudAuxiliares.findByCantidadHoras", query = "SELECT s FROM SolicitudAuxiliares s WHERE s.cantidadHoras = :cantidadHoras"), @NamedQuery(name = "SolicitudAuxiliares.findByDescSolicitudAuxiliares", query = "SELECT s FROM SolicitudAuxiliares s WHERE s.descSolicitudAuxiliares = :descSolicitudAuxiliares"), @NamedQuery(name = "SolicitudAuxiliares.findByFechaCreacion", query = "SELECT s FROM SolicitudAuxiliares s WHERE s.fechaCreacion = :fechaCreacion")}) public class SolicitudAuxiliares implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "SOLICITUD_AUXILIARES_ID", nullable = false, length = 20) private String solicitudAuxiliaresId; @Basic(optional = false) @Column(name = "CANTIDAD_AUXILIARES", nullable = false) private short cantidadAuxiliares; @Basic(optional = false) @Column(name = "CANTIDAD_HORAS", nullable = false) private short cantidadHoras; @Basic(optional = false) @Column(name = "DESC_SOLICITUD_AUXILIARES", nullable = false, length = 255) private String descSolicitudAuxiliares; @Basic(optional = false) @Column(name = "FECHA_CREACION", nullable = false) @Temporal(TemporalType.TIMESTAMP) private Date fechaCreacion; @ManyToMany(mappedBy = "solicitudAuxiliaresList", fetch = FetchType.LAZY) private List<Requisito> requisitoList; @JoinColumn(name = "ID_SOLICITANTE", referencedColumnName = "SOLICITANTE_ID", nullable = false) @ManyToOne(optional = false, fetch = FetchType.LAZY) private Solicitante idSolicitante; @OneToOne(cascade = CascadeType.ALL, mappedBy = "idSolicitudAuxiliares", fetch = FetchType.LAZY) private Convocatoria convocatoria; public SolicitudAuxiliares() { } public SolicitudAuxiliares(String solicitudAuxiliaresId) { this.solicitudAuxiliaresId = solicitudAuxiliaresId; } public SolicitudAuxiliares(String solicitudAuxiliaresId, short cantidadAuxiliares, short cantidadHoras, String descSolicitudAuxiliares, Date fechaCreacion) { this.solicitudAuxiliaresId = solicitudAuxiliaresId; this.cantidadAuxiliares = cantidadAuxiliares; this.cantidadHoras = cantidadHoras; this.descSolicitudAuxiliares = descSolicitudAuxiliares; this.fechaCreacion = fechaCreacion; } public String getSolicitudAuxiliaresId() { return solicitudAuxiliaresId; } public void setSolicitudAuxiliaresId(String solicitudAuxiliaresId) { this.solicitudAuxiliaresId = solicitudAuxiliaresId; } public short getCantidadAuxiliares() { return cantidadAuxiliares; } public void setCantidadAuxiliares(short cantidadAuxiliares) { this.cantidadAuxiliares = cantidadAuxiliares; } public short getCantidadHoras() { return cantidadHoras; } public void setCantidadHoras(short cantidadHoras) { this.cantidadHoras = cantidadHoras; } public String getDescSolicitudAuxiliares() { return descSolicitudAuxiliares; } public void setDescSolicitudAuxiliares(String descSolicitudAuxiliares) { this.descSolicitudAuxiliares = descSolicitudAuxiliares; } public Date getFechaCreacion() { return fechaCreacion; } public void setFechaCreacion(Date fechaCreacion) { this.fechaCreacion = fechaCreacion; } @XmlTransient public List<Requisito> getRequisitoList() { return requisitoList; } public void setRequisitoList(List<Requisito> requisitoList) { this.requisitoList = requisitoList; } public Solicitante getIdSolicitante() { return idSolicitante; } public void setIdSolicitante(Solicitante idSolicitante) { this.idSolicitante = idSolicitante; } public Convocatoria getConvocatoria() { return convocatoria; } public void setConvocatoria(Convocatoria convocatoria) { this.convocatoria = convocatoria; } @Override public int hashCode() { int hash = 0; hash += (solicitudAuxiliaresId != null ? solicitudAuxiliaresId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof SolicitudAuxiliares)) { return false; } SolicitudAuxiliares other = (SolicitudAuxiliares) object; if ((this.solicitudAuxiliaresId == null && other.solicitudAuxiliaresId != null) || (this.solicitudAuxiliaresId != null && !this.solicitudAuxiliaresId.equals(other.solicitudAuxiliaresId))) { return false; } return true; } @Override public String toString() { return "Entities.SolicitudAuxiliares[ solicitudAuxiliaresId=" + solicitudAuxiliaresId + " ]"; } }
UTF-8
Java
6,439
java
SolicitudAuxiliares.java
Java
[ { "context": "l.bind.annotation.XmlTransient;\n\n/**\n *\n * @author DavidMontoya\n */\n@Entity\n@Table(name = \"SOLICITUD_AUXILIARES\",", "end": 935, "score": 0.8020620346069336, "start": 923, "tag": "NAME", "value": "DavidMontoya" } ]
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 Entities; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author DavidMontoya */ @Entity @Table(name = "SOLICITUD_AUXILIARES", catalog = "", schema = "PROYECTO_FINAL") @XmlRootElement @NamedQueries({ @NamedQuery(name = "SolicitudAuxiliares.findAll", query = "SELECT s FROM SolicitudAuxiliares s"), @NamedQuery(name = "SolicitudAuxiliares.findBySolicitudAuxiliaresId", query = "SELECT s FROM SolicitudAuxiliares s WHERE s.solicitudAuxiliaresId = :solicitudAuxiliaresId"), @NamedQuery(name = "SolicitudAuxiliares.findByCantidadAuxiliares", query = "SELECT s FROM SolicitudAuxiliares s WHERE s.cantidadAuxiliares = :cantidadAuxiliares"), @NamedQuery(name = "SolicitudAuxiliares.findByCantidadHoras", query = "SELECT s FROM SolicitudAuxiliares s WHERE s.cantidadHoras = :cantidadHoras"), @NamedQuery(name = "SolicitudAuxiliares.findByDescSolicitudAuxiliares", query = "SELECT s FROM SolicitudAuxiliares s WHERE s.descSolicitudAuxiliares = :descSolicitudAuxiliares"), @NamedQuery(name = "SolicitudAuxiliares.findByFechaCreacion", query = "SELECT s FROM SolicitudAuxiliares s WHERE s.fechaCreacion = :fechaCreacion")}) public class SolicitudAuxiliares implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "SOLICITUD_AUXILIARES_ID", nullable = false, length = 20) private String solicitudAuxiliaresId; @Basic(optional = false) @Column(name = "CANTIDAD_AUXILIARES", nullable = false) private short cantidadAuxiliares; @Basic(optional = false) @Column(name = "CANTIDAD_HORAS", nullable = false) private short cantidadHoras; @Basic(optional = false) @Column(name = "DESC_SOLICITUD_AUXILIARES", nullable = false, length = 255) private String descSolicitudAuxiliares; @Basic(optional = false) @Column(name = "FECHA_CREACION", nullable = false) @Temporal(TemporalType.TIMESTAMP) private Date fechaCreacion; @ManyToMany(mappedBy = "solicitudAuxiliaresList", fetch = FetchType.LAZY) private List<Requisito> requisitoList; @JoinColumn(name = "ID_SOLICITANTE", referencedColumnName = "SOLICITANTE_ID", nullable = false) @ManyToOne(optional = false, fetch = FetchType.LAZY) private Solicitante idSolicitante; @OneToOne(cascade = CascadeType.ALL, mappedBy = "idSolicitudAuxiliares", fetch = FetchType.LAZY) private Convocatoria convocatoria; public SolicitudAuxiliares() { } public SolicitudAuxiliares(String solicitudAuxiliaresId) { this.solicitudAuxiliaresId = solicitudAuxiliaresId; } public SolicitudAuxiliares(String solicitudAuxiliaresId, short cantidadAuxiliares, short cantidadHoras, String descSolicitudAuxiliares, Date fechaCreacion) { this.solicitudAuxiliaresId = solicitudAuxiliaresId; this.cantidadAuxiliares = cantidadAuxiliares; this.cantidadHoras = cantidadHoras; this.descSolicitudAuxiliares = descSolicitudAuxiliares; this.fechaCreacion = fechaCreacion; } public String getSolicitudAuxiliaresId() { return solicitudAuxiliaresId; } public void setSolicitudAuxiliaresId(String solicitudAuxiliaresId) { this.solicitudAuxiliaresId = solicitudAuxiliaresId; } public short getCantidadAuxiliares() { return cantidadAuxiliares; } public void setCantidadAuxiliares(short cantidadAuxiliares) { this.cantidadAuxiliares = cantidadAuxiliares; } public short getCantidadHoras() { return cantidadHoras; } public void setCantidadHoras(short cantidadHoras) { this.cantidadHoras = cantidadHoras; } public String getDescSolicitudAuxiliares() { return descSolicitudAuxiliares; } public void setDescSolicitudAuxiliares(String descSolicitudAuxiliares) { this.descSolicitudAuxiliares = descSolicitudAuxiliares; } public Date getFechaCreacion() { return fechaCreacion; } public void setFechaCreacion(Date fechaCreacion) { this.fechaCreacion = fechaCreacion; } @XmlTransient public List<Requisito> getRequisitoList() { return requisitoList; } public void setRequisitoList(List<Requisito> requisitoList) { this.requisitoList = requisitoList; } public Solicitante getIdSolicitante() { return idSolicitante; } public void setIdSolicitante(Solicitante idSolicitante) { this.idSolicitante = idSolicitante; } public Convocatoria getConvocatoria() { return convocatoria; } public void setConvocatoria(Convocatoria convocatoria) { this.convocatoria = convocatoria; } @Override public int hashCode() { int hash = 0; hash += (solicitudAuxiliaresId != null ? solicitudAuxiliaresId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof SolicitudAuxiliares)) { return false; } SolicitudAuxiliares other = (SolicitudAuxiliares) object; if ((this.solicitudAuxiliaresId == null && other.solicitudAuxiliaresId != null) || (this.solicitudAuxiliaresId != null && !this.solicitudAuxiliaresId.equals(other.solicitudAuxiliaresId))) { return false; } return true; } @Override public String toString() { return "Entities.SolicitudAuxiliares[ solicitudAuxiliaresId=" + solicitudAuxiliaresId + " ]"; } }
6,439
0.728995
0.727753
176
35.585228
37.186165
197
false
false
0
0
0
0
0
0
0.539773
false
false
10
d67dd526675893e0ee1028bee6b4c597f90ee67b
39,591,008,536,824
735738c50aa70c3e35bd80e0fc90e2d12a156a32
/manage/src/main/java/com/rainbow/xlpp/manage/interceptor/CrossDomainFilter.java
1355ae0ee07238836b77bc5928bcffb5628d5589
[]
no_license
ZZJupiter/xlpp
https://github.com/ZZJupiter/xlpp
876b844296eaec4ecb2847d92e1ce52be1cb6043
ae96320182e9842811d3f92f9f87ac6e7e2c37ea
refs/heads/master
2020-03-18T19:14:33.943000
2018-06-01T10:35:27
2018-06-01T10:35:27
135,143,066
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rainbow.xlpp.manage.interceptor; /** * Created by 张钟 on 2017/10/19. */ import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * * 跨域过滤器 * @author 张钟 * @version * @since 2016年6月19日 */ @Component public class CrossDomainFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin","*"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With"); chain.doFilter(req, res); } @Override public void init(FilterConfig filterConfig) { } @Override public void destroy() { } }
UTF-8
Java
1,329
java
CrossDomainFilter.java
Java
[ { "context": "inbow.xlpp.manage.interceptor;\n\n/**\n * Created by 张钟 on 2017/10/19.\n */\n\nimport org.springframework.st", "end": 66, "score": 0.8754745721817017, "start": 64, "tag": "USERNAME", "value": "张钟" }, { "context": "java.io.IOException;\n\n/**\n *\n * 跨域过滤器\n * @author 张钟\n * @version\n * @since 2016年6月19日\n */\n@Component\np", "end": 313, "score": 0.9371981620788574, "start": 311, "tag": "USERNAME", "value": "张钟" } ]
null
[]
package com.rainbow.xlpp.manage.interceptor; /** * Created by 张钟 on 2017/10/19. */ import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * * 跨域过滤器 * @author 张钟 * @version * @since 2016年6月19日 */ @Component public class CrossDomainFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin","*"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With"); chain.doFilter(req, res); } @Override public void init(FilterConfig filterConfig) { } @Override public void destroy() { } }
1,329
0.688889
0.67433
46
27.369566
27.656557
89
false
false
0
0
0
0
0
0
0.652174
false
false
10
85f7395bdb7d161a474d1782d83847d347ec0ffd
34,514,357,234,218
c6992ce8db7e5aab6fd959c0c448659ab91b16ce
/sdk/purview/azure-analytics-purview-catalog/src/test/java/com/azure/analytics/purview/catalog/GlossaryBaseClientTests.java
b10e8a2e57540862c6e975272bfd84ed61477dc4
[ "MIT", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause", "CC0-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-or-later" ]
permissive
g2vinay/azure-sdk-for-java
https://github.com/g2vinay/azure-sdk-for-java
ae6d94d583cc2983a5088ec8f6146744ee82cb55
b88918a2ba0c3b3e88a36c985e6f83fc2bae2af2
refs/heads/master
2023-09-01T17:46:08.256000
2021-09-23T22:20:20
2021-09-23T22:20:20
161,234,198
3
1
MIT
true
2020-01-16T20:22:43
2018-12-10T20:44:41
2019-11-13T16:53:51
2020-01-16T19:50:34
397,442
0
0
0
Java
false
false
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.analytics.purview.catalog; import com.azure.core.experimental.http.DynamicResponse; import org.junit.jupiter.api.Test; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import java.io.StringReader; import static org.junit.jupiter.api.Assertions.assertEquals; public class GlossaryBaseClientTests extends PurviewCatalogClientTestBase { private GlossaryBaseClient client; @Override protected void beforeTest() { client = clientSetup(httpPipeline -> new PurviewCatalogClientBuilder() .endpoint(getEndpoint()) .pipeline(httpPipeline) .buildGlossaryBaseClient()); } @Test public void testListGlossaries() { DynamicResponse res = client.listGlossaries().send(); assertEquals(200, res.getStatusCode()); JsonReader jsonReader = Json.createReader(new StringReader(res.getBody().toString())); JsonArray glossaries = jsonReader.readArray(); assertEquals(1, glossaries.size()); JsonObject glossary = glossaries.get(0).asJsonObject(); assertEquals("Glossary", glossary.getString("name")); JsonArray terms = glossary.getJsonArray("terms"); assertEquals(1, terms.size()); } }
UTF-8
Java
1,404
java
GlossaryBaseClientTests.java
Java
[]
null
[]
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.analytics.purview.catalog; import com.azure.core.experimental.http.DynamicResponse; import org.junit.jupiter.api.Test; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import java.io.StringReader; import static org.junit.jupiter.api.Assertions.assertEquals; public class GlossaryBaseClientTests extends PurviewCatalogClientTestBase { private GlossaryBaseClient client; @Override protected void beforeTest() { client = clientSetup(httpPipeline -> new PurviewCatalogClientBuilder() .endpoint(getEndpoint()) .pipeline(httpPipeline) .buildGlossaryBaseClient()); } @Test public void testListGlossaries() { DynamicResponse res = client.listGlossaries().send(); assertEquals(200, res.getStatusCode()); JsonReader jsonReader = Json.createReader(new StringReader(res.getBody().toString())); JsonArray glossaries = jsonReader.readArray(); assertEquals(1, glossaries.size()); JsonObject glossary = glossaries.get(0).asJsonObject(); assertEquals("Glossary", glossary.getString("name")); JsonArray terms = glossary.getJsonArray("terms"); assertEquals(1, terms.size()); } }
1,404
0.707977
0.703704
43
31.651163
25.628731
94
false
false
0
0
0
0
0
0
0.55814
false
false
10
179543b638dc866ab1fdc48f30c87e00ad358a83
2,052,994,418,395
f237c51927290ffd046bd04723687f3e1ceb061b
/src/LinkedList.java
7997e9bb0c97da41ebf0ec4d08efa3da78c3ef6d
[]
no_license
khaled-988/Electric-power-grid
https://github.com/khaled-988/Electric-power-grid
502ea51c88dbf4c92dc2b6999d46f53e8c12ed2b
65db26be225124449681867790c3f3d4dafed2d2
refs/heads/master
2021-01-05T05:27:00.870000
2020-06-04T06:44:47
2020-06-04T06:44:47
240,896,654
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class LinkedList<T> { private Node1<T> head; private Node1<T> cur; public LinkedList() { head = null; cur = null; } public LinkedList(Node1<T> head) { super(); this.head = head; cur = null; } public LinkedList(Node1<T> head, Node1<T> cur) { super(); this.head = null; this.cur = null; } public void setCur(Node1<T> c) { cur=c; } public Node1<T> getCur(){ return cur; } public int length() { Node1 <T> tmp =head; int x=0; while (tmp != null) { x++; tmp=tmp.next; } return x; } public boolean empty() { // TODO Auto-generated method stub return head == null; } public boolean full() { // TODO Auto-generated method stub return false; } public void findFirst() { cur = head; // TODO Auto-generated method stub } public void findNext() { cur = cur.getNext(); // TODO Auto-generated method stub } public boolean last() { // TODO Auto-generated method stub return cur.getNext() == null; } public T retrieve() { // TODO Auto-generated method stub return cur.getData(); } public void update(T e) { cur.setData(e); // TODO Auto-generated method stub } public void insert(T e) { /* 1. allocate node * 2. put in the data */ Node1<T> new_node = new Node1<T>(e); Node1<T> last = head; /* used in step 5*/ /* 3. This new node is going to be the last node, so * make next of it as NULL*/ new_node.next = null; /* 4. If the Linked List is empty, then make the new * node as head */ if (head == null) { new_node.til = null; head = new_node; return; } /* 5. Else traverse till the last node */ while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; /* 7. Make last node as previous of new node */ new_node.til = last; /* if (head == null) cur = head = new Node1<T>(e); else { Node1<T> tmp = cur.getNext(); Node1<T> tmp1 = head; while (tmp1.next != cur) { tmp1=tmp1.next; } tmp1.next.setNext(new Node1<T>(e)); tmp1=tmp1.next; cur=cur.next; cur.setNext(new Node1<T>(e)); cur = cur.getNext(); cur.setNext(tmp); }*/ } public void remove() { if (cur == head) head = head.getNext(); else { Node1<T> tmp = head; while (tmp.getNext() != cur) tmp = tmp.getNext(); tmp.setNext(cur.getNext()); } if (cur.getNext() == null) cur = head; else cur = cur.getNext(); } }
UTF-8
Java
2,726
java
LinkedList.java
Java
[]
null
[]
public class LinkedList<T> { private Node1<T> head; private Node1<T> cur; public LinkedList() { head = null; cur = null; } public LinkedList(Node1<T> head) { super(); this.head = head; cur = null; } public LinkedList(Node1<T> head, Node1<T> cur) { super(); this.head = null; this.cur = null; } public void setCur(Node1<T> c) { cur=c; } public Node1<T> getCur(){ return cur; } public int length() { Node1 <T> tmp =head; int x=0; while (tmp != null) { x++; tmp=tmp.next; } return x; } public boolean empty() { // TODO Auto-generated method stub return head == null; } public boolean full() { // TODO Auto-generated method stub return false; } public void findFirst() { cur = head; // TODO Auto-generated method stub } public void findNext() { cur = cur.getNext(); // TODO Auto-generated method stub } public boolean last() { // TODO Auto-generated method stub return cur.getNext() == null; } public T retrieve() { // TODO Auto-generated method stub return cur.getData(); } public void update(T e) { cur.setData(e); // TODO Auto-generated method stub } public void insert(T e) { /* 1. allocate node * 2. put in the data */ Node1<T> new_node = new Node1<T>(e); Node1<T> last = head; /* used in step 5*/ /* 3. This new node is going to be the last node, so * make next of it as NULL*/ new_node.next = null; /* 4. If the Linked List is empty, then make the new * node as head */ if (head == null) { new_node.til = null; head = new_node; return; } /* 5. Else traverse till the last node */ while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; /* 7. Make last node as previous of new node */ new_node.til = last; /* if (head == null) cur = head = new Node1<T>(e); else { Node1<T> tmp = cur.getNext(); Node1<T> tmp1 = head; while (tmp1.next != cur) { tmp1=tmp1.next; } tmp1.next.setNext(new Node1<T>(e)); tmp1=tmp1.next; cur=cur.next; cur.setNext(new Node1<T>(e)); cur = cur.getNext(); cur.setNext(tmp); }*/ } public void remove() { if (cur == head) head = head.getNext(); else { Node1<T> tmp = head; while (tmp.getNext() != cur) tmp = tmp.getNext(); tmp.setNext(cur.getNext()); } if (cur.getNext() == null) cur = head; else cur = cur.getNext(); } }
2,726
0.529347
0.517241
153
15.803922
14.415886
58
false
false
0
0
0
0
0
0
1.712418
false
false
10
6f577ab381e3021c12b4ecd3e53c96441f3badfb
9,543,417,333,224
ea35ed96ac466d4184627de1f2408f22c02a3741
/com.brindysoft.necronomud/src/com/brindysoft/necronomud/web/MapGraphGenerator.java
baa14d8c115ed6315d0807274f31813f9320daaa
[]
no_license
brindy/osgi-mud
https://github.com/brindy/osgi-mud
e15c03a25d10cc2e1b54a726efd367751d3eb49e
ecc4e0954b361cdb768ccbb25c88a7d5940c3a25
refs/heads/master
2016-09-05T15:22:23.807000
2012-10-24T23:57:24
2012-10-24T23:57:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.brindysoft.necronomud.web; import com.brindysoft.mud.mpi.MudPlace; public class MapGraphGenerator { public MapGraph generate(MudPlace place) { MapGraph mapGraph = new MapGraph(); add(place, 0, 0, 0, 0, mapGraph); return mapGraph; } private void add(MudPlace place, int x, int y, int xMod, int yMod, MapGraph mapGraph) { if (null == place) { return; } if (mapGraph.contains(place)) { return; } if (mapGraph.contains(x + xMod, y + yMod)) { if (xMod != 0) { mapGraph.shiftColumn(x, -xMod); } else if (yMod != 0) { mapGraph.shiftRow(y, -yMod); } } else { x += xMod; y += yMod; } mapGraph.add(new MapNode(place, x, y)); add(place.getExit("north"), x, y, 0, -1, mapGraph); add(place.getExit("east"), x, y, 1, 0, mapGraph); add(place.getExit("south"), x, y, 0, 1, mapGraph); add(place.getExit("west"), x, y, -1, 0, mapGraph); } }
UTF-8
Java
910
java
MapGraphGenerator.java
Java
[]
null
[]
package com.brindysoft.necronomud.web; import com.brindysoft.mud.mpi.MudPlace; public class MapGraphGenerator { public MapGraph generate(MudPlace place) { MapGraph mapGraph = new MapGraph(); add(place, 0, 0, 0, 0, mapGraph); return mapGraph; } private void add(MudPlace place, int x, int y, int xMod, int yMod, MapGraph mapGraph) { if (null == place) { return; } if (mapGraph.contains(place)) { return; } if (mapGraph.contains(x + xMod, y + yMod)) { if (xMod != 0) { mapGraph.shiftColumn(x, -xMod); } else if (yMod != 0) { mapGraph.shiftRow(y, -yMod); } } else { x += xMod; y += yMod; } mapGraph.add(new MapNode(place, x, y)); add(place.getExit("north"), x, y, 0, -1, mapGraph); add(place.getExit("east"), x, y, 1, 0, mapGraph); add(place.getExit("south"), x, y, 0, 1, mapGraph); add(place.getExit("west"), x, y, -1, 0, mapGraph); } }
910
0.615385
0.6
44
19.681818
21.116316
88
false
false
0
0
0
0
0
0
2.590909
false
false
10
75f04d1b6699e5117ba83ade33ed443a20ff7185
704,374,658,272
6932fc06a4006f2961dd27ab9d3dab2789f75fc3
/sell-order/order-server/src/main/java/com/learn/springcloud/sell/order/server/message/StreamClient.java
3c8a13fb53f0d8f4d2a3a21c2779d429a5f51e78
[ "MIT" ]
permissive
yeehomfoo/sell-spring-cloud
https://github.com/yeehomfoo/sell-spring-cloud
179472ba2a049ee6c99458e412813c6b80d1dfda
f57caa7064f8294be5a79655ffbd072aefdb4576
refs/heads/master
2020-04-11T18:54:37.538000
2018-12-27T17:54:32
2018-12-27T17:54:32
162,016,215
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.learn.springcloud.sell.order.server.message; import org.springframework.cloud.stream.annotation.Input; import org.springframework.cloud.stream.annotation.Output; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.SubscribableChannel; /** * @author yFoo * @date 2018-12-28 */ public interface StreamClient { String INPUT = "myInput"; String RETURN = "myReturn"; String OUTPUT = "myOutput"; @Input(StreamClient.INPUT) SubscribableChannel input(); @Input(StreamClient.RETURN) SubscribableChannel returnInput(); @Output(StreamClient.OUTPUT) MessageChannel output(); }
UTF-8
Java
661
java
StreamClient.java
Java
[ { "context": "ork.messaging.SubscribableChannel;\n\n/**\n * @author yFoo\n * @date 2018-12-28\n */\n\npublic interface StreamC", "end": 306, "score": 0.9994709491729736, "start": 302, "tag": "USERNAME", "value": "yFoo" } ]
null
[]
package com.learn.springcloud.sell.order.server.message; import org.springframework.cloud.stream.annotation.Input; import org.springframework.cloud.stream.annotation.Output; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.SubscribableChannel; /** * @author yFoo * @date 2018-12-28 */ public interface StreamClient { String INPUT = "myInput"; String RETURN = "myReturn"; String OUTPUT = "myOutput"; @Input(StreamClient.INPUT) SubscribableChannel input(); @Input(StreamClient.RETURN) SubscribableChannel returnInput(); @Output(StreamClient.OUTPUT) MessageChannel output(); }
661
0.753404
0.741301
27
23.481482
20.440285
58
false
false
0
0
0
0
0
0
0.407407
false
false
10
5a413f8f4594dbdf2144f1b27f39f582435404eb
19,490,561,592,306
f3c091b970f915877291baf5aa9a3adf79b95ce7
/rest-service/java-spring-eclipse-example/java/com/example/demo/JavaSpringEclipseExampleApplication.java
a25f9a020ba56d6a489318958c1ec5dd3ae06caf
[]
no_license
GoldenShiber/MTGA_Booting
https://github.com/GoldenShiber/MTGA_Booting
edbda2cddd00adf6cccd9ed8a543aa4b045c048e
adebe9e3361efeb917b9243282174b662d1a0b81
refs/heads/master
2023-08-27T01:21:10.106000
2021-11-06T15:23:19
2021-11-06T15:23:19
379,935,226
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo; import java.util.Timer; import java.util.TimerTask; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import status.CharacterList; import util.JSONUtilities; @SpringBootApplication public class JavaSpringEclipseExampleApplication { public static void main(String[] args) { CharacterList.getInstance(); JSONUtilities.importJSONFile("GUItest.json"); SpringApplication.run(JavaSpringEclipseExampleApplication.class, args); // Add a backup saved, so we have one running each 30 min. Timer timer = new Timer(); timer.schedule( new TimerTask() { public void run() { JSONUtilities.saveCharacterList(CharacterList.getInstance().getCharacterList(), "GUItestBackup.json"); } }, 0, 60*1000); } }
UTF-8
Java
833
java
JavaSpringEclipseExampleApplication.java
Java
[]
null
[]
package com.example.demo; import java.util.Timer; import java.util.TimerTask; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import status.CharacterList; import util.JSONUtilities; @SpringBootApplication public class JavaSpringEclipseExampleApplication { public static void main(String[] args) { CharacterList.getInstance(); JSONUtilities.importJSONFile("GUItest.json"); SpringApplication.run(JavaSpringEclipseExampleApplication.class, args); // Add a backup saved, so we have one running each 30 min. Timer timer = new Timer(); timer.schedule( new TimerTask() { public void run() { JSONUtilities.saveCharacterList(CharacterList.getInstance().getCharacterList(), "GUItestBackup.json"); } }, 0, 60*1000); } }
833
0.759904
0.7491
31
25.870968
26.569134
111
false
false
0
0
0
0
0
0
1.419355
false
false
10
1c92cdf279333af26febb25bbbcc76e112d7cfc2
33,139,967,717,684
648f42dbb1280df63d2be942a02e6cdc3b9d96e3
/PA2/Submission/ServerAP.java
c20a9aaad8fa761b5b37a8da3ab4823bbbcf486d
[]
no_license
nugglet/50.005-CSE-Shell
https://github.com/nugglet/50.005-CSE-Shell
38dda7a92fb40875a1e0ae1b6d3d6d7773a0a968
2e51f9d59c9c2c4211d1c73f1c19a2cb0388fee5
refs/heads/main
2023-04-06T22:23:01.800000
2021-04-21T10:29:07
2021-04-21T10:29:07
335,631,062
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.*; import java.security.spec.*; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; public class ServerAP { private InputStream fis; private CertificateFactory cf = null; private byte[] certificate; private X509Certificate ServerCert; private PublicKey serverPublicKey; private static PrivateKey privateKey; // Nonce private static byte[] nonce = new byte[32]; private static byte[] encryptedNonce = new byte[128]; private static Cipher eCipher; private static Cipher dCipher; private final String keyPath = "private_key.der"; public static final String path = "certificate_1004289.crt"; public ServerAP(String fis) throws IOException { this.fis = new FileInputStream(fis); try { this.cf = CertificateFactory.getInstance("X.509"); // Get signed server certificate this.ServerCert = (X509Certificate) cf.generateCertificate(this.fis); this.certificate = this.ServerCert.getEncoded(); // Get server public key this.serverPublicKey = this.ServerCert.getPublicKey(); // Get server private key privateKey = getPrivateKey(keyPath); } catch (Exception e) { e.printStackTrace(); } this.fis.close(); } public PrivateKey getPrivateKey(String filename) throws Exception { byte[] keyBytes = Files.readAllBytes(Paths.get(filename)); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate(spec); } public PublicKey getPublicKey(String filename) throws Exception { byte[] keyBytes = Files.readAllBytes(Paths.get(filename)); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePublic(spec); } // encrypt plaintext nonce sent by client public void encryptNonce() throws Exception { eCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); eCipher.init(Cipher.ENCRYPT_MODE, privateKey); encryptedNonce = eCipher.doFinal(nonce); } // CP1, decrypt message sent by client using private key public static byte[] decryptMsg(byte[] fileByte) throws Exception { dCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); dCipher.init(Cipher.DECRYPT_MODE, privateKey); return dCipher.doFinal(fileByte); } public byte[] getNonce() { return nonce; } public byte[] getEncryptedNonce() { return encryptedNonce; } public byte[] getCertificate() { return certificate; } }
UTF-8
Java
3,253
java
ServerAP.java
Java
[]
null
[]
import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.*; import java.security.spec.*; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; public class ServerAP { private InputStream fis; private CertificateFactory cf = null; private byte[] certificate; private X509Certificate ServerCert; private PublicKey serverPublicKey; private static PrivateKey privateKey; // Nonce private static byte[] nonce = new byte[32]; private static byte[] encryptedNonce = new byte[128]; private static Cipher eCipher; private static Cipher dCipher; private final String keyPath = "private_key.der"; public static final String path = "certificate_1004289.crt"; public ServerAP(String fis) throws IOException { this.fis = new FileInputStream(fis); try { this.cf = CertificateFactory.getInstance("X.509"); // Get signed server certificate this.ServerCert = (X509Certificate) cf.generateCertificate(this.fis); this.certificate = this.ServerCert.getEncoded(); // Get server public key this.serverPublicKey = this.ServerCert.getPublicKey(); // Get server private key privateKey = getPrivateKey(keyPath); } catch (Exception e) { e.printStackTrace(); } this.fis.close(); } public PrivateKey getPrivateKey(String filename) throws Exception { byte[] keyBytes = Files.readAllBytes(Paths.get(filename)); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate(spec); } public PublicKey getPublicKey(String filename) throws Exception { byte[] keyBytes = Files.readAllBytes(Paths.get(filename)); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePublic(spec); } // encrypt plaintext nonce sent by client public void encryptNonce() throws Exception { eCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); eCipher.init(Cipher.ENCRYPT_MODE, privateKey); encryptedNonce = eCipher.doFinal(nonce); } // CP1, decrypt message sent by client using private key public static byte[] decryptMsg(byte[] fileByte) throws Exception { dCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); dCipher.init(Cipher.DECRYPT_MODE, privateKey); return dCipher.doFinal(fileByte); } public byte[] getNonce() { return nonce; } public byte[] getEncryptedNonce() { return encryptedNonce; } public byte[] getCertificate() { return certificate; } }
3,253
0.692284
0.681217
106
29.688679
23.504461
81
false
false
0
0
0
0
0
0
0.537736
false
false
10
42fc020628d53717c12aa08b6051a058713b4969
23,880,018,185,592
213331ba00f0a57cdde074da9de70346e49d81f8
/app/src/main/java/com/maymeskul/hometask12/InfoReaderContract.java
fd9518e423627fd7880719837ed00cdfff8db94b
[]
no_license
Maymeskul/HomeTask12
https://github.com/Maymeskul/HomeTask12
4c25b3f5207f836dfb7a5173de171ee8a9211e32
06b400a0e9859f1a59d87042adb92a85e9bd288c
refs/heads/master
2016-08-04T01:42:57.109000
2015-03-14T12:05:46
2015-03-14T12:05:46
31,615,013
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.maymeskul.hometask12; import android.provider.BaseColumns; /** * Created by ivan on 3/3/15. */ public final class InfoReaderContract { public InfoReaderContract() {} public static abstract class InfoEntry implements BaseColumns { public static final String TABLE_NAME = "my_table"; public static final String COLUMN_NAME_TITLE = "my_column"; } }
UTF-8
Java
391
java
InfoReaderContract.java
Java
[ { "context": "t android.provider.BaseColumns;\n\n/**\n * Created by ivan on 3/3/15.\n */\npublic final class InfoReaderContr", "end": 95, "score": 0.517278254032135, "start": 91, "tag": "USERNAME", "value": "ivan" } ]
null
[]
package com.maymeskul.hometask12; import android.provider.BaseColumns; /** * Created by ivan on 3/3/15. */ public final class InfoReaderContract { public InfoReaderContract() {} public static abstract class InfoEntry implements BaseColumns { public static final String TABLE_NAME = "my_table"; public static final String COLUMN_NAME_TITLE = "my_column"; } }
391
0.710997
0.695652
15
25.066668
24.468937
67
false
false
0
0
0
0
0
0
0.266667
false
false
10
dd7f196784fd0787ab53584e6957a6ff6acf7265
33,698,313,469,349
e1f4fa8661f9e845f6a4edc749e258be9749aa6b
/src/kwrig/AI/EnemyEstimateAndAttack.java
c5dc3dea12986d840ffd959fb11e9124e5fbb3b8
[]
no_license
kwrig/SamurAI_coding_2015_16
https://github.com/kwrig/SamurAI_coding_2015_16
c4b2cc4343826540eaf8ed8f5775ddadea96c13e
5bcac3c41810ecb1e73d7244ce9842848aba0a2a
refs/heads/master
2016-09-12T13:31:38.929000
2016-05-15T13:25:01
2016-05-15T13:25:01
58,861,508
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kwrig.AI; import kwrig.Field; import kwrig.General; import java.util.ArrayList; import java.util.List; /** * Created by kwrig on 2016/02/06. */ public class EnemyEstimateAndAttack extends EnemyEstimate { public EnemyEstimateAndAttack(int n, boolean isEnemyAttack) { super(n, isEnemyAttack); } public EnemyEstimateAndAttack(int n) { super(n); } public EnemyEstimateAndAttack(int n , boolean isEnemyAttack , int w){ super(n,isEnemyAttack); DataStrage strage = new DataStrage(); Weights = strage.getWeights(w); this.w = w; } int w = -1; /* @Override double getUtility(Field f, int moveTurn) { int util = 0; if (prevField == null) { return super.getUtility(f, moveTurn); } if(estimateFlag == false){ return super.getUtility(f,moveTurn); } if (moveTurn == 0) { for (int i = 0; i < 6; i++) { if (i / 3 == samurAINumber / 3) { continue; } if( i%3 == samurAINumber%3){ continue; } List<Integer> dist = new ArrayList<>(3); int[] mypos = General.getXY(f.players[samurAINumber].position); int[] enemypos; if(f.players[i].isHide==false){ enemypos = General.getXY(f.players[i].position); dist.add(enemypos[0] - mypos[0]); dist.add(enemypos[1]-mypos[1]); if(General.NEARATTACKRANGE.get(samurAINumber%3).contains(dist)){ util += 10; } } for (Integer pos : estimatePos.get(i)) { if (f.field[pos] == samurAINumber) { util += 10; } else if (General.isCanAttackRange(i, pos, f.players[samurAINumber].position)) { util -= 20; } enemypos = General.getXY(pos); dist.add(enemypos[0] - mypos[0]); dist.add(enemypos[1]-mypos[1]); if(General.NEARATTACKRANGE.get(samurAINumber%3).contains(dist)){ util += 5; } } } } if(moveTurn == 1 && General.leaveMoveTurnInEqualBuki(f.turn , samurAINumber)==1){ util += f.score.death[ (samurAINumber+3)%6 ] * 100; } return super.getUtility(f, moveTurn) +(double)util; } */ @Override double getUtility(Field f, int moveTurn) { int util = 0; if (prevField == null) { return super.getUtility(f, moveTurn); } if(estimateFlag == false){ return super.getUtility(f,moveTurn); } if (moveTurn == 0) { for (int i = 0; i < 6; i++) { if (i / 3 == samurAINumber / 3) { continue; } if( i%3 == samurAINumber%3){ continue; } List<Integer> dist = new ArrayList<>(3); int[] mypos = General.getXY(f.players[samurAINumber].position); int[] enemypos; if(f.players[i].isHide==false){ enemypos = General.getXY(f.players[i].position); dist.add(enemypos[0] - mypos[0]); dist.add(enemypos[1]-mypos[1]); if(General.NEARATTACKRANGE.get(samurAINumber%3).contains(dist)){ if(f.players[samurAINumber].isHide){ util += getWeight(10); //util += 10.0 * getWeight(10); }else { util += getWeight(11); //util += 5.0 * getWeight(11); } } } for (Integer pos : estimatePos.get(i)) { enemypos = General.getXY(pos); dist.add(enemypos[0] - mypos[0]); dist.add(enemypos[1]-mypos[1]); if(General.NEARATTACKRANGE.get(samurAINumber%3).contains(dist)){ if(f.players[samurAINumber].isHide){ util += getWeight(12) / estimatePos.size(); // util += 10.0/estimatePos.size() * getWeight(12); }else { util += getWeight(13)/estimatePos.size(); //util += 5.0/estimatePos.size() * getWeight(13); } } } } } if(moveTurn == 1 && General.leaveMoveTurnInEqualBuki(f.turn , samurAINumber)==1 && f.players[(samurAINumber+3)%6].isHide==false){ util += f.score.death[ (samurAINumber+3)%6 ] * getWeight(14); // util += f.score.death[ (samurAINumber+3)%6 ] * 100 * getWeight(14); int[] mypos = General.getXY(f.players[samurAINumber].position); int[] enemypos = General.getXY(f.players[(samurAINumber+3)%6 ].position); int[] ddd = {enemypos[0] - mypos[0] , enemypos[1]-mypos[1]}; boolean flag = true; for(List<Integer> dist : General.NEARATTACKRANGE.get(samurAINumber%3)){ int[] dd = {dist.get(0) , dist.get(1)}; if( Math.abs(dd[0]-ddd[0]) + Math.abs(dd[1]-ddd[1]) == 1 && flag == true){ flag = false; util -= getWeight(15); //util -= 20 * getWeight(15); } } } return super.getUtility(f, moveTurn) +(double)util; } @Override public String getName() { return "AttackAIattack" + isEnemyAttack + " W=" + w +" "; } }
UTF-8
Java
5,969
java
EnemyEstimateAndAttack.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by kwrig on 2016/02/06.\n */\npublic class EnemyEstimateAndA", "end": 137, "score": 0.9996510744094849, "start": 132, "tag": "USERNAME", "value": "kwrig" } ]
null
[]
package kwrig.AI; import kwrig.Field; import kwrig.General; import java.util.ArrayList; import java.util.List; /** * Created by kwrig on 2016/02/06. */ public class EnemyEstimateAndAttack extends EnemyEstimate { public EnemyEstimateAndAttack(int n, boolean isEnemyAttack) { super(n, isEnemyAttack); } public EnemyEstimateAndAttack(int n) { super(n); } public EnemyEstimateAndAttack(int n , boolean isEnemyAttack , int w){ super(n,isEnemyAttack); DataStrage strage = new DataStrage(); Weights = strage.getWeights(w); this.w = w; } int w = -1; /* @Override double getUtility(Field f, int moveTurn) { int util = 0; if (prevField == null) { return super.getUtility(f, moveTurn); } if(estimateFlag == false){ return super.getUtility(f,moveTurn); } if (moveTurn == 0) { for (int i = 0; i < 6; i++) { if (i / 3 == samurAINumber / 3) { continue; } if( i%3 == samurAINumber%3){ continue; } List<Integer> dist = new ArrayList<>(3); int[] mypos = General.getXY(f.players[samurAINumber].position); int[] enemypos; if(f.players[i].isHide==false){ enemypos = General.getXY(f.players[i].position); dist.add(enemypos[0] - mypos[0]); dist.add(enemypos[1]-mypos[1]); if(General.NEARATTACKRANGE.get(samurAINumber%3).contains(dist)){ util += 10; } } for (Integer pos : estimatePos.get(i)) { if (f.field[pos] == samurAINumber) { util += 10; } else if (General.isCanAttackRange(i, pos, f.players[samurAINumber].position)) { util -= 20; } enemypos = General.getXY(pos); dist.add(enemypos[0] - mypos[0]); dist.add(enemypos[1]-mypos[1]); if(General.NEARATTACKRANGE.get(samurAINumber%3).contains(dist)){ util += 5; } } } } if(moveTurn == 1 && General.leaveMoveTurnInEqualBuki(f.turn , samurAINumber)==1){ util += f.score.death[ (samurAINumber+3)%6 ] * 100; } return super.getUtility(f, moveTurn) +(double)util; } */ @Override double getUtility(Field f, int moveTurn) { int util = 0; if (prevField == null) { return super.getUtility(f, moveTurn); } if(estimateFlag == false){ return super.getUtility(f,moveTurn); } if (moveTurn == 0) { for (int i = 0; i < 6; i++) { if (i / 3 == samurAINumber / 3) { continue; } if( i%3 == samurAINumber%3){ continue; } List<Integer> dist = new ArrayList<>(3); int[] mypos = General.getXY(f.players[samurAINumber].position); int[] enemypos; if(f.players[i].isHide==false){ enemypos = General.getXY(f.players[i].position); dist.add(enemypos[0] - mypos[0]); dist.add(enemypos[1]-mypos[1]); if(General.NEARATTACKRANGE.get(samurAINumber%3).contains(dist)){ if(f.players[samurAINumber].isHide){ util += getWeight(10); //util += 10.0 * getWeight(10); }else { util += getWeight(11); //util += 5.0 * getWeight(11); } } } for (Integer pos : estimatePos.get(i)) { enemypos = General.getXY(pos); dist.add(enemypos[0] - mypos[0]); dist.add(enemypos[1]-mypos[1]); if(General.NEARATTACKRANGE.get(samurAINumber%3).contains(dist)){ if(f.players[samurAINumber].isHide){ util += getWeight(12) / estimatePos.size(); // util += 10.0/estimatePos.size() * getWeight(12); }else { util += getWeight(13)/estimatePos.size(); //util += 5.0/estimatePos.size() * getWeight(13); } } } } } if(moveTurn == 1 && General.leaveMoveTurnInEqualBuki(f.turn , samurAINumber)==1 && f.players[(samurAINumber+3)%6].isHide==false){ util += f.score.death[ (samurAINumber+3)%6 ] * getWeight(14); // util += f.score.death[ (samurAINumber+3)%6 ] * 100 * getWeight(14); int[] mypos = General.getXY(f.players[samurAINumber].position); int[] enemypos = General.getXY(f.players[(samurAINumber+3)%6 ].position); int[] ddd = {enemypos[0] - mypos[0] , enemypos[1]-mypos[1]}; boolean flag = true; for(List<Integer> dist : General.NEARATTACKRANGE.get(samurAINumber%3)){ int[] dd = {dist.get(0) , dist.get(1)}; if( Math.abs(dd[0]-ddd[0]) + Math.abs(dd[1]-ddd[1]) == 1 && flag == true){ flag = false; util -= getWeight(15); //util -= 20 * getWeight(15); } } } return super.getUtility(f, moveTurn) +(double)util; } @Override public String getName() { return "AttackAIattack" + isEnemyAttack + " W=" + w +" "; } }
5,969
0.456525
0.436086
197
29.299492
27.85216
137
false
false
0
0
0
0
0
0
0.451777
false
false
10
9314605527d2810629a3777aae4d4485b5eea27f
33,698,313,468,014
38b5ccf14f710ba8aefcca4de4a347d8f13c0bad
/core/src/com/bstq/Game/PlayGameScreen.java
8b5bfbcee3f273154b002dbe8db94897d344c61e
[]
no_license
JoseMoranMu/BSTQ
https://github.com/JoseMoranMu/BSTQ
75e6162ef9749acb0d05ceafb9b34b22067f9584
23c5089ab03c48d89128bfafac9eaf56dc649218
refs/heads/master
2021-01-22T20:12:45.906000
2017-06-10T17:12:33
2017-06-10T17:12:33
85,294,454
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bstq.Game; import com.badlogic.gdx.Files; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Dialog; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.Timer; import com.bstq.Main; import com.bstq.Model.UsersDAO; import com.bstq.view.ButtonHandler; import com.bstq.view.MainMenu; import java.net.UnknownHostException; import static com.badlogic.gdx.scenes.scene2d.actions.Actions.moveBy; /** * Created by Jose on 07/03/2017. */ public class PlayGameScreen extends TableGame { final Main main; Stage stage; Texture casillaTextura,tuercaBlue,tuercaRead,explode, lightning; Table t,tc,bt; Barril bar; Tablero tablero; SpriteBatch b; BitmapFont font; Skin sk; UsersDAO service; Texture back; Sprite background; Music mp3Music; Sound explosion; public PlayGameScreen(final Main main){ this.main=main; Gdx.input.setCatchBackKey(true); service = new UsersDAO(); stage = new Stage(); back = new Texture(Gdx.files.internal("background.jpg")); background = new Sprite(back); mp3Music = Gdx.audio.newMusic(Gdx.files.internal("sounds/music.mp3")); explosion = Gdx.audio.newSound( Gdx.files.getFileHandle("sounds/explode.mp3", Files.FileType.Internal) ); mp3Music.play(); prepareStyle(); createLogicTable(); initTextures(); createTableGame(); createTableContent(); createTableButtons(); stage.addActor(t); stage.addActor(tc); stage.addActor(bt); } /** * Method to prepare style */ private void prepareStyle() { sk = new Skin(Gdx.files.internal("uiskin.json"),new TextureAtlas(Gdx.files.internal("uiskin.atlas"))); sk.getFont("default-font").getData().setScale(3f,3f); font = new BitmapFont(); font.getData().setScale(5,5); b= new SpriteBatch(); } /** * Method to initialize textures */ private void initTextures() { tuercaBlue = new Texture("blueGear.png"); tuercaRead = new Texture("redGear.png"); explode = new Texture("explode.png"); lightning = new Texture("lightning.png"); } /** * Method to initialize */ private void createLogicTable() { tablero = new Tablero(6); tablero.generateAllContent(); tablero.startTimer(); } /** * Method to create Buttons and their listeners */ private void createTableButtons() { bt = new Table(); bt.setPosition(Gdx.graphics.getWidth(),Gdx.graphics.getHeight()); ButtonHandler bh = new ButtonHandler(); Boton b; int i=0; for(int p=162;p<912;p=p+125){ b = bh.getButton(new Texture(Gdx.files.internal("magnetUp.png")), p, 1225); b.setId(i); b.addCaptureListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { Boton b = (Boton) actor; tablero.moveUpColumn(b.getId()); } }); stage.addActor(b); i++; } i=0; for(int p=162;p<912;p=p+125){ b = bh.getButton(new Texture(Gdx.files.internal("magnetDown.png")), p, 350); b.setId(i); b.addCaptureListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { Boton b = (Boton) actor; tablero.moveDownColumn(b.getId()); } }); stage.addActor(b); i++; } i=0; for(int p=1100;p>350;p=p-125){ b = bh.getButton(new Texture(Gdx.files.internal("magnetLeft.png")), 37, p); b.setId(i); b.addCaptureListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { Boton b = (Boton) actor; tablero.moveLeftRow(b.getId()); } }); stage.addActor(b); i++; } i=0; for(int p=1100;p>350;p=p-125){ b = bh.getButton(new Texture(Gdx.files.internal("magnetRight.png")), 912, p); b.setId(i); b.addCaptureListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { Boton b = (Boton) actor; tablero.moveRigthRow(b.getId()); } }); stage.addActor(b); i++; } } /** * Method to fill the table with the info given of Tablero class checks if * there is a full line * @return true if there is a full line/ false otherwise */ private boolean refreshTable() { tc.clearChildren(); boolean bo=tablero.check(); int a=0; int b=0; for(int i=1100;i>350;i=i-125){ for(int p=162;p<912;p=p+125){ if(tablero.getCell(a,b)==1){ tc.add(new Barril(tuercaBlue,p,i,0)); }else if(tablero.getCell(a,b)==2){ tc.add(new Barril(tuercaRead,p,i,0)); }else if(tablero.getCell(a,b)==88){ tc.add(new Barril(explode,p,i,0)); }else if(tablero.getCell(a,b)==3){ tc.add(new Barril(lightning,p,i,0)); } b++; } b=0; a++; } tc.add(bar); return bo; } /** * Initialize table content */ private void createTableContent() { tc = new Table(); refreshTable(); } /** * Create table texture */ private void createTableGame() { t = new Table(); casillaTextura = new Texture("casillafin.png"); for(int i=1100;i>350;i=i-125){ for(int p=162;p<912;p=p+125){ t.add(new Casilla(casillaTextura,p,i)); } } } @Override public void show() { Gdx.input.setInputProcessor(stage); } @Override public void render(float delta) { boolean bool; BackButton(); Gdx.gl.glClearColor(0.0f, 153f/255.0f, 0.0f, 0.0f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); b.begin(); background.draw(b); font.draw(b,"Points: "+Integer.toString(tablero.getPoints()),100,1600); font.draw(b,"Time: "+Integer.toString(tablero.getTime()),100,1500); b.end(); if(refreshTable()){ destroyContent(); } if(tablero.getTime()==0) endGame(); stage.act(); stage.draw(); } /** * Method to execute end of game check the points */ private void endGame() { int points = tablero.getPoints(); String s; mp3Music.stop(); if(points>main.getUserLoged().getMaxScore()){ s ="You have a new record : "+points; showDialog(s,true); }else{ s ="Time's up! \n"+"You points : "+points; showDialog(s,false); } } /** * Method to execute animation of explosion */ private void destroyContent() { explosion.play(); Timer.schedule(new Timer.Task() { @Override public void run() { tablero.generateNewContent(); } }, 0.5f); } /** * Method to go back */ private void BackButton() { if (Gdx.input.isKeyJustPressed(Input.Keys.BACK)) { mp3Music.stop(); main.setScreen(new MainMenu(main)); } } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { /* stage.dispose(); b.dispose(); casillaTextura.dispose(); tuercaBlue.dispose(); tuercaRead.dispose(); explode.dispose(); */ } @Override public void dispose() { stage.dispose(); b.dispose(); casillaTextura.dispose(); tuercaBlue.dispose(); tuercaRead.dispose(); explode.dispose(); back.dispose(); mp3Music.dispose(); explosion.dispose(); } /** * Method to show a dialog message * @param s message to show * @param exit boolean to registern new record or not */ private void showDialog(String s, boolean exit) { Label label = new Label(s, sk); label.setWrap(true); label.setAlignment(Align.center); Dialog d =new Dialog("", sk, "dialog") { protected void result (Object object) { this.clear(); if(object.equals(true)){ try { service.registPoints(main.getUserLoged().getId(),tablero.getPoints()); } catch (UnknownHostException e) { e.printStackTrace(); } main.getUserLoged().setMaxScore(tablero.getPoints()); } main.setScreen(new MainMenu(main)); } }; d.padTop(50).padBottom(50).padLeft(50).padRight(50); d.getContentTable().padBottom(50); d.getContentTable().add(label).width(850).row(); d.button("Close", exit).show(stage); } }
UTF-8
Java
10,359
java
PlayGameScreen.java
Java
[ { "context": "scene2d.actions.Actions.moveBy;\n\n/**\n * Created by Jose on 07/03/2017.\n */\n\npublic class PlayGameScreen e", "end": 1144, "score": 0.8335685729980469, "start": 1140, "tag": "NAME", "value": "Jose" } ]
null
[]
package com.bstq.Game; import com.badlogic.gdx.Files; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Dialog; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.Timer; import com.bstq.Main; import com.bstq.Model.UsersDAO; import com.bstq.view.ButtonHandler; import com.bstq.view.MainMenu; import java.net.UnknownHostException; import static com.badlogic.gdx.scenes.scene2d.actions.Actions.moveBy; /** * Created by Jose on 07/03/2017. */ public class PlayGameScreen extends TableGame { final Main main; Stage stage; Texture casillaTextura,tuercaBlue,tuercaRead,explode, lightning; Table t,tc,bt; Barril bar; Tablero tablero; SpriteBatch b; BitmapFont font; Skin sk; UsersDAO service; Texture back; Sprite background; Music mp3Music; Sound explosion; public PlayGameScreen(final Main main){ this.main=main; Gdx.input.setCatchBackKey(true); service = new UsersDAO(); stage = new Stage(); back = new Texture(Gdx.files.internal("background.jpg")); background = new Sprite(back); mp3Music = Gdx.audio.newMusic(Gdx.files.internal("sounds/music.mp3")); explosion = Gdx.audio.newSound( Gdx.files.getFileHandle("sounds/explode.mp3", Files.FileType.Internal) ); mp3Music.play(); prepareStyle(); createLogicTable(); initTextures(); createTableGame(); createTableContent(); createTableButtons(); stage.addActor(t); stage.addActor(tc); stage.addActor(bt); } /** * Method to prepare style */ private void prepareStyle() { sk = new Skin(Gdx.files.internal("uiskin.json"),new TextureAtlas(Gdx.files.internal("uiskin.atlas"))); sk.getFont("default-font").getData().setScale(3f,3f); font = new BitmapFont(); font.getData().setScale(5,5); b= new SpriteBatch(); } /** * Method to initialize textures */ private void initTextures() { tuercaBlue = new Texture("blueGear.png"); tuercaRead = new Texture("redGear.png"); explode = new Texture("explode.png"); lightning = new Texture("lightning.png"); } /** * Method to initialize */ private void createLogicTable() { tablero = new Tablero(6); tablero.generateAllContent(); tablero.startTimer(); } /** * Method to create Buttons and their listeners */ private void createTableButtons() { bt = new Table(); bt.setPosition(Gdx.graphics.getWidth(),Gdx.graphics.getHeight()); ButtonHandler bh = new ButtonHandler(); Boton b; int i=0; for(int p=162;p<912;p=p+125){ b = bh.getButton(new Texture(Gdx.files.internal("magnetUp.png")), p, 1225); b.setId(i); b.addCaptureListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { Boton b = (Boton) actor; tablero.moveUpColumn(b.getId()); } }); stage.addActor(b); i++; } i=0; for(int p=162;p<912;p=p+125){ b = bh.getButton(new Texture(Gdx.files.internal("magnetDown.png")), p, 350); b.setId(i); b.addCaptureListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { Boton b = (Boton) actor; tablero.moveDownColumn(b.getId()); } }); stage.addActor(b); i++; } i=0; for(int p=1100;p>350;p=p-125){ b = bh.getButton(new Texture(Gdx.files.internal("magnetLeft.png")), 37, p); b.setId(i); b.addCaptureListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { Boton b = (Boton) actor; tablero.moveLeftRow(b.getId()); } }); stage.addActor(b); i++; } i=0; for(int p=1100;p>350;p=p-125){ b = bh.getButton(new Texture(Gdx.files.internal("magnetRight.png")), 912, p); b.setId(i); b.addCaptureListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { Boton b = (Boton) actor; tablero.moveRigthRow(b.getId()); } }); stage.addActor(b); i++; } } /** * Method to fill the table with the info given of Tablero class checks if * there is a full line * @return true if there is a full line/ false otherwise */ private boolean refreshTable() { tc.clearChildren(); boolean bo=tablero.check(); int a=0; int b=0; for(int i=1100;i>350;i=i-125){ for(int p=162;p<912;p=p+125){ if(tablero.getCell(a,b)==1){ tc.add(new Barril(tuercaBlue,p,i,0)); }else if(tablero.getCell(a,b)==2){ tc.add(new Barril(tuercaRead,p,i,0)); }else if(tablero.getCell(a,b)==88){ tc.add(new Barril(explode,p,i,0)); }else if(tablero.getCell(a,b)==3){ tc.add(new Barril(lightning,p,i,0)); } b++; } b=0; a++; } tc.add(bar); return bo; } /** * Initialize table content */ private void createTableContent() { tc = new Table(); refreshTable(); } /** * Create table texture */ private void createTableGame() { t = new Table(); casillaTextura = new Texture("casillafin.png"); for(int i=1100;i>350;i=i-125){ for(int p=162;p<912;p=p+125){ t.add(new Casilla(casillaTextura,p,i)); } } } @Override public void show() { Gdx.input.setInputProcessor(stage); } @Override public void render(float delta) { boolean bool; BackButton(); Gdx.gl.glClearColor(0.0f, 153f/255.0f, 0.0f, 0.0f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); b.begin(); background.draw(b); font.draw(b,"Points: "+Integer.toString(tablero.getPoints()),100,1600); font.draw(b,"Time: "+Integer.toString(tablero.getTime()),100,1500); b.end(); if(refreshTable()){ destroyContent(); } if(tablero.getTime()==0) endGame(); stage.act(); stage.draw(); } /** * Method to execute end of game check the points */ private void endGame() { int points = tablero.getPoints(); String s; mp3Music.stop(); if(points>main.getUserLoged().getMaxScore()){ s ="You have a new record : "+points; showDialog(s,true); }else{ s ="Time's up! \n"+"You points : "+points; showDialog(s,false); } } /** * Method to execute animation of explosion */ private void destroyContent() { explosion.play(); Timer.schedule(new Timer.Task() { @Override public void run() { tablero.generateNewContent(); } }, 0.5f); } /** * Method to go back */ private void BackButton() { if (Gdx.input.isKeyJustPressed(Input.Keys.BACK)) { mp3Music.stop(); main.setScreen(new MainMenu(main)); } } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { /* stage.dispose(); b.dispose(); casillaTextura.dispose(); tuercaBlue.dispose(); tuercaRead.dispose(); explode.dispose(); */ } @Override public void dispose() { stage.dispose(); b.dispose(); casillaTextura.dispose(); tuercaBlue.dispose(); tuercaRead.dispose(); explode.dispose(); back.dispose(); mp3Music.dispose(); explosion.dispose(); } /** * Method to show a dialog message * @param s message to show * @param exit boolean to registern new record or not */ private void showDialog(String s, boolean exit) { Label label = new Label(s, sk); label.setWrap(true); label.setAlignment(Align.center); Dialog d =new Dialog("", sk, "dialog") { protected void result (Object object) { this.clear(); if(object.equals(true)){ try { service.registPoints(main.getUserLoged().getId(),tablero.getPoints()); } catch (UnknownHostException e) { e.printStackTrace(); } main.getUserLoged().setMaxScore(tablero.getPoints()); } main.setScreen(new MainMenu(main)); } }; d.padTop(50).padBottom(50).padLeft(50).padRight(50); d.getContentTable().padBottom(50); d.getContentTable().add(label).width(850).row(); d.button("Close", exit).show(stage); } }
10,359
0.545999
0.528236
377
26.477453
21.420389
113
false
false
0
0
0
0
0
0
0.676393
false
false
10
cff42f43bf850a1b487b514e5f28a6dce3e49fdf
2,791,728,755,718
8a1b46fe92416d26637df043eb277946b3585b9e
/commons/src/test/java/com/elminster/common/escape/test/RegexEscaperTest.java
e99c68fe2dfaa48ea9872d981e028c9580f4e5dc
[]
no_license
elminsterjimmy/javacommons
https://github.com/elminsterjimmy/javacommons
aeefb33cd0227445a4ddfb973abff337e43de2e1
72c7a56677f5defba15219ee51e2be07a7ad7d99
refs/heads/master
2022-10-12T10:47:04.729000
2022-05-17T02:49:03
2022-05-17T02:49:03
25,282,802
1
0
null
false
2022-09-22T17:52:39
2014-10-16T02:22:02
2022-05-17T02:49:20
2022-09-22T17:52:36
393
1
0
1
Java
false
false
package com.elminster.common.escape.test; import com.elminster.common.escape.RegexEscaper; import org.junit.Assert; import org.junit.Test; import java.util.regex.Pattern; public class RegexEscaperTest { @Test public void testEscape() { RegexEscaper escaper = new RegexEscaper(); String string = "(a*b^c) * [(d+e-f),(g/h)] ?"; String unescaped = string; String escaped = escaper.escape(string); Pattern unescapedPattern = Pattern.compile(unescaped); Pattern escapedPattern = Pattern.compile(escaped); Assert.assertFalse(unescapedPattern.matcher(string).find()); Assert.assertTrue(escapedPattern.matcher(string).find()); } }
UTF-8
Java
665
java
RegexEscaperTest.java
Java
[]
null
[]
package com.elminster.common.escape.test; import com.elminster.common.escape.RegexEscaper; import org.junit.Assert; import org.junit.Test; import java.util.regex.Pattern; public class RegexEscaperTest { @Test public void testEscape() { RegexEscaper escaper = new RegexEscaper(); String string = "(a*b^c) * [(d+e-f),(g/h)] ?"; String unescaped = string; String escaped = escaper.escape(string); Pattern unescapedPattern = Pattern.compile(unescaped); Pattern escapedPattern = Pattern.compile(escaped); Assert.assertFalse(unescapedPattern.matcher(string).find()); Assert.assertTrue(escapedPattern.matcher(string).find()); } }
665
0.72782
0.72782
22
29.227272
21.914984
64
false
false
0
0
0
0
0
0
0.636364
false
false
10
a4fce1343d171e269fea9bcef7f82958f0f38a94
26,895,085,272,057
e6d09e4f927c1a890bc4f949de5bbc82093e3d4d
/src/main/java/com/servletdemoproject/UserLoginServlet.java
ae3a235049777be3be36a2be65d4966df99fd12c
[]
no_license
karthik-karotra/User-Login_And-Registration-Using-Servlet
https://github.com/karthik-karotra/User-Login_And-Registration-Using-Servlet
2221aa2db2e130ba65f264b4fbef268c577962e3
0b2450bf552c9b7ebcf6a651d5ecbf4c8f135076
refs/heads/master
2021-05-26T23:25:06.102000
2020-04-09T00:59:49
2020-04-09T00:59:49
254,186,450
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.servletdemoproject; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet( description = "User Login Servlet Testing", urlPatterns = {"/loginServlet"} ) public class UserLoginServlet extends HttpServlet { static String VALID_NAME_PATTERN = "^[A-Z]{1}[a-z]{2,}$"; static String VALID_PASSWORD_PATTERN = "^((?=[^@|#|&|%|$]*[@|&|#|%|$][^@|#|&|%|$]*$)(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9#@$?]{8,})$"; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName = request.getParameter("userName"); String userPassword = request.getParameter("userPassword"); boolean validCredentials = userName.matches(VALID_NAME_PATTERN) && userPassword.matches(VALID_PASSWORD_PATTERN); if (validCredentials) { request.setAttribute("userName", userName); request.getRequestDispatcher("LoginPageSuccessful.jsp").forward(request, response); } else { RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/LoginPage.jsp"); PrintWriter out = response.getWriter(); out.print("<script>alert('Please enter valid credentials');</script>"); requestDispatcher.include(request, response); } } }
UTF-8
Java
1,612
java
UserLoginServlet.java
Java
[ { "context": "{\n String userName = request.getParameter(\"userName\");\n String userPassword = request.getParam", "end": 894, "score": 0.8854278326034546, "start": 886, "tag": "USERNAME", "value": "userName" } ]
null
[]
package com.servletdemoproject; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet( description = "User Login Servlet Testing", urlPatterns = {"/loginServlet"} ) public class UserLoginServlet extends HttpServlet { static String VALID_NAME_PATTERN = "^[A-Z]{1}[a-z]{2,}$"; static String VALID_PASSWORD_PATTERN = "^((?=[^@|#|&|%|$]*[@|&|#|%|$][^@|#|&|%|$]*$)(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9#@$?]{8,})$"; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName = request.getParameter("userName"); String userPassword = request.getParameter("userPassword"); boolean validCredentials = userName.matches(VALID_NAME_PATTERN) && userPassword.matches(VALID_PASSWORD_PATTERN); if (validCredentials) { request.setAttribute("userName", userName); request.getRequestDispatcher("LoginPageSuccessful.jsp").forward(request, response); } else { RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/LoginPage.jsp"); PrintWriter out = response.getWriter(); out.print("<script>alert('Please enter valid credentials');</script>"); requestDispatcher.include(request, response); } } }
1,612
0.689826
0.685484
37
42.567566
36.565041
133
false
false
0
0
0
0
0
0
1.108108
false
false
10
5e97170c4f9b3e9c831e12d0594674d6fb6c2a10
1,735,166,799,211
fe4567702f67c8a66d39fa82033140bea5ca6abc
/src/main/java/com/example/whiteboardsp19/model/Course.java
687cd52a00958d1f761e79a3d92bd80508e7d982
[]
no_license
kndsatya/Learning-Management-System-Server
https://github.com/kndsatya/Learning-Management-System-Server
e253f24e72fbedc27edea6d351b75553a7bddacf
3e433f5044ac98361e14366d97e6f9632f18603b
refs/heads/master
2022-07-05T05:57:09.342000
2019-03-16T03:30:00
2019-03-16T03:30:00
196,693,831
1
0
null
false
2022-06-21T01:26:48
2019-07-13T07:45:44
2019-07-13T07:51:14
2022-06-21T01:26:45
83
0
0
2
Java
false
false
package com.example.whiteboardsp19.model; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; @Entity public class Course { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String courseName; @ManyToOne() @JsonIgnore private User author; @OneToMany(mappedBy = "course", cascade = CascadeType.ALL, orphanRemoval = true) private List<Module> modules; public Course(){ } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public User getAuthor() { return author; } public void setAuthor(User author) { this.author = author; } public List<Module> getModules() { return modules; } public void setModules(List<Module> modules) { this.modules = modules; } public void set(Course newCourse){ this.author = newCourse.getAuthor(); this.courseName = newCourse.courseName; } }
UTF-8
Java
1,359
java
Course.java
Java
[]
null
[]
package com.example.whiteboardsp19.model; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; @Entity public class Course { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String courseName; @ManyToOne() @JsonIgnore private User author; @OneToMany(mappedBy = "course", cascade = CascadeType.ALL, orphanRemoval = true) private List<Module> modules; public Course(){ } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public User getAuthor() { return author; } public void setAuthor(User author) { this.author = author; } public List<Module> getModules() { return modules; } public void setModules(List<Module> modules) { this.modules = modules; } public void set(Course newCourse){ this.author = newCourse.getAuthor(); this.courseName = newCourse.courseName; } }
1,359
0.721118
0.719647
69
18.695652
18.156569
82
false
false
0
0
0
0
0
0
0.376812
false
false
10
1ad3aaddfc462d9213736c41d627c87b51b03fef
17,557,826,313,535
c5d1d4103eac759d227f35c51463d0cb7a6b87cf
/src/main/java/ec/edu/ctrlsolutions/service/impl/TipoDocumentoServiceImpl.java
8b9dcd6ecf3b7fbdc8cdae196163da8b1d41c662
[]
no_license
LuisFrnkMorocho/ProyectoWeb-Tesis
https://github.com/LuisFrnkMorocho/ProyectoWeb-Tesis
8c757869444ef7b7384b3ccc9da3afd3a882b51f
c7c402d13f00ae22ae4645aa6d20fe24cc562a88
refs/heads/master
2023-06-28T01:40:52.677000
2021-08-06T22:09:08
2021-08-06T22:09:08
393,514,669
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ec.edu.ctrlsolutions.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ec.edu.ctrlsolutions.model.TipoDocumento; import ec.edu.ctrlsolutions.repository.TipoDocumentoRepository; import ec.edu.ctrlsolutions.service.TipoDocumentoService; @Service public class TipoDocumentoServiceImpl implements TipoDocumentoService { @Autowired private TipoDocumentoRepository tipoDocumentoRepository; @Override public List<TipoDocumento> findAll(){ return tipoDocumentoRepository.findAll(); } @Override public TipoDocumento findTipoDocumentoById(Integer id) { return tipoDocumentoRepository.findTipoDocumentoById(id); } }
UTF-8
Java
767
java
TipoDocumentoServiceImpl.java
Java
[]
null
[]
package ec.edu.ctrlsolutions.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ec.edu.ctrlsolutions.model.TipoDocumento; import ec.edu.ctrlsolutions.repository.TipoDocumentoRepository; import ec.edu.ctrlsolutions.service.TipoDocumentoService; @Service public class TipoDocumentoServiceImpl implements TipoDocumentoService { @Autowired private TipoDocumentoRepository tipoDocumentoRepository; @Override public List<TipoDocumento> findAll(){ return tipoDocumentoRepository.findAll(); } @Override public TipoDocumento findTipoDocumentoById(Integer id) { return tipoDocumentoRepository.findTipoDocumentoById(id); } }
767
0.804433
0.804433
28
25.392857
25.625517
71
false
false
0
0
0
0
0
0
0.821429
false
false
10
eb3ee8d3233b5e847622b48cdddff4a6b962bc58
28,836,410,456,837
5b35339fae2e0c730d46b1ed4d9395311bbdb467
/JavaFundamental/JavaAdvance/src/javaOOPBasics/encapsulation/pizzaCalories/src/Pizza.java
9372b217e9301265309f23d31b4473819d19cea5
[]
no_license
sahwar/SoftUni-2
https://github.com/sahwar/SoftUni-2
2bd59f1f18c8339194cd569ae3b2eb6315f20c6d
c7c891afe475c07e1f43f337e77fc5f0524ee876
refs/heads/master
2020-05-17T03:33:31.443000
2016-09-28T15:04:52
2016-09-28T15:04:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package javaOOPBasics.encapsulation.pizzaCalories.src; import java.util.ArrayList; import java.util.List; class Pizza { private String name; private int numberOfTopings; private Dough dough; private List<Toping> topings; Pizza(String name, int numberOfTopings) throws Exception { this.setName(name); this.setNumberOfToppings(numberOfTopings); this.topings = new ArrayList<>(); } public String getName() { return this.name; } int getNumberOfToppings() { return this.numberOfTopings; } double getCalories() { double doughCalories = this.dough.getCalories(); double toppingCalories = this.topings .stream() .map(Toping::getCalories) .reduce((t1, t2) -> t1 + t2) .get(); return doughCalories + toppingCalories; } void addTopping(Toping topping) { this.topings.add(topping); } void setDough(Dough dough) { this.dough = dough; } private void setName(String name) { this.name = name; } private void setNumberOfToppings(int numberOfToppings) throws Exception { if (numberOfToppings < 0 || numberOfToppings > 10) { throw new Exception("Number of toppings should be in range [0..10]."); } this.numberOfTopings = numberOfToppings; } }
UTF-8
Java
1,404
java
Pizza.java
Java
[]
null
[]
package javaOOPBasics.encapsulation.pizzaCalories.src; import java.util.ArrayList; import java.util.List; class Pizza { private String name; private int numberOfTopings; private Dough dough; private List<Toping> topings; Pizza(String name, int numberOfTopings) throws Exception { this.setName(name); this.setNumberOfToppings(numberOfTopings); this.topings = new ArrayList<>(); } public String getName() { return this.name; } int getNumberOfToppings() { return this.numberOfTopings; } double getCalories() { double doughCalories = this.dough.getCalories(); double toppingCalories = this.topings .stream() .map(Toping::getCalories) .reduce((t1, t2) -> t1 + t2) .get(); return doughCalories + toppingCalories; } void addTopping(Toping topping) { this.topings.add(topping); } void setDough(Dough dough) { this.dough = dough; } private void setName(String name) { this.name = name; } private void setNumberOfToppings(int numberOfToppings) throws Exception { if (numberOfToppings < 0 || numberOfToppings > 10) { throw new Exception("Number of toppings should be in range [0..10]."); } this.numberOfTopings = numberOfToppings; } }
1,404
0.614672
0.60755
56
24.071428
21.410826
82
false
false
0
0
0
0
0
0
0.428571
false
false
10
29e6c158c4572d6ddd9d175f59ddaffa4190595c
24,842,090,870,083
f3593b34538c60d449cc9c6f6d3bc78dd5f18133
/src/Thread/Pool/App.java
db2e768a1d37e38d4be9123fbdff1a97315e7e95
[]
no_license
ShantKhayalian/TasksCollections
https://github.com/ShantKhayalian/TasksCollections
36e0c5aeedf41d2c3a2c5b444915912467d346a9
40a5c7ec242e75b1c5b960be3547fac5103bd26f
refs/heads/master
2021-11-24T17:38:54.930000
2021-11-08T17:17:45
2021-11-08T17:17:45
203,539,046
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Thread.Pool; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; class Pool extends Thread { private String name; public Pool(String name) { this.name = name; } @Override public void run() { System.out.println("Starting thread: "+name); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Thread ended: "+name); } } public class App { public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(8); Pool thread1 = new Pool("Thread 1"); Pool thread2 = new Pool("Thread 2"); Pool thread3 = new Pool("Thread 3"); Pool thread4 = new Pool("Thread 4"); Pool thread5 = new Pool("Thread 5"); Pool thread6 = new Pool("Thread 6"); Pool thread7 = new Pool("Thread 7"); Pool thread8 = new Pool("Thread 8"); Pool thread9 = new Pool("Thread 9"); Pool thread10 = new Pool("Thread 10"); Pool thread11 = new Pool("Thread 11"); Pool thread12 = new Pool("Thread 12"); Pool thread13 = new Pool("Thread 13"); Pool thread14 = new Pool("Thread 14"); Pool thread15 = new Pool("Thread 15"); Pool thread16 = new Pool("Thread 16"); executorService.execute(thread1); executorService.execute(thread2); executorService.execute(thread3); executorService.execute(thread4); executorService.execute(thread5); executorService.execute(thread6); executorService.execute(thread7); executorService.execute(thread8); executorService.execute(thread9); executorService.execute(thread10); executorService.execute(thread11); executorService.execute(thread12); executorService.execute(thread13); executorService.execute(thread14); executorService.execute(thread15); executorService.execute(thread16); executorService.shutdown(); } }
UTF-8
Java
2,179
java
App.java
Java
[]
null
[]
package Thread.Pool; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; class Pool extends Thread { private String name; public Pool(String name) { this.name = name; } @Override public void run() { System.out.println("Starting thread: "+name); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Thread ended: "+name); } } public class App { public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(8); Pool thread1 = new Pool("Thread 1"); Pool thread2 = new Pool("Thread 2"); Pool thread3 = new Pool("Thread 3"); Pool thread4 = new Pool("Thread 4"); Pool thread5 = new Pool("Thread 5"); Pool thread6 = new Pool("Thread 6"); Pool thread7 = new Pool("Thread 7"); Pool thread8 = new Pool("Thread 8"); Pool thread9 = new Pool("Thread 9"); Pool thread10 = new Pool("Thread 10"); Pool thread11 = new Pool("Thread 11"); Pool thread12 = new Pool("Thread 12"); Pool thread13 = new Pool("Thread 13"); Pool thread14 = new Pool("Thread 14"); Pool thread15 = new Pool("Thread 15"); Pool thread16 = new Pool("Thread 16"); executorService.execute(thread1); executorService.execute(thread2); executorService.execute(thread3); executorService.execute(thread4); executorService.execute(thread5); executorService.execute(thread6); executorService.execute(thread7); executorService.execute(thread8); executorService.execute(thread9); executorService.execute(thread10); executorService.execute(thread11); executorService.execute(thread12); executorService.execute(thread13); executorService.execute(thread14); executorService.execute(thread15); executorService.execute(thread16); executorService.shutdown(); } }
2,179
0.616338
0.582377
74
28.445946
19.81546
74
false
false
0
0
0
0
0
0
0.581081
false
false
10
bea703840e9ccf163c6425c17aef9349f7252f52
1,743,756,792,389
ab9f0d798cc8f88e2fce3925085db3d2603e9639
/leagueofcrafters/LeagueSounds.java
6829350a6c80e94df8ab9832719753557bcc5030
[]
no_license
Proxying/LeagueofCrafters
https://github.com/Proxying/LeagueofCrafters
11ca2e4ca8bf76f680161bac7114b2502e656497
fce158062e3695f032465eed24125900382053ed
refs/heads/master
2021-05-28T06:18:46.994000
2013-12-30T23:11:38
2013-12-30T23:11:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package leagueofcrafters; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.AbstractResourcePack; import cpw.mods.fml.client.FMLClientHandler; public class LeagueSounds { private static final String[] MusicList = { "GetJinxed", "SummonersCall", "SurprisePartyFiddlesticks" }; public static boolean installMusic() { AbstractResourcePack resourcePack = (AbstractResourcePack) FMLClientHandler.instance().getResourcePackFor("LoC"); for (String songName : MusicList) { Minecraft.getMinecraft().sndManager.addMusic("league:league/" + songName + ".ogg"); } return true; } }
UTF-8
Java
613
java
LeagueSounds.java
Java
[]
null
[]
package leagueofcrafters; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.AbstractResourcePack; import cpw.mods.fml.client.FMLClientHandler; public class LeagueSounds { private static final String[] MusicList = { "GetJinxed", "SummonersCall", "SurprisePartyFiddlesticks" }; public static boolean installMusic() { AbstractResourcePack resourcePack = (AbstractResourcePack) FMLClientHandler.instance().getResourcePackFor("LoC"); for (String songName : MusicList) { Minecraft.getMinecraft().sndManager.addMusic("league:league/" + songName + ".ogg"); } return true; } }
613
0.776509
0.776509
18
33.055557
35.972942
115
false
false
0
0
0
0
0
0
1.333333
false
false
10
eba1f61cc6fa039bbc142b587ea55c117045b582
32,006,096,341,902
51f6f8d5f76b5f515781bdfca8d6d3eaf46e2174
/myblog-provider/src/main/java/com/lianekai/myblog/controller/ExportController.java
ea08465d10cb3c88a62b5c74dae91d03f0e871ea
[ "Apache-2.0" ]
permissive
lianekai/MyBlog-SpringBoot
https://github.com/lianekai/MyBlog-SpringBoot
fb31fb907e55fc683342aba22ccde4b431c2cd77
44eaefffcadb8bdd1d1bab35d57f524d67e6e3ec
refs/heads/main
2022-11-24T00:17:24.758000
2022-05-25T15:44:13
2022-05-25T15:44:13
284,089,748
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lianekai.myblog.controller; import com.lianekai.myblog.dto.ExportParamDTO; import com.lianekai.myblog.handler.BaseExportHandler; import com.lianekai.myblog.service.ExcelHandleService; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; /** * @author lianekai * @date 2022/5/25 23:13 * @version: 1.0 * @description TODO */ public class ExportController extends BaseExportHandler { @Resource ExcelHandleService excelHandleService; @ApiOperation(value = "导出动态参数接口", httpMethod = "POST") @PostMapping(value = "/my-blog/export/exportForDynamic") public void exportForDynamic(HttpServletResponse response, @RequestBody ExportParamDTO exportParamDTO) throws UnsupportedEncodingException { String fileName = URLEncoder.encode("团队成员导出", StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20"); super.setResponseHeadAsExcel(response,fileName); excelHandleService.exportForDynamic(response,exportParamDTO); } }
UTF-8
Java
1,308
java
ExportController.java
Java
[ { "context": "java.nio.charset.StandardCharsets;\n\n/**\n * @author lianekai\n * @date 2022/5/25 23:13\n * @version: 1.0\n * @des", "end": 582, "score": 0.9996951818466187, "start": 574, "tag": "USERNAME", "value": "lianekai" } ]
null
[]
package com.lianekai.myblog.controller; import com.lianekai.myblog.dto.ExportParamDTO; import com.lianekai.myblog.handler.BaseExportHandler; import com.lianekai.myblog.service.ExcelHandleService; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; /** * @author lianekai * @date 2022/5/25 23:13 * @version: 1.0 * @description TODO */ public class ExportController extends BaseExportHandler { @Resource ExcelHandleService excelHandleService; @ApiOperation(value = "导出动态参数接口", httpMethod = "POST") @PostMapping(value = "/my-blog/export/exportForDynamic") public void exportForDynamic(HttpServletResponse response, @RequestBody ExportParamDTO exportParamDTO) throws UnsupportedEncodingException { String fileName = URLEncoder.encode("团队成员导出", StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20"); super.setResponseHeadAsExcel(response,fileName); excelHandleService.exportForDynamic(response,exportParamDTO); } }
1,308
0.7875
0.775
36
34.555557
32.168346
144
false
false
0
0
0
0
0
0
0.611111
false
false
10
51335605b9e374553e92043ed17d198618e20580
29,025,388,997,539
ecaf33e833a7e14a066e59fe2b53ff7c000ff2e2
/course-1/task-5-stream-api/src/main/java/ru/spbau/mit/SecondPartTasks.java
0993eddf7c7327275a2e98ddac8d1058ba6b2f83
[ "MIT" ]
permissive
fedochet/au-java-assignments
https://github.com/fedochet/au-java-assignments
05cdb7907d8098f22e2f1f369d87266a9e74a42b
5dd65bd41acb891b245f9f003bda6948d5ca0478
refs/heads/master
2021-01-25T14:44:37.579000
2018-09-07T10:59:19
2018-09-07T10:59:19
123,722,959
0
0
MIT
false
2018-12-11T14:17:12
2018-03-03T19:08:51
2018-09-07T10:59:45
2018-12-11T14:15:10
462
0
0
4
Java
false
null
package ru.spbau.mit; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import java.util.stream.Stream; public final class SecondPartTasks { private SecondPartTasks() {} // Найти строки из переданных файлов, в которых встречается указанная подстрока. public static List<String> findQuotes(List<String> paths, CharSequence sequence) { return paths.stream() .map(Paths::get) .flatMap(SecondPartTasks::getLines) .filter(s -> s.contains(sequence)) .collect(Collectors.toList()); } private static Stream<String> getLines(Path path) { try { return Files.lines(path); } catch (IOException e) { throw new RuntimeException(e); } } // В квадрат с длиной стороны 1 вписана мишень. // Стрелок атакует мишень и каждый раз попадает в произвольную точку квадрата. // Надо промоделировать этот процесс с помощью класса java.util.Random и посчитать, какова вероятность попасть в мишень. public static double piDividedBy4() { class Shot { private final double radius = 0.5; private final double x = ThreadLocalRandom.current().nextDouble(1.0); private final double y = ThreadLocalRandom.current().nextDouble(1.0); private boolean isHit() { double fromCenterX = x - radius; double fromCenterY = y - radius; double distanceFromCenter = Math.sqrt(Math.pow(fromCenterX, 2) + Math.pow(fromCenterY, 2)); return distanceFromCenter <= radius; } } IntSummaryStatistics stats = Stream.generate(Shot::new).limit(1000000).collect( Collectors.summarizingInt(s -> s.isHit() ? 1 : 0) ); return (double) stats.getSum() / stats.getCount(); } // Дано отображение из имени автора в список с содержанием его произведений. // Надо вычислить, чья общая длина произведений наибольшая. public static Optional<String> findPrinter(Map<String, List<String>> compositions) { return compositions.entrySet().stream() .max(Comparator.comparing(e -> String.join("", e.getValue()).length())) .map(Map.Entry::getKey); } // Вы крупный поставщик продуктов. Каждая торговая сеть делает вам заказ // в виде Map<Товар, Количество>. // Необходимо вычислить, какой товар и в каком количестве надо поставить. public static Map<String, Integer> calculateGlobalOrder(List<Map<String, Integer>> orders) { return orders.stream() .flatMap(m -> m.entrySet().stream()) .collect(Collectors.groupingBy( Map.Entry::getKey, Collectors.summingInt(Map.Entry::getValue) )); } }
UTF-8
Java
3,446
java
SecondPartTasks.java
Java
[ { "context": "etCount();\n }\n\n // Дано отображение из имени автора в список с содержанием его произведений.\n // Н", "end": 2045, "score": 0.9553084969520569, "start": 2039, "tag": "NAME", "value": "автора" } ]
null
[]
package ru.spbau.mit; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import java.util.stream.Stream; public final class SecondPartTasks { private SecondPartTasks() {} // Найти строки из переданных файлов, в которых встречается указанная подстрока. public static List<String> findQuotes(List<String> paths, CharSequence sequence) { return paths.stream() .map(Paths::get) .flatMap(SecondPartTasks::getLines) .filter(s -> s.contains(sequence)) .collect(Collectors.toList()); } private static Stream<String> getLines(Path path) { try { return Files.lines(path); } catch (IOException e) { throw new RuntimeException(e); } } // В квадрат с длиной стороны 1 вписана мишень. // Стрелок атакует мишень и каждый раз попадает в произвольную точку квадрата. // Надо промоделировать этот процесс с помощью класса java.util.Random и посчитать, какова вероятность попасть в мишень. public static double piDividedBy4() { class Shot { private final double radius = 0.5; private final double x = ThreadLocalRandom.current().nextDouble(1.0); private final double y = ThreadLocalRandom.current().nextDouble(1.0); private boolean isHit() { double fromCenterX = x - radius; double fromCenterY = y - radius; double distanceFromCenter = Math.sqrt(Math.pow(fromCenterX, 2) + Math.pow(fromCenterY, 2)); return distanceFromCenter <= radius; } } IntSummaryStatistics stats = Stream.generate(Shot::new).limit(1000000).collect( Collectors.summarizingInt(s -> s.isHit() ? 1 : 0) ); return (double) stats.getSum() / stats.getCount(); } // Дано отображение из имени автора в список с содержанием его произведений. // Надо вычислить, чья общая длина произведений наибольшая. public static Optional<String> findPrinter(Map<String, List<String>> compositions) { return compositions.entrySet().stream() .max(Comparator.comparing(e -> String.join("", e.getValue()).length())) .map(Map.Entry::getKey); } // Вы крупный поставщик продуктов. Каждая торговая сеть делает вам заказ // в виде Map<Товар, Количество>. // Необходимо вычислить, какой товар и в каком количестве надо поставить. public static Map<String, Integer> calculateGlobalOrder(List<Map<String, Integer>> orders) { return orders.stream() .flatMap(m -> m.entrySet().stream()) .collect(Collectors.groupingBy( Map.Entry::getKey, Collectors.summingInt(Map.Entry::getValue) )); } }
3,446
0.643148
0.636703
77
37.285713
30.318165
124
false
false
0
0
0
0
0
0
0.467532
false
false
10
e54f5964a0a366c2672da294ec1671861a9273e1
19,602,230,786,274
bf66120dcdd4efb2b3f1816335ea4531ac9fd9f3
/org.maven.ide.eclipse.integration.tests/src/org/maven/ide/eclipse/integration/tests/MEclipse182RangeHandlingTest.java
51df8a9f5c2bbd4822121497ad6e25fe1e5f8b5a
[]
no_license
jdcasey/m2eclipse-core
https://github.com/jdcasey/m2eclipse-core
71432d91ae32eff3e0abdbbf1211b98a07b272a2
47d272f56235956cc10d96c448e71d81c8895ee0
refs/heads/master
2020-04-05T23:29:31.450000
2010-07-29T16:24:58
2010-07-29T16:24:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/******************************************************************************* * Copyright (c) 2008 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.maven.ide.eclipse.integration.tests; import static org.eclipse.swtbot.swt.finder.matchers.WidgetMatcherFactory.withMnemonic; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor; import org.junit.Assert; import org.junit.Test; import org.maven.ide.eclipse.integration.tests.common.ContextMenuHelper; import org.maven.ide.eclipse.integration.tests.common.matchers.ContainsMnemonic; /** * @author Administrator */ public class MEclipse182RangeHandlingTest extends M2EUIIntegrationTestCase { @SuppressWarnings("unchecked") @Test public void testRangeHandling() throws Exception { String project1Name = "versionProject1"; String project2Name = "versionProject2"; importZippedProject("projects/versionRange.zip"); //Install version 1.0-SNAPSHOT of project2 ContextMenuHelper.clickContextMenu(selectProject(project2Name), withMnemonic("Run As"), ContainsMnemonic.containsMnemonic("Maven install")); waitForAllLaunchesToComplete(60 * 1000); waitForAllBuildsToComplete(); assertProjectsHaveNoErrors(); // Change version of project2 to 1.1-SNAPSHOT SWTBotEditor editor = bot.editorByTitle(openPomFile(project2Name + "/pom.xml").getTitle()); editor.bot().textWithLabel("Version:").setText("1.1-SNAPSHOT"); editor.saveAndClose(); waitForAllBuildsToComplete(); // Change method signature referenced by original project IProject project2 = ResourcesPlugin.getWorkspace().getRoot().getProject(project2Name); editor = bot.editorByTitle(openFile(project2, "src/main/java/org/sonatype/test/versionProject2/Simple.java") .getTitle()); replaceText("add(", "add2("); editor.saveAndClose(); // There should be no compile errors, project2:1.0-SNAPSHOT should come from local repository. waitForAllBuildsToComplete(); assertProjectsHaveNoErrors(); // Change original project to depend on version range which includes 1.1-SNAPSHOT editor = bot.editorByTitle(openPomFile(project1Name + "/pom.xml").getTitle()); editor.bot().cTabItem("pom.xml").activate(); replaceText("1.0-SNAPSHOT", "[1.0-SNAPSHOT,1.1-SNAPSHOT]"); editor.saveAndClose(); waitForAllBuildsToComplete(); // Original project should now be using workspace project, this should cause a compile error. IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(project1Name); int problemSeverity = project.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE); bot.viewByTitle("Problems").show(); Assert.assertEquals("project should have compile errors: " + takeScreenShot("compile"), IMarker.SEVERITY_ERROR, problemSeverity); } }
UTF-8
Java
3,320
java
MEclipse182RangeHandlingTest.java
Java
[ { "context": "common.matchers.ContainsMnemonic;\n\n\n/**\n * @author Administrator\n */\npublic class MEclipse182RangeHandlingTest ext", "end": 1064, "score": 0.8944321274757385, "start": 1051, "tag": "NAME", "value": "Administrator" } ]
null
[]
/******************************************************************************* * Copyright (c) 2008 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.maven.ide.eclipse.integration.tests; import static org.eclipse.swtbot.swt.finder.matchers.WidgetMatcherFactory.withMnemonic; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor; import org.junit.Assert; import org.junit.Test; import org.maven.ide.eclipse.integration.tests.common.ContextMenuHelper; import org.maven.ide.eclipse.integration.tests.common.matchers.ContainsMnemonic; /** * @author Administrator */ public class MEclipse182RangeHandlingTest extends M2EUIIntegrationTestCase { @SuppressWarnings("unchecked") @Test public void testRangeHandling() throws Exception { String project1Name = "versionProject1"; String project2Name = "versionProject2"; importZippedProject("projects/versionRange.zip"); //Install version 1.0-SNAPSHOT of project2 ContextMenuHelper.clickContextMenu(selectProject(project2Name), withMnemonic("Run As"), ContainsMnemonic.containsMnemonic("Maven install")); waitForAllLaunchesToComplete(60 * 1000); waitForAllBuildsToComplete(); assertProjectsHaveNoErrors(); // Change version of project2 to 1.1-SNAPSHOT SWTBotEditor editor = bot.editorByTitle(openPomFile(project2Name + "/pom.xml").getTitle()); editor.bot().textWithLabel("Version:").setText("1.1-SNAPSHOT"); editor.saveAndClose(); waitForAllBuildsToComplete(); // Change method signature referenced by original project IProject project2 = ResourcesPlugin.getWorkspace().getRoot().getProject(project2Name); editor = bot.editorByTitle(openFile(project2, "src/main/java/org/sonatype/test/versionProject2/Simple.java") .getTitle()); replaceText("add(", "add2("); editor.saveAndClose(); // There should be no compile errors, project2:1.0-SNAPSHOT should come from local repository. waitForAllBuildsToComplete(); assertProjectsHaveNoErrors(); // Change original project to depend on version range which includes 1.1-SNAPSHOT editor = bot.editorByTitle(openPomFile(project1Name + "/pom.xml").getTitle()); editor.bot().cTabItem("pom.xml").activate(); replaceText("1.0-SNAPSHOT", "[1.0-SNAPSHOT,1.1-SNAPSHOT]"); editor.saveAndClose(); waitForAllBuildsToComplete(); // Original project should now be using workspace project, this should cause a compile error. IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(project1Name); int problemSeverity = project.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE); bot.viewByTitle("Problems").show(); Assert.assertEquals("project should have compile errors: " + takeScreenShot("compile"), IMarker.SEVERITY_ERROR, problemSeverity); } }
3,320
0.723494
0.708434
78
41.564102
35.613159
145
false
false
0
0
0
0
0
0
0.653846
false
false
10
ac98dba973b92bb04070297314b2ea94ee2c3e9b
19,602,230,785,209
7fa36ceb0cc198e9412c1ca0d16cb207d9df645e
/src/com/esoft/ischool/service/ProjectService.java
b1a83e86c747e3c8ac73476836b58a4325e469c6
[]
no_license
panawe/ischool
https://github.com/panawe/ischool
b362b086305bc62ad3a846f322421c3d5eb4e150
bed9b0c2dbe0eb76add000388a63249a8f366ce7
refs/heads/master
2021-01-11T05:48:52.862000
2016-10-24T04:16:27
2016-10-24T04:16:27
71,744,115
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.esoft.ischool.service; import java.util.List; import com.esoft.ischool.model.Event; import com.esoft.ischool.model.Project; public interface ProjectService extends BaseService { List<Project> loadAllProjects(Class<Project> class1); }
UTF-8
Java
264
java
ProjectService.java
Java
[]
null
[]
package com.esoft.ischool.service; import java.util.List; import com.esoft.ischool.model.Event; import com.esoft.ischool.model.Project; public interface ProjectService extends BaseService { List<Project> loadAllProjects(Class<Project> class1); }
264
0.765152
0.761364
12
20
21.322914
54
false
false
0
0
0
0
0
0
0.5
false
false
10
1b82e4f55c334fc5d9ee55454102fe3440fabee6
11,029,476,058,245
253b341d2e41a5f53c823d61d57d465ebaba6ca5
/Lab1/src/com/company/Main.java
06ab918cea197eda63a4752d8e65acdeca46a6dd
[]
no_license
AlexCiho/JAVA
https://github.com/AlexCiho/JAVA
a9f15b7968cac816034706f40a96a173197c5c53
f0f665ea564f7ed7ccad7378fca5e704e18aa3c7
refs/heads/master
2021-04-02T23:47:18.885000
2020-05-27T13:28:48
2020-05-27T13:28:48
248,337,335
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class Main { public static void main(String[] args) { String[] languages = {"C", "C++", "C#", "Python", "Go", "Rust", "JavaScript", "PHP", "Swift", "Java"}; System.out.println("Hello World"); int controlCode; int n = (int) (Math.random() * 1_000_000); System.out.println(n); n *= 3; n = n + 0b10101; n = n + 0xFF; n *= 6; if (n % 9 != 0) controlCode = n % 9; else controlCode = 9; System.out.println(n); System.out.println(controlCode); System.out.println(n); System.out.println("Willy-nilly, this semester I will learn " + languages[controlCode]); //Validate arguments final int alphabetMaxSize = 256; int alphabetCounter = 0; char[] alphabet = new char[alphabetMaxSize]; for (int i = 0; i < 2; i++) { boolean check = true; for (int j = 0; j < args[i].length(); j++) { if (checkDigit(args[i].charAt(j)) == false) { check = false; break; } } if (check == true) { System.out.println("Al " + i + " lea argument este valid\n"); } else { System.out.println("Al " + i + " lea argument nu este valid\n"); } } for (int i = 2; i < args.length; i++) { char character = args[i].charAt(0); int argumentLength = args[i].length(); if (checkLetter(character) == true && argumentLength == 1) { System.out.println("Al " + i + " lea argument este valid\n"); alphabet[alphabetCounter++] = character; } else { System.out.println("Al " + i + " lea argument nu este valid\n"); } } System.out.println(alphabet); //create array of strings int numberOfWords = Integer.parseInt(args[0]); int numberOfLetters = Integer.parseInt(args[1]); System.out.println(numberOfWords + " " + numberOfLetters); String words[] = generate(numberOfWords, numberOfLetters, alphabetCounter, alphabet); for (String word : words) { System.out.println(word); } boolean neighbors[][] = new boolean[numberOfWords][numberOfWords]; for (int i = 0; i < numberOfWords; i++) { for (int j = 0; j < numberOfWords; j++) { neighbors[i][j] = neighbor(words[i], words[j]); } } displayMatrix(numberOfWords, neighbors); displayMaxNeighbors(numberOfWords, neighbors); System.out.println(checkAllNeighbors(numberOfWords, neighbors)); boolean viz[] = new boolean[numberOfWords]; dfs(numberOfWords, neighbors, viz, 0); checkConnected(numberOfWords, viz); displayComponent(numberOfWords, viz, words); boolean exist = true; while (exist) { exist = false; boolean[] newViz = new boolean[numberOfWords]; for (int i = 0; i < viz.length; i++) { if (viz[i] == false) { dfs(numberOfWords, neighbors, newViz, i); exist = true; break; } } displayComponent(numberOfWords, newViz, words); } } public static boolean checkLetter(char c) { if (c >= 'a' && c <= 'z') return true; return false; } public static boolean checkDigit(char c) { if (c >= '0' && c <= '9') return true; return false; } public static String[] generate(int n, int k, int length, char[] alphabet) { String[] words = new String[n]; for (int i = 0; i < n; i++) { StringBuilder sb = new StringBuilder(); int copyOfk = k; while (copyOfk > 0) { int position = (int) ((Math.random() * length) % 10); sb.append(alphabet[position]); copyOfk--; } words[i] = sb.toString(); } return words; } public static boolean neighbor(String string1, String string2) { for (int i = 0; i < string1.length(); i++) { char c = string1.charAt(i); if (string2.indexOf(c) >= 0) return true; } return false; } public static void displayMatrix(int n, boolean[][] matrix) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } public static void displayMaxNeighbors(int n, boolean[][] matrix) { int maxNeighbors = 0; for (int i = 0; i < n; i++) { int numberOfNeighbors = 0; for (int j = 0; j < n; j++) { if (matrix[i][j] == true) numberOfNeighbors++; } if (maxNeighbors < numberOfNeighbors) maxNeighbors = numberOfNeighbors; } System.out.println(maxNeighbors); } public static boolean checkAllNeighbors(int n, boolean[][] matrix) { int numberOfNeighbors = 0; for (int j = 0; j < n; j++) if (matrix[0][j] == true) numberOfNeighbors++; for (int i = 1; i < n; i++) { int nr = 0; for (int j = 0; j < n; j++) { if (matrix[i][j] == true) nr++; } if (nr != numberOfNeighbors) return false; } return true; } public static void dfs(int n, boolean[][] matrix, boolean[] viz, int currentNode) { viz[currentNode] = true; for (int i = 0; i < n; i++) { if (i == currentNode) continue; if (matrix[currentNode][i] == true && viz[i] == false) { viz[i] = true; dfs(n, matrix, viz, i); } } } public static void checkConnected(int n, boolean[] viz) { boolean check = true; for (int i = 0; i < n; i++) { if (viz[i] == false) { check = false; break; } } if (check == true) System.out.println("Connected"); else System.out.println("Is not connected"); } public static void displayComponent(int n, boolean[] viz, String[] words) { for (int i = 0; i < n; i++) if (viz[i] == true) System.out.print(words[i] + " "); System.out.println(); } }
UTF-8
Java
6,964
java
Main.java
Java
[]
null
[]
package com.company; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class Main { public static void main(String[] args) { String[] languages = {"C", "C++", "C#", "Python", "Go", "Rust", "JavaScript", "PHP", "Swift", "Java"}; System.out.println("Hello World"); int controlCode; int n = (int) (Math.random() * 1_000_000); System.out.println(n); n *= 3; n = n + 0b10101; n = n + 0xFF; n *= 6; if (n % 9 != 0) controlCode = n % 9; else controlCode = 9; System.out.println(n); System.out.println(controlCode); System.out.println(n); System.out.println("Willy-nilly, this semester I will learn " + languages[controlCode]); //Validate arguments final int alphabetMaxSize = 256; int alphabetCounter = 0; char[] alphabet = new char[alphabetMaxSize]; for (int i = 0; i < 2; i++) { boolean check = true; for (int j = 0; j < args[i].length(); j++) { if (checkDigit(args[i].charAt(j)) == false) { check = false; break; } } if (check == true) { System.out.println("Al " + i + " lea argument este valid\n"); } else { System.out.println("Al " + i + " lea argument nu este valid\n"); } } for (int i = 2; i < args.length; i++) { char character = args[i].charAt(0); int argumentLength = args[i].length(); if (checkLetter(character) == true && argumentLength == 1) { System.out.println("Al " + i + " lea argument este valid\n"); alphabet[alphabetCounter++] = character; } else { System.out.println("Al " + i + " lea argument nu este valid\n"); } } System.out.println(alphabet); //create array of strings int numberOfWords = Integer.parseInt(args[0]); int numberOfLetters = Integer.parseInt(args[1]); System.out.println(numberOfWords + " " + numberOfLetters); String words[] = generate(numberOfWords, numberOfLetters, alphabetCounter, alphabet); for (String word : words) { System.out.println(word); } boolean neighbors[][] = new boolean[numberOfWords][numberOfWords]; for (int i = 0; i < numberOfWords; i++) { for (int j = 0; j < numberOfWords; j++) { neighbors[i][j] = neighbor(words[i], words[j]); } } displayMatrix(numberOfWords, neighbors); displayMaxNeighbors(numberOfWords, neighbors); System.out.println(checkAllNeighbors(numberOfWords, neighbors)); boolean viz[] = new boolean[numberOfWords]; dfs(numberOfWords, neighbors, viz, 0); checkConnected(numberOfWords, viz); displayComponent(numberOfWords, viz, words); boolean exist = true; while (exist) { exist = false; boolean[] newViz = new boolean[numberOfWords]; for (int i = 0; i < viz.length; i++) { if (viz[i] == false) { dfs(numberOfWords, neighbors, newViz, i); exist = true; break; } } displayComponent(numberOfWords, newViz, words); } } public static boolean checkLetter(char c) { if (c >= 'a' && c <= 'z') return true; return false; } public static boolean checkDigit(char c) { if (c >= '0' && c <= '9') return true; return false; } public static String[] generate(int n, int k, int length, char[] alphabet) { String[] words = new String[n]; for (int i = 0; i < n; i++) { StringBuilder sb = new StringBuilder(); int copyOfk = k; while (copyOfk > 0) { int position = (int) ((Math.random() * length) % 10); sb.append(alphabet[position]); copyOfk--; } words[i] = sb.toString(); } return words; } public static boolean neighbor(String string1, String string2) { for (int i = 0; i < string1.length(); i++) { char c = string1.charAt(i); if (string2.indexOf(c) >= 0) return true; } return false; } public static void displayMatrix(int n, boolean[][] matrix) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } public static void displayMaxNeighbors(int n, boolean[][] matrix) { int maxNeighbors = 0; for (int i = 0; i < n; i++) { int numberOfNeighbors = 0; for (int j = 0; j < n; j++) { if (matrix[i][j] == true) numberOfNeighbors++; } if (maxNeighbors < numberOfNeighbors) maxNeighbors = numberOfNeighbors; } System.out.println(maxNeighbors); } public static boolean checkAllNeighbors(int n, boolean[][] matrix) { int numberOfNeighbors = 0; for (int j = 0; j < n; j++) if (matrix[0][j] == true) numberOfNeighbors++; for (int i = 1; i < n; i++) { int nr = 0; for (int j = 0; j < n; j++) { if (matrix[i][j] == true) nr++; } if (nr != numberOfNeighbors) return false; } return true; } public static void dfs(int n, boolean[][] matrix, boolean[] viz, int currentNode) { viz[currentNode] = true; for (int i = 0; i < n; i++) { if (i == currentNode) continue; if (matrix[currentNode][i] == true && viz[i] == false) { viz[i] = true; dfs(n, matrix, viz, i); } } } public static void checkConnected(int n, boolean[] viz) { boolean check = true; for (int i = 0; i < n; i++) { if (viz[i] == false) { check = false; break; } } if (check == true) System.out.println("Connected"); else System.out.println("Is not connected"); } public static void displayComponent(int n, boolean[] viz, String[] words) { for (int i = 0; i < n; i++) if (viz[i] == true) System.out.print(words[i] + " "); System.out.println(); } }
6,964
0.47085
0.46166
218
29.944954
23.715374
110
false
false
0
0
0
0
0
0
0.793578
false
false
10
a9e6c74e2c6d65c181ead4d444f4d8add66652cb
37,941,741,105,820
1cf5cce5e75db9832e4ca477adadbf857bc638e0
/app/src/main/java/com/example/movies/MainActivity.java
15395d2246e9463d2647423deb776c441b9ac2b5
[]
no_license
henhiro4r/Jetpack-Submission
https://github.com/henhiro4r/Jetpack-Submission
699f3f9d1daeb6d987b04c54b64e161c0b7bbb31
a76a72a642f07f9501b25d53ae59d8510b7160b7
refs/heads/master
2020-08-03T03:06:42.501000
2019-09-29T07:22:20
2019-09-29T07:22:20
211,607,200
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.movies; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Bundle; import com.example.movies.fragment.MovieFragment; import com.example.movies.fragment.TvShowFragment; import com.google.android.material.bottomnavigation.BottomNavigationView; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.annotation.NonNull; import android.util.DisplayMetrics; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import com.example.movies.preference.Pref; import java.util.Locale; public class MainActivity extends AppCompatActivity { private ActionBar toolbar; private Pref pref; private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { Fragment fragment; toolbar.setDisplayShowHomeEnabled(true); switch (item.getItemId()) { case R.id.nav_movie: toolbar.setIcon(R.drawable.ic_outline_movie); toolbar.setTitle(" " + getString(R.string.title_movie)); fragment = new MovieFragment(); loadFragment(fragment); return true; case R.id.nav_tv_show: toolbar.setIcon(R.drawable.ic_outline_tv); toolbar.setTitle(" " + getString(R.string.title_tv_show)); fragment = new TvShowFragment(); loadFragment(fragment); return true; } return false; } }; private void loadFragment(Fragment fragment) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.container_layout, fragment); transaction.commit(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pref = new Pref(this); toolbar = getSupportActionBar(); BottomNavigationView navView = findViewById(R.id.nav_view); navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); if (savedInstanceState == null){ navView.setSelectedItemId(R.id.nav_movie); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.settings_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.trans) { changelanguage(); } return super.onOptionsItemSelected(item); } private void changelanguage() { int checked = pref.getLangPreference(); String[] lang = new String[]{getResources().getString(R.string.en), getResources().getString(R.string.in)}; final int[] choose = new int[1]; AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle(getString(R.string.lang)); alert.setSingleChoiceItems(lang, checked, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int which) { choose[0] = which; } }); alert.setPositiveButton(getResources().getString(R.string.change), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { setLocale(choose[0]); pref.setLangPreference(choose[0]); dialog.dismiss(); refresh(); } }); alert.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alertDialog = alert.create(); alertDialog.show(); } private void setLocale(int i) { String[] lang = new String[]{"en", "in"}; String language = lang[i]; Locale locale = new Locale(language); Locale.setDefault(locale); Resources res = getResources(); DisplayMetrics dm = res.getDisplayMetrics(); Configuration conf = res.getConfiguration(); conf.locale = locale; res.updateConfiguration(conf, dm); } private void refresh() { finish(); startActivity(getIntent()); } public boolean doubleBackToExitPressedOnce = false; @Override protected void onResume() { super.onResume(); this.doubleBackToExitPressedOnce = false; } @Override public void onBackPressed() { if (doubleBackToExitPressedOnce) { Intent a = new Intent(Intent.ACTION_MAIN); a.addCategory(Intent.CATEGORY_HOME); a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); finish(); startActivity(a); } this.doubleBackToExitPressedOnce = true; Toast.makeText(MainActivity.this, R.string.press_exit, Toast.LENGTH_SHORT).show(); } }
UTF-8
Java
5,663
java
MainActivity.java
Java
[]
null
[]
package com.example.movies; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Bundle; import com.example.movies.fragment.MovieFragment; import com.example.movies.fragment.TvShowFragment; import com.google.android.material.bottomnavigation.BottomNavigationView; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.annotation.NonNull; import android.util.DisplayMetrics; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import com.example.movies.preference.Pref; import java.util.Locale; public class MainActivity extends AppCompatActivity { private ActionBar toolbar; private Pref pref; private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { Fragment fragment; toolbar.setDisplayShowHomeEnabled(true); switch (item.getItemId()) { case R.id.nav_movie: toolbar.setIcon(R.drawable.ic_outline_movie); toolbar.setTitle(" " + getString(R.string.title_movie)); fragment = new MovieFragment(); loadFragment(fragment); return true; case R.id.nav_tv_show: toolbar.setIcon(R.drawable.ic_outline_tv); toolbar.setTitle(" " + getString(R.string.title_tv_show)); fragment = new TvShowFragment(); loadFragment(fragment); return true; } return false; } }; private void loadFragment(Fragment fragment) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.container_layout, fragment); transaction.commit(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pref = new Pref(this); toolbar = getSupportActionBar(); BottomNavigationView navView = findViewById(R.id.nav_view); navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); if (savedInstanceState == null){ navView.setSelectedItemId(R.id.nav_movie); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.settings_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.trans) { changelanguage(); } return super.onOptionsItemSelected(item); } private void changelanguage() { int checked = pref.getLangPreference(); String[] lang = new String[]{getResources().getString(R.string.en), getResources().getString(R.string.in)}; final int[] choose = new int[1]; AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle(getString(R.string.lang)); alert.setSingleChoiceItems(lang, checked, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int which) { choose[0] = which; } }); alert.setPositiveButton(getResources().getString(R.string.change), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { setLocale(choose[0]); pref.setLangPreference(choose[0]); dialog.dismiss(); refresh(); } }); alert.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alertDialog = alert.create(); alertDialog.show(); } private void setLocale(int i) { String[] lang = new String[]{"en", "in"}; String language = lang[i]; Locale locale = new Locale(language); Locale.setDefault(locale); Resources res = getResources(); DisplayMetrics dm = res.getDisplayMetrics(); Configuration conf = res.getConfiguration(); conf.locale = locale; res.updateConfiguration(conf, dm); } private void refresh() { finish(); startActivity(getIntent()); } public boolean doubleBackToExitPressedOnce = false; @Override protected void onResume() { super.onResume(); this.doubleBackToExitPressedOnce = false; } @Override public void onBackPressed() { if (doubleBackToExitPressedOnce) { Intent a = new Intent(Intent.ACTION_MAIN); a.addCategory(Intent.CATEGORY_HOME); a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); finish(); startActivity(a); } this.doubleBackToExitPressedOnce = true; Toast.makeText(MainActivity.this, R.string.press_exit, Toast.LENGTH_SHORT).show(); } }
5,663
0.642239
0.641533
158
34.841774
25.585676
115
false
false
0
0
0
0
0
0
0.64557
false
false
10
249e1f2147991b20b62f8bc8dcc55f0327e46763
7,164,005,513,971
e1eec0a7426e4774261d52833cbf7fb22953d866
/Module_4/Model/EmployeeTest.java
e4416523657fea7c40af7f22c144d2bda6615200
[]
no_license
Skyblueballykid/CS320-JUnit-Tests
https://github.com/Skyblueballykid/CS320-JUnit-Tests
c6f438c431b4fda895dbe67cab5a789f5156ca84
97ca361ce05b84b5dc512ae9e4d412d4a224bae1
refs/heads/master
2020-04-22T14:12:11.357000
2019-02-15T20:33:28
2019-02-15T20:33:28
170,435,145
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package medicalApplication.model; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import medical.com.medicalApplication.model.Employee; public class EmployeeTest { private Employee employee; @Before public void before() { this.employee = new Employee("Texas Steve", "123"); } @Test public void testGetName() { assertTrue(employee.getName().equals("Texas Steve")); } @Test public void testGetId() { assertTrue(employee.getId().equals("123")); } @Test public void testGetPassword() { assertTrue(employee.getPassword().equals("Open")); } }
UTF-8
Java
606
java
EmployeeTest.java
Java
[ { "context": "c void before() {\n\t\tthis.employee = new Employee(\"Texas Steve\", \"123\");\n\t\t\n\t}\n\n\t@Test\n\tpublic void testGetName(", "end": 308, "score": 0.9998263716697693, "start": 297, "tag": "NAME", "value": "Texas Steve" }, { "context": "tName() {\n\t\tassertTrue(employee.getName().equals(\"Texas Steve\"));\n\t}\n\t\n\t@Test\n\tpublic void testGetId() {\n\t\tasse", "end": 413, "score": 0.99981689453125, "start": 402, "tag": "NAME", "value": "Texas Steve" }, { "context": "d() {\n\t\tassertTrue(employee.getPassword().equals(\"Open\"));\n\t}\n\n}", "end": 596, "score": 0.8993812799453735, "start": 592, "tag": "PASSWORD", "value": "Open" } ]
null
[]
package medicalApplication.model; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import medical.com.medicalApplication.model.Employee; public class EmployeeTest { private Employee employee; @Before public void before() { this.employee = new Employee("<NAME>", "123"); } @Test public void testGetName() { assertTrue(employee.getName().equals("<NAME>")); } @Test public void testGetId() { assertTrue(employee.getId().equals("123")); } @Test public void testGetPassword() { assertTrue(employee.getPassword().equals("<PASSWORD>")); } }
602
0.716172
0.706271
34
16.852942
18.487089
55
false
false
0
0
0
0
0
0
1.088235
false
false
10
ff600d0ff50fb8af2ae9461fbf52b66991a06285
39,015,482,949,791
1881cefd2156c72348f34f24925fdd6f390b9133
/UVA10282.java
d8b70bb6d3b381aeec3186a72c589989d06fc761
[]
no_license
hcyuser/2017_CPE
https://github.com/hcyuser/2017_CPE
e61cc48c30d6e5c768e0f235e6d83dea6210ae34
53e86b7bf54aba6377ded465ae541c793f989ef8
refs/heads/master
2021-01-23T08:09:50.550000
2017-03-30T02:43:27
2017-03-30T02:43:27
86,477,706
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; class UVA10282{ public static void main(String[] args){ boolean isOK = false; Scanner input = new Scanner(System.in); HashMap<String,String> hm = new HashMap<String,String>(); while(input.hasNext()){ String str2 = input.nextLine(); String[] str = str2.split(" "); if((str.length==2)&&(!str2.equals(""))){ hm.put(str[1],str[0]); }else if(str.length==1){ if(hm.get(str[0])!=null) System.out.println(hm.get(str[0])); else if(isOK) {System.out.println("eh");} else{ isOK = true; } } } } }
UTF-8
Java
605
java
UVA10282.java
Java
[]
null
[]
import java.util.*; class UVA10282{ public static void main(String[] args){ boolean isOK = false; Scanner input = new Scanner(System.in); HashMap<String,String> hm = new HashMap<String,String>(); while(input.hasNext()){ String str2 = input.nextLine(); String[] str = str2.split(" "); if((str.length==2)&&(!str2.equals(""))){ hm.put(str[1],str[0]); }else if(str.length==1){ if(hm.get(str[0])!=null) System.out.println(hm.get(str[0])); else if(isOK) {System.out.println("eh");} else{ isOK = true; } } } } }
605
0.553719
0.530578
28
19.678572
18.862385
64
false
false
0
0
0
0
0
0
2.857143
false
false
10
6569d08fb4fe5b2030e7d63a566404472904f2b2
37,366,215,498,419
bcbc994f806d9510ce9b0da7a10c8e50d4e75e1b
/src/main/java/pdfgenerator/models/StructurePositionDimension.java
58393c7d5a3c7fb7ef3235556c3e84b2b5d5e0b4
[ "MIT" ]
permissive
LandRegistry/pdf-generation-api
https://github.com/LandRegistry/pdf-generation-api
82804e2659bfaaf04263b85591b697b28afe51e3
64588e4496baedd361d33502602e8d580a300c43
refs/heads/master
2020-04-03T21:17:21.293000
2018-10-29T16:57:47
2018-10-30T10:55:34
155,569,219
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package pdfgenerator.models; import com.fasterxml.jackson.annotation.*; @JsonIgnoreProperties(ignoreUnknown=true) @JsonPropertyOrder({ "height", "units", "extent-covered", "part-explanatory-text" }) public class StructurePositionDimension { @JsonProperty("height") private String height; @JsonSetter("height") public void setHeight(String height) { this.height = height; } @JsonGetter("height") public String getHeight() { return this.height; } @JsonProperty("units") private String units; @JsonSetter("units") public void setUnits(String units) { this.units = units; } @JsonGetter("units") public String getUnits() { return this.units; } @JsonProperty("extent-covered") private String extentCovered; @JsonSetter("extent-covered") public void setExtentCovered(String extentCovered) { this.extentCovered = extentCovered; } @JsonGetter("extent-covered") public String getExtentCovered() { return this.extentCovered; } @JsonProperty("part-explanatory-text") private String partExplanatoryText; @JsonSetter("part-explanatory-text") public void setPartExplanatoryText(String partExplanatoryText) { // replace \r\n for line feed as this will cause problems in rendering pdf this.partExplanatoryText = partExplanatoryText.replace("\r\n", "\n"); } @JsonGetter("part-explanatory-text") public String getPartExplanatoryText() { return this.partExplanatoryText; } public String toPositionString() { if(this.extentCovered.equalsIgnoreCase("All of the extent")) { return this.extentCovered; } else { return this.partExplanatoryText; } } public String toHeightString() { if(!this.height.equalsIgnoreCase("Unlimited height")) { return this.height + " " + this.units; } else { return this.height; } } }
UTF-8
Java
1,962
java
StructurePositionDimension.java
Java
[]
null
[]
package pdfgenerator.models; import com.fasterxml.jackson.annotation.*; @JsonIgnoreProperties(ignoreUnknown=true) @JsonPropertyOrder({ "height", "units", "extent-covered", "part-explanatory-text" }) public class StructurePositionDimension { @JsonProperty("height") private String height; @JsonSetter("height") public void setHeight(String height) { this.height = height; } @JsonGetter("height") public String getHeight() { return this.height; } @JsonProperty("units") private String units; @JsonSetter("units") public void setUnits(String units) { this.units = units; } @JsonGetter("units") public String getUnits() { return this.units; } @JsonProperty("extent-covered") private String extentCovered; @JsonSetter("extent-covered") public void setExtentCovered(String extentCovered) { this.extentCovered = extentCovered; } @JsonGetter("extent-covered") public String getExtentCovered() { return this.extentCovered; } @JsonProperty("part-explanatory-text") private String partExplanatoryText; @JsonSetter("part-explanatory-text") public void setPartExplanatoryText(String partExplanatoryText) { // replace \r\n for line feed as this will cause problems in rendering pdf this.partExplanatoryText = partExplanatoryText.replace("\r\n", "\n"); } @JsonGetter("part-explanatory-text") public String getPartExplanatoryText() { return this.partExplanatoryText; } public String toPositionString() { if(this.extentCovered.equalsIgnoreCase("All of the extent")) { return this.extentCovered; } else { return this.partExplanatoryText; } } public String toHeightString() { if(!this.height.equalsIgnoreCase("Unlimited height")) { return this.height + " " + this.units; } else { return this.height; } } }
1,962
0.667686
0.667686
68
27.867647
24.666544
94
false
false
0
0
0
0
0
0
0.323529
false
false
10
2150368cf883edd494cac3800ae419a8c5e36f97
36,627,481,125,868
8329af3dcfb9a44b09b6cbb9725ee446922e024d
/docs/src/main/paradox/tutorial/testing/answering_requests/answering-requests/src/main/java/se/sics/test/Ponger.java
b82ce29d9ec9032eb2965e1645c9176a9cd4af09
[]
no_license
kompics/kompics-scala
https://github.com/kompics/kompics-scala
da74c905f0c5305b878418f548ca2d42866f77d1
58b82e2da3f916b5dc4b9c6d7b010ee60fc54b90
refs/heads/master
2022-02-08T17:51:01.219000
2020-01-04T17:05:13
2020-01-04T17:05:13
10,551,653
23
7
null
false
2022-02-01T21:06:24
2013-06-07T14:35:32
2022-01-30T17:14:17
2022-02-01T21:06:23
2,459
19
5
3
Scala
false
false
package se.sics.test; import se.sics.kompics.ComponentDefinition; import se.sics.kompics.Handler; import se.sics.kompics.Negative; public class Ponger extends ComponentDefinition { public static int pingsReceived = 0; Negative<PingPongPort> ppp = provides(PingPongPort.class); Handler<Ping> pingHandler = new Handler<Ping>() { public void handle(Ping ping) { pingsReceived++; if (ping.id == 0) { trigger(new Pong(1), ppp); trigger(new Pong(2), ppp); } else { // echo the id trigger(new Pong(ping.id), ppp); } } }; { subscribe(pingHandler, ppp); } }
UTF-8
Java
629
java
Ponger.java
Java
[]
null
[]
package se.sics.test; import se.sics.kompics.ComponentDefinition; import se.sics.kompics.Handler; import se.sics.kompics.Negative; public class Ponger extends ComponentDefinition { public static int pingsReceived = 0; Negative<PingPongPort> ppp = provides(PingPongPort.class); Handler<Ping> pingHandler = new Handler<Ping>() { public void handle(Ping ping) { pingsReceived++; if (ping.id == 0) { trigger(new Pong(1), ppp); trigger(new Pong(2), ppp); } else { // echo the id trigger(new Pong(ping.id), ppp); } } }; { subscribe(pingHandler, ppp); } }
629
0.643879
0.63752
24
25.25
17.173744
60
false
false
0
0
0
0
0
0
0.666667
false
false
10
c28d195e8f76bdcf422cac2c705934928b1bb142
3,633,542,350,542
5a9c2c90ea3e229d1f44d06d6dcaf8b046ca1a7a
/eclipse-workspace/GuessNumber/src/GuessNumber/ExClass.java
f0085c2b76bbb331c403efb66fd62eb8dcd77f71
[]
no_license
liuyuanbwin/socketgame
https://github.com/liuyuanbwin/socketgame
c98e863750722b725f0a06977e83c88ba071ace3
cdcff833ea4957d6ec2b4d0e7c3433f7e712887b
refs/heads/master
2022-04-18T03:47:16.466000
2020-04-20T04:57:16
2020-04-20T04:57:16
255,551,723
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package GuessNumber; public class ExClass { public static void pname() { System.err.println("name ... !!"); } }
UTF-8
Java
121
java
ExClass.java
Java
[]
null
[]
package GuessNumber; public class ExClass { public static void pname() { System.err.println("name ... !!"); } }
121
0.636364
0.636364
7
16.285715
14.048022
38
false
false
0
0
0
0
0
0
0.285714
false
false
10