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
2d8cc16c131dad5b1effbae40910fcb1c900f64c
5,892,695,178,362
d55d3b2121c7253e625f0287cdcdd8f57c1e291d
/src/org/egorlitvinenko/certification/oca/book1/chapter3/Q13.java
1c2e3cb58d80b79c69d31ab4bfed427647803e71
[ "Apache-2.0" ]
permissive
egorlitvinenko/JavaLearning
https://github.com/egorlitvinenko/JavaLearning
3970f2f84dd484033484679e6d06a089223b7777
9611c0925a1285e4af276abfcdf9aa9144aebbd4
refs/heads/master
2022-07-12T10:04:35.672000
2021-05-26T08:36:01
2021-05-26T08:36:01
85,112,309
0
0
Apache-2.0
false
2022-05-25T05:05:33
2017-03-15T19:22:21
2021-05-26T08:36:41
2022-05-25T05:05:31
51
0
0
2
Java
false
false
package org.egorlitvinenko.certification.oca.book1.chapter3; /** * @author Egor Litvinenko */ public class Q13 { public static void main(String[] args) { StringBuilder b = new StringBuilder(); System.out.println(b); } }
UTF-8
Java
249
java
Q13.java
Java
[ { "context": ".certification.oca.book1.chapter3;\n\n/**\n * @author Egor Litvinenko\n */\npublic class Q13 {\n\n public static void ma", "end": 92, "score": 0.9997870922088623, "start": 77, "tag": "NAME", "value": "Egor Litvinenko" } ]
null
[]
package org.egorlitvinenko.certification.oca.book1.chapter3; /** * @author <NAME> */ public class Q13 { public static void main(String[] args) { StringBuilder b = new StringBuilder(); System.out.println(b); } }
240
0.658635
0.64257
13
18.153847
20.213652
60
false
false
0
0
0
0
0
0
0.230769
false
false
3
fbc2441e006b0bf187bae6d155ec5901a8a45170
4,612,794,927,877
b0c2f20fe7f84f2d9600b1582b1dfc779b00b2e5
/src/main/java/RIPS_Calendar_2019/Day23_Ivy_ShowCalendar.java
f5cd03f6c4da2f5ec9ca09cfc103151452534cc7
[]
no_license
agigleux/analyzers-playground
https://github.com/agigleux/analyzers-playground
1504ec7d7971c5fd76a65a21fdc8ddca509f4251
5a2c249e3d1e56926e6c1daba8f4009230c93b81
refs/heads/master
2023-04-29T19:02:40.533000
2022-12-20T14:52:30
2022-12-20T14:52:30
138,036,875
0
1
null
false
2023-04-14T17:56:22
2018-06-20T13:30:51
2022-12-09T14:22:21
2023-04-14T17:56:20
2,804
0
1
3
Java
false
false
package RIPS_Calendar_2019; import javax.servlet.http.*; import java.io.*; import java.text.*; import java.util.*; import org.apache.commons.lang3.StringEscapeUtils; public class Day23_Ivy_ShowCalendar extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { response.setContentType("text/html"); GregorianCalendar calendar = new GregorianCalendar(); SimpleTimeZone x = new SimpleTimeZone(0, request.getParameter("id")); SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy"); calendar.setTime(parser.parse(request.getParameter("current_time"))); calendar.setTimeZone(x); Formatter formatter = new Formatter(); String name = StringEscapeUtils.escapeHtml4(request.getParameter("name")); formatter.format("Name of your calendar: " + name + " and your current date is: %1$te.%1$tm.%1$tY", calendar); PrintWriter pw = response.getWriter(); pw.print(formatter.toString()); } catch (ParseException e) { response.sendRedirect("/"); } } }
UTF-8
Java
1,224
java
Day23_Ivy_ShowCalendar.java
Java
[]
null
[]
package RIPS_Calendar_2019; import javax.servlet.http.*; import java.io.*; import java.text.*; import java.util.*; import org.apache.commons.lang3.StringEscapeUtils; public class Day23_Ivy_ShowCalendar extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { response.setContentType("text/html"); GregorianCalendar calendar = new GregorianCalendar(); SimpleTimeZone x = new SimpleTimeZone(0, request.getParameter("id")); SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy"); calendar.setTime(parser.parse(request.getParameter("current_time"))); calendar.setTimeZone(x); Formatter formatter = new Formatter(); String name = StringEscapeUtils.escapeHtml4(request.getParameter("name")); formatter.format("Name of your calendar: " + name + " and your current date is: %1$te.%1$tm.%1$tY", calendar); PrintWriter pw = response.getWriter(); pw.print(formatter.toString()); } catch (ParseException e) { response.sendRedirect("/"); } } }
1,224
0.647876
0.638072
29
41.206898
31.809107
111
false
false
0
0
0
0
0
0
0.724138
false
false
3
1c2d8e261b98f86cafcd409dbfd6e2eb739b4015
5,488,968,256,519
3d87148a5b5d11d9c0e30f38271566ad108b29b0
/src/org/treblefrei/kedr/filesystem/AlbumSaver.java
1f56e7137c15796d2a7841e6f73745b95e073fe0
[]
no_license
worklez/kedr
https://github.com/worklez/kedr
ed786ae2de8406ec3924f1d4a589dc7dbf528a45
6ff89ddc163df7330be02b7adf9a65f35be20836
refs/heads/master
2021-01-20T04:49:45.030000
2009-12-16T10:26:50
2009-12-16T10:26:50
4,820,756
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.treblefrei.kedr.filesystem; import org.treblefrei.kedr.model.Album; import org.treblefrei.kedr.model.Track; public class AlbumSaver { public static boolean saveAlbum(Album album) { for (Track track : album.getTracks()) { try { TrackSaver.saveTrack(track); } catch (TrackIOException e) { // problem with track } } return true; } }
UTF-8
Java
453
java
AlbumSaver.java
Java
[]
null
[]
package org.treblefrei.kedr.filesystem; import org.treblefrei.kedr.model.Album; import org.treblefrei.kedr.model.Track; public class AlbumSaver { public static boolean saveAlbum(Album album) { for (Track track : album.getTracks()) { try { TrackSaver.saveTrack(track); } catch (TrackIOException e) { // problem with track } } return true; } }
453
0.576159
0.576159
21
20.476191
18.099247
47
false
false
0
0
0
0
0
0
0.333333
false
false
3
60d2682d87c3d733a76ca7f96184b61a367ea836
9,990,093,974,770
91716aa27cc5897fcb6609dbfd3f12710f726f77
/src/test/java/org/pom/Task3.java
ce76ecc1e7c7ef6e1e89f661fb75b511351c0e90
[]
no_license
anuradhajune/project
https://github.com/anuradhajune/project
76a31b51ee4d17ddc891b563df4081fdefe39028
d853a486b89cc914f1b8b04f4bc2f0194239f74a
refs/heads/master
2023-07-14T16:31:53.208000
2021-08-23T09:55:19
2021-08-23T09:55:19
399,048,408
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.pom; import org.first.BaseClass; import org.first.GreensPojo; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; public class Task3 extends BaseClass { public static void main(String[] args) { loadBrowser(); launchUrl("http://www.greenstechnologys.com/"); maxWindow(); GreensPojo g=new GreensPojo(); btnClk(g.getCert()); btnClk(g.getCourse()); System.out.println("Selenium"); getTxt(g.getPara()); moveElement(g.getCou()); moveElement(g.getJava()); moveElement(g.getCore()); elementContextClk(g.getCore()); scrollDown(g.getScroll()); getTxt(g.getPrint()); btnClk(g.getCareer()); scrollDown(g.getDown()); getTxt(g.getMailprint()); previouspage(); btnClk(g.getTestim()); scrollDown(g.getSclldwn()); getlastTxt(g.getTestimoniprint()); previouspage(); btnClk(g.getContact()); getTxt(g.getPp()); scrollDown(g.getDd()); getTxt(g.getCopyright()); } }
UTF-8
Java
923
java
Task3.java
Java
[]
null
[]
package org.pom; import org.first.BaseClass; import org.first.GreensPojo; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; public class Task3 extends BaseClass { public static void main(String[] args) { loadBrowser(); launchUrl("http://www.greenstechnologys.com/"); maxWindow(); GreensPojo g=new GreensPojo(); btnClk(g.getCert()); btnClk(g.getCourse()); System.out.println("Selenium"); getTxt(g.getPara()); moveElement(g.getCou()); moveElement(g.getJava()); moveElement(g.getCore()); elementContextClk(g.getCore()); scrollDown(g.getScroll()); getTxt(g.getPrint()); btnClk(g.getCareer()); scrollDown(g.getDown()); getTxt(g.getMailprint()); previouspage(); btnClk(g.getTestim()); scrollDown(g.getSclldwn()); getlastTxt(g.getTestimoniprint()); previouspage(); btnClk(g.getContact()); getTxt(g.getPp()); scrollDown(g.getDd()); getTxt(g.getCopyright()); } }
923
0.704225
0.703142
43
20.465117
12.854009
49
false
false
0
0
0
0
0
0
1.674419
false
false
3
2d7a8f3d6653f2bb4ad077a6527e029f7290a184
9,251,359,617,454
98c51bb43f794b4effff3adefeabe54f358da72d
/app/src/main/java/com/example/facebookmovies/MovieTrailerActivity.java
3ee77fbcaecece0205632cd0daa555992d0dd1a8
[ "Apache-2.0" ]
permissive
acantusoto/FacebookMovies
https://github.com/acantusoto/FacebookMovies
97c0db10a0c2950c68b64301f9ba22a4a1eece2c
8f7b76cad9906bd70c2167c830970b2f68dbf215
refs/heads/master
2022-11-21T04:48:31.196000
2020-06-27T08:17:23
2020-06-27T08:17:23
275,203,716
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.facebookmovies; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import com.codepath.asynchttpclient.AsyncHttpClient; import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler; import com.example.facebookmovies.databinding.ActivityMovieDetailsBinding; import com.example.facebookmovies.databinding.ActivityMovieTrailerBinding; import com.example.facebookmovies.models.Movie; import com.google.android.youtube.player.YouTubeBaseActivity; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.parceler.Parcels; import okhttp3.Headers; public class MovieTrailerActivity extends YouTubeBaseActivity { public static final String API_KEY = "f1cc5258f770587bdee59fdae894bb9c"; public static String TAG = "YouTubeBaseActivity"; String NOW_PLAYING_URL; Movie movie; String videoId = null; JSONArray results; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityMovieTrailerBinding binding = ActivityMovieTrailerBinding.inflate(getLayoutInflater()); View view = binding.getRoot(); setContentView(view); movie = Parcels.unwrap(getIntent().getParcelableExtra(Movie.class.getSimpleName())); NOW_PLAYING_URL = String.format("https://api.themoviedb.org/3/movie/%s/videos?api_key=%s" , movie.getId(),API_KEY); Log.d(TAG, "onCreate: "+NOW_PLAYING_URL); AsyncHttpClient client = new AsyncHttpClient(); client.get(NOW_PLAYING_URL, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Headers headers, JSON json) { Log.d(TAG,"onSuccess"); JSONObject jsonObject = json.jsonObject; try { results = jsonObject.getJSONArray("results"); Log.i(TAG, "Results: "+results.toString()); videoId = results.getJSONObject(0).getString("key"); Log.i(TAG, "Id1: "+results.getJSONObject(0).getString("key")); Log.i(TAG, "Id2: "+videoId); } catch (JSONException e) { Log.e(TAG, "Hit json exception", e); endActivity(); } } @Override public void onFailure(int statusCode, Headers headers, String response, Throwable throwable) { Log.d(TAG,"onFailure"); endActivity(); } }); // resolve the player view from the layout YouTubePlayerView playerView = binding.player; // initialize with API key stored in secrets.xml playerView.initialize(getString(R.string.youtube_api_key), new YouTubePlayer.OnInitializedListener() { @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) { Log.d(TAG, "onInitializationSuccess: videoId: " + videoId); // // do any work here to cue video, play video, etc. // youTubePlayer.cueVideo(videoId); // youTubePlayer.play(); } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) { // log the error Log.e("MovieTrailerActivity", "Error initializing YouTube player"); } }); endActivity(); } public void endActivity(){ Intent intent = new Intent(this, MovieDetailsActivity.class);// New activity intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // serialize the movie using parceler, use its short name as a key intent.putExtra(Movie.class.getSimpleName(), Parcels.wrap(movie)); startActivity(intent); finish(); } }
UTF-8
Java
4,398
java
MovieTrailerActivity.java
Java
[ { "context": "vity {\n\n public static final String API_KEY = \"f1cc5258f770587bdee59fdae894bb9c\";\n public static String TAG = \"YouTubeBaseActi", "end": 1046, "score": 0.9997275471687317, "start": 1014, "tag": "KEY", "value": "f1cc5258f770587bdee59fdae894bb9c" } ]
null
[]
package com.example.facebookmovies; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import com.codepath.asynchttpclient.AsyncHttpClient; import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler; import com.example.facebookmovies.databinding.ActivityMovieDetailsBinding; import com.example.facebookmovies.databinding.ActivityMovieTrailerBinding; import com.example.facebookmovies.models.Movie; import com.google.android.youtube.player.YouTubeBaseActivity; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.parceler.Parcels; import okhttp3.Headers; public class MovieTrailerActivity extends YouTubeBaseActivity { public static final String API_KEY = "<KEY>"; public static String TAG = "YouTubeBaseActivity"; String NOW_PLAYING_URL; Movie movie; String videoId = null; JSONArray results; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityMovieTrailerBinding binding = ActivityMovieTrailerBinding.inflate(getLayoutInflater()); View view = binding.getRoot(); setContentView(view); movie = Parcels.unwrap(getIntent().getParcelableExtra(Movie.class.getSimpleName())); NOW_PLAYING_URL = String.format("https://api.themoviedb.org/3/movie/%s/videos?api_key=%s" , movie.getId(),API_KEY); Log.d(TAG, "onCreate: "+NOW_PLAYING_URL); AsyncHttpClient client = new AsyncHttpClient(); client.get(NOW_PLAYING_URL, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Headers headers, JSON json) { Log.d(TAG,"onSuccess"); JSONObject jsonObject = json.jsonObject; try { results = jsonObject.getJSONArray("results"); Log.i(TAG, "Results: "+results.toString()); videoId = results.getJSONObject(0).getString("key"); Log.i(TAG, "Id1: "+results.getJSONObject(0).getString("key")); Log.i(TAG, "Id2: "+videoId); } catch (JSONException e) { Log.e(TAG, "Hit json exception", e); endActivity(); } } @Override public void onFailure(int statusCode, Headers headers, String response, Throwable throwable) { Log.d(TAG,"onFailure"); endActivity(); } }); // resolve the player view from the layout YouTubePlayerView playerView = binding.player; // initialize with API key stored in secrets.xml playerView.initialize(getString(R.string.youtube_api_key), new YouTubePlayer.OnInitializedListener() { @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) { Log.d(TAG, "onInitializationSuccess: videoId: " + videoId); // // do any work here to cue video, play video, etc. // youTubePlayer.cueVideo(videoId); // youTubePlayer.play(); } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) { // log the error Log.e("MovieTrailerActivity", "Error initializing YouTube player"); } }); endActivity(); } public void endActivity(){ Intent intent = new Intent(this, MovieDetailsActivity.class);// New activity intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // serialize the movie using parceler, use its short name as a key intent.putExtra(Movie.class.getSimpleName(), Parcels.wrap(movie)); startActivity(intent); finish(); } }
4,371
0.635971
0.630741
117
36.598289
31.776749
123
false
false
0
0
0
0
0
0
0.726496
false
false
3
b0663e51e3f95844cecff0a927da71fffc9709f1
9,251,359,619,867
0bf4e1a95afc82874dc3e8c904aa5b3c57fa6d89
/app/src/main/java/com/apps/myapplication/firebaseClasses/MyFirebaseInstanceIDService.java
22d444b1a1b2509fc715f028630eee941f720bd0
[]
no_license
VattipalliSridhar/My-Samples-Codes
https://github.com/VattipalliSridhar/My-Samples-Codes
f91ec4f392f6e7c7983cd34862749ea3b29290af
c8bc9a0e18470b99dcf8b0b989d95d8141923123
refs/heads/master
2023-03-24T02:00:28.583000
2021-03-23T11:12:24
2021-03-23T11:12:24
348,597,841
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.apps.myapplication.firebaseClasses; import android.annotation.SuppressLint; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.util.Log; import androidx.annotation.NonNull; import androidx.core.app.NotificationCompat; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.apps.myapplication.CalenderActivity; import com.apps.myapplication.R; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; public class MyFirebaseInstanceIDService extends FirebaseMessagingService { @Override public void onNewToken(@NonNull String s) { super.onNewToken(s); String refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.e("msgs",""+s); } @Override public void onMessageReceived(@NonNull RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); if (remoteMessage.getData().size() > 0) { String message=remoteMessage.getData().get("message"); String title=remoteMessage.getData().get("title"); Log.e("data",""+message+" "+title); sendNotification(message,title); } } private void sendNotification(String messageBody, String title) { int NOTIFICATION_ID = 1; Intent intent = new Intent(this, CalenderActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); String channelId = getString(R.string.default_notification_channel_id); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId) .setSmallIcon(R.drawable.ic_play) .setContentTitle(title) .setContentText(messageBody) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Since android Oreo notification channel is needed. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(channelId, "Channel human readable title", NotificationManager.IMPORTANCE_DEFAULT); notificationManager.createNotificationChannel(channel); } /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(channelId, "My Notifications", NotificationManager.IMPORTANCE_MAX); // Configure the notification channel. notificationChannel.setDescription("Sample Channel description"); notificationChannel.enableLights(true); notificationChannel.setLightColor(Color.RED); notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000}); notificationChannel.enableVibration(true); notificationManager.createNotificationChannel(notificationChannel); }*/ if (NOTIFICATION_ID > 1073741824) { NOTIFICATION_ID = 0; } int i = NOTIFICATION_ID; NOTIFICATION_ID = i + 1; notificationManager.notify(( int ) System. currentTimeMillis (), notificationBuilder.build()); } }
UTF-8
Java
4,021
java
MyFirebaseInstanceIDService.java
Java
[]
null
[]
package com.apps.myapplication.firebaseClasses; import android.annotation.SuppressLint; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.util.Log; import androidx.annotation.NonNull; import androidx.core.app.NotificationCompat; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.apps.myapplication.CalenderActivity; import com.apps.myapplication.R; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; public class MyFirebaseInstanceIDService extends FirebaseMessagingService { @Override public void onNewToken(@NonNull String s) { super.onNewToken(s); String refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.e("msgs",""+s); } @Override public void onMessageReceived(@NonNull RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); if (remoteMessage.getData().size() > 0) { String message=remoteMessage.getData().get("message"); String title=remoteMessage.getData().get("title"); Log.e("data",""+message+" "+title); sendNotification(message,title); } } private void sendNotification(String messageBody, String title) { int NOTIFICATION_ID = 1; Intent intent = new Intent(this, CalenderActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); String channelId = getString(R.string.default_notification_channel_id); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId) .setSmallIcon(R.drawable.ic_play) .setContentTitle(title) .setContentText(messageBody) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Since android Oreo notification channel is needed. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(channelId, "Channel human readable title", NotificationManager.IMPORTANCE_DEFAULT); notificationManager.createNotificationChannel(channel); } /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(channelId, "My Notifications", NotificationManager.IMPORTANCE_MAX); // Configure the notification channel. notificationChannel.setDescription("Sample Channel description"); notificationChannel.enableLights(true); notificationChannel.setLightColor(Color.RED); notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000}); notificationChannel.enableVibration(true); notificationManager.createNotificationChannel(notificationChannel); }*/ if (NOTIFICATION_ID > 1073741824) { NOTIFICATION_ID = 0; } int i = NOTIFICATION_ID; NOTIFICATION_ID = i + 1; notificationManager.notify(( int ) System. currentTimeMillis (), notificationBuilder.build()); } }
4,021
0.687142
0.680428
95
41.326317
28.831066
145
false
false
0
0
0
0
0
0
0.694737
false
false
3
1a72a287d5c2392ce5b6ca41ddc837b6b8faa351
2,095,944,107,129
b46bc26bd93f43aaab379f5ff1e0e983544c379e
/JediDroid/src/org/jediDroid/activity/CalculadoraActivity.java
60f5d34ba7ddb1516db76975f67a14b4024b5f11
[]
no_license
Jandir25/jedidroid
https://github.com/Jandir25/jedidroid
bb88a3c871d4bd52baee0c574bd2a73e8cdec6b7
5e4da5a9505def26de44d7373e2851eae3329d10
refs/heads/master
2021-01-10T16:34:05.738000
2013-01-30T22:40:43
2013-01-30T22:40:43
52,049,679
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.jediDroid.activity; import org.jediDroid.domain.Calculadora; import android.app.Activity; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; /* Activity de la calculadora */ public class CalculadoraActivity extends Activity { protected static final String LOG = "JediDroid - CalculadoraActivity"; Calculadora calculadora = new Calculadora(); boolean limpiar = true; /** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) { Log.v(LOG, "onCreate"); super.onCreate(savedInstanceState); setContentView(R.layout.calculadora); TextView inputResult = (TextView) findViewById(R.id.inputResult); /* Modificar el texto de un TextView */ inputResult.setText("0"); /* Defino los listeners */ MyListenerOnClick listener = new MyListenerOnClick(); Button number0 = (Button) findViewById(R.id.buttonNumber0); Button number1 = (Button) findViewById(R.id.buttonNumber1); Button number2 = (Button) findViewById(R.id.buttonNumber2); Button number3 = (Button) findViewById(R.id.buttonNumber3); Button number4 = (Button) findViewById(R.id.buttonNumber4); Button number5 = (Button) findViewById(R.id.buttonNumber5); Button number6 = (Button) findViewById(R.id.buttonNumber6); Button number7 = (Button) findViewById(R.id.buttonNumber7); Button number8 = (Button) findViewById(R.id.buttonNumber8); Button number9 = (Button) findViewById(R.id.buttonNumber9); Button suma = (Button) findViewById(R.id.buttonSuma); Button resta = (Button) findViewById(R.id.buttonResta); Button multiplicacio = (Button) findViewById(R.id.buttonMultiplicacio); Button divisio = (Button) findViewById(R.id.buttonDivisio); Button clear = (Button) findViewById(R.id.buttonClearCalculator); Button igual = (Button) findViewById(R.id.buttonIgual); number0.setOnClickListener(listener); number1.setOnClickListener(listener); number2.setOnClickListener(listener); number3.setOnClickListener(listener); number4.setOnClickListener(listener); number5.setOnClickListener(listener); number6.setOnClickListener(listener); number7.setOnClickListener(listener); number8.setOnClickListener(listener); number9.setOnClickListener(listener); suma.setOnClickListener(listener); resta.setOnClickListener(listener); multiplicacio.setOnClickListener(listener); divisio.setOnClickListener(listener); igual.setOnClickListener(listener); clear.setOnClickListener(listener); /* Bloqueamos el giro de pantalla */ this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } @Override protected void onStart() { super.onStart(); Log.v(LOG, "onStart"); } @Override protected void onResume() { super.onResume(); Log.v(LOG, "onResume"); /* Bloqueamos el giro de pantalla */ this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } @Override protected void onPause() { super.onPause(); Log.v(LOG, "onPause"); } @Override protected void onStop() { super.onStop(); Log.v(LOG, "onStop"); } @Override protected void onDestroy() { Log.v(LOG, "onDestroy"); super.onDestroy(); } /* MyListeners */ protected class MyListenerOnClick implements OnClickListener { @Override public void onClick(View v) { TextView inputResult = (TextView) findViewById(R.id.inputResult); if (!pulsacioNumero(v, inputResult)) { pulsacioOperador(v, inputResult); } } } /* Guardar estado */ @Override protected void onSaveInstanceState(Bundle outState) { Log.v(LOG, "onSaveInstanceState"); super.onSaveInstanceState(outState); TextView textView = (TextView) findViewById(R.id.inputResult); Double resultat = calculadora.getResultat(); String operador = calculadora.getOperador(); outState.putString("inputResultat", textView.getText().toString()); outState.putString("operador", operador); if (resultat != null) { outState.putDouble("resultat", resultat.doubleValue()); } outState.putBoolean("limpiar", limpiar); } @Override protected void onRestoreInstanceState(Bundle outState) { Log.v(LOG, "onRestoreInstanceState"); super.onRestoreInstanceState(outState); TextView textView = (TextView) findViewById(R.id.inputResult); textView.setText(outState.getString("inputResultat")); limpiar = outState.getBoolean("limpiar"); calculadora = new Calculadora(); calculadora.setResultat(outState.getDouble("resultat")); calculadora.setOperador(outState.getString("operador")); } /* Funciones privadas */ private boolean pulsacioNumero(View v, TextView textView) { switch (v.getId()) { case R.id.buttonNumber0: anadirNumero("0", textView); break; case R.id.buttonNumber1: anadirNumero("1", textView); break; case R.id.buttonNumber2: anadirNumero("2", textView); break; case R.id.buttonNumber3: anadirNumero("3", textView); break; case R.id.buttonNumber4: anadirNumero("4", textView); break; case R.id.buttonNumber5: anadirNumero("5", textView); break; case R.id.buttonNumber6: anadirNumero("6", textView); break; case R.id.buttonNumber7: anadirNumero("7", textView); break; case R.id.buttonNumber8: anadirNumero("8", textView); break; case R.id.buttonNumber9: anadirNumero("9", textView); break; default: return false; } return true; } private boolean pulsacioOperador(View v, TextView textView) { if (comprobarCampos(textView)) { Double valor = Double.valueOf(textView.getText().toString()); switch (v.getId()) { case R.id.buttonSuma: if (calculadora.setResultat(valor, textView)) { textView.setText(calculadora.getResultat().toString()); } calculadora.setOperador("+"); limpiar = true; break; case R.id.buttonResta: if (calculadora.setResultat(valor, textView)) { textView.setText(calculadora.getResultat().toString()); } calculadora.setOperador("-"); limpiar = true; break; case R.id.buttonMultiplicacio: if (calculadora.setResultat(valor, textView)) { textView.setText(calculadora.getResultat().toString()); } calculadora.setOperador("*"); limpiar = true; break; case R.id.buttonDivisio: if (calculadora.setResultat(valor, textView)) { textView.setText(calculadora.getResultat().toString()); } calculadora.setOperador("/"); limpiar = true; break; case R.id.buttonIgual: if (calculadora.setResultat(valor, textView)) { textView.setText(calculadora.getResultat().toString()); } calculadora.setOperador(null); limpiar = true; break; case R.id.buttonClearCalculator: calculadora.setResultat(null); calculadora.setOperador(null); limpiar = true; textView.setText("0"); break; } } return true; } private boolean comprobarCampos(TextView input) { if (input.getText().toString().equals("")) { return false; } return true; } private void anadirNumero(String numero, TextView vista) { String aux = vista.getText().toString(); if (limpiar) { limpiar = false; aux = ""; } aux = aux.concat(numero); vista.setText(aux); } }
UTF-8
Java
7,589
java
CalculadoraActivity.java
Java
[]
null
[]
package org.jediDroid.activity; import org.jediDroid.domain.Calculadora; import android.app.Activity; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; /* Activity de la calculadora */ public class CalculadoraActivity extends Activity { protected static final String LOG = "JediDroid - CalculadoraActivity"; Calculadora calculadora = new Calculadora(); boolean limpiar = true; /** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) { Log.v(LOG, "onCreate"); super.onCreate(savedInstanceState); setContentView(R.layout.calculadora); TextView inputResult = (TextView) findViewById(R.id.inputResult); /* Modificar el texto de un TextView */ inputResult.setText("0"); /* Defino los listeners */ MyListenerOnClick listener = new MyListenerOnClick(); Button number0 = (Button) findViewById(R.id.buttonNumber0); Button number1 = (Button) findViewById(R.id.buttonNumber1); Button number2 = (Button) findViewById(R.id.buttonNumber2); Button number3 = (Button) findViewById(R.id.buttonNumber3); Button number4 = (Button) findViewById(R.id.buttonNumber4); Button number5 = (Button) findViewById(R.id.buttonNumber5); Button number6 = (Button) findViewById(R.id.buttonNumber6); Button number7 = (Button) findViewById(R.id.buttonNumber7); Button number8 = (Button) findViewById(R.id.buttonNumber8); Button number9 = (Button) findViewById(R.id.buttonNumber9); Button suma = (Button) findViewById(R.id.buttonSuma); Button resta = (Button) findViewById(R.id.buttonResta); Button multiplicacio = (Button) findViewById(R.id.buttonMultiplicacio); Button divisio = (Button) findViewById(R.id.buttonDivisio); Button clear = (Button) findViewById(R.id.buttonClearCalculator); Button igual = (Button) findViewById(R.id.buttonIgual); number0.setOnClickListener(listener); number1.setOnClickListener(listener); number2.setOnClickListener(listener); number3.setOnClickListener(listener); number4.setOnClickListener(listener); number5.setOnClickListener(listener); number6.setOnClickListener(listener); number7.setOnClickListener(listener); number8.setOnClickListener(listener); number9.setOnClickListener(listener); suma.setOnClickListener(listener); resta.setOnClickListener(listener); multiplicacio.setOnClickListener(listener); divisio.setOnClickListener(listener); igual.setOnClickListener(listener); clear.setOnClickListener(listener); /* Bloqueamos el giro de pantalla */ this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } @Override protected void onStart() { super.onStart(); Log.v(LOG, "onStart"); } @Override protected void onResume() { super.onResume(); Log.v(LOG, "onResume"); /* Bloqueamos el giro de pantalla */ this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } @Override protected void onPause() { super.onPause(); Log.v(LOG, "onPause"); } @Override protected void onStop() { super.onStop(); Log.v(LOG, "onStop"); } @Override protected void onDestroy() { Log.v(LOG, "onDestroy"); super.onDestroy(); } /* MyListeners */ protected class MyListenerOnClick implements OnClickListener { @Override public void onClick(View v) { TextView inputResult = (TextView) findViewById(R.id.inputResult); if (!pulsacioNumero(v, inputResult)) { pulsacioOperador(v, inputResult); } } } /* Guardar estado */ @Override protected void onSaveInstanceState(Bundle outState) { Log.v(LOG, "onSaveInstanceState"); super.onSaveInstanceState(outState); TextView textView = (TextView) findViewById(R.id.inputResult); Double resultat = calculadora.getResultat(); String operador = calculadora.getOperador(); outState.putString("inputResultat", textView.getText().toString()); outState.putString("operador", operador); if (resultat != null) { outState.putDouble("resultat", resultat.doubleValue()); } outState.putBoolean("limpiar", limpiar); } @Override protected void onRestoreInstanceState(Bundle outState) { Log.v(LOG, "onRestoreInstanceState"); super.onRestoreInstanceState(outState); TextView textView = (TextView) findViewById(R.id.inputResult); textView.setText(outState.getString("inputResultat")); limpiar = outState.getBoolean("limpiar"); calculadora = new Calculadora(); calculadora.setResultat(outState.getDouble("resultat")); calculadora.setOperador(outState.getString("operador")); } /* Funciones privadas */ private boolean pulsacioNumero(View v, TextView textView) { switch (v.getId()) { case R.id.buttonNumber0: anadirNumero("0", textView); break; case R.id.buttonNumber1: anadirNumero("1", textView); break; case R.id.buttonNumber2: anadirNumero("2", textView); break; case R.id.buttonNumber3: anadirNumero("3", textView); break; case R.id.buttonNumber4: anadirNumero("4", textView); break; case R.id.buttonNumber5: anadirNumero("5", textView); break; case R.id.buttonNumber6: anadirNumero("6", textView); break; case R.id.buttonNumber7: anadirNumero("7", textView); break; case R.id.buttonNumber8: anadirNumero("8", textView); break; case R.id.buttonNumber9: anadirNumero("9", textView); break; default: return false; } return true; } private boolean pulsacioOperador(View v, TextView textView) { if (comprobarCampos(textView)) { Double valor = Double.valueOf(textView.getText().toString()); switch (v.getId()) { case R.id.buttonSuma: if (calculadora.setResultat(valor, textView)) { textView.setText(calculadora.getResultat().toString()); } calculadora.setOperador("+"); limpiar = true; break; case R.id.buttonResta: if (calculadora.setResultat(valor, textView)) { textView.setText(calculadora.getResultat().toString()); } calculadora.setOperador("-"); limpiar = true; break; case R.id.buttonMultiplicacio: if (calculadora.setResultat(valor, textView)) { textView.setText(calculadora.getResultat().toString()); } calculadora.setOperador("*"); limpiar = true; break; case R.id.buttonDivisio: if (calculadora.setResultat(valor, textView)) { textView.setText(calculadora.getResultat().toString()); } calculadora.setOperador("/"); limpiar = true; break; case R.id.buttonIgual: if (calculadora.setResultat(valor, textView)) { textView.setText(calculadora.getResultat().toString()); } calculadora.setOperador(null); limpiar = true; break; case R.id.buttonClearCalculator: calculadora.setResultat(null); calculadora.setOperador(null); limpiar = true; textView.setText("0"); break; } } return true; } private boolean comprobarCampos(TextView input) { if (input.getText().toString().equals("")) { return false; } return true; } private void anadirNumero(String numero, TextView vista) { String aux = vista.getText().toString(); if (limpiar) { limpiar = false; aux = ""; } aux = aux.concat(numero); vista.setText(aux); } }
7,589
0.693372
0.68652
276
25.496376
21.190903
73
false
false
0
0
0
0
0
0
2.438406
false
false
3
ba32754cc9b033d5237e862dfa2b4d876e2a2fa8
29,549,375,042,541
74e42af4f1ef560d4d510dd933b5cadc78886bf1
/src/main/java/com/kobe/spider/SpiderBootStrap.java
7bba9df94a9c723384cb59847b8c3f5103693d3c
[]
no_license
kobelv/mySpider
https://github.com/kobelv/mySpider
4f936e987e6c3bee37836cb7de9b9a1f405c46d2
6c99264ec3d2a25fd91693fc130a4405f4ce3274
refs/heads/master
2020-03-22T10:41:01.739000
2018-07-06T01:53:30
2018-07-06T01:53:30
139,919,748
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kobe.spider; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.kobe.spider.cache.Cache; import com.kobe.spider.constants.Constants; import com.kobe.spider.crawler.Crawler; import com.kobe.spider.parser.Parser; import com.kobe.spider.repository.Repository; import com.kobe.spider.utility.JedisUtility; import com.kobe.spider.utility.Utility; import redis.clients.jedis.Jedis; public class SpiderBootStrap { private Logger logger = LoggerFactory.getLogger(SpiderBootStrap.class); private Crawler crawler; private Map<String, Parser> parsers = new HashMap<>(); private Repository repository; private List<String> seedUrls = new ArrayList<>(); private Cache cache; private Map<String, String> urlLevels = new HashMap<>(); public SpiderBootStrap setCrawler(Crawler crawler){ this.crawler = crawler; return this; } public SpiderBootStrap setDomainUrl(String...dormainUrl){ Jedis jedis = JedisUtility.getJedis(); jedis.del(Constants.REDIS_KEY_DOMAINURLS); for(String tempStr : dormainUrl){ jedis.sadd(Constants.REDIS_KEY_DOMAINURLS, tempStr); } JedisUtility.returnJedis(jedis); return this; } public SpiderBootStrap addParser(String domain, Parser parser){ parsers.put(domain, parser); return this; } public SpiderBootStrap addUrlLevel(String id, String url){ urlLevels.put(id, url); return this; } public SpiderBootStrap setRepository(Repository repository){ this.repository = repository; return this; } public SpiderBootStrap setCache(Cache cache){ this.cache = cache; return this; } public SpiderBootStrap setSeedUrls(String... url){ for(String tmpStr : url){ this.seedUrls.add(tmpStr); } return this; } public void start(){ registerZooKeeper(); processInParallel(); } private void processInParallel() { ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(Constants.THREAD_POOL_SIZE); for(int i=0; i<Constants.THREAD_POOL_SIZE; i++){ executor.execute(new Runnable(){ @Override public void run() { process(); } private void process() { String url = cache.getNextAvailableUrl(); if(null != url){ Page page = crawler.download(url); String domain = Utility.getTopDomain(url); if(page.getContent() != null){ parsers.get(domain).parse(page); for(String urlInPage : page.getUrls()){ String higherUrl = urlLevels.get(domain+Constants.REDIS_KEY_SUFFIX_HIGHER); String lowerUrl = urlLevels.get(domain+Constants.REDIS_KEY_SUFFIX_LOWER); if (urlInPage.startsWith(higherUrl)) { cache.saveUrlLevelInfo(urlInPage, Constants.REDIS_KEY_SUFFIX_HIGHER); } else if (urlInPage.startsWith(lowerUrl)) { cache.saveUrlLevelInfo(urlInPage, Constants.REDIS_KEY_SUFFIX_LOWER); } } if(page.getId() != null){ repository.save(page); } } Utility.sleep(1000); } else { logger.info("no url anymore, pls add soon."); Utility.sleep(1000); } } }); } } private void registerZooKeeper() { // TODO Auto-generated method stub } }
UTF-8
Java
3,541
java
SpiderBootStrap.java
Java
[]
null
[]
package com.kobe.spider; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.kobe.spider.cache.Cache; import com.kobe.spider.constants.Constants; import com.kobe.spider.crawler.Crawler; import com.kobe.spider.parser.Parser; import com.kobe.spider.repository.Repository; import com.kobe.spider.utility.JedisUtility; import com.kobe.spider.utility.Utility; import redis.clients.jedis.Jedis; public class SpiderBootStrap { private Logger logger = LoggerFactory.getLogger(SpiderBootStrap.class); private Crawler crawler; private Map<String, Parser> parsers = new HashMap<>(); private Repository repository; private List<String> seedUrls = new ArrayList<>(); private Cache cache; private Map<String, String> urlLevels = new HashMap<>(); public SpiderBootStrap setCrawler(Crawler crawler){ this.crawler = crawler; return this; } public SpiderBootStrap setDomainUrl(String...dormainUrl){ Jedis jedis = JedisUtility.getJedis(); jedis.del(Constants.REDIS_KEY_DOMAINURLS); for(String tempStr : dormainUrl){ jedis.sadd(Constants.REDIS_KEY_DOMAINURLS, tempStr); } JedisUtility.returnJedis(jedis); return this; } public SpiderBootStrap addParser(String domain, Parser parser){ parsers.put(domain, parser); return this; } public SpiderBootStrap addUrlLevel(String id, String url){ urlLevels.put(id, url); return this; } public SpiderBootStrap setRepository(Repository repository){ this.repository = repository; return this; } public SpiderBootStrap setCache(Cache cache){ this.cache = cache; return this; } public SpiderBootStrap setSeedUrls(String... url){ for(String tmpStr : url){ this.seedUrls.add(tmpStr); } return this; } public void start(){ registerZooKeeper(); processInParallel(); } private void processInParallel() { ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(Constants.THREAD_POOL_SIZE); for(int i=0; i<Constants.THREAD_POOL_SIZE; i++){ executor.execute(new Runnable(){ @Override public void run() { process(); } private void process() { String url = cache.getNextAvailableUrl(); if(null != url){ Page page = crawler.download(url); String domain = Utility.getTopDomain(url); if(page.getContent() != null){ parsers.get(domain).parse(page); for(String urlInPage : page.getUrls()){ String higherUrl = urlLevels.get(domain+Constants.REDIS_KEY_SUFFIX_HIGHER); String lowerUrl = urlLevels.get(domain+Constants.REDIS_KEY_SUFFIX_LOWER); if (urlInPage.startsWith(higherUrl)) { cache.saveUrlLevelInfo(urlInPage, Constants.REDIS_KEY_SUFFIX_HIGHER); } else if (urlInPage.startsWith(lowerUrl)) { cache.saveUrlLevelInfo(urlInPage, Constants.REDIS_KEY_SUFFIX_LOWER); } } if(page.getId() != null){ repository.save(page); } } Utility.sleep(1000); } else { logger.info("no url anymore, pls add soon."); Utility.sleep(1000); } } }); } } private void registerZooKeeper() { // TODO Auto-generated method stub } }
3,541
0.672127
0.66902
125
27.327999
24.554193
105
false
false
0
0
0
0
0
0
2.512
false
false
3
1c7a212ab472ed5eeed0ffe29199dc585a668fe2
24,627,342,527,572
a37366bb899b43eaa289d27626c3fefe9d2d534e
/online-bookstore-server/microservice-bookstore-order/src/main/java/com/onlinebookstore/util/rocketmq/RocketMQMessageSendUtils.java
f8a89801547a13a8b2687d714c25afb7e3c6c6f8
[ "Apache-2.0" ]
permissive
egret-al/onlineBookStore
https://github.com/egret-al/onlineBookStore
c2f8cc5d091a60a0c6f8e282bd0e70a0c13dfd19
035217a449378bb56912d99be4a3f6c10adaa486
refs/heads/master
2023-02-20T05:52:38.106000
2021-01-20T13:39:10
2021-01-20T13:39:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.onlinebookstore.util.rocketmq; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import org.apache.rocketmq.client.producer.DefaultMQProducer; import org.apache.rocketmq.client.producer.SendCallback; import org.apache.rocketmq.client.producer.SendResult; import org.apache.rocketmq.common.message.Message; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.ObjectUtils; import javax.annotation.Resource; /** * @author rkc * @version 1.0 * @date 2020/12/2 9:36 */ @Slf4j @Component public class RocketMQMessageSendUtils { @Autowired private DefaultMQProducer rocketMqProducer; /** * 发送普通消息 * @param topic topic * @param tag tag * @param body 消息体 * @return 是否成功 */ public boolean sendNormalMessage(String topic, String tag, Object body) { Message message = new Message(topic, tag, JSON.toJSONBytes(body)); try { SendResult sendResult = rocketMqProducer.send(message); if (!ObjectUtils.isEmpty(sendResult)) { log.info("普通消息发送成功"); return true; } else { return false; } } catch (Exception e) { log.error("普通消息发送失败:" + e.getMessage()); e.printStackTrace(); return false; } } /** * 发送普通延时消息 * @param topic topic * @param tag tag * @param body 消息体 * @param level 延时等级,从1开始:1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h * @return 是否发送成功 */ public boolean sendNormalDelayMessage(String topic, String tag, Object body, int level) { Message message = new Message(topic, tag, JSON.toJSONBytes(body)); //设置延时 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h message.setDelayTimeLevel(level); try { SendResult sendResult = rocketMqProducer.send(message); if (!ObjectUtils.isEmpty(sendResult)) { log.info("延时消息发送成功"); return true; } else { return false; } } catch (Exception e) { log.error("延时消息发送失败:" + e.getMessage()); return false; } } /** * 异步发送消息 * @param topic topic * @param tag tag * @param body 消息体 * @param sendCallback 发送消息失败或者成功后的回调接口,业务逻辑需要实现这个接口,并且作为参数传入进来 */ public void sendMessageAsync(String topic, String tag, Object body, SendCallback sendCallback) { Message message = new Message(topic, tag, JSON.toJSONBytes(body)); try { rocketMqProducer.send(message, sendCallback); } catch (Exception e) { log.error("异步消息发送失败:" + e.getMessage()); } } /** * 异步发送延迟消息 * @param topic topic * @param tag tag * @param body 消息体 * @param sendCallback 发送消息失败或者成功后的回调接口,业务逻辑需要实现这个接口,并且作为参数传入进来 * @param level 延时等级,从1开始:1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h */ public void sendDelayMessageAsync(String topic, String tag, Object body, SendCallback sendCallback, int level) { Message message = new Message(topic, tag, JSON.toJSONBytes(body)); message.setDelayTimeLevel(level); try { rocketMqProducer.send(message, sendCallback); } catch (Exception e) { log.error("异步消息发送失败:" + e.getMessage()); } } /** * sendOneWay:无需要等待响应,TPS最快,但是没有结果反馈且消息可能丢失 * @param topic topic * @param tag tag * @param body 消息体 */ public void sendOneWay(String topic, String tag, Object body) { Message message = new Message(topic, tag, JSON.toJSONBytes(body)); try { rocketMqProducer.sendOneway(message); } catch (Exception e) { log.error("OneWay"); } } }
UTF-8
Java
4,395
java
RocketMQMessageSendUtils.java
Java
[ { "context": "\nimport javax.annotation.Resource;\n\n/**\n * @author rkc\n * @version 1.0\n * @date 2020/12/2 9:36\n */\n@Slf4", "end": 548, "score": 0.9996170401573181, "start": 545, "tag": "USERNAME", "value": "rkc" } ]
null
[]
package com.onlinebookstore.util.rocketmq; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import org.apache.rocketmq.client.producer.DefaultMQProducer; import org.apache.rocketmq.client.producer.SendCallback; import org.apache.rocketmq.client.producer.SendResult; import org.apache.rocketmq.common.message.Message; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.ObjectUtils; import javax.annotation.Resource; /** * @author rkc * @version 1.0 * @date 2020/12/2 9:36 */ @Slf4j @Component public class RocketMQMessageSendUtils { @Autowired private DefaultMQProducer rocketMqProducer; /** * 发送普通消息 * @param topic topic * @param tag tag * @param body 消息体 * @return 是否成功 */ public boolean sendNormalMessage(String topic, String tag, Object body) { Message message = new Message(topic, tag, JSON.toJSONBytes(body)); try { SendResult sendResult = rocketMqProducer.send(message); if (!ObjectUtils.isEmpty(sendResult)) { log.info("普通消息发送成功"); return true; } else { return false; } } catch (Exception e) { log.error("普通消息发送失败:" + e.getMessage()); e.printStackTrace(); return false; } } /** * 发送普通延时消息 * @param topic topic * @param tag tag * @param body 消息体 * @param level 延时等级,从1开始:1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h * @return 是否发送成功 */ public boolean sendNormalDelayMessage(String topic, String tag, Object body, int level) { Message message = new Message(topic, tag, JSON.toJSONBytes(body)); //设置延时 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h message.setDelayTimeLevel(level); try { SendResult sendResult = rocketMqProducer.send(message); if (!ObjectUtils.isEmpty(sendResult)) { log.info("延时消息发送成功"); return true; } else { return false; } } catch (Exception e) { log.error("延时消息发送失败:" + e.getMessage()); return false; } } /** * 异步发送消息 * @param topic topic * @param tag tag * @param body 消息体 * @param sendCallback 发送消息失败或者成功后的回调接口,业务逻辑需要实现这个接口,并且作为参数传入进来 */ public void sendMessageAsync(String topic, String tag, Object body, SendCallback sendCallback) { Message message = new Message(topic, tag, JSON.toJSONBytes(body)); try { rocketMqProducer.send(message, sendCallback); } catch (Exception e) { log.error("异步消息发送失败:" + e.getMessage()); } } /** * 异步发送延迟消息 * @param topic topic * @param tag tag * @param body 消息体 * @param sendCallback 发送消息失败或者成功后的回调接口,业务逻辑需要实现这个接口,并且作为参数传入进来 * @param level 延时等级,从1开始:1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h */ public void sendDelayMessageAsync(String topic, String tag, Object body, SendCallback sendCallback, int level) { Message message = new Message(topic, tag, JSON.toJSONBytes(body)); message.setDelayTimeLevel(level); try { rocketMqProducer.send(message, sendCallback); } catch (Exception e) { log.error("异步消息发送失败:" + e.getMessage()); } } /** * sendOneWay:无需要等待响应,TPS最快,但是没有结果反馈且消息可能丢失 * @param topic topic * @param tag tag * @param body 消息体 */ public void sendOneWay(String topic, String tag, Object body) { Message message = new Message(topic, tag, JSON.toJSONBytes(body)); try { rocketMqProducer.sendOneway(message); } catch (Exception e) { log.error("OneWay"); } } }
4,395
0.610135
0.588235
125
30.416
25.476322
116
false
false
0
0
0
0
0
0
0.512
false
false
3
5b131a424d5ec40e5acf247676f3001b56cdaf8d
18,897,856,156,246
3bc67d2f04504e77d035a4792c289fa0d7233ce5
/app/src/androidTestRider/java/cases/s5_core_flow/s3_driver_arrived/s5_recovery/DriverArrivedRecoverySuite.java
a259e77176a633a13d6e20b256ad307fe342330f
[ "MIT" ]
permissive
hookoor/android
https://github.com/hookoor/android
5217c0c09f309a430b83cb3dc220c654f55cfb34
f58f57804f41061977e53238fc4535c262dabcd2
refs/heads/master
2022-02-21T16:54:13.549000
2019-09-23T17:43:48
2019-09-23T17:43:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cases.s5_core_flow.s3_driver_arrived.s5_recovery; import android.os.RemoteException; import android.support.test.filters.LargeTest; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.support.test.uiautomator.UiObjectNotFoundException; import com.rideaustin.BaseUITest; import com.rideaustin.R; import com.rideaustin.RaActivityRule; import com.rideaustin.RequestType; import com.rideaustin.RiderMockResponseFactory; import com.rideaustin.TestCases; import com.rideaustin.ui.drawer.NavigationDrawerActivity; import com.rideaustin.ui.utils.UIUtils; import com.rideaustin.utils.DeviceTestUtils; import com.rideaustin.utils.Matchers; import com.rideaustin.utils.NavigationUtils; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.swipeDown; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static com.rideaustin.utils.MatcherUtils.exists; import static com.rideaustin.utils.MatcherUtils.hasDrawable; import static com.rideaustin.utils.Matchers.condition; import static com.rideaustin.utils.ViewActionUtils.waitForCompletelyDisplayed; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.not; /** * Reference: RA-11582 * Created by Sergey Petrov on 05/07/2017. */ @LargeTest @RunWith(AndroidJUnit4.class) public class DriverArrivedRecoverySuite extends BaseUITest { @Rule public ActivityTestRule<NavigationDrawerActivity> activityRule = new RaActivityRule<>(NavigationDrawerActivity.class, false, false); @Override public void setUp() { super.setUp(); initMockResponseFactory(RiderMockResponseFactory.class); mockRequests(RequestType.GLOBAL_APP_INFO_200_GET, RequestType.LOGIN_SUCCESS_200_POST, RequestType.TOKENS_200_POST, RequestType.RIDER_DATA_NO_RIDE_200_GET, RequestType.DRIVER_TYPES_200_GET, RequestType.SURGE_AREA_EMPTY_200_GET, RequestType.CONFIG_RIDER_200_GET, RequestType.EVENTS_EMPTY_200_GET, RequestType.CONFIG_ZIPCODES_200_GET, RequestType.ACDR_REGULAR_200_GET, // has drivers RequestType.RIDE_CANCELLATION_SETTINGS_200_GET); } /** * C1930729: Put into background and bring back to foreground * C1930730: Lock, unlock device * C1930731: Switch off/on internet connection */ @Test @TestCases({"C1930729", "C1930730", "C1930731"}) public void test_Recovery() throws InterruptedException, RemoteException, UiObjectNotFoundException { NavigationUtils.startActivity(activityRule); // login NavigationUtils.throughLogin("valid@email.com", "whatever"); // request ride NavigationUtils.throughRideRequest(this); // simulate reached state NavigationUtils.toAssignedState(this); NavigationUtils.toReachedState(this); checkUiState(); //------------------------------------------------------------------------------------------ // C1930729: Put into background and bring back to foreground // C1930730: Lock, unlock device //------------------------------------------------------------------------------------------ DeviceTestUtils.pressHome(); DeviceTestUtils.restoreFromRecentApps(); checkUiState(); //------------------------------------------------------------------------------------------ // C1930731: Switch off/on internet connection //------------------------------------------------------------------------------------------ DeviceTestUtils.setWifiEnabled(false); DeviceTestUtils.pressHome(); DeviceTestUtils.restoreFromRecentApps(); tryCloseNetworkError(); checkUiState(); DeviceTestUtils.setWifiEnabled(true); tryCloseNetworkError(); DeviceTestUtils.pressHome(); DeviceTestUtils.restoreFromRecentApps(); checkUiState(); } private void checkUiState() throws InterruptedException { String name = "Ride15"; String rating = UIUtils.formatRating(5.0); String category = "STANDARD"; String car = "Blue Cadillac CTS Wagon"; String plate = "CADILLAC"; // check collapsed state onView(allOf(withId(R.id.driver_name_small), isDisplayed())).check(matches(withText(name))); onView(allOf(withId(R.id.driver_rate_small), isDisplayed())).check(matches(withText(rating))); onView(allOf(withId(R.id.car_category_small), isDisplayed())).check(matches(withText(category))); onView(allOf(withId(R.id.car_make_small), isDisplayed())).check(matches(withText(car))); onView(allOf(withId(R.id.car_plate_small), isDisplayed())).check(matches(withText(plate))); onView(allOf(withId(R.id.driver_image_small), isDisplayed())).check(matches(hasDrawable())); // tap on driver image should cause panel expand onView(withId(R.id.driver_image_small)).perform(click()); waitForCompletelyDisplayed(R.id.ride_details); Matchers.waitFor(condition("Driver small image should be hidden") .withMatcher(withId(R.id.driver_image_small)) .withCheck(not(isDisplayed()))); onView(withId(R.id.driver_name_small)).check(matches(not(isDisplayed()))); onView(withId(R.id.driver_rate_small)).check(matches(not(isDisplayed()))); onView(withId(R.id.car_category_small)).check(matches(not(isDisplayed()))); onView(withId(R.id.car_make_small)).check(matches(not(isDisplayed()))); onView(withId(R.id.car_plate_small)).check(matches(not(isDisplayed()))); // check expanded state onView(allOf(withId(R.id.tv_driver_name), isDisplayed())).check(matches(withText(name))); onView(allOf(withId(R.id.tv_driver_rate), isDisplayed())).check(matches(withText(rating))); onView(allOf(withId(R.id.car_category), isDisplayed())).check(matches(withText(category))); onView(allOf(withId(R.id.car_color_make_model), isDisplayed())).check(matches(withText(car))); onView(allOf(withId(R.id.car_plate), isDisplayed())).check(matches(withText(plate))); onView(allOf(withId(R.id.driver_image), isDisplayed())).check(matches(hasDrawable())); onView(allOf(withId(R.id.car_image), isDisplayed())).check(matches(hasDrawable())); // collapse panel onView(withId(R.id.ride_details)).perform(swipeDown()); Matchers.waitFor(condition("Driver small image should become visible") .withMatcher(withId(R.id.driver_image_small))); } private void tryCloseNetworkError() { if (exists(withText(R.string.network_error))) { onView(withId(R.id.md_buttonDefaultPositive)).perform(click()); } } }
UTF-8
Java
7,350
java
DriverArrivedRecoverySuite.java
Java
[ { "context": "ers.not;\n\n/**\n * Reference: RA-11582\n * Created by Sergey Petrov on 05/07/2017.\n */\n\n@LargeTest\n@RunWith(AndroidJU", "end": 1729, "score": 0.9998443722724915, "start": 1716, "tag": "NAME", "value": "Sergey Petrov" }, { "context": " // login\n NavigationUtils.throughLogin(\"valid@email.com\", \"whatever\");\n\n // request ride\n N", "end": 3197, "score": 0.999923050403595, "start": 3182, "tag": "EMAIL", "value": "valid@email.com" }, { "context": "ows InterruptedException {\n String name = \"Ride15\";\n String rating = UIUtils.formatRating(5.", "end": 4608, "score": 0.9967513680458069, "start": 4602, "tag": "USERNAME", "value": "Ride15" } ]
null
[]
package cases.s5_core_flow.s3_driver_arrived.s5_recovery; import android.os.RemoteException; import android.support.test.filters.LargeTest; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.support.test.uiautomator.UiObjectNotFoundException; import com.rideaustin.BaseUITest; import com.rideaustin.R; import com.rideaustin.RaActivityRule; import com.rideaustin.RequestType; import com.rideaustin.RiderMockResponseFactory; import com.rideaustin.TestCases; import com.rideaustin.ui.drawer.NavigationDrawerActivity; import com.rideaustin.ui.utils.UIUtils; import com.rideaustin.utils.DeviceTestUtils; import com.rideaustin.utils.Matchers; import com.rideaustin.utils.NavigationUtils; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.swipeDown; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static com.rideaustin.utils.MatcherUtils.exists; import static com.rideaustin.utils.MatcherUtils.hasDrawable; import static com.rideaustin.utils.Matchers.condition; import static com.rideaustin.utils.ViewActionUtils.waitForCompletelyDisplayed; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.not; /** * Reference: RA-11582 * Created by <NAME> on 05/07/2017. */ @LargeTest @RunWith(AndroidJUnit4.class) public class DriverArrivedRecoverySuite extends BaseUITest { @Rule public ActivityTestRule<NavigationDrawerActivity> activityRule = new RaActivityRule<>(NavigationDrawerActivity.class, false, false); @Override public void setUp() { super.setUp(); initMockResponseFactory(RiderMockResponseFactory.class); mockRequests(RequestType.GLOBAL_APP_INFO_200_GET, RequestType.LOGIN_SUCCESS_200_POST, RequestType.TOKENS_200_POST, RequestType.RIDER_DATA_NO_RIDE_200_GET, RequestType.DRIVER_TYPES_200_GET, RequestType.SURGE_AREA_EMPTY_200_GET, RequestType.CONFIG_RIDER_200_GET, RequestType.EVENTS_EMPTY_200_GET, RequestType.CONFIG_ZIPCODES_200_GET, RequestType.ACDR_REGULAR_200_GET, // has drivers RequestType.RIDE_CANCELLATION_SETTINGS_200_GET); } /** * C1930729: Put into background and bring back to foreground * C1930730: Lock, unlock device * C1930731: Switch off/on internet connection */ @Test @TestCases({"C1930729", "C1930730", "C1930731"}) public void test_Recovery() throws InterruptedException, RemoteException, UiObjectNotFoundException { NavigationUtils.startActivity(activityRule); // login NavigationUtils.throughLogin("<EMAIL>", "whatever"); // request ride NavigationUtils.throughRideRequest(this); // simulate reached state NavigationUtils.toAssignedState(this); NavigationUtils.toReachedState(this); checkUiState(); //------------------------------------------------------------------------------------------ // C1930729: Put into background and bring back to foreground // C1930730: Lock, unlock device //------------------------------------------------------------------------------------------ DeviceTestUtils.pressHome(); DeviceTestUtils.restoreFromRecentApps(); checkUiState(); //------------------------------------------------------------------------------------------ // C1930731: Switch off/on internet connection //------------------------------------------------------------------------------------------ DeviceTestUtils.setWifiEnabled(false); DeviceTestUtils.pressHome(); DeviceTestUtils.restoreFromRecentApps(); tryCloseNetworkError(); checkUiState(); DeviceTestUtils.setWifiEnabled(true); tryCloseNetworkError(); DeviceTestUtils.pressHome(); DeviceTestUtils.restoreFromRecentApps(); checkUiState(); } private void checkUiState() throws InterruptedException { String name = "Ride15"; String rating = UIUtils.formatRating(5.0); String category = "STANDARD"; String car = "Blue Cadillac CTS Wagon"; String plate = "CADILLAC"; // check collapsed state onView(allOf(withId(R.id.driver_name_small), isDisplayed())).check(matches(withText(name))); onView(allOf(withId(R.id.driver_rate_small), isDisplayed())).check(matches(withText(rating))); onView(allOf(withId(R.id.car_category_small), isDisplayed())).check(matches(withText(category))); onView(allOf(withId(R.id.car_make_small), isDisplayed())).check(matches(withText(car))); onView(allOf(withId(R.id.car_plate_small), isDisplayed())).check(matches(withText(plate))); onView(allOf(withId(R.id.driver_image_small), isDisplayed())).check(matches(hasDrawable())); // tap on driver image should cause panel expand onView(withId(R.id.driver_image_small)).perform(click()); waitForCompletelyDisplayed(R.id.ride_details); Matchers.waitFor(condition("Driver small image should be hidden") .withMatcher(withId(R.id.driver_image_small)) .withCheck(not(isDisplayed()))); onView(withId(R.id.driver_name_small)).check(matches(not(isDisplayed()))); onView(withId(R.id.driver_rate_small)).check(matches(not(isDisplayed()))); onView(withId(R.id.car_category_small)).check(matches(not(isDisplayed()))); onView(withId(R.id.car_make_small)).check(matches(not(isDisplayed()))); onView(withId(R.id.car_plate_small)).check(matches(not(isDisplayed()))); // check expanded state onView(allOf(withId(R.id.tv_driver_name), isDisplayed())).check(matches(withText(name))); onView(allOf(withId(R.id.tv_driver_rate), isDisplayed())).check(matches(withText(rating))); onView(allOf(withId(R.id.car_category), isDisplayed())).check(matches(withText(category))); onView(allOf(withId(R.id.car_color_make_model), isDisplayed())).check(matches(withText(car))); onView(allOf(withId(R.id.car_plate), isDisplayed())).check(matches(withText(plate))); onView(allOf(withId(R.id.driver_image), isDisplayed())).check(matches(hasDrawable())); onView(allOf(withId(R.id.car_image), isDisplayed())).check(matches(hasDrawable())); // collapse panel onView(withId(R.id.ride_details)).perform(swipeDown()); Matchers.waitFor(condition("Driver small image should become visible") .withMatcher(withId(R.id.driver_image_small))); } private void tryCloseNetworkError() { if (exists(withText(R.string.network_error))) { onView(withId(R.id.md_buttonDefaultPositive)).perform(click()); } } }
7,335
0.667075
0.65102
172
41.732559
32.219063
136
false
false
0
0
0
0
0
0
0.680233
false
false
3
337cb6edf574688c3770ba3867e0a246f171f745
12,094,627,963,139
464a2241ca82e34f4bf805207de74b2dbcb67587
/stock-quote-manager/src/test/java/com/leonardo/stockquotemanager/service/CacheServiceTest.java
b3a4abd715322fe53c82597667ca6064d17bb6df
[]
no_license
AleixoLeonardo/stock-quote-manager
https://github.com/AleixoLeonardo/stock-quote-manager
740d7e64eb5d91624014fe93d67a274ca1bb7672
bf1673ea91d9fc0b56ea287a18dece616466aedb
refs/heads/main
2023-02-15T08:41:47.706000
2021-01-16T23:20:45
2021-01-16T23:20:45
330,271,990
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.leonardo.stockquotemanager.service; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cache.CacheManager; import com.leonardo.stockquotemanager.service.CacheService; @SpringBootTest public class CacheServiceTest { @Autowired private CacheService cacheService; @Autowired private CacheManager cacheManager; @Test public void checkIfCacheIsClear() { cacheService.clearCacheStock(); cacheManager.getCache("stock-cache"); } }
UTF-8
Java
590
java
CacheServiceTest.java
Java
[]
null
[]
package com.leonardo.stockquotemanager.service; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cache.CacheManager; import com.leonardo.stockquotemanager.service.CacheService; @SpringBootTest public class CacheServiceTest { @Autowired private CacheService cacheService; @Autowired private CacheManager cacheManager; @Test public void checkIfCacheIsClear() { cacheService.clearCacheStock(); cacheManager.getCache("stock-cache"); } }
590
0.818644
0.818644
24
23.583334
21.297333
62
false
false
0
0
0
0
0
0
1
false
false
3
e75d52e73136ce55062b6af3c3dd934d66f7cab2
6,777,458,448,998
b1af0aa7a46d2caa5db8d8b736815e2d3697f594
/cb/array-1/firstLast6/Main.java
ffc55858c75470b4cdeb4e4cfabd50fc711eb303
[]
no_license
lnafiz/apcs-2
https://github.com/lnafiz/apcs-2
ad98bcb142552a07940b81d4cdf301408327486c
3dd31c79face34b014c2f9e88a5cc9848f93fa63
refs/heads/main
2023-09-03T12:57:15.663000
2021-11-19T17:31:08
2021-11-19T17:31:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// https://codingbat.com/prob/p185685 public class Main { public static void main(String[] args) { int[] test1 = {1,2,6}; int[] test2 = {6,1,2,3}; int[] test3 = {13,6,1,2,3}; System.out.println(firstLast6(test1)); // true System.out.println(firstLast6(test2)); // true System.out.println(firstLast6(test3)); // false } /* Given an array of ints, return true if 6 appears as either the first or last element in the array. The array will be length 1 or more. */ public static boolean firstLast6(int[] nums) { if (nums[0] == 6 || nums[nums.length -1] == 6){ return true; } return false; } }
UTF-8
Java
698
java
Main.java
Java
[]
null
[]
// https://codingbat.com/prob/p185685 public class Main { public static void main(String[] args) { int[] test1 = {1,2,6}; int[] test2 = {6,1,2,3}; int[] test3 = {13,6,1,2,3}; System.out.println(firstLast6(test1)); // true System.out.println(firstLast6(test2)); // true System.out.println(firstLast6(test3)); // false } /* Given an array of ints, return true if 6 appears as either the first or last element in the array. The array will be length 1 or more. */ public static boolean firstLast6(int[] nums) { if (nums[0] == 6 || nums[nums.length -1] == 6){ return true; } return false; } }
698
0.574499
0.524355
26
25.846153
20.728451
57
false
false
0
0
0
0
0
0
0.769231
false
false
3
da3a45115760f623db6194d74877c490c976ed7c
20,933,670,661,102
ede49ff8cd01793c0c6fe6caaef8567db128bb26
/src/main/java/com/roof/sql/literal/FloatLiteral.java
ec8875eedf7b3972276629e244045cdb7a3d6d69
[ "Apache-2.0" ]
permissive
theoneroof/PreparedSquiggle
https://github.com/theoneroof/PreparedSquiggle
921e0587402c21677000d77a8e640de0b18ee7a9
c0a4ea0c552a5d13271bc19472ed18c4c1dff350
refs/heads/master
2016-08-09T02:43:35.397000
2015-12-09T17:53:37
2015-12-09T17:53:37
47,646,283
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.roof.sql.literal; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.concurrent.atomic.AtomicInteger; public class FloatLiteral extends LiteralWithSameRepresentationInJavaAndSql { public FloatLiteral(double literalValue) { super(new Double(literalValue)); } @Override public void processPrepared(PreparedStatement statement, AtomicInteger index) { try { statement.setFloat(index.getAndIncrement(), Float.valueOf((String) literalValue)); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
UTF-8
Java
785
java
FloatLiteral.java
Java
[]
null
[]
package com.roof.sql.literal; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.concurrent.atomic.AtomicInteger; public class FloatLiteral extends LiteralWithSameRepresentationInJavaAndSql { public FloatLiteral(double literalValue) { super(new Double(literalValue)); } @Override public void processPrepared(PreparedStatement statement, AtomicInteger index) { try { statement.setFloat(index.getAndIncrement(), Float.valueOf((String) literalValue)); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
785
0.678981
0.678981
25
30.4
26.275463
94
false
false
0
0
0
0
0
0
0.4
false
false
3
31b92a713cec0b3951b75e228d41515bc87b38fd
32,469,952,819,844
a752f4341b8b563128bb05f01e8e96e2b7038182
/src/main/java/com/luxoft/intern/parser/TextParser.java
3abfb4f6b96d46ac4dabb2507102502d88fca757
[]
no_license
KoV96/TextParser
https://github.com/KoV96/TextParser
2062d0110ed517082d4f2e5053181569c30bba83
0b037fc621d0543cfe8b20a441c7c57eba951001
refs/heads/master
2023-07-02T12:39:58.754000
2021-08-02T13:22:47
2021-08-02T13:22:47
391,912,213
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main.java.com.luxoft.intern.parser; import java.io.*; import java.util.*; import java.util.logging.Logger; /** * This class must have functionality of parsing text and count * how many times each word found in that text */ public class TextParser { private final Logger log = Logger.getLogger(TextParser.class.getName()); public Map<String, Integer> wordCounter(String fileName) { Map<String, Integer> map = new HashMap<>(); try (Scanner scanner = new Scanner(new File(fileName))) { while (scanner.hasNextLine()) { Arrays.stream(scanner.next().toLowerCase().split(" +\\n?")).forEach( w -> { if (map.containsKey(w)) { map.put(w, map.get(w) + 1); } else { map.put(w, 1); } } ); } } catch (FileNotFoundException e) { log.severe("File not found!!!" + e.getMessage()); } return map; } }
UTF-8
Java
1,112
java
TextParser.java
Java
[]
null
[]
package main.java.com.luxoft.intern.parser; import java.io.*; import java.util.*; import java.util.logging.Logger; /** * This class must have functionality of parsing text and count * how many times each word found in that text */ public class TextParser { private final Logger log = Logger.getLogger(TextParser.class.getName()); public Map<String, Integer> wordCounter(String fileName) { Map<String, Integer> map = new HashMap<>(); try (Scanner scanner = new Scanner(new File(fileName))) { while (scanner.hasNextLine()) { Arrays.stream(scanner.next().toLowerCase().split(" +\\n?")).forEach( w -> { if (map.containsKey(w)) { map.put(w, map.get(w) + 1); } else { map.put(w, 1); } } ); } } catch (FileNotFoundException e) { log.severe("File not found!!!" + e.getMessage()); } return map; } }
1,112
0.499101
0.497302
33
32.696968
23.944994
84
false
false
0
0
0
0
0
0
0.454545
false
false
3
d1cfd7bdd0a57dfb8e43d000dd98ed8bc382181a
13,030,930,836,818
6d946d77febba89d84266ccd747ede7712f30016
/src/main/java/com/hch/dao/UserDao.java
f73e12a3c0502b739ecb31396d7709f94b665da8
[]
no_license
hch814/springboot-practice
https://github.com/hch814/springboot-practice
55412a6918deeb2c9fd84738c4dba4d434b04302
519fc488ad5cb1ebe2baa5fdc1ed949ab7c35023
refs/heads/master
2023-03-13T22:57:12.942000
2021-03-12T14:56:11
2021-03-12T14:56:11
234,901,522
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hch.dao; import com.hch.pojo.po.UserDO; import org.apache.ibatis.annotations.*; import java.util.List; /** * @author hch * @since 2020/8/16 */ @Mapper public interface UserDao { @Select("SELECT * FROM tbl_user") List<UserDO> listUsers(); void insertUser(UserDO userDO); }
UTF-8
Java
303
java
UserDao.java
Java
[ { "context": "tations.*;\n\nimport java.util.List;\n\n/**\n * @author hch\n * @since 2020/8/16\n */\n@Mapper\npublic interface ", "end": 136, "score": 0.9996496438980103, "start": 133, "tag": "USERNAME", "value": "hch" } ]
null
[]
package com.hch.dao; import com.hch.pojo.po.UserDO; import org.apache.ibatis.annotations.*; import java.util.List; /** * @author hch * @since 2020/8/16 */ @Mapper public interface UserDao { @Select("SELECT * FROM tbl_user") List<UserDO> listUsers(); void insertUser(UserDO userDO); }
303
0.683168
0.660066
18
15.833333
14.000992
39
false
false
0
0
0
0
0
0
0.333333
false
false
3
abe95ff31e4188b21ca62eb4750fc4daee0241fc
25,769,803,845,238
3b65561c4113544cd0b410cc44cc96d3531023f6
/taier-common/src/main/java/com/dtstack/taier/common/util/Xml2JsonUtil.java
c6b5e114a1d717c6382993684ffee3ed621b5720
[ "Apache-2.0" ]
permissive
DTStack/Taier
https://github.com/DTStack/Taier
2bc168d802b028f669131017c996d61286d4f2db
5116f9ee195ee0c53b75ddf9724b0dedc62e6b4c
refs/heads/master
2023-09-04T02:42:02.266000
2023-08-10T05:51:36
2023-08-10T05:51:36
343,649,088
1,195
308
Apache-2.0
false
2023-09-10T11:35:57
2021-03-02T04:49:33
2023-09-09T08:20:07
2023-09-10T11:35:52
153,991
1,187
288
57
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 com.dtstack.taier.common.util; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.QName; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.dom4j.tree.DefaultElement; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * company: www.dtstack.com * author: toutian * create: 2018/7/20 */ public class Xml2JsonUtil { private final static String PROPERTY = "property"; /** * xml转map */ public static Map<String, Object> xml2map(File xmlFile) throws Exception { JSONObject json = xml2Json(xmlFile); if (json.containsKey(PROPERTY)) { Object o = json.get(PROPERTY); JSONArray jsona; if (o instanceof JSONObject) { JSONObject jsono = (JSONObject) o; jsona = new JSONArray(); jsona.add(jsono); } else if (o instanceof JSONArray) { jsona = (JSONArray) o; } else { return Collections.emptyMap(); } Map<String, Object> map = new HashMap<>(jsona.size()); for (Object obj : jsona) { Map subMap = (Map) obj; map.put(subMap.get("name").toString(), subMap.get("value")); } return map; } return Collections.emptyMap(); } /** * xml转json * * @throws DocumentException */ public static JSONObject xml2Json(File xmlFile) throws Exception { String xmlStr = readFile(xmlFile); Document doc = DocumentHelper.parseText(xmlStr); JSONObject json = new JSONObject(); dom4j2Json(doc.getRootElement(), json); return json; } public static String readFile(File file) throws IOException { String str = null; FileChannel fc = null; FileInputStream fis = null; try { fis = new FileInputStream(file); fc = fis.getChannel(); ByteBuffer bb = ByteBuffer.allocate(new Long(file.length()).intValue()); fc.read(bb); bb.flip(); str = new String(bb.array(), "UTF8"); } catch (IOException e) { throw new IOException("读取文件失败"); } finally { if (null != fis) { try { fis.close(); } catch (IOException e) { } } if (null != fc) { try { fc.close(); } catch (IOException e) { } } } return str; } /** * xml转json * * @param element * @param json */ private static void dom4j2Json(Element element, JSONObject json) { //如果是属性 for (Object o : element.attributes()) { Attribute attr = (Attribute) o; if (!isEmpty(attr.getValue())) { json.put("@" + attr.getName(), attr.getValue()); } } List<Element> chdEl = element.elements(); if (chdEl.isEmpty() && !isEmpty(element.getText())) {//如果没有子元素,只有一个值 json.put(element.getName(), element.getText()); } for (Element e : chdEl) {//有子元素 if (!e.elements().isEmpty()) {//子元素也有子元素 JSONObject chdjson = new JSONObject(); dom4j2Json(e, chdjson); Object o = json.get(e.getName()); if (o != null) { JSONArray jsona = null; if (o instanceof JSONObject) {//如果此元素已存在,则转为jsonArray JSONObject jsono = (JSONObject) o; json.remove(e.getName()); jsona = new JSONArray(); jsona.add(jsono); jsona.add(chdjson); json.put(e.getName(), jsona); } if (o instanceof JSONArray) { jsona = (JSONArray) o; jsona.add(chdjson); } } else { if (!chdjson.isEmpty()) { json.put(e.getName(), chdjson); } } } else {//子元素没有子元素 for (Object o : element.attributes()) { Attribute attr = (Attribute) o; if (!isEmpty(attr.getValue())) { json.put("@" + attr.getName(), attr.getValue()); } } if (!e.getText().isEmpty() && !json.containsKey(e.getName())) { json.put(e.getName(), e.getText()); } } } } private static boolean isEmpty(String str) { if (str == null || str.trim().isEmpty() || "null".equals(str)) { return true; } return false; } /** * 添加配置信息到对于的xml文件中 * * @param xmlFile * @param extraConfig * @param isOverride 是否强制覆盖 * @throws Exception */ public static void addInfoIntoXml(File xmlFile, Map<String, Object> extraConfig, boolean isOverride) throws Exception { if (MapUtils.isEmpty(extraConfig)) { return; } SAXReader reader = new SAXReader(); Document read = reader.read(xmlFile); //得到根节点 Element root = read.getRootElement(); List<String> keys = new ArrayList<>(); List propertys = root.elements("property"); for (Object o : propertys) { Element e = (Element) o; if (CollectionUtils.isNotEmpty(e.elements())) { for (Object element : e.elements()) { if (element instanceof Element) { QName qName = ((DefaultElement) element).getQName(); if ("name".equalsIgnoreCase(qName.getName())) { keys.add(((Element) element).getText()); } } } } } for (String key : extraConfig.keySet()) { if (!keys.contains(key) || isOverride) { Element property = root.addElement("property"); Element name = property.addElement("name"); name.setText(key); Element value = property.addElement("value"); value.setText((String) extraConfig.get(key)); } } OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setEncoding("UTF-8"); XMLWriter xmlWriter = new XMLWriter(new FileWriter(xmlFile), outputFormat); xmlWriter.write(read); xmlWriter.close(); } }
UTF-8
Java
8,275
java
Xml2JsonUtil.java
Java
[ { "context": "l.Map;\n\n/**\n * company: www.dtstack.com\n * author: toutian\n * create: 2018/7/20\n */\npublic class Xml2JsonUti", "end": 1688, "score": 0.999100923538208, "start": 1681, "tag": "USERNAME", "value": "toutian" } ]
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 com.dtstack.taier.common.util; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.QName; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.dom4j.tree.DefaultElement; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * company: www.dtstack.com * author: toutian * create: 2018/7/20 */ public class Xml2JsonUtil { private final static String PROPERTY = "property"; /** * xml转map */ public static Map<String, Object> xml2map(File xmlFile) throws Exception { JSONObject json = xml2Json(xmlFile); if (json.containsKey(PROPERTY)) { Object o = json.get(PROPERTY); JSONArray jsona; if (o instanceof JSONObject) { JSONObject jsono = (JSONObject) o; jsona = new JSONArray(); jsona.add(jsono); } else if (o instanceof JSONArray) { jsona = (JSONArray) o; } else { return Collections.emptyMap(); } Map<String, Object> map = new HashMap<>(jsona.size()); for (Object obj : jsona) { Map subMap = (Map) obj; map.put(subMap.get("name").toString(), subMap.get("value")); } return map; } return Collections.emptyMap(); } /** * xml转json * * @throws DocumentException */ public static JSONObject xml2Json(File xmlFile) throws Exception { String xmlStr = readFile(xmlFile); Document doc = DocumentHelper.parseText(xmlStr); JSONObject json = new JSONObject(); dom4j2Json(doc.getRootElement(), json); return json; } public static String readFile(File file) throws IOException { String str = null; FileChannel fc = null; FileInputStream fis = null; try { fis = new FileInputStream(file); fc = fis.getChannel(); ByteBuffer bb = ByteBuffer.allocate(new Long(file.length()).intValue()); fc.read(bb); bb.flip(); str = new String(bb.array(), "UTF8"); } catch (IOException e) { throw new IOException("读取文件失败"); } finally { if (null != fis) { try { fis.close(); } catch (IOException e) { } } if (null != fc) { try { fc.close(); } catch (IOException e) { } } } return str; } /** * xml转json * * @param element * @param json */ private static void dom4j2Json(Element element, JSONObject json) { //如果是属性 for (Object o : element.attributes()) { Attribute attr = (Attribute) o; if (!isEmpty(attr.getValue())) { json.put("@" + attr.getName(), attr.getValue()); } } List<Element> chdEl = element.elements(); if (chdEl.isEmpty() && !isEmpty(element.getText())) {//如果没有子元素,只有一个值 json.put(element.getName(), element.getText()); } for (Element e : chdEl) {//有子元素 if (!e.elements().isEmpty()) {//子元素也有子元素 JSONObject chdjson = new JSONObject(); dom4j2Json(e, chdjson); Object o = json.get(e.getName()); if (o != null) { JSONArray jsona = null; if (o instanceof JSONObject) {//如果此元素已存在,则转为jsonArray JSONObject jsono = (JSONObject) o; json.remove(e.getName()); jsona = new JSONArray(); jsona.add(jsono); jsona.add(chdjson); json.put(e.getName(), jsona); } if (o instanceof JSONArray) { jsona = (JSONArray) o; jsona.add(chdjson); } } else { if (!chdjson.isEmpty()) { json.put(e.getName(), chdjson); } } } else {//子元素没有子元素 for (Object o : element.attributes()) { Attribute attr = (Attribute) o; if (!isEmpty(attr.getValue())) { json.put("@" + attr.getName(), attr.getValue()); } } if (!e.getText().isEmpty() && !json.containsKey(e.getName())) { json.put(e.getName(), e.getText()); } } } } private static boolean isEmpty(String str) { if (str == null || str.trim().isEmpty() || "null".equals(str)) { return true; } return false; } /** * 添加配置信息到对于的xml文件中 * * @param xmlFile * @param extraConfig * @param isOverride 是否强制覆盖 * @throws Exception */ public static void addInfoIntoXml(File xmlFile, Map<String, Object> extraConfig, boolean isOverride) throws Exception { if (MapUtils.isEmpty(extraConfig)) { return; } SAXReader reader = new SAXReader(); Document read = reader.read(xmlFile); //得到根节点 Element root = read.getRootElement(); List<String> keys = new ArrayList<>(); List propertys = root.elements("property"); for (Object o : propertys) { Element e = (Element) o; if (CollectionUtils.isNotEmpty(e.elements())) { for (Object element : e.elements()) { if (element instanceof Element) { QName qName = ((DefaultElement) element).getQName(); if ("name".equalsIgnoreCase(qName.getName())) { keys.add(((Element) element).getText()); } } } } } for (String key : extraConfig.keySet()) { if (!keys.contains(key) || isOverride) { Element property = root.addElement("property"); Element name = property.addElement("name"); name.setText(key); Element value = property.addElement("value"); value.setText((String) extraConfig.get(key)); } } OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setEncoding("UTF-8"); XMLWriter xmlWriter = new XMLWriter(new FileWriter(xmlFile), outputFormat); xmlWriter.write(read); xmlWriter.close(); } }
8,275
0.539011
0.534944
240
32.804165
22.156244
123
false
false
0
0
0
0
0
0
0.5375
false
false
3
07f25daa101e01ef32d5b257c51ae214c234fac9
26,749,056,362,447
ef9213aab41007f66aff607868b1d82d00a2d7ec
/src/main/java/com/br/ProvaAPI/services/UsuarioService.java
95484865780bf68e2c203f99ac62a6250135d468
[]
no_license
GleistonMachado/RestAPI_Java
https://github.com/GleistonMachado/RestAPI_Java
441a9d4650fc34b993848b88e512fb7f123541c6
a4e86d8ce4c3924fe84e34097fe4bd10d7f7d333
refs/heads/master
2023-06-24T19:41:48.215000
2021-07-21T14:22:19
2021-07-21T14:22:19
388,141,561
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.br.ProvaAPI.services; import java.util.List; import com.br.ProvaAPI.models.Usuario; public interface UsuarioService { public List<Usuario> findAll(); public Usuario find(Long id); public Usuario create(Usuario product); public Usuario update(Long id, Usuario product); public void delete(Long id); }
UTF-8
Java
321
java
UsuarioService.java
Java
[]
null
[]
package com.br.ProvaAPI.services; import java.util.List; import com.br.ProvaAPI.models.Usuario; public interface UsuarioService { public List<Usuario> findAll(); public Usuario find(Long id); public Usuario create(Usuario product); public Usuario update(Long id, Usuario product); public void delete(Long id); }
321
0.772586
0.772586
14
21.928572
17.198273
49
false
false
0
0
0
0
0
0
1
false
false
3
0ec3a6f7e4d515c7a33b4954b4f6570451966750
11,639,361,409,821
4d6e201e553e895d86692f0fd58c42fc1f75e750
/src/fr/uge/poo/paint/ex6/Point.java
0bdf8696c1ced2a0452fc84a0db1ddeb8f3bb705
[]
no_license
Gogo-IGM-BK/Design-Patterns
https://github.com/Gogo-IGM-BK/Design-Patterns
d65f372c2861c475439d1a0be096379c35d952d0
a59b7f370d4ab439c6c8c73e3b25391c0190e4f4
refs/heads/main
2023-08-28T16:56:32.569000
2021-11-03T22:05:25
2021-11-03T22:05:25
424,390,464
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.uge.poo.paint.ex6; public record Point (int x, int y) { @Override public String toString() { return x+" "+y; } public int distance (Point a) { return (a.x()-this.x)*(a.x()-this.x) + (a.y()-this.y)*(a.y()-this.y); } }
UTF-8
Java
268
java
Point.java
Java
[]
null
[]
package fr.uge.poo.paint.ex6; public record Point (int x, int y) { @Override public String toString() { return x+" "+y; } public int distance (Point a) { return (a.x()-this.x)*(a.x()-this.x) + (a.y()-this.y)*(a.y()-this.y); } }
268
0.526119
0.522388
15
16.933332
21.037954
77
false
false
0
0
0
0
0
0
0.266667
false
false
3
c934617b2557d6127c44a8f98a74411bb50e0d1c
21,483,426,441,956
c4d66f66859df1e8662ec615403c630507d6b9b8
/src/admin/Notice.java
5b4fbe2dd71669f19bb332dd6c3025120fb3d07d
[]
no_license
spy99007/palago
https://github.com/spy99007/palago
53c99013b6cd8bbe9b86913266c7b9b68882714e
98ad1aed2ab4d5915bdaa5f63fc11f5a1bc131b7
refs/heads/master
2023-05-12T12:53:11.698000
2021-06-04T09:08:38
2021-06-04T09:08:38
371,728,940
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package admin; import java.awt.*; import java.awt.event.*; import java.io.*; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.util.*; public class Notice extends JPanel { JPanel p = new JPanel(new BorderLayout()); JPanel p1 = new JPanel(new BorderLayout()); JPanel p2 = new JPanel(new GridLayout(1, 0, 10, 10)); JTextArea ta; JButton btWrite, btDelete, btView; MainPage mainF; NoticeWrite noticeWrite; NoticeSee noticesee; WriteMessage wrtiemessage; JTable table; Object[][] noticeData = { { null, null, null, null } }; String[] header = { "제목", "내용", "글쓴이", "작성일" }; DefaultTableModel model; ObjectOutputStream out; ObjectInputStream in; FileOutputStream fout; FileInputStream fin; // hashtable 생성 Hashtable<String, WriteMessage> noticeTable = new Hashtable<>(); public Notice(MainPage frame) { this.mainF = frame; add(p); p.add(p1, "Center"); p.add(p2, "South"); p.setBackground(Color.white); p1.setBackground(Color.white); noticeWrite=new NoticeWrite(this); btWrite = new JButton("글쓰기"); btDelete = new JButton("글삭제"); //btView = new JButton("글보기"); p2.add(btWrite); p2.add(btDelete); //p2.add(btView); btWrite.setBackground(new Color(50, 100, 170)); btWrite.setForeground(Color.white); btDelete.setBackground(Color.DARK_GRAY); btDelete.setForeground(Color.white); model = new DefaultTableModel(noticeData, header); table = new JTable(model); p1.add(new JScrollPane(table), "Center"); Handelr2 hand = new Handelr2(); btWrite.addActionListener(hand); btDelete.addMouseListener(hand); readFile("src/admin/notice.txt"); showNoticeTable(); noticesee=new NoticeSee(this); //더블클릭시 게시물보기 table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { mainF.setTitle("더블클릭"); table = (JTable)e.getComponent(); model = (DefaultTableModel)table.getModel(); //선택한 행 열번호를 알아냄 int nRow = table.getSelectedRow(); //int nColumn = table.getSelectedColumn(); //알아낸 행열번호를 통해서 각각의 값을 알아냄 Object viewtext = table.getValueAt(nRow,1);//열이름 //Object cValue = model.getValueAt(nRow, nColumn); //값 noticesee.ta.setText((String) viewtext); //WriteMessage wm=noticeTable.get(wrtiemessage); noticesee.pack(); noticesee.setVisible(true); // 행은 선택하고 열 고정 System.out.println(table.getValueAt(table.getSelectedRow(), 1)); // (행, 열) } }); }// 생성자------------------------------------------ // 해시테이블 모델전달,설정 public void showNoticeTable() { Collection<WriteMessage> cols = noticeTable.values(); if (cols == null) return; Iterator<WriteMessage> it = cols.iterator(); noticeData = new Object[noticeTable.size()][4]; System.out.println(noticeTable.size()); for (int i = 0; it.hasNext(); i++) { WriteMessage writeM = it.next(); noticeData[i][0] = writeM.getTitle(); noticeData[i][1] = writeM.getText(); noticeData[i][2] = writeM.getName(); noticeData[i][3] = writeM.getRegDate(); } model.setDataVector(noticeData, header); table.setModel(model); table.setRowHeight(20); table.setModel(model); }//////// public void shownotice() { int size = noticeTable.size(); ta.setText("제목\t내용\t글쓴이\t작성일\n"); ta.append("-------------\n"); Collection<WriteMessage> cols = noticeTable.values(); for (WriteMessage writeM : cols) { ta.append(writeM.getTitle() + "\t" + writeM.getText() + "\t" + writeM.getName() + "\t" + writeM.getRegDate() + "\n"); } ta.append("----------------------"); ta.append("게시글 등록완료: " + size + "개\n"); } //hashtable 게시물삭제 버튼 public void deletenotice() { int row=table.getSelectedRow(); if(row<0) { JOptionPane.showMessageDialog(p,"삭제할 글을 선택하세요"); //mainF.setTitle("삭제할 글을 선택하세요"); return; } String title=table.getValueAt(row, 0).toString(); System.out.println(title+"<<<<<"); WriteMessage wm=noticeTable.remove(title); System.out.println("wm=="+wm); saveFile("src/admin/notice.txt"); readFile("src/admin/notice.txt"); showNoticeTable(); JOptionPane.showMessageDialog(p, "삭제완료"); } class Handelr2 extends MouseAdapter implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // setTitle("As"); Object o = e.getSource(); if (o == btWrite) { noticeWrite.pack(); noticeWrite.setVisible(true); }else if(o == btDelete) { deletenotice(); } } // hashtable 클릭시 게시물삭제 @Override public void mousePressed(MouseEvent e) { mainF.setTitle("Daf"); Object o = e.getSource(); if(o==btDelete) { deletenotice(); } } }////////////////////////////////// // read 파일메소드 public void readFile(String fileName) { try { fin = new FileInputStream(fileName); in = new ObjectInputStream(fin); Object obj = in.readObject(); noticeTable = (Hashtable<String, WriteMessage>) obj; noticeWrite.setTitle("현재 등록된글: " + noticeTable.size()); } catch (Exception e) { noticeWrite.setTitle("읽는중 에러: " + e.getMessage()); } }/////////////////////////////////// // save 파일 메소드 public void saveFile(String fileName) { System.out.println("saveFile타는지....."+fileName); try { fout = new FileOutputStream(fileName); out = new ObjectOutputStream(fout); out.writeObject(noticeTable); out.flush(); out.close(); fout.close(); System.out.println("noticeWrite=="+noticeWrite); noticeWrite.setTitle(fileName + "저장 완료"); System.out.println(fileName + "에 저장완료"); } catch (IOException e) { noticeWrite.setTitle("저장중 에러발생: " + e.getMessage()); e.printStackTrace(); } } }/////////////////////////////////////////
UHC
Java
6,289
java
Notice.java
Java
[]
null
[]
package admin; import java.awt.*; import java.awt.event.*; import java.io.*; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.util.*; public class Notice extends JPanel { JPanel p = new JPanel(new BorderLayout()); JPanel p1 = new JPanel(new BorderLayout()); JPanel p2 = new JPanel(new GridLayout(1, 0, 10, 10)); JTextArea ta; JButton btWrite, btDelete, btView; MainPage mainF; NoticeWrite noticeWrite; NoticeSee noticesee; WriteMessage wrtiemessage; JTable table; Object[][] noticeData = { { null, null, null, null } }; String[] header = { "제목", "내용", "글쓴이", "작성일" }; DefaultTableModel model; ObjectOutputStream out; ObjectInputStream in; FileOutputStream fout; FileInputStream fin; // hashtable 생성 Hashtable<String, WriteMessage> noticeTable = new Hashtable<>(); public Notice(MainPage frame) { this.mainF = frame; add(p); p.add(p1, "Center"); p.add(p2, "South"); p.setBackground(Color.white); p1.setBackground(Color.white); noticeWrite=new NoticeWrite(this); btWrite = new JButton("글쓰기"); btDelete = new JButton("글삭제"); //btView = new JButton("글보기"); p2.add(btWrite); p2.add(btDelete); //p2.add(btView); btWrite.setBackground(new Color(50, 100, 170)); btWrite.setForeground(Color.white); btDelete.setBackground(Color.DARK_GRAY); btDelete.setForeground(Color.white); model = new DefaultTableModel(noticeData, header); table = new JTable(model); p1.add(new JScrollPane(table), "Center"); Handelr2 hand = new Handelr2(); btWrite.addActionListener(hand); btDelete.addMouseListener(hand); readFile("src/admin/notice.txt"); showNoticeTable(); noticesee=new NoticeSee(this); //더블클릭시 게시물보기 table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { mainF.setTitle("더블클릭"); table = (JTable)e.getComponent(); model = (DefaultTableModel)table.getModel(); //선택한 행 열번호를 알아냄 int nRow = table.getSelectedRow(); //int nColumn = table.getSelectedColumn(); //알아낸 행열번호를 통해서 각각의 값을 알아냄 Object viewtext = table.getValueAt(nRow,1);//열이름 //Object cValue = model.getValueAt(nRow, nColumn); //값 noticesee.ta.setText((String) viewtext); //WriteMessage wm=noticeTable.get(wrtiemessage); noticesee.pack(); noticesee.setVisible(true); // 행은 선택하고 열 고정 System.out.println(table.getValueAt(table.getSelectedRow(), 1)); // (행, 열) } }); }// 생성자------------------------------------------ // 해시테이블 모델전달,설정 public void showNoticeTable() { Collection<WriteMessage> cols = noticeTable.values(); if (cols == null) return; Iterator<WriteMessage> it = cols.iterator(); noticeData = new Object[noticeTable.size()][4]; System.out.println(noticeTable.size()); for (int i = 0; it.hasNext(); i++) { WriteMessage writeM = it.next(); noticeData[i][0] = writeM.getTitle(); noticeData[i][1] = writeM.getText(); noticeData[i][2] = writeM.getName(); noticeData[i][3] = writeM.getRegDate(); } model.setDataVector(noticeData, header); table.setModel(model); table.setRowHeight(20); table.setModel(model); }//////// public void shownotice() { int size = noticeTable.size(); ta.setText("제목\t내용\t글쓴이\t작성일\n"); ta.append("-------------\n"); Collection<WriteMessage> cols = noticeTable.values(); for (WriteMessage writeM : cols) { ta.append(writeM.getTitle() + "\t" + writeM.getText() + "\t" + writeM.getName() + "\t" + writeM.getRegDate() + "\n"); } ta.append("----------------------"); ta.append("게시글 등록완료: " + size + "개\n"); } //hashtable 게시물삭제 버튼 public void deletenotice() { int row=table.getSelectedRow(); if(row<0) { JOptionPane.showMessageDialog(p,"삭제할 글을 선택하세요"); //mainF.setTitle("삭제할 글을 선택하세요"); return; } String title=table.getValueAt(row, 0).toString(); System.out.println(title+"<<<<<"); WriteMessage wm=noticeTable.remove(title); System.out.println("wm=="+wm); saveFile("src/admin/notice.txt"); readFile("src/admin/notice.txt"); showNoticeTable(); JOptionPane.showMessageDialog(p, "삭제완료"); } class Handelr2 extends MouseAdapter implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // setTitle("As"); Object o = e.getSource(); if (o == btWrite) { noticeWrite.pack(); noticeWrite.setVisible(true); }else if(o == btDelete) { deletenotice(); } } // hashtable 클릭시 게시물삭제 @Override public void mousePressed(MouseEvent e) { mainF.setTitle("Daf"); Object o = e.getSource(); if(o==btDelete) { deletenotice(); } } }////////////////////////////////// // read 파일메소드 public void readFile(String fileName) { try { fin = new FileInputStream(fileName); in = new ObjectInputStream(fin); Object obj = in.readObject(); noticeTable = (Hashtable<String, WriteMessage>) obj; noticeWrite.setTitle("현재 등록된글: " + noticeTable.size()); } catch (Exception e) { noticeWrite.setTitle("읽는중 에러: " + e.getMessage()); } }/////////////////////////////////// // save 파일 메소드 public void saveFile(String fileName) { System.out.println("saveFile타는지....."+fileName); try { fout = new FileOutputStream(fileName); out = new ObjectOutputStream(fout); out.writeObject(noticeTable); out.flush(); out.close(); fout.close(); System.out.println("noticeWrite=="+noticeWrite); noticeWrite.setTitle(fileName + "저장 완료"); System.out.println(fileName + "에 저장완료"); } catch (IOException e) { noticeWrite.setTitle("저장중 에러발생: " + e.getMessage()); e.printStackTrace(); } } }/////////////////////////////////////////
6,289
0.616726
0.610293
221
24.728506
18.911285
111
false
false
0
0
0
0
0
0
2.656109
false
false
3
f039c07fc074a6c564840c5b1537b2bb68c263f8
15,642,270,920,141
f2159616f7435ae590533f4c685a84345e0e24c7
/demo/算法/src/负载均衡算法/随机/Random.java
dfccc1eb4722b83aa1446ba4791232692fd64708
[]
no_license
mxg694/project
https://github.com/mxg694/project
2ca4587a23943e15335de47a13ca9ec40089b639
a893b4eacbbec90f791151b3f01b3ce6d7614e9e
refs/heads/master
2022-12-23T11:07:27.542000
2020-08-04T09:44:42
2020-08-04T09:44:42
252,129,520
0
0
null
false
2022-12-16T09:41:20
2020-04-01T09:26:19
2020-08-04T09:42:47
2022-12-16T09:41:17
32,226
0
0
17
Java
false
false
package 负载均衡算法.随机; import cn.it.luban.负载均衡算法.ServiceIps; import java.util.ArrayList; import java.util.List; /** * author: mxg * * @author 17934 */ public class Random { public static void main(String[] args) { for (int i = 0; i < 4; i++) { System.out.println(getServer()); } } private static String getServer() { java.util.Random random = new java.util.Random(); int pos = random.nextInt(ServiceIps.list.size()); return ServiceIps.list.get(pos); } // 太耗时 权重随机算法 private static String getWeightServer() { List<String> ips = new ArrayList<>(); for (String key : ServiceIps.weight_list.keySet()) { Integer num = ServiceIps.weight_list.get(key); for (int i = 0; i < num; i++) { ips.add(key); } } java.util.Random random = new java.util.Random(); int pos = random.nextInt(ips.size()); return ips.get(pos); } /** * 更进一步: 判断权重是否一样,如果一样, 可以用简单的方法 * * @return */ private static String getWeightServer2() { Integer totalWeight = 0; for (Integer weight : ServiceIps.weight_list.values()) { totalWeight += weight; } java.util.Random random = new java.util.Random(); int pos = random.nextInt(totalWeight); for (String ip : ServiceIps.weight_list.keySet()) { Integer weight = ServiceIps.weight_list.get(ip); if (pos <= weight) { return ip; } pos -= weight; } return null; } }
UTF-8
Java
1,729
java
Random.java
Java
[ { "context": ".ArrayList;\nimport java.util.List;\n\n/**\n * author: mxg\n *\n * @author 17934\n */\npublic class Random {\n\n ", "end": 129, "score": 0.9996271133422852, "start": 126, "tag": "USERNAME", "value": "mxg" }, { "context": "java.util.List;\n\n/**\n * author: mxg\n *\n * @author 17934\n */\npublic class Random {\n\n public static void", "end": 149, "score": 0.9993481636047363, "start": 144, "tag": "USERNAME", "value": "17934" } ]
null
[]
package 负载均衡算法.随机; import cn.it.luban.负载均衡算法.ServiceIps; import java.util.ArrayList; import java.util.List; /** * author: mxg * * @author 17934 */ public class Random { public static void main(String[] args) { for (int i = 0; i < 4; i++) { System.out.println(getServer()); } } private static String getServer() { java.util.Random random = new java.util.Random(); int pos = random.nextInt(ServiceIps.list.size()); return ServiceIps.list.get(pos); } // 太耗时 权重随机算法 private static String getWeightServer() { List<String> ips = new ArrayList<>(); for (String key : ServiceIps.weight_list.keySet()) { Integer num = ServiceIps.weight_list.get(key); for (int i = 0; i < num; i++) { ips.add(key); } } java.util.Random random = new java.util.Random(); int pos = random.nextInt(ips.size()); return ips.get(pos); } /** * 更进一步: 判断权重是否一样,如果一样, 可以用简单的方法 * * @return */ private static String getWeightServer2() { Integer totalWeight = 0; for (Integer weight : ServiceIps.weight_list.values()) { totalWeight += weight; } java.util.Random random = new java.util.Random(); int pos = random.nextInt(totalWeight); for (String ip : ServiceIps.weight_list.keySet()) { Integer weight = ServiceIps.weight_list.get(ip); if (pos <= weight) { return ip; } pos -= weight; } return null; } }
1,729
0.54205
0.535912
66
23.681818
20.494019
64
false
false
0
0
0
0
0
0
0.393939
false
false
3
681966a8234ef13a8dc57fcd18435b39c4bda596
19,653,770,356,902
e59a0ed5e380c2b23a821af970c9c57f270651e5
/src/client/FtpClient.java
cc50802672338b52d7f28327284a4760ea4470bb
[]
no_license
zzlian/FTP_Server
https://github.com/zzlian/FTP_Server
02463973960735b031c002f79e944a9877b5ba72
bd56c7caa515f030e92aa33fad955511a499a589
refs/heads/master
2020-03-21T16:04:33.744000
2018-06-26T14:20:57
2018-06-26T14:20:57
138,749,169
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package client; import javax.swing.*; import java.io.*; import java.net.Socket; /** * 创建FTP客户端 * 使用socket与FTP服务器建立连接 */ public class FtpClient { private String userDir = System.getProperty("user.dir") + "\\src\\client\\clientDir"; // 默认下载文件路径 private PrintWriter writer; // 打印输出流 private Socket socket; private BufferedReader reader; public BufferedReader getReader() { return reader; } public void setReader(BufferedReader reader) { this.reader = reader; } public PrintWriter getWriter() { return writer; } public void setWriter(PrintWriter writer) { this.writer = writer; } public Socket getSocket() { return socket; } public void setSocket(Socket socket) { this.socket = socket; } public String getUserDir() { return userDir; } public void setUserDir(String userDir) { this.userDir = userDir; } // 建立连接 public boolean link(String IP, int PORT, JTextArea respInfo) throws IOException { String message; try { this.socket = new Socket(IP, PORT);// 建立连接 System.out.println("连接成功"); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new PrintWriter(socket.getOutputStream()); message = reader.readLine(); // 获取服务器响应的问候信息 respInfo.append(message + "\n"); // 显示收到的信息 return true; } catch (Exception e) { return false; } } }
UTF-8
Java
1,750
java
FtpClient.java
Java
[]
null
[]
package client; import javax.swing.*; import java.io.*; import java.net.Socket; /** * 创建FTP客户端 * 使用socket与FTP服务器建立连接 */ public class FtpClient { private String userDir = System.getProperty("user.dir") + "\\src\\client\\clientDir"; // 默认下载文件路径 private PrintWriter writer; // 打印输出流 private Socket socket; private BufferedReader reader; public BufferedReader getReader() { return reader; } public void setReader(BufferedReader reader) { this.reader = reader; } public PrintWriter getWriter() { return writer; } public void setWriter(PrintWriter writer) { this.writer = writer; } public Socket getSocket() { return socket; } public void setSocket(Socket socket) { this.socket = socket; } public String getUserDir() { return userDir; } public void setUserDir(String userDir) { this.userDir = userDir; } // 建立连接 public boolean link(String IP, int PORT, JTextArea respInfo) throws IOException { String message; try { this.socket = new Socket(IP, PORT);// 建立连接 System.out.println("连接成功"); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new PrintWriter(socket.getOutputStream()); message = reader.readLine(); // 获取服务器响应的问候信息 respInfo.append(message + "\n"); // 显示收到的信息 return true; } catch (Exception e) { return false; } } }
1,750
0.576593
0.576593
70
21.342857
22.778992
101
false
false
0
0
0
0
0
0
0.4
false
false
3
ad2e7c6d163e3d804fe2ed4fe142d1f3f4d4cff7
32,719,060,897,524
283e70345a6362755d82863139772734199dbd04
/src/main/java/org/clicker/domain/Student.java
8dc0c6112e9f3d93b7e0a0099950570f4ef9a781
[]
no_license
jekd96/akite
https://github.com/jekd96/akite
5c1869806e8f9010c3cd09f1040a873caf8c46ec
2e10da63e1e51e74f20e6f90454cde2d24c6390a
refs/heads/master
2021-01-10T09:03:33.807000
2016-03-18T18:17:14
2016-03-18T18:17:14
54,222,424
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.clicker.domain; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javax.persistence.*; import java.util.Date; /** * Created by Admin on 29.01.2016. */ @Entity @Table(name = "students") @Component @Scope("prototype") public class Student extends GenericEntity<Student> { @Column(name = "name") private String name; @Column(name = "surname") private String surname; @Column(name = "patronymic") private String patronymic; @Column(name = "year_birth") private Date yearBirth; @Column(name = "year_revenue") private Date yearRevenue; @JoinColumn(name = "group_id") @ManyToOne private Group group; @JoinColumn(name = "speciality_id") @ManyToOne private Speciality speciality; @Column(name = "phone_student") private String phoneStudent; @Column(name = "phone_parents") private String phoneParents; @Column(name = "address") private String address; @JoinColumn(name = "sex_id") @ManyToOne private Sex sex; @Column(name = "passport_data") private String passportData; @Column(name = "indifikatsionny_code") private String indifikatsionnyCode; @JoinColumn(name = "form_training_id") @ManyToOne private FormTraining formTraining; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public Date getYearBirth() { return yearBirth; } public void setYearBirth(Date yearBirth) { this.yearBirth = yearBirth; } public Date getYearRevenue() { return yearRevenue; } public void setYearRevenue(Date yearRevenue) { this.yearRevenue = yearRevenue; } public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } public String getPatronymic() { return patronymic; } public void setPatronymic(String patronymic) { this.patronymic = patronymic; } public Speciality getSpeciality() { return speciality; } public void setSpeciality(Speciality speciality) { this.speciality = speciality; } public String getPhoneStudent() { return phoneStudent; } public void setPhoneStudent(String phoneStudent) { this.phoneStudent = phoneStudent; } public String getPhoneParents() { return phoneParents; } public void setPhoneParents(String phoneParents) { this.phoneParents = phoneParents; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Sex getSex() { return sex; } public void setSex(Sex sex) { this.sex = sex; } public String getPassportData() { return passportData; } public void setPassportData(String passportData) { this.passportData = passportData; } public String getIndifikatsionnyCode() { return indifikatsionnyCode; } public void setIndifikatsionnyCode(String indifikatsionnyCode) { this.indifikatsionnyCode = indifikatsionnyCode; } public FormTraining getFormTraining() { return formTraining; } public void setFormTraining(FormTraining formTraining) { this.formTraining = formTraining; } }
UTF-8
Java
3,615
java
Student.java
Java
[ { "context": "tence.*;\nimport java.util.Date;\n\n/**\n * Created by Admin on 29.01.2016.\n */\n@Entity\n@Table(name = \"student", "end": 207, "score": 0.4937817454338074, "start": 202, "tag": "USERNAME", "value": "Admin" } ]
null
[]
package org.clicker.domain; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javax.persistence.*; import java.util.Date; /** * Created by Admin on 29.01.2016. */ @Entity @Table(name = "students") @Component @Scope("prototype") public class Student extends GenericEntity<Student> { @Column(name = "name") private String name; @Column(name = "surname") private String surname; @Column(name = "patronymic") private String patronymic; @Column(name = "year_birth") private Date yearBirth; @Column(name = "year_revenue") private Date yearRevenue; @JoinColumn(name = "group_id") @ManyToOne private Group group; @JoinColumn(name = "speciality_id") @ManyToOne private Speciality speciality; @Column(name = "phone_student") private String phoneStudent; @Column(name = "phone_parents") private String phoneParents; @Column(name = "address") private String address; @JoinColumn(name = "sex_id") @ManyToOne private Sex sex; @Column(name = "passport_data") private String passportData; @Column(name = "indifikatsionny_code") private String indifikatsionnyCode; @JoinColumn(name = "form_training_id") @ManyToOne private FormTraining formTraining; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public Date getYearBirth() { return yearBirth; } public void setYearBirth(Date yearBirth) { this.yearBirth = yearBirth; } public Date getYearRevenue() { return yearRevenue; } public void setYearRevenue(Date yearRevenue) { this.yearRevenue = yearRevenue; } public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } public String getPatronymic() { return patronymic; } public void setPatronymic(String patronymic) { this.patronymic = patronymic; } public Speciality getSpeciality() { return speciality; } public void setSpeciality(Speciality speciality) { this.speciality = speciality; } public String getPhoneStudent() { return phoneStudent; } public void setPhoneStudent(String phoneStudent) { this.phoneStudent = phoneStudent; } public String getPhoneParents() { return phoneParents; } public void setPhoneParents(String phoneParents) { this.phoneParents = phoneParents; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Sex getSex() { return sex; } public void setSex(Sex sex) { this.sex = sex; } public String getPassportData() { return passportData; } public void setPassportData(String passportData) { this.passportData = passportData; } public String getIndifikatsionnyCode() { return indifikatsionnyCode; } public void setIndifikatsionnyCode(String indifikatsionnyCode) { this.indifikatsionnyCode = indifikatsionnyCode; } public FormTraining getFormTraining() { return formTraining; } public void setFormTraining(FormTraining formTraining) { this.formTraining = formTraining; } }
3,615
0.64592
0.643707
163
21.177914
17.523663
68
false
false
0
0
0
0
0
0
0.288344
false
false
3
df75fb7a8de2fba9c26f90c349259ed243d9a76f
22,900,765,633,123
eb29ef2b71f03f6f7a72e32d2001cf12c1b15bf2
/src/main/java/com/example/pojo/procurement/Custclass.java
e54672d644d428dda9c13b5439c95f72fd447d1a
[ "Apache-2.0" ]
permissive
PanGGAdmin/Navigator
https://github.com/PanGGAdmin/Navigator
902b8b250d74b0712dc5ef55f41a6781125d2a09
b134907a764f27a658572fdac73fa3fdebb1bed4
refs/heads/master
2020-03-16T22:01:58.667000
2018-05-13T10:15:07
2018-05-13T10:15:07
132,144,057
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.pojo.procurement; /** * 客户类别设定的实体类 */ public class Custclass { private String classid;//类别编号 private String classname;//类别名称 private String engname;// 英文名称 private String memo;// 备注 public String getClassid() { return classid; } public void setClassid(String classid) { this.classid = classid == null ? null : classid.trim(); } public String getClassname() { return classname; } public void setClassname(String classname) { this.classname = classname == null ? null : classname.trim(); } public String getEngname() { return engname; } public void setEngname(String engname) { this.engname = engname == null ? null : engname.trim(); } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo == null ? null : memo.trim(); } }
UTF-8
Java
988
java
Custclass.java
Java
[]
null
[]
package com.example.pojo.procurement; /** * 客户类别设定的实体类 */ public class Custclass { private String classid;//类别编号 private String classname;//类别名称 private String engname;// 英文名称 private String memo;// 备注 public String getClassid() { return classid; } public void setClassid(String classid) { this.classid = classid == null ? null : classid.trim(); } public String getClassname() { return classname; } public void setClassname(String classname) { this.classname = classname == null ? null : classname.trim(); } public String getEngname() { return engname; } public void setEngname(String engname) { this.engname = engname == null ? null : engname.trim(); } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo == null ? null : memo.trim(); } }
988
0.604255
0.604255
47
19.021276
20.13834
69
false
false
0
0
0
0
0
0
0.276596
false
false
3
f1cb1fce724bad3ac74ea514ebe773a1376f8220
10,788,957,861,661
a2df6764e9f4350e0d9184efadb6c92c40d40212
/aliyun-java-sdk-sofa/src/main/java/com/aliyuncs/sofa/transform/v20190815/QueryLinkeBahamutWebapiexpressiontestResponseUnmarshaller.java
9068f6a39456409bb39142fac2b232ecabb81b65
[ "Apache-2.0" ]
permissive
warriorsZXX/aliyun-openapi-java-sdk
https://github.com/warriorsZXX/aliyun-openapi-java-sdk
567840c4bdd438d43be6bd21edde86585cd6274a
f8fd2b81a5f2cd46b1e31974ff6a7afed111a245
refs/heads/master
2022-12-06T15:45:20.418000
2020-08-20T08:37:31
2020-08-26T06:17:49
290,450,773
1
0
NOASSERTION
true
2020-08-26T09:15:48
2020-08-26T09:15:47
2020-08-26T06:17:55
2020-08-26T08:27:38
37,198
0
0
0
null
false
false
/* * 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.aliyuncs.sofa.transform.v20190815; import com.aliyuncs.sofa.model.v20190815.QueryLinkeBahamutWebapiexpressiontestResponse; import com.aliyuncs.transform.UnmarshallerContext; public class QueryLinkeBahamutWebapiexpressiontestResponseUnmarshaller { public static QueryLinkeBahamutWebapiexpressiontestResponse unmarshall(QueryLinkeBahamutWebapiexpressiontestResponse queryLinkeBahamutWebapiexpressiontestResponse, UnmarshallerContext _ctx) { queryLinkeBahamutWebapiexpressiontestResponse.setRequestId(_ctx.stringValue("QueryLinkeBahamutWebapiexpressiontestResponse.RequestId")); queryLinkeBahamutWebapiexpressiontestResponse.setResultCode(_ctx.stringValue("QueryLinkeBahamutWebapiexpressiontestResponse.ResultCode")); queryLinkeBahamutWebapiexpressiontestResponse.setResultMessage(_ctx.stringValue("QueryLinkeBahamutWebapiexpressiontestResponse.ResultMessage")); queryLinkeBahamutWebapiexpressiontestResponse.setResponseContent(_ctx.stringValue("QueryLinkeBahamutWebapiexpressiontestResponse.ResponseContent")); queryLinkeBahamutWebapiexpressiontestResponse.setResponseStatusCode(_ctx.longValue("QueryLinkeBahamutWebapiexpressiontestResponse.ResponseStatusCode")); return queryLinkeBahamutWebapiexpressiontestResponse; } }
UTF-8
Java
1,821
java
QueryLinkeBahamutWebapiexpressiontestResponseUnmarshaller.java
Java
[]
null
[]
/* * 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.aliyuncs.sofa.transform.v20190815; import com.aliyuncs.sofa.model.v20190815.QueryLinkeBahamutWebapiexpressiontestResponse; import com.aliyuncs.transform.UnmarshallerContext; public class QueryLinkeBahamutWebapiexpressiontestResponseUnmarshaller { public static QueryLinkeBahamutWebapiexpressiontestResponse unmarshall(QueryLinkeBahamutWebapiexpressiontestResponse queryLinkeBahamutWebapiexpressiontestResponse, UnmarshallerContext _ctx) { queryLinkeBahamutWebapiexpressiontestResponse.setRequestId(_ctx.stringValue("QueryLinkeBahamutWebapiexpressiontestResponse.RequestId")); queryLinkeBahamutWebapiexpressiontestResponse.setResultCode(_ctx.stringValue("QueryLinkeBahamutWebapiexpressiontestResponse.ResultCode")); queryLinkeBahamutWebapiexpressiontestResponse.setResultMessage(_ctx.stringValue("QueryLinkeBahamutWebapiexpressiontestResponse.ResultMessage")); queryLinkeBahamutWebapiexpressiontestResponse.setResponseContent(_ctx.stringValue("QueryLinkeBahamutWebapiexpressiontestResponse.ResponseContent")); queryLinkeBahamutWebapiexpressiontestResponse.setResponseStatusCode(_ctx.longValue("QueryLinkeBahamutWebapiexpressiontestResponse.ResponseStatusCode")); return queryLinkeBahamutWebapiexpressiontestResponse; } }
1,821
0.846787
0.835805
33
54.030304
55.326843
192
false
false
0
0
0
0
0
0
0.969697
false
false
3
40e7053cbbf7d3930810cde031fa30eb39f873ad
10,204,842,296,420
ce07d5a69397e2674a5c812bbca1fc291c946366
/src/MyClassInfo.java
f52dcacccdbea4b692f4a43e2028ceb15ce8f1fc
[]
no_license
agatarychter/JavaCodeGenerator
https://github.com/agatarychter/JavaCodeGenerator
c80f50b3957165bbf6259604a9ad41828e57a3a4
28e125dc9fb801be242465f097cb6a169de9679f
refs/heads/master
2020-05-18T06:00:56.458000
2019-04-30T08:29:32
2019-04-30T08:29:32
184,223,093
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.List; public class MyClassInfo { private String className; private List<ParameterInfo> parameters; private boolean isChosenGetters; private boolean isChosenSetters; private boolean isChosenSingleton; public MyClassInfo() { parameters = new ArrayList<>(); } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public List<ParameterInfo> getParameters() { return parameters; } public void setParameters(List<ParameterInfo> parameters) { this.parameters = parameters; } public boolean isChosenGetters() { return isChosenGetters; } public void setChosenGetters(boolean chosenGetters) { isChosenGetters = chosenGetters; } public boolean isChosenSetters() { return isChosenSetters; } public void setChosenSetters(boolean chosenSetters) { isChosenSetters = chosenSetters; } public boolean isChosenSingleton() { return isChosenSingleton; } public void setChosenSingleton(boolean chosenSingleton) { isChosenSingleton = chosenSingleton; } @Override public String toString() { return "MyClassInfo{" + "className='" + className + '\'' + ", parameters=" + parameters + ", isChosenGetters=" + isChosenGetters + ", isChosenSetters=" + isChosenSetters + ", isChosenSingleton=" + isChosenSingleton + '}'; } }
UTF-8
Java
1,642
java
MyClassInfo.java
Java
[]
null
[]
import java.util.ArrayList; import java.util.List; public class MyClassInfo { private String className; private List<ParameterInfo> parameters; private boolean isChosenGetters; private boolean isChosenSetters; private boolean isChosenSingleton; public MyClassInfo() { parameters = new ArrayList<>(); } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public List<ParameterInfo> getParameters() { return parameters; } public void setParameters(List<ParameterInfo> parameters) { this.parameters = parameters; } public boolean isChosenGetters() { return isChosenGetters; } public void setChosenGetters(boolean chosenGetters) { isChosenGetters = chosenGetters; } public boolean isChosenSetters() { return isChosenSetters; } public void setChosenSetters(boolean chosenSetters) { isChosenSetters = chosenSetters; } public boolean isChosenSingleton() { return isChosenSingleton; } public void setChosenSingleton(boolean chosenSingleton) { isChosenSingleton = chosenSingleton; } @Override public String toString() { return "MyClassInfo{" + "className='" + className + '\'' + ", parameters=" + parameters + ", isChosenGetters=" + isChosenGetters + ", isChosenSetters=" + isChosenSetters + ", isChosenSingleton=" + isChosenSingleton + '}'; } }
1,642
0.626675
0.626675
68
23.147058
20.293627
63
false
false
0
0
0
0
0
0
0.338235
false
false
3
d9c2b9edd204e7e09884364108b897f243b22521
22,110,491,653,280
f6fbd6a2bf4984291dc66535691d94772dd44531
/extensions/datastores/foundationdb/src/main/java/org/locationtech/geowave/datastore/foundationdb/util/AbstractFoundationDBIterator.java
e9a2b12fe61b94954f9e6e8a4fcd81c00a69ed10
[ "Apache-2.0" ]
permissive
aniroodh-ravikumar/geowave
https://github.com/aniroodh-ravikumar/geowave
b36abcc46cab5954ecdff0e43a9a6449fdb20d52
71e51b5053b7470de20ce0dd630e2579a080f8b9
refs/heads/foundationDB-master
2020-07-26T02:23:26.546000
2019-12-14T02:48:30
2019-12-14T02:48:30
208,492,407
0
0
Apache-2.0
true
2019-12-14T02:48:32
2019-09-14T19:25:44
2019-12-11T03:00:46
2019-12-14T02:48:31
901,678
0
0
0
Java
false
false
package org.locationtech.geowave.datastore.foundationdb.util; import com.apple.foundationdb.KeyValue; import org.locationtech.geowave.core.store.CloseableIterator; import java.util.Iterator; import java.util.NoSuchElementException; public abstract class AbstractFoundationDBIterator<T> implements CloseableIterator<T> { protected boolean closed = false; protected Iterator<KeyValue> it; public AbstractFoundationDBIterator(final Iterator<KeyValue> it) { super(); this.it = it; } @Override public boolean hasNext() { return !closed && it.hasNext(); } @Override public T next() { if (closed) { throw new NoSuchElementException(); } return readRow(it.next()); } protected abstract T readRow(KeyValue keyValue); @Override public void close() { closed = true; } }
UTF-8
Java
829
java
AbstractFoundationDBIterator.java
Java
[]
null
[]
package org.locationtech.geowave.datastore.foundationdb.util; import com.apple.foundationdb.KeyValue; import org.locationtech.geowave.core.store.CloseableIterator; import java.util.Iterator; import java.util.NoSuchElementException; public abstract class AbstractFoundationDBIterator<T> implements CloseableIterator<T> { protected boolean closed = false; protected Iterator<KeyValue> it; public AbstractFoundationDBIterator(final Iterator<KeyValue> it) { super(); this.it = it; } @Override public boolean hasNext() { return !closed && it.hasNext(); } @Override public T next() { if (closed) { throw new NoSuchElementException(); } return readRow(it.next()); } protected abstract T readRow(KeyValue keyValue); @Override public void close() { closed = true; } }
829
0.722557
0.722557
36
22
22.261078
87
false
false
0
0
0
0
0
0
0.388889
false
false
3
04cc90d143e9e9254d40c769ef1a74dc45410e3d
4,458,176,071,361
d003ccef9778409f32f07b2b143a8b0c8f5ff370
/app/src/main/java/com/project/sii/proxyapp/VPNGatewayService.java
df911f7cbc2481465bd2b85f605f5168a6aed7e6
[]
no_license
jacklametta/ProxyApplication
https://github.com/jacklametta/ProxyApplication
774fcfa5000d32cad3eb998e4ab33a0ee42dff22
8dd5491e5d12a91f399bb448cb989eff36cb77ec
refs/heads/master
2021-01-10T10:31:18.532000
2016-01-10T16:00:35
2016-01-10T16:00:35
48,315,230
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.project.sii.proxyapp; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; import android.util.Pair; import java.net.DatagramSocket; import java.util.Hashtable; // DEPRECATED /** * The class provides a background service for several purpose: * - Creation and Update of the log; * - Hashtables management; * - Multithread management; */ public class VPNGatewayService extends Service { private static String TAG = "VPNGatewayService"; /* One hashtable for every managed transport protocol */ Hashtable udpTable, tcpTable, icmpTable; /** * TO DO * @param intent Received Intent from MainActivity * @return Nothing */ @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } // It is used only when the service is instantiated @Override public void onCreate() { super.onCreate(); Log.d(TAG, "VPNGatewayService created"); udpTable = new Hashtable(); tcpTable = new Hashtable(); icmpTable = new Hashtable(); } /** * The function is called when @see MainActivity starts the service who has been already * created * @param intent Received Intent from MainActivity * @param flags arguments * @param startId token representing the MainActivity's start request * @return flag explicits if the service's killed before finishing, don't recreate it */ @Override public int onStartCommand(Intent intent, int flags, int startId) { //TODO do something useful Log.d(TAG, "VPNGatewayService resumed"); return Service.START_NOT_STICKY; } /** * The method is dalled by the system to notify Service is no longer used and is being removed */ @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "VPNGatewayService destroyed"); } /** * The method inserts an UDP record in the hashtable * @param key key record * @param gateway socket * @param ttl time to live */ private void udpInsert(KeyRecord key, DatagramSocket gateway, long ttl) { Pair<DatagramSocket,Long> udpPair; udpTable.put(key, new Pair<DatagramSocket, Long>(gateway, ttl)); } /** * The method removes the UDP record based on the value of the key * @param key Key of the record */ private void udpDelete(KeyRecord key){ udpTable.remove(key); } /** * The method removes the TCP record based on the value of the key * @param key Key of the record */ private void tcpDelete(KeyRecord key){ tcpTable.remove(key); } /** * The method removes the ICMP record based on the value of the key * @param key Key of the record */ private void icmpDelete(KeyRecord key){ icmpTable.remove(key); } /** * The function returns the table who contains UDP Records * @return UDP Records Hashtable */ private Hashtable getUdpTable(){ return udpTable; } /** * The function returns the table who contains TCP Records * @return TCP Records Hashtable */ private Hashtable getTcpTable(){ return tcpTable; } /** * The function returns the table who contains ICMP Records * @return ICMP Records Hashtable */ private Hashtable getIcmpTable(){ return icmpTable; } /** * The function returns the Gateway Socket of the record * @param key Key of the record * @return DatagramSocket of the record */ private DatagramSocket getUdpDestination(KeyRecord key){ return (DatagramSocket)(((Pair) udpTable.get(key)).first); } /** * The function returns the TTL of the record * @param key Key of the record * @return TTL of the record */ private long getUdpTTL(KeyRecord key){ return (long)(((Pair) udpTable.get(key)).second); } }
UTF-8
Java
4,209
java
VPNGatewayService.java
Java
[]
null
[]
package com.project.sii.proxyapp; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; import android.util.Pair; import java.net.DatagramSocket; import java.util.Hashtable; // DEPRECATED /** * The class provides a background service for several purpose: * - Creation and Update of the log; * - Hashtables management; * - Multithread management; */ public class VPNGatewayService extends Service { private static String TAG = "VPNGatewayService"; /* One hashtable for every managed transport protocol */ Hashtable udpTable, tcpTable, icmpTable; /** * TO DO * @param intent Received Intent from MainActivity * @return Nothing */ @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } // It is used only when the service is instantiated @Override public void onCreate() { super.onCreate(); Log.d(TAG, "VPNGatewayService created"); udpTable = new Hashtable(); tcpTable = new Hashtable(); icmpTable = new Hashtable(); } /** * The function is called when @see MainActivity starts the service who has been already * created * @param intent Received Intent from MainActivity * @param flags arguments * @param startId token representing the MainActivity's start request * @return flag explicits if the service's killed before finishing, don't recreate it */ @Override public int onStartCommand(Intent intent, int flags, int startId) { //TODO do something useful Log.d(TAG, "VPNGatewayService resumed"); return Service.START_NOT_STICKY; } /** * The method is dalled by the system to notify Service is no longer used and is being removed */ @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "VPNGatewayService destroyed"); } /** * The method inserts an UDP record in the hashtable * @param key key record * @param gateway socket * @param ttl time to live */ private void udpInsert(KeyRecord key, DatagramSocket gateway, long ttl) { Pair<DatagramSocket,Long> udpPair; udpTable.put(key, new Pair<DatagramSocket, Long>(gateway, ttl)); } /** * The method removes the UDP record based on the value of the key * @param key Key of the record */ private void udpDelete(KeyRecord key){ udpTable.remove(key); } /** * The method removes the TCP record based on the value of the key * @param key Key of the record */ private void tcpDelete(KeyRecord key){ tcpTable.remove(key); } /** * The method removes the ICMP record based on the value of the key * @param key Key of the record */ private void icmpDelete(KeyRecord key){ icmpTable.remove(key); } /** * The function returns the table who contains UDP Records * @return UDP Records Hashtable */ private Hashtable getUdpTable(){ return udpTable; } /** * The function returns the table who contains TCP Records * @return TCP Records Hashtable */ private Hashtable getTcpTable(){ return tcpTable; } /** * The function returns the table who contains ICMP Records * @return ICMP Records Hashtable */ private Hashtable getIcmpTable(){ return icmpTable; } /** * The function returns the Gateway Socket of the record * @param key Key of the record * @return DatagramSocket of the record */ private DatagramSocket getUdpDestination(KeyRecord key){ return (DatagramSocket)(((Pair) udpTable.get(key)).first); } /** * The function returns the TTL of the record * @param key Key of the record * @return TTL of the record */ private long getUdpTTL(KeyRecord key){ return (long)(((Pair) udpTable.get(key)).second); } }
4,209
0.634593
0.634593
148
27.43919
24.158325
98
false
false
0
0
0
0
0
0
0.317568
false
false
3
0ee1cc83c1176aaa43f3a5ebc0df83bd2df411f5
9,216,999,854,952
73163223ceefea93083f8f405e5a5fb056cbdd37
/app/src/main/java/com/example/com/wisdomcommunity/ui/person/set/SetPresenter.java
92597713c5b3be5f1824a4eb0d71959b0f2bb9fa
[]
no_license
Fessible/WisdomCommunity
https://github.com/Fessible/WisdomCommunity
859adc3ef035cc1072bc334f1e8fb9a29dc3b884
c8b067ddf531af5a7266a1780c0b016b01b42da1
refs/heads/master
2021-05-12T03:31:52.058000
2018-04-16T12:15:20
2018-04-16T12:15:20
116,202,954
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.com.wisdomcommunity.ui.person.set; import android.content.Context; import android.text.TextUtils; import com.example.com.support_business.api.CommunityServer; import com.example.com.support_business.api.RestyServer; import com.example.com.support_business.domain.personal.Info; import com.example.com.support_business.domain.personal.Version; import com.example.com.support_business.module.ResultEntity; import com.example.com.wisdomcommunity.mvp.SetContract; import java.util.Date; /** * Created by rhm on 2018/3/26. */ public class SetPresenter extends SetContract.Presenter { public SetPresenter(Context context, SetContract.View view) { super(context, view); } @Override public void version(int curVersion) { if (destroyFlag.get()) { return; } showProgress(); CommunityServer.with(context).version(compositeTag, curVersion, new RestyServer.SSOCallback<ResultEntity<Version>>() { @Override public void onUnauthorized() { } @Override public void onResponse(Date receivedDate, Date servedDate, ResultEntity<Version> entity) { hideProgress(); if (entity != null) { if (entity.isOk()) { if (view != null) { view.versionSuccess(entity.result,entity.msg); } } else { if (view != null) { view.versionFailure(!TextUtils.isEmpty(entity.msg) ? entity.msg : serverResponseError); } } } else { if (view != null) { view.versionFailure(networkError); } } } @Override public void onFailure(Throwable throwable) { hideProgress(); if (view != null) { view.versionFailure(networkError); } } }); } }
UTF-8
Java
2,111
java
SetPresenter.java
Java
[ { "context": "ntract;\n\nimport java.util.Date;\n\n/**\n * Created by rhm on 2018/3/26.\n */\n\npublic class SetPresenter exte", "end": 528, "score": 0.9995344877243042, "start": 525, "tag": "USERNAME", "value": "rhm" } ]
null
[]
package com.example.com.wisdomcommunity.ui.person.set; import android.content.Context; import android.text.TextUtils; import com.example.com.support_business.api.CommunityServer; import com.example.com.support_business.api.RestyServer; import com.example.com.support_business.domain.personal.Info; import com.example.com.support_business.domain.personal.Version; import com.example.com.support_business.module.ResultEntity; import com.example.com.wisdomcommunity.mvp.SetContract; import java.util.Date; /** * Created by rhm on 2018/3/26. */ public class SetPresenter extends SetContract.Presenter { public SetPresenter(Context context, SetContract.View view) { super(context, view); } @Override public void version(int curVersion) { if (destroyFlag.get()) { return; } showProgress(); CommunityServer.with(context).version(compositeTag, curVersion, new RestyServer.SSOCallback<ResultEntity<Version>>() { @Override public void onUnauthorized() { } @Override public void onResponse(Date receivedDate, Date servedDate, ResultEntity<Version> entity) { hideProgress(); if (entity != null) { if (entity.isOk()) { if (view != null) { view.versionSuccess(entity.result,entity.msg); } } else { if (view != null) { view.versionFailure(!TextUtils.isEmpty(entity.msg) ? entity.msg : serverResponseError); } } } else { if (view != null) { view.versionFailure(networkError); } } } @Override public void onFailure(Throwable throwable) { hideProgress(); if (view != null) { view.versionFailure(networkError); } } }); } }
2,111
0.549029
0.545713
65
31.476923
27.384502
126
false
false
0
0
0
0
0
0
0.415385
false
false
3
a263ad82d3ab440540612a2809666b0dec950455
31,181,462,576,736
0087fcadaf07d0e572a9fb5db890138cb9586e3d
/src/main/java/com/decagon/springsecurityjwt/repository/AppUserRepository.java
ccd80b5d9d846b3677bc88a66e4b42fdbec84a28
[]
no_license
Omojolade/Spring_Security
https://github.com/Omojolade/Spring_Security
28017bccc48a08484fd20da322e70b24661b47de
91bd2ae6f679ee8468c25e798392949cf5b74a63
refs/heads/master
2023-01-01T17:26:46.192000
2020-10-27T09:15:42
2020-10-27T09:15:42
307,644,175
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.decagon.springsecurityjwt.repository; import com.decagon.springsecurityjwt.model.AppUser; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.Optional; public interface AppUserRepository extends JpaRepository<AppUser, Long> { /** * Finds a user by email when the user is enabled * * @param email user email * @return <AppUser> */ @Query(name = "select * from app_user where app_user.email =:email and app_user.enabled = true", nativeQuery = true) Optional<AppUser> findByEmail(@Param("email") String email); }
UTF-8
Java
713
java
AppUserRepository.java
Java
[]
null
[]
package com.decagon.springsecurityjwt.repository; import com.decagon.springsecurityjwt.model.AppUser; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.Optional; public interface AppUserRepository extends JpaRepository<AppUser, Long> { /** * Finds a user by email when the user is enabled * * @param email user email * @return <AppUser> */ @Query(name = "select * from app_user where app_user.email =:email and app_user.enabled = true", nativeQuery = true) Optional<AppUser> findByEmail(@Param("email") String email); }
713
0.732118
0.732118
22
31.40909
28.869076
100
false
false
0
0
0
0
0
0
0.409091
false
false
3
742f41218dd7b6f3eaa7e3e874e1d903250af8f3
781,684,064,257
b52feb20530d8ab6b069bc46c958f0297c2df9f7
/utils/CATIA/PARTTYPELIB/CloseSurface.java
84982c2179990733cdb898742f6511b225ccdc9a
[]
no_license
pawelsadlo2/CatiaV5Com4j
https://github.com/pawelsadlo2/CatiaV5Com4j
e9a1c8c62163117c70c8166c462247bf87ca3df5
e985324b4d79e8b5a37662beeb6b914948b86758
refs/heads/master
2020-05-05T00:35:01.191000
2019-08-05T15:01:08
2019-08-05T15:01:08
179,579,412
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import com4j.*; @IID("{5F06E422-B21C-11D2-A628-00A0C95AF7F0}") public interface CloseSurface extends SurfaceBasedShape { // Methods: // Properties: }
UTF-8
Java
155
java
CloseSurface.java
Java
[]
null
[]
import com4j.*; @IID("{5F06E422-B21C-11D2-A628-00A0C95AF7F0}") public interface CloseSurface extends SurfaceBasedShape { // Methods: // Properties: }
155
0.735484
0.593548
7
21.142857
20.307835
57
false
false
0
0
0
0
0
0
0.142857
false
false
3
25e2e3f48cbdfc8b3a4657b7ef0ed9e4a4e9bc92
19,396,072,310,705
72b89d4c540813605f502d34f920a1f97a1dcf1a
/app-mvp/src/main/java/com/pfh/app_mvp/network/ApiClient.java
5cef68073cbeb97518e7085654bdcfc73ef2e11a
[]
no_license
afayp/Architecture
https://github.com/afayp/Architecture
e698b625f922c94a0babc09e69065a925f666c85
5573565e3fdbbea6b1db4d493e77a226ea12a5dd
refs/heads/master
2020-06-13T22:45:54.745000
2017-06-22T09:35:05
2017-06-22T09:35:05
75,544,435
54
9
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pfh.app_mvp.network; import com.pfh.app_mvp.model.Repository; import com.pfh.app_mvp.model.User; import java.util.List; import rx.Observable; import rx.Subscriber; import rx.Subscription; public class ApiClient extends RetrofitClient { private ApiClient(){ init(); } public static ApiClient getInstance(){ return SingletonHolder.INSTANCE; } private static class SingletonHolder{ private static final ApiClient INSTANCE = new ApiClient(); } //****所有具体的网络请求方法都要在下面注册,方便后期维护和测试、替换网络框架****// public Observable<List<Repository>> publicRepositories(String username){ return apiService.publicRepositories(username) .compose(defaultSchedulers); } public Subscription userFromUrl(String userUrl, Subscriber<User> subscriber){ return apiService.userFromUrl(userUrl) .compose(defaultSchedulers) .subscribe(subscriber); } }
UTF-8
Java
1,033
java
ApiClient.java
Java
[]
null
[]
package com.pfh.app_mvp.network; import com.pfh.app_mvp.model.Repository; import com.pfh.app_mvp.model.User; import java.util.List; import rx.Observable; import rx.Subscriber; import rx.Subscription; public class ApiClient extends RetrofitClient { private ApiClient(){ init(); } public static ApiClient getInstance(){ return SingletonHolder.INSTANCE; } private static class SingletonHolder{ private static final ApiClient INSTANCE = new ApiClient(); } //****所有具体的网络请求方法都要在下面注册,方便后期维护和测试、替换网络框架****// public Observable<List<Repository>> publicRepositories(String username){ return apiService.publicRepositories(username) .compose(defaultSchedulers); } public Subscription userFromUrl(String userUrl, Subscriber<User> subscriber){ return apiService.userFromUrl(userUrl) .compose(defaultSchedulers) .subscribe(subscriber); } }
1,033
0.691589
0.691589
35
26.514286
23.227289
81
false
false
0
0
0
0
0
0
0.371429
false
false
3
77a19cb448d97b3417c15ff0815740304955545e
19,396,072,312,136
8fc5decb1c39db9843f9eb68797832432e82c63f
/myProject_movie6_board/src/mvc/command/board/BoardCommand_upload.java
0610ded97f57802cc09bda8788afc467758ca1f6
[]
no_license
jonny-ddns/web-project-movie
https://github.com/jonny-ddns/web-project-movie
b41505ea4e9b6eff8c17bc970262f896cc99193a
85d2003a80c18860dadd9950ffb79e2cd43a90d4
refs/heads/master
2023-07-07T16:01:29.070000
2021-08-05T05:47:32
2021-08-05T05:47:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mvc.command.board; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import mvc.db.dao.BoardDao; import mvc.db.vo.BoardVO; public class BoardCommand_upload implements BoardCommand { @Override public void execute(HttpServletRequest request, HttpServletResponse response) { try { System.out.println(">>BoardCommand_upload()"); //µð¹ö±ë String str1 = request.getParameter("title"); String str2 = request.getParameter("content"); String str3 = request.getParameter("topic"); String str4 = request.getParameter("openPublic"); System.out.println("parameter È®ÀÎ"); System.out.println(str1); System.out.println(str2); System.out.println(str3); System.out.println(str4); BoardVO board = new BoardVO(); board.setArtiTitle(request.getParameter("title")) .setContent(request.getParameter("content")) .setOpenPublic(request.getParameter("openPublic")) ; BoardDao dao = BoardDao.getInstance(); dao.boardWrite(board); System.out.println("BoardCommand_list() end"); } catch (NullPointerException npe) { System.out.println("BoardCommand_upload - NullPointerException"); npe.getMessage(); } catch (Exception e) { System.out.println("BoardCommand_upload - Exception"); e.printStackTrace(); } } }
WINDOWS-1252
Java
1,362
java
BoardCommand_upload.java
Java
[]
null
[]
package mvc.command.board; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import mvc.db.dao.BoardDao; import mvc.db.vo.BoardVO; public class BoardCommand_upload implements BoardCommand { @Override public void execute(HttpServletRequest request, HttpServletResponse response) { try { System.out.println(">>BoardCommand_upload()"); //µð¹ö±ë String str1 = request.getParameter("title"); String str2 = request.getParameter("content"); String str3 = request.getParameter("topic"); String str4 = request.getParameter("openPublic"); System.out.println("parameter È®ÀÎ"); System.out.println(str1); System.out.println(str2); System.out.println(str3); System.out.println(str4); BoardVO board = new BoardVO(); board.setArtiTitle(request.getParameter("title")) .setContent(request.getParameter("content")) .setOpenPublic(request.getParameter("openPublic")) ; BoardDao dao = BoardDao.getInstance(); dao.boardWrite(board); System.out.println("BoardCommand_list() end"); } catch (NullPointerException npe) { System.out.println("BoardCommand_upload - NullPointerException"); npe.getMessage(); } catch (Exception e) { System.out.println("BoardCommand_upload - Exception"); e.printStackTrace(); } } }
1,362
0.70932
0.702663
48
27.166666
21.725882
80
false
false
0
0
0
0
0
0
2.791667
false
false
3
8d39f089c35baf9d14ae0b8e88580d05f7b69047
7,327,214,246,906
0b1c32c4f508dbf900d5ac8ad2af7942476fbfc4
/src/monitor/Windows/WindowsOS.java
51540c77ebf521662c82870ec1667438e8668fd1
[]
no_license
leo113000/SysMo
https://github.com/leo113000/SysMo
3eb98b2bf26b665ca3c7494c51f20e377bd379c1
ca495a6deff0fe0b6ee2727d2fb4f962e9657c30
refs/heads/master
2021-01-21T20:22:55.831000
2017-06-16T19:22:28
2017-06-16T19:22:28
92,225,057
0
1
null
false
2017-06-16T16:20:14
2017-05-23T22:11:58
2017-05-25T02:55:20
2017-06-16T16:20:14
9,944
0
0
0
Java
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 monitor.Windows; import monitor.OS; import oshi.software.os.windows.WindowsOperatingSystem; /** * * @author Leo J. Vazquez */ class WindowsOS extends OS{ public WindowsOS() { super(new WindowsOperatingSystem()); } }
UTF-8
Java
448
java
WindowsOS.java
Java
[ { "context": "windows.WindowsOperatingSystem;\n\n/**\n *\n * @author Leo J. Vazquez\n */\nclass WindowsOS extends OS{\n \n public W", "end": 319, "score": 0.9998636245727539, "start": 305, "tag": "NAME", "value": "Leo J. Vazquez" } ]
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 monitor.Windows; import monitor.OS; import oshi.software.os.windows.WindowsOperatingSystem; /** * * @author <NAME> */ class WindowsOS extends OS{ public WindowsOS() { super(new WindowsOperatingSystem()); } }
440
0.685268
0.685268
22
19.363636
22.048594
79
false
false
0
0
0
0
0
0
0.318182
false
false
3
32e0729db81ff7c585aa787d56c0f2e1d8ff3534
27,504,970,596,759
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/6/6_894ab25475cf601d7e108cf4bfbcf7bd1a9943a2/ArtifactProcessorTest/6_894ab25475cf601d7e108cf4bfbcf7bd1a9943a2_ArtifactProcessorTest_t.java
5c4a4b95d92ab55c591bff015da397763f7573d0
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
package net.masterthought.cucumber; import net.masterthought.cucumber.json.Artifact; import org.junit.Test; import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class ArtifactProcessorTest { @Test public void validConfigurationShouldReturnMap() throws Exception { String configuration = "Account has sufficient funds again~the account balance is 300~account~account_balance.txt~xml"; ArtifactProcessor artifactProcessor = new ArtifactProcessor(configuration); Map<String,Artifact> map = artifactProcessor.process(); Artifact artifact = map.get("Account has sufficient funds againthe account balance is 300"); assertThat(artifact.getScenario(),is("Account has sufficient funds again")); assertThat(artifact.getStep(),is("the account balance is 300")); assertThat(artifact.getKeyword(),is("account")); assertThat(artifact.getArtifactFile(),is("account_balance.txt")); assertThat(artifact.getContentType(),is("xml")); } }
UTF-8
Java
1,095
java
6_894ab25475cf601d7e108cf4bfbcf7bd1a9943a2_ArtifactProcessorTest_t.java
Java
[]
null
[]
package net.masterthought.cucumber; import net.masterthought.cucumber.json.Artifact; import org.junit.Test; import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class ArtifactProcessorTest { @Test public void validConfigurationShouldReturnMap() throws Exception { String configuration = "Account has sufficient funds again~the account balance is 300~account~account_balance.txt~xml"; ArtifactProcessor artifactProcessor = new ArtifactProcessor(configuration); Map<String,Artifact> map = artifactProcessor.process(); Artifact artifact = map.get("Account has sufficient funds againthe account balance is 300"); assertThat(artifact.getScenario(),is("Account has sufficient funds again")); assertThat(artifact.getStep(),is("the account balance is 300")); assertThat(artifact.getKeyword(),is("account")); assertThat(artifact.getArtifactFile(),is("account_balance.txt")); assertThat(artifact.getContentType(),is("xml")); } }
1,095
0.725114
0.716895
26
41.076923
35.550529
127
false
false
0
0
0
0
0
0
0.807692
false
false
3
5fcaba0a93996e50ff1a3c4ee9b3be1a39a8e2f7
8,881,992,393,877
7f070e7d6bd8122b1adcfd2a4d8f026dd62234b7
/bannerdemo/src/main/java/org/daimhim/bannerdemo/MainActivity.java
2606206d375ab40059d08c147eb15797df3fb6b4
[]
no_license
Daimhim/vision
https://github.com/Daimhim/vision
95239e999dc1f1f2a9e3de0ccd62a0e9a43ff23d
183bbc6cdca448e8268a7a24ce376565887c7a4c
refs/heads/master
2021-07-07T14:29:03.492000
2019-04-19T13:50:05
2019-04-19T13:50:05
132,336,381
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.daimhim.bannerdemo; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import com.bumptech.glide.Glide; import org.daimhim.banner.Banner; import org.daimhim.banner.loader.ImageLoader; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Banner lBanner = (Banner) findViewById(R.id.b_banner); lBanner.setImageLoader(new ImageLoader() { @Override public void displayImage(Context context, Object path, ImageView imageView) { Glide.with(context).load(path).into(imageView); } }); List<String> lStrings = new ArrayList<>(); lStrings.add("http://pic1.win4000.com/wallpaper/8/58f5a79da3b60.jpg"); lStrings.add("http://himg2.huanqiu.com/attachment2010/2017/0503/14/47/20170503024755104.jpg"); lStrings.add("https://image.tmdb.org/t/p/original/wdxWpq6lzgWxH8N8YgqQmLPvgn5.jpg"); lStrings.add("http://image.jisuxz.com/desktop/1834/jisuxz_wangzhe_yadianna_1_05.jpg"); lStrings.add("http://i.imgur.com/R0ySZg5.jpg"); lStrings.add("http://pic1.win4000.com/wallpaper/7/5902e207bc663.jpg"); lStrings.add("https://cn.best-wallpaper.net/wallpaper/1920x1080/1608/Gal-Gadot-as-Wonder-Woman_1920x1080.jpg"); lBanner.update(lStrings); lBanner.setBackgroundResource(R.color.colorAccent); } }
UTF-8
Java
1,655
java
MainActivity.java
Java
[]
null
[]
package org.daimhim.bannerdemo; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import com.bumptech.glide.Glide; import org.daimhim.banner.Banner; import org.daimhim.banner.loader.ImageLoader; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Banner lBanner = (Banner) findViewById(R.id.b_banner); lBanner.setImageLoader(new ImageLoader() { @Override public void displayImage(Context context, Object path, ImageView imageView) { Glide.with(context).load(path).into(imageView); } }); List<String> lStrings = new ArrayList<>(); lStrings.add("http://pic1.win4000.com/wallpaper/8/58f5a79da3b60.jpg"); lStrings.add("http://himg2.huanqiu.com/attachment2010/2017/0503/14/47/20170503024755104.jpg"); lStrings.add("https://image.tmdb.org/t/p/original/wdxWpq6lzgWxH8N8YgqQmLPvgn5.jpg"); lStrings.add("http://image.jisuxz.com/desktop/1834/jisuxz_wangzhe_yadianna_1_05.jpg"); lStrings.add("http://i.imgur.com/R0ySZg5.jpg"); lStrings.add("http://pic1.win4000.com/wallpaper/7/5902e207bc663.jpg"); lStrings.add("https://cn.best-wallpaper.net/wallpaper/1920x1080/1608/Gal-Gadot-as-Wonder-Woman_1920x1080.jpg"); lBanner.update(lStrings); lBanner.setBackgroundResource(R.color.colorAccent); } }
1,655
0.706344
0.64713
42
38.404762
31.836681
119
false
false
0
0
0
0
0
0
0.642857
false
false
3
ecf58430159a2b94e8c75f985147c8d85afe3926
910,533,118,657
a2ceeb5ed04bfbf7a8fd6e54b04777e1b7f59435
/KucingJoko/app/src/main/java/com/reg/home/kucingjoko/AddCatActivity.java
6173cd6fcd91a06ca97341e137428b1f50d50fe6
[]
no_license
rijalwafi/android-mycats
https://github.com/rijalwafi/android-mycats
c4a508de217d6d8578f9129440a99bdaf05b6185
a9b3ca4aabddd0275740f1e365b4fdd47d8d2bba
refs/heads/master
2020-11-25T00:55:26.801000
2020-11-23T17:23:14
2020-11-23T17:23:14
228,418,004
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.reg.home.kucingjoko; import androidx.appcompat.app.AppCompatActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceDataStore; import android.preference.PreferenceGroup; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class AddCatActivity extends AppCompatActivity { private EditText mEdt_cat_name,mEdt_cat_gender,mEdt_cat_type,mEdt_cat_color,mEdt_cat_food; private Button mBtn_add_cat; private static final String URL_ADD_CAT="http://192.168.137.1/mycats/addCat.php"; SessionManager sessionManager; String getId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_cat); mEdt_cat_name=findViewById(R.id.edt_cat_name); mEdt_cat_gender=findViewById(R.id.edt_cat_gender); mEdt_cat_type=findViewById(R.id.edt_cat_type); mEdt_cat_color=findViewById(R.id.edt_cat_color); mEdt_cat_food=findViewById(R.id.edt_cat_food); mBtn_add_cat=findViewById(R.id.btn_add_cat); sessionManager=new SessionManager(this); sessionManager.getUserDetail(); HashMap<String,String>user=sessionManager.getUserDetail(); getId=user.get(SessionManager.ID_USER); mBtn_add_cat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String cat_name=mEdt_cat_name.getText().toString().trim(); String cat_gender=mEdt_cat_gender.getText().toString().trim(); String cat_type=mEdt_cat_type.getText().toString().trim(); String cat_colour=mEdt_cat_color.getText().toString().trim(); String cat_food=mEdt_cat_food.getText().toString().trim(); if (TextUtils.isEmpty(cat_name)){ mEdt_cat_name.setError("Please Enter Your Cat Name"); mEdt_cat_name.requestFocus(); return; } if (TextUtils.isEmpty(cat_gender)){ mEdt_cat_gender.setError("Please Enter Your Cat Gender"); mEdt_cat_gender.requestFocus(); return; } if (TextUtils.isEmpty(cat_type)){ mEdt_cat_type.setError("Please Enter Yoyr Cat type"); mEdt_cat_type.requestFocus(); return; } if (TextUtils.isEmpty(cat_colour)){ mEdt_cat_color.setError("Please Enter Your Cat Colour"); mEdt_cat_food.requestFocus(); return; } if (TextUtils.isEmpty(cat_food)){ mEdt_cat_food.setError("Please Enter Your Cat Food"); mEdt_cat_food.requestFocus(); }else{ AddCat(cat_name,cat_gender,cat_type,cat_colour,cat_food); } } }); } private void AddCat(final String cat_name,final String cat_gender,final String cat_type, final String cat_colour,final String cat_food) { final ProgressDialog progressDialog=new ProgressDialog(this); progressDialog.setMessage("Loading..."); progressDialog.show(); StringRequest str=new StringRequest(Request.Method.POST, URL_ADD_CAT, new Response.Listener<String>() { @Override public void onResponse(String response) { progressDialog.dismiss(); try { JSONObject jsonObject = new JSONObject(response); String success = jsonObject.getString("success"); if (success.equals("1")) { Intent a = new Intent(AddCatActivity.this, MessageAddCat.class); startActivity(a); } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(AddCatActivity.this, "Ada data yang salah" + e.toString(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(AddCatActivity.this, "Error Connection" + error.toString(), Toast.LENGTH_LONG).show(); } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String,String>params=new HashMap<>(); params.put("cat_name",cat_name); params.put("id_user",getId); params.put("cat_gender",cat_gender); params.put("cat_type",cat_type); params.put("cat_colour",cat_colour); params.put("cat_food",cat_food); return params; } }; RequestQueue req= Volley.newRequestQueue(this); req.add(str); } }
UTF-8
Java
5,611
java
AddCatActivity.java
Java
[ { "context": " private static final String URL_ADD_CAT=\"http://192.168.137.1/mycats/addCat.php\";\n SessionManager sessionMan", "end": 1059, "score": 0.9996567368507385, "start": 1046, "tag": "IP_ADDRESS", "value": "192.168.137.1" } ]
null
[]
package com.reg.home.kucingjoko; import androidx.appcompat.app.AppCompatActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceDataStore; import android.preference.PreferenceGroup; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class AddCatActivity extends AppCompatActivity { private EditText mEdt_cat_name,mEdt_cat_gender,mEdt_cat_type,mEdt_cat_color,mEdt_cat_food; private Button mBtn_add_cat; private static final String URL_ADD_CAT="http://192.168.137.1/mycats/addCat.php"; SessionManager sessionManager; String getId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_cat); mEdt_cat_name=findViewById(R.id.edt_cat_name); mEdt_cat_gender=findViewById(R.id.edt_cat_gender); mEdt_cat_type=findViewById(R.id.edt_cat_type); mEdt_cat_color=findViewById(R.id.edt_cat_color); mEdt_cat_food=findViewById(R.id.edt_cat_food); mBtn_add_cat=findViewById(R.id.btn_add_cat); sessionManager=new SessionManager(this); sessionManager.getUserDetail(); HashMap<String,String>user=sessionManager.getUserDetail(); getId=user.get(SessionManager.ID_USER); mBtn_add_cat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String cat_name=mEdt_cat_name.getText().toString().trim(); String cat_gender=mEdt_cat_gender.getText().toString().trim(); String cat_type=mEdt_cat_type.getText().toString().trim(); String cat_colour=mEdt_cat_color.getText().toString().trim(); String cat_food=mEdt_cat_food.getText().toString().trim(); if (TextUtils.isEmpty(cat_name)){ mEdt_cat_name.setError("Please Enter Your Cat Name"); mEdt_cat_name.requestFocus(); return; } if (TextUtils.isEmpty(cat_gender)){ mEdt_cat_gender.setError("Please Enter Your Cat Gender"); mEdt_cat_gender.requestFocus(); return; } if (TextUtils.isEmpty(cat_type)){ mEdt_cat_type.setError("Please Enter Yoyr Cat type"); mEdt_cat_type.requestFocus(); return; } if (TextUtils.isEmpty(cat_colour)){ mEdt_cat_color.setError("Please Enter Your Cat Colour"); mEdt_cat_food.requestFocus(); return; } if (TextUtils.isEmpty(cat_food)){ mEdt_cat_food.setError("Please Enter Your Cat Food"); mEdt_cat_food.requestFocus(); }else{ AddCat(cat_name,cat_gender,cat_type,cat_colour,cat_food); } } }); } private void AddCat(final String cat_name,final String cat_gender,final String cat_type, final String cat_colour,final String cat_food) { final ProgressDialog progressDialog=new ProgressDialog(this); progressDialog.setMessage("Loading..."); progressDialog.show(); StringRequest str=new StringRequest(Request.Method.POST, URL_ADD_CAT, new Response.Listener<String>() { @Override public void onResponse(String response) { progressDialog.dismiss(); try { JSONObject jsonObject = new JSONObject(response); String success = jsonObject.getString("success"); if (success.equals("1")) { Intent a = new Intent(AddCatActivity.this, MessageAddCat.class); startActivity(a); } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(AddCatActivity.this, "Ada data yang salah" + e.toString(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(AddCatActivity.this, "Error Connection" + error.toString(), Toast.LENGTH_LONG).show(); } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String,String>params=new HashMap<>(); params.put("cat_name",cat_name); params.put("id_user",getId); params.put("cat_gender",cat_gender); params.put("cat_type",cat_type); params.put("cat_colour",cat_colour); params.put("cat_food",cat_food); return params; } }; RequestQueue req= Volley.newRequestQueue(this); req.add(str); } }
5,611
0.593121
0.59116
135
40.562962
25.859337
120
false
false
0
0
0
0
0
0
0.82963
false
false
3
e4e42a7d514630b81e31d1bad57df80153d122c9
21,646,635,218,503
db231084b4b7669e25191bb39366be2390213a90
/SB_FRAMEWORK/SBWebPaginasSemTagLib/src/main/java/com/super_bits/modulosSB/webPaginas/JSFBeans/util/ConversorEnumSBString.java
7153df02ebb5afd852c962a06866f50cfe39934c
[ "Apache-2.0" ]
permissive
salviof/SuperBits_FrameWork
https://github.com/salviof/SuperBits_FrameWork
ebad11623646d8564bff5528260c1a9b65be451b
52993f67683e18897b3a035dc005ba0514b33a5f
refs/heads/master
2018-10-10T03:31:15.200000
2018-10-08T23:53:56
2018-10-08T23:53:56
48,012,093
4
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Desenvolvido pela equipe Super-Bits.com CNPJ 20.019.971/0001-90 */ package com.super_bits.modulosSB.webPaginas.JSFBeans.util; import com.super_bits.modulosSB.SBCore.ConfigGeral.SBCore; import com.super_bits.modulosSB.SBCore.modulos.TratamentoDeErros.FabErro; import com.super_bits.modulosSB.SBCore.modulos.fabrica.ItfFabrica; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.FacesConverter; import javax.persistence.EnumType; /** * * * @author SalvioF */ @FacesConverter(value = "conversorEnumSBString", forClass = EnumType.class) public class ConversorEnumSBString extends ConversorSB { private final String ATRIBUTO_CLASSE_FABRICA = "CLASSE_FABRICA"; @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { try { if (value != null) { return Enum.valueOf((Class) getAttributoDoComponente(component, ATRIBUTO_CLASSE_FABRICA), value); } } catch (Throwable t) { SBCore.RelatarErro(FabErro.SOLICITAR_REPARO, "Erro convertendo String em enum", t); } return null; } @Override public String getAsString(FacesContext context, UIComponent component, Object value) { try { Class enumFabrica = (Class) getAttributoDoComponente(component, ATRIBUTO_CLASSE_FABRICA); if (enumFabrica == null) { addAtributoEmComponente(component, ATRIBUTO_CLASSE_FABRICA, value.getClass()); } else { } if (value != null && value instanceof ItfFabrica) { return (value).toString(); } else { throw new UnsupportedOperationException("O valor que está utilizando ConversorEnum não é do tipo enum"); } } catch (Throwable t) { SBCore.RelatarErro(FabErro.SOLICITAR_REPARO, "", t); return null; } } }
UTF-8
Java
1,982
java
ConversorEnumSBString.java
Java
[ { "context": " javax.persistence.EnumType;\n\n/**\n *\n *\n * @author SalvioF\n */\n@FacesConverter(value = \"conversorEnumSBStri", "end": 525, "score": 0.745674729347229, "start": 519, "tag": "NAME", "value": "Salvio" }, { "context": "persistence.EnumType;\n\n/**\n *\n *\n * @author SalvioF\n */\n@FacesConverter(value = \"conversorEnumSBStrin", "end": 526, "score": 0.7109110355377197, "start": 525, "tag": "USERNAME", "value": "F" } ]
null
[]
/* * Desenvolvido pela equipe Super-Bits.com CNPJ 20.019.971/0001-90 */ package com.super_bits.modulosSB.webPaginas.JSFBeans.util; import com.super_bits.modulosSB.SBCore.ConfigGeral.SBCore; import com.super_bits.modulosSB.SBCore.modulos.TratamentoDeErros.FabErro; import com.super_bits.modulosSB.SBCore.modulos.fabrica.ItfFabrica; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.FacesConverter; import javax.persistence.EnumType; /** * * * @author SalvioF */ @FacesConverter(value = "conversorEnumSBString", forClass = EnumType.class) public class ConversorEnumSBString extends ConversorSB { private final String ATRIBUTO_CLASSE_FABRICA = "CLASSE_FABRICA"; @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { try { if (value != null) { return Enum.valueOf((Class) getAttributoDoComponente(component, ATRIBUTO_CLASSE_FABRICA), value); } } catch (Throwable t) { SBCore.RelatarErro(FabErro.SOLICITAR_REPARO, "Erro convertendo String em enum", t); } return null; } @Override public String getAsString(FacesContext context, UIComponent component, Object value) { try { Class enumFabrica = (Class) getAttributoDoComponente(component, ATRIBUTO_CLASSE_FABRICA); if (enumFabrica == null) { addAtributoEmComponente(component, ATRIBUTO_CLASSE_FABRICA, value.getClass()); } else { } if (value != null && value instanceof ItfFabrica) { return (value).toString(); } else { throw new UnsupportedOperationException("O valor que está utilizando ConversorEnum não é do tipo enum"); } } catch (Throwable t) { SBCore.RelatarErro(FabErro.SOLICITAR_REPARO, "", t); return null; } } }
1,982
0.662961
0.655887
60
31.983334
33.738449
120
false
false
0
0
0
0
0
0
0.533333
false
false
3
d67ee0045e8a73c2c541a8de8c6110126baa4408
29,472,065,593,604
f81d2ab1290ab26cb95072a6508d13011049aaf2
/core/src/hu/csanyzeg/master/MyBaseClasses/Bluetooth/BluetoothChooseServerClientStage.java
d104de504f98d1a9d67d28b5a2b27136419a1a91
[]
no_license
tuskeb/mester
https://github.com/tuskeb/mester
5ca72390e3a42b85a6b791c0df75ca15e8b2dd61
40d027277e0853596fdcf165733f59396b8a8a71
refs/heads/master
2021-01-18T19:51:27.565000
2019-12-10T08:00:30
2019-12-10T08:00:30
69,664,665
1
2
null
false
2017-12-15T18:50:14
2016-09-30T12:23:51
2016-09-30T12:24:18
2017-12-15T18:50:14
2,722
0
0
0
Java
false
null
package hu.csanyzeg.master.MyBaseClasses.Bluetooth; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.utils.viewport.ExtendViewport; import hu.csanyzeg.master.Demos.GlobalClasses.Styles; import hu.csanyzeg.master.MyBaseClasses.Game.MyGame; import hu.csanyzeg.master.MyBaseClasses.UI.MyButton; import hu.csanyzeg.master.MyBaseClasses.Scene2D.MyStage; /** * Created by tuskeb on 2017. 01. 16.. */ abstract public class BluetoothChooseServerClientStage extends MyStage { public BluetoothChooseServerClientStage(MyGame game) { super(new ExtendViewport(1280, 720, new OrthographicCamera(1280, 720)), game); } abstract public void startServer(); abstract public void startClient(); @Override public void init() { Gdx.app.error("BTM", "Choose client/server"); addBackButtonScreenBackByStackPopListener(); addActor(new MyButton("Start server", Styles.getTextButtonStyle()) { @Override public void init() { super.init(); setPosition(200, 380); addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { super.clicked(event, x, y); startServer(); } }); } }); addActor(new MyButton("Start client", Styles.getTextButtonStyle()) { @Override public void init() { super.init(); setPosition(700, 380); addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { super.clicked(event, x, y); startClient(); } }); } }); } }
UTF-8
Java
2,118
java
BluetoothChooseServerClientStage.java
Java
[ { "context": ".MyBaseClasses.Scene2D.MyStage;\n\n/**\n * Created by tuskeb on 2017. 01. 16..\n */\n\nabstract public class Blue", "end": 593, "score": 0.9996460676193237, "start": 587, "tag": "USERNAME", "value": "tuskeb" } ]
null
[]
package hu.csanyzeg.master.MyBaseClasses.Bluetooth; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.utils.viewport.ExtendViewport; import hu.csanyzeg.master.Demos.GlobalClasses.Styles; import hu.csanyzeg.master.MyBaseClasses.Game.MyGame; import hu.csanyzeg.master.MyBaseClasses.UI.MyButton; import hu.csanyzeg.master.MyBaseClasses.Scene2D.MyStage; /** * Created by tuskeb on 2017. 01. 16.. */ abstract public class BluetoothChooseServerClientStage extends MyStage { public BluetoothChooseServerClientStage(MyGame game) { super(new ExtendViewport(1280, 720, new OrthographicCamera(1280, 720)), game); } abstract public void startServer(); abstract public void startClient(); @Override public void init() { Gdx.app.error("BTM", "Choose client/server"); addBackButtonScreenBackByStackPopListener(); addActor(new MyButton("Start server", Styles.getTextButtonStyle()) { @Override public void init() { super.init(); setPosition(200, 380); addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { super.clicked(event, x, y); startServer(); } }); } }); addActor(new MyButton("Start client", Styles.getTextButtonStyle()) { @Override public void init() { super.init(); setPosition(700, 380); addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { super.clicked(event, x, y); startClient(); } }); } }); } }
2,118
0.593012
0.575071
60
34.25
23.37422
86
false
false
0
0
0
0
0
0
0.75
false
false
3
2f46081f039cf27a06dc3ce4e0196d3bead7ba4d
1,503,238,611,353
45d48f0e324b9e3ffbdaafd572adc2794275da69
/src/main/java/com/july/util/OwnException.java
1b94ee80eeb95a98bba8bd90394f7a63a44d8275
[]
no_license
zengxueqi-yu/springboot-login
https://github.com/zengxueqi-yu/springboot-login
5cd333ed6d5af8fc1dd682ee312a61d04ccab367
abad3a93619c90506bb80d826aca4e60535bafb3
refs/heads/master
2022-07-13T03:48:45.963000
2019-12-06T06:45:57
2019-12-06T06:45:57
225,985,714
0
0
null
false
2022-06-17T02:44:35
2019-12-05T00:55:25
2019-12-06T06:46:11
2022-06-17T02:44:32
78
0
0
1
Java
false
false
package com.july.util; import java.io.PrintWriter; import java.io.StringWriter; import java.text.MessageFormat; import java.util.Objects; import java.util.Properties; /** * 自定义异常类 * @author zqk * @since 2019/12/4 */ public class OwnException extends RuntimeException { private static final long serialVersionUID = -1494138156106032736L; private static final Properties prop = new Properties(); public static final Integer ERR_CODE = 99999; public static final String ERR_MESG = "业务错误"; public static final Integer NONNULL = 10000; public static final Integer NONBLANK = 10001; private Integer code; public OwnException() { this.code = ERR_CODE; } public OwnException(Integer code, String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); this.code = ERR_CODE; this.code = code; } public OwnException(String message, Throwable cause) { super(message, cause); this.code = ERR_CODE; } public OwnException(Throwable cause) { super(cause); this.code = ERR_CODE; } public OwnException(Integer code, String message) { super(message); this.code = ERR_CODE; this.code = code; } public OwnException(Integer code) { this(code, "业务错误"); } public OwnException(String message) { this(ERR_CODE, message); } public Integer code() { return this.code; } public String message() { String msg = super.getMessage(); if (msg != null && !"null".equals(msg) && msg.trim().length() > 0) { return msg; } else { try { StringWriter sw = new StringWriter(); Throwable var3 = null; Object var6; try { PrintWriter pw = new PrintWriter(sw); Throwable var5 = null; try { this.printStackTrace(pw); var6 = sw.toString(); } catch (Throwable var31) { var6 = var31; var5 = var31; throw var31; } finally { if (pw != null) { if (var5 != null) { try { pw.close(); } catch (Throwable var30) { var5.addSuppressed(var30); } } else { pw.close(); } } } } catch (Throwable var33) { var3 = var33; throw var33; } finally { if (sw != null) { if (var3 != null) { try { sw.close(); } catch (Throwable var29) { var3.addSuppressed(var29); } } else { sw.close(); } } } return (String)var6; } catch (Exception var35) { return var35.getMessage(); } } } @Override public String getMessage() { return this.message(); } private static OwnException on(Integer code, String message, Object... args) { if (code == null) { return new OwnException("on(code/message/args)中code不允许为空"); } else if (message == null) { return new OwnException("on(code/message/args)中message不允许为空"); } else { return args == null ? new OwnException("on(code/message/args)中args不允许为空") : new OwnException(code, MessageFormat.format(message, args)); } } private static void of(boolean checked, Integer code, String message, Object... args) { if (checked) { throw on(code, message, args); } } public static void of(boolean checked, Integer code, Object... args) { String msg = prop.getProperty(String.valueOf(code), "业务错误"); of(checked, code, msg, args); } public static void of(boolean checked, String message, Object... args) { of(checked, ERR_CODE, message, args); } public static void of(String message, Object... args) { of(true, ERR_CODE, message, args); } public static void of(Integer code, Object... args) { String msg = prop.getProperty(String.valueOf(code), "业务错误"); of(true, code, msg, args); } public static OwnException on(Integer code, Object... args) { String msg = prop.getProperty(String.valueOf(code), "业务错误"); return on(code, msg, args); } public static OwnException on(String message, Object... args) { return on(ERR_CODE, message, args); } public static <T> void ofNull(T nullChecked, Object... args) { String msg = prop.getProperty(String.valueOf(NONNULL), "业务错误"); of(Objects.isNull(nullChecked), NONNULL, msg, args); } public static <T> void ofBlank(T blankChecked, Object... args) { String msg = prop.getProperty(String.valueOf(NONBLANK), "业务错误"); of(Objects.isNull(blankChecked) || blankChecked.toString().trim().length() == 0, NONBLANK, msg, args); } @Override public String toString() { return "[code=" + this.code() + ", message=" + this.message() + "]"; } static { try { prop.load(OwnException.class.getResourceAsStream("/errors.properties")); } catch (Exception var1) { var1.printStackTrace(); } } }
UTF-8
Java
6,083
java
OwnException.java
Java
[ { "context": "rt java.util.Properties;\n\n/**\n * 自定义异常类\n * @author zqk\n * @since 2019/12/4\n */\npublic class OwnException", "end": 197, "score": 0.9996148943901062, "start": 194, "tag": "USERNAME", "value": "zqk" } ]
null
[]
package com.july.util; import java.io.PrintWriter; import java.io.StringWriter; import java.text.MessageFormat; import java.util.Objects; import java.util.Properties; /** * 自定义异常类 * @author zqk * @since 2019/12/4 */ public class OwnException extends RuntimeException { private static final long serialVersionUID = -1494138156106032736L; private static final Properties prop = new Properties(); public static final Integer ERR_CODE = 99999; public static final String ERR_MESG = "业务错误"; public static final Integer NONNULL = 10000; public static final Integer NONBLANK = 10001; private Integer code; public OwnException() { this.code = ERR_CODE; } public OwnException(Integer code, String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); this.code = ERR_CODE; this.code = code; } public OwnException(String message, Throwable cause) { super(message, cause); this.code = ERR_CODE; } public OwnException(Throwable cause) { super(cause); this.code = ERR_CODE; } public OwnException(Integer code, String message) { super(message); this.code = ERR_CODE; this.code = code; } public OwnException(Integer code) { this(code, "业务错误"); } public OwnException(String message) { this(ERR_CODE, message); } public Integer code() { return this.code; } public String message() { String msg = super.getMessage(); if (msg != null && !"null".equals(msg) && msg.trim().length() > 0) { return msg; } else { try { StringWriter sw = new StringWriter(); Throwable var3 = null; Object var6; try { PrintWriter pw = new PrintWriter(sw); Throwable var5 = null; try { this.printStackTrace(pw); var6 = sw.toString(); } catch (Throwable var31) { var6 = var31; var5 = var31; throw var31; } finally { if (pw != null) { if (var5 != null) { try { pw.close(); } catch (Throwable var30) { var5.addSuppressed(var30); } } else { pw.close(); } } } } catch (Throwable var33) { var3 = var33; throw var33; } finally { if (sw != null) { if (var3 != null) { try { sw.close(); } catch (Throwable var29) { var3.addSuppressed(var29); } } else { sw.close(); } } } return (String)var6; } catch (Exception var35) { return var35.getMessage(); } } } @Override public String getMessage() { return this.message(); } private static OwnException on(Integer code, String message, Object... args) { if (code == null) { return new OwnException("on(code/message/args)中code不允许为空"); } else if (message == null) { return new OwnException("on(code/message/args)中message不允许为空"); } else { return args == null ? new OwnException("on(code/message/args)中args不允许为空") : new OwnException(code, MessageFormat.format(message, args)); } } private static void of(boolean checked, Integer code, String message, Object... args) { if (checked) { throw on(code, message, args); } } public static void of(boolean checked, Integer code, Object... args) { String msg = prop.getProperty(String.valueOf(code), "业务错误"); of(checked, code, msg, args); } public static void of(boolean checked, String message, Object... args) { of(checked, ERR_CODE, message, args); } public static void of(String message, Object... args) { of(true, ERR_CODE, message, args); } public static void of(Integer code, Object... args) { String msg = prop.getProperty(String.valueOf(code), "业务错误"); of(true, code, msg, args); } public static OwnException on(Integer code, Object... args) { String msg = prop.getProperty(String.valueOf(code), "业务错误"); return on(code, msg, args); } public static OwnException on(String message, Object... args) { return on(ERR_CODE, message, args); } public static <T> void ofNull(T nullChecked, Object... args) { String msg = prop.getProperty(String.valueOf(NONNULL), "业务错误"); of(Objects.isNull(nullChecked), NONNULL, msg, args); } public static <T> void ofBlank(T blankChecked, Object... args) { String msg = prop.getProperty(String.valueOf(NONBLANK), "业务错误"); of(Objects.isNull(blankChecked) || blankChecked.toString().trim().length() == 0, NONBLANK, msg, args); } @Override public String toString() { return "[code=" + this.code() + ", message=" + this.message() + "]"; } static { try { prop.load(OwnException.class.getResourceAsStream("/errors.properties")); } catch (Exception var1) { var1.printStackTrace(); } } }
6,083
0.509282
0.495401
192
30.145834
26.17767
148
false
false
0
0
0
0
0
0
0.682292
false
false
3
46b72caabeb2cda006895ff5cc8f42b94096799b
20,761,871,914,793
3ec46918e2c720fde839d3a344c39dc05d570a05
/singleton/pattern-singleton/src/main/java/com/scu/pattern/HungryST.java
963019a758cf6c2b61def76635d24a0a7e16b294
[]
no_license
curryInIT/design-pattern
https://github.com/curryInIT/design-pattern
33c2700cd64c97ccacca545cf463ca5a6876b4d0
8a8fe69108ea9b5ef4802a407b885dc936a9ac5e
refs/heads/master
2020-04-28T00:55:29.606000
2019-03-20T14:32:05
2019-03-20T14:32:05
174,834,129
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.scu.pattern; /** * 单例-饿汉式 */ public class HungryST { private static final HungryST instance; static{ instance = new HungryST(); } private HungryST(){} public static final HungryST getInstance(){ return instance; } }
UTF-8
Java
285
java
HungryST.java
Java
[]
null
[]
package com.scu.pattern; /** * 单例-饿汉式 */ public class HungryST { private static final HungryST instance; static{ instance = new HungryST(); } private HungryST(){} public static final HungryST getInstance(){ return instance; } }
285
0.610909
0.610909
19
13.473684
15.031085
47
false
false
0
0
0
0
0
0
0.210526
false
false
3
db45c3242f03e56330b5211aabcb430fec2bd861
31,147,102,843,770
668960d4d3d02dcb6161b8260ecc863dd7517636
/persistence/src/main/java/org/openstack/atlas/service/domain/usage/entities/HostUsage.java
bbd72ef5244828262f626e1b84d4e59fa840a5c6
[]
no_license
lbrackspace/atlas-lb
https://github.com/lbrackspace/atlas-lb
de1eb3c45427b08308d348fe3dbcf3d38ce116cb
dde84090fefc9c6e5861d7f4d39dd291c745f392
refs/heads/master
2022-06-16T02:33:58.445000
2021-06-11T21:47:56
2021-06-11T21:47:56
2,043,124
3
16
null
true
2016-10-13T23:36:49
2011-07-13T17:12:25
2016-08-05T21:13:07
2016-10-13T22:25:01
120,199
11
4
0
Java
null
null
package org.openstack.atlas.service.domain.usage.entities; import javax.persistence.Column; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import java.io.Serializable; import java.util.Calendar; @javax.persistence.Entity @Table(name = "host_usage") public class HostUsage extends Entity implements Serializable { private final static long serialVersionUID = 532512317L; @Column(name = "host_id", nullable = false) Integer hostId; @Column(name = "bandwidth_bytes_in", nullable = false) Long bandwidthBytesIn = 0L; @Column(name = "bandwidth_bytes_out", nullable = false) Long bandwidthBytesOut = 0L; @Column(name = "snapshot_time", nullable = false) @Temporal(TemporalType.TIMESTAMP) Calendar snapshotTime; public Integer getHostId() { return hostId; } public void setHostId(Integer hostId) { this.hostId = hostId; } public Long getBandwidthBytesIn() { return bandwidthBytesIn; } public void setBandwidthBytesIn(Long bandwidthBytesIn) { this.bandwidthBytesIn = bandwidthBytesIn; } public Long getBandwidthBytesOut() { return bandwidthBytesOut; } public void setBandwidthBytesOut(Long bandwidthBytesOut) { this.bandwidthBytesOut = bandwidthBytesOut; } public Calendar getSnapshotTime() { return snapshotTime; } public void setSnapshotTime(Calendar snapshotTime) { this.snapshotTime = snapshotTime; } }
UTF-8
Java
1,537
java
HostUsage.java
Java
[]
null
[]
package org.openstack.atlas.service.domain.usage.entities; import javax.persistence.Column; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import java.io.Serializable; import java.util.Calendar; @javax.persistence.Entity @Table(name = "host_usage") public class HostUsage extends Entity implements Serializable { private final static long serialVersionUID = 532512317L; @Column(name = "host_id", nullable = false) Integer hostId; @Column(name = "bandwidth_bytes_in", nullable = false) Long bandwidthBytesIn = 0L; @Column(name = "bandwidth_bytes_out", nullable = false) Long bandwidthBytesOut = 0L; @Column(name = "snapshot_time", nullable = false) @Temporal(TemporalType.TIMESTAMP) Calendar snapshotTime; public Integer getHostId() { return hostId; } public void setHostId(Integer hostId) { this.hostId = hostId; } public Long getBandwidthBytesIn() { return bandwidthBytesIn; } public void setBandwidthBytesIn(Long bandwidthBytesIn) { this.bandwidthBytesIn = bandwidthBytesIn; } public Long getBandwidthBytesOut() { return bandwidthBytesOut; } public void setBandwidthBytesOut(Long bandwidthBytesOut) { this.bandwidthBytesOut = bandwidthBytesOut; } public Calendar getSnapshotTime() { return snapshotTime; } public void setSnapshotTime(Calendar snapshotTime) { this.snapshotTime = snapshotTime; } }
1,537
0.707872
0.700716
56
26.446428
20.967594
63
false
false
0
0
0
0
0
0
0.428571
false
false
3
d8342cbe8551b51b1fdfc4b36a606aee3385383a
1,683,627,236,480
1eeef811dadff72d33d180886969fc021a3e5471
/src/edu/uci/asleepawake/SleepinessGeneral.java
5b3ddb385a2eccd22e0db2d6cd9f73946fe59d6e
[]
no_license
vecust/AsleepAwake
https://github.com/vecust/AsleepAwake
03244c3a19343eaa2d7a9c92576c6f8b4edde803
ea0b78dcb73de581df9c57fa33077b22608ba081
refs/heads/master
2020-05-14T19:47:44.158000
2014-07-02T23:36:52
2014-07-02T23:36:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.uci.asleepawake; //This class reads in the answers to the sleepiness survey (general version) //and sends them to the Google Form via the HttpRequest class import java.net.URLEncoder; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.Color; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TableRow; import android.widget.Toast; import android.os.AsyncTask; public class SleepinessGeneral extends Activity implements OnClickListener{ Button submit; private Spinner morningGen; private Spinner wholeDayGen; private Spinner laterDayGen; private Spinner carGen; private Spinner awakeWholeDayGen; private Spinner alertAllDayGen; private Spinner busCarTrainGen; private Spinner realizedGen; String data; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sleepiness_general); //Assign ids of spinners (dropdown menus) on layout to local Spinner objects morningGen = (Spinner) findViewById(R.id.MorningGen); // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.survey_spinner, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_list_item_1); // Apply the adapter to the spinner morningGen.setAdapter(adapter); morningGen.setPrompt("I fell asleep during the morning"); wholeDayGen = (Spinner) findViewById(R.id.WholeDayGen); wholeDayGen.setAdapter(adapter); wholeDayGen.setPrompt("I got through the whole day without feeling tired"); laterDayGen = (Spinner) findViewById(R.id.LaterDayGen); laterDayGen.setAdapter(adapter); laterDayGen.setPrompt("I fell asleep during the later in the day"); carGen = (Spinner) findViewById(R.id.CarGen); carGen.setAdapter(adapter); carGen.setPrompt("I felt drowsy when I rode in a car for longer than 5 minutes"); awakeWholeDayGen = (Spinner) findViewById(R.id.AwakeWholeDayGen); awakeWholeDayGen.setAdapter(adapter); awakeWholeDayGen.setPrompt("I felt wide-awake the whole day"); alertAllDayGen = (Spinner) findViewById(R.id.AlertAllDayGen); alertAllDayGen.setAdapter(adapter); alertAllDayGen.setPrompt("I felt alert all day"); busCarTrainGen = (Spinner) findViewById(R.id.BusCarTrainGen); busCarTrainGen.setAdapter(adapter); busCarTrainGen.setPrompt("I fell alseep when I rode in a bus, car, or train"); realizedGen = (Spinner) findViewById(R.id.RealizedGen); realizedGen.setAdapter(adapter); realizedGen.setPrompt("During the day, there were times when I realized that I had just fallen asleep"); //Assign id to submit button and set listener submit = (Button)findViewById(R.id.SleepinessGenSubmitButton); submit.setOnClickListener(this); } public void onClick(View arg0) { //This is the listener for the submit button //If at least one of the questions haven't been answered, //display an alert telling the user to answer all the questions if (morningGen.getSelectedItem().toString().equals("") || wholeDayGen.getSelectedItem().toString().equals("") || laterDayGen.getSelectedItem().toString().equals("") || carGen.getSelectedItem().toString().equals("") || awakeWholeDayGen.getSelectedItem().toString().equals("") || alertAllDayGen.getSelectedItem().toString().equals("") || busCarTrainGen.getSelectedItem().toString().equals("") || realizedGen.getSelectedItem().toString().equals("")) { TableRow morningGenRow = (TableRow) findViewById(R.id.MorningGenRow); TableRow laterDayGenRow = (TableRow) findViewById(R.id.LaterDayGenRow); TableRow carGenRow = (TableRow) findViewById(R.id.CarGenRow); TableRow awakeWholeDayGenRow = (TableRow) findViewById(R.id.AwakeWholeDayGenRow); TableRow alertAllDayGenRow = (TableRow) findViewById(R.id.AlertAllDayGenRow); TableRow busCarTrainGenRow = (TableRow) findViewById(R.id.BusCarTrainGenRow); TableRow realizedGenRow = (TableRow) findViewById(R.id.RealizedGenRow); TableRow wholeDayGenRow = (TableRow) findViewById(R.id.WholeDayGenRow); if(morningGen.getSelectedItem().toString().equals("")){ morningGenRow.setBackgroundColor(Color.YELLOW); } else { morningGenRow.setBackgroundColor(Color.WHITE); } if(laterDayGen.getSelectedItem().toString().equals("")){ laterDayGenRow.setBackgroundColor(Color.YELLOW); } else { laterDayGenRow.setBackgroundColor(Color.WHITE); } if(carGen.getSelectedItem().toString().equals("")){ carGenRow.setBackgroundColor(Color.YELLOW); } else { carGenRow.setBackgroundColor(Color.WHITE); } if(awakeWholeDayGen.getSelectedItem().toString().equals("")){ awakeWholeDayGenRow.setBackgroundColor(Color.YELLOW); } else { awakeWholeDayGenRow.setBackgroundColor(Color.WHITE); } if(alertAllDayGen.getSelectedItem().toString().equals("")){ alertAllDayGenRow.setBackgroundColor(Color.YELLOW); } else { alertAllDayGenRow.setBackgroundColor(Color.WHITE); } if(busCarTrainGen.getSelectedItem().toString().equals("")){ busCarTrainGenRow.setBackgroundColor(Color.YELLOW); } else { busCarTrainGenRow.setBackgroundColor(Color.WHITE); } if(realizedGen.getSelectedItem().toString().equals("")){ realizedGenRow.setBackgroundColor(Color.YELLOW); } else { realizedGenRow.setBackgroundColor(Color.WHITE); } if(wholeDayGen.getSelectedItem().toString().equals("")){ wholeDayGenRow.setBackgroundColor(Color.YELLOW); } else { wholeDayGenRow.setBackgroundColor(Color.WHITE); } AlertDialog.Builder builder = new AlertDialog.Builder(SleepinessGeneral.this); builder.setTitle("Please answer all questions before submitting") .setMessage("Unanswered questions are highlighted") .setCancelable(false) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //do things dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); //With all the questions answered, make a connection to the Google Form and //send the answers to the spreadsheet //Instructions for getting Google Form URL and entry code can be found here: //http://www.youtube.com/watch?v=GyuJ2GtpZd0 } else { String fullUrl = "https://docs.google.com/a/uci.edu/forms/d/1x-YIb5tAnkImWDLaw0YtNIyqa0AXCroq26ogf_2yS9o/formResponse"; HttpRequest mReq = new HttpRequest(); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String participant = sp.getString("Participant", ""); String entryType = sp.getString("ManualSurveys", ""); data = "entry_1794600332=" + URLEncoder.encode(participant) + "&" + "entry_2039569836=" + URLEncoder.encode(morningGen.getSelectedItem().toString()) + "&" + "entry_633281223=" + URLEncoder.encode(wholeDayGen.getSelectedItem().toString()) + "&" + "entry_84773151=" + URLEncoder.encode(laterDayGen.getSelectedItem().toString()) + "&" + "entry_1236987037=" + URLEncoder.encode(carGen.getSelectedItem().toString()) + "&" + "entry_1480764914=" + URLEncoder.encode(awakeWholeDayGen.getSelectedItem().toString()) + "&" + "entry_581428323=" + URLEncoder.encode(alertAllDayGen.getSelectedItem().toString()) + "&" + "entry_502584888=" + URLEncoder.encode(busCarTrainGen.getSelectedItem().toString()) + "&" + "entry_1297174710=" + URLEncoder.encode(realizedGen.getSelectedItem().toString()) + "&" + "entry_12534346=" + URLEncoder.encode(entryType); // String response = mReq.sendPost(fullUrl, data); // System.out.println("postData response: " + response); UploadFormData doItNow = new UploadFormData(); doItNow.execute(fullUrl); savePrefs("sleepinessSurveyIgnored","NO"); // finish(); Intent surveyPage = new Intent(SleepinessGeneral.this,FeelRightNow.class); surveyPage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); SleepinessGeneral.this.startActivity(surveyPage); } } private class UploadFormData extends AsyncTask<String, Void, String>{ @Override protected String doInBackground(String... urls) { // TODO Auto-generated method stub String response = ""; for (String url : urls){ try{ HttpRequest mReq = new HttpRequest(); String mdata = data; System.out.print(url); response = mReq.sendPost(url, mdata); }catch (Exception e){ e.printStackTrace(); } } return response; } protected void onPostExecute(String result){ Context context = getApplicationContext(); CharSequence text = "Sleepiness Form data submitted."; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } } private void savePrefs(String key, String value) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); Editor edit = sp.edit(); edit.putString(key, value); edit.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_sleepiness, menu); return true; } }
UTF-8
Java
10,052
java
SleepinessGeneral.java
Java
[]
null
[]
package edu.uci.asleepawake; //This class reads in the answers to the sleepiness survey (general version) //and sends them to the Google Form via the HttpRequest class import java.net.URLEncoder; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.Color; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TableRow; import android.widget.Toast; import android.os.AsyncTask; public class SleepinessGeneral extends Activity implements OnClickListener{ Button submit; private Spinner morningGen; private Spinner wholeDayGen; private Spinner laterDayGen; private Spinner carGen; private Spinner awakeWholeDayGen; private Spinner alertAllDayGen; private Spinner busCarTrainGen; private Spinner realizedGen; String data; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sleepiness_general); //Assign ids of spinners (dropdown menus) on layout to local Spinner objects morningGen = (Spinner) findViewById(R.id.MorningGen); // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.survey_spinner, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_list_item_1); // Apply the adapter to the spinner morningGen.setAdapter(adapter); morningGen.setPrompt("I fell asleep during the morning"); wholeDayGen = (Spinner) findViewById(R.id.WholeDayGen); wholeDayGen.setAdapter(adapter); wholeDayGen.setPrompt("I got through the whole day without feeling tired"); laterDayGen = (Spinner) findViewById(R.id.LaterDayGen); laterDayGen.setAdapter(adapter); laterDayGen.setPrompt("I fell asleep during the later in the day"); carGen = (Spinner) findViewById(R.id.CarGen); carGen.setAdapter(adapter); carGen.setPrompt("I felt drowsy when I rode in a car for longer than 5 minutes"); awakeWholeDayGen = (Spinner) findViewById(R.id.AwakeWholeDayGen); awakeWholeDayGen.setAdapter(adapter); awakeWholeDayGen.setPrompt("I felt wide-awake the whole day"); alertAllDayGen = (Spinner) findViewById(R.id.AlertAllDayGen); alertAllDayGen.setAdapter(adapter); alertAllDayGen.setPrompt("I felt alert all day"); busCarTrainGen = (Spinner) findViewById(R.id.BusCarTrainGen); busCarTrainGen.setAdapter(adapter); busCarTrainGen.setPrompt("I fell alseep when I rode in a bus, car, or train"); realizedGen = (Spinner) findViewById(R.id.RealizedGen); realizedGen.setAdapter(adapter); realizedGen.setPrompt("During the day, there were times when I realized that I had just fallen asleep"); //Assign id to submit button and set listener submit = (Button)findViewById(R.id.SleepinessGenSubmitButton); submit.setOnClickListener(this); } public void onClick(View arg0) { //This is the listener for the submit button //If at least one of the questions haven't been answered, //display an alert telling the user to answer all the questions if (morningGen.getSelectedItem().toString().equals("") || wholeDayGen.getSelectedItem().toString().equals("") || laterDayGen.getSelectedItem().toString().equals("") || carGen.getSelectedItem().toString().equals("") || awakeWholeDayGen.getSelectedItem().toString().equals("") || alertAllDayGen.getSelectedItem().toString().equals("") || busCarTrainGen.getSelectedItem().toString().equals("") || realizedGen.getSelectedItem().toString().equals("")) { TableRow morningGenRow = (TableRow) findViewById(R.id.MorningGenRow); TableRow laterDayGenRow = (TableRow) findViewById(R.id.LaterDayGenRow); TableRow carGenRow = (TableRow) findViewById(R.id.CarGenRow); TableRow awakeWholeDayGenRow = (TableRow) findViewById(R.id.AwakeWholeDayGenRow); TableRow alertAllDayGenRow = (TableRow) findViewById(R.id.AlertAllDayGenRow); TableRow busCarTrainGenRow = (TableRow) findViewById(R.id.BusCarTrainGenRow); TableRow realizedGenRow = (TableRow) findViewById(R.id.RealizedGenRow); TableRow wholeDayGenRow = (TableRow) findViewById(R.id.WholeDayGenRow); if(morningGen.getSelectedItem().toString().equals("")){ morningGenRow.setBackgroundColor(Color.YELLOW); } else { morningGenRow.setBackgroundColor(Color.WHITE); } if(laterDayGen.getSelectedItem().toString().equals("")){ laterDayGenRow.setBackgroundColor(Color.YELLOW); } else { laterDayGenRow.setBackgroundColor(Color.WHITE); } if(carGen.getSelectedItem().toString().equals("")){ carGenRow.setBackgroundColor(Color.YELLOW); } else { carGenRow.setBackgroundColor(Color.WHITE); } if(awakeWholeDayGen.getSelectedItem().toString().equals("")){ awakeWholeDayGenRow.setBackgroundColor(Color.YELLOW); } else { awakeWholeDayGenRow.setBackgroundColor(Color.WHITE); } if(alertAllDayGen.getSelectedItem().toString().equals("")){ alertAllDayGenRow.setBackgroundColor(Color.YELLOW); } else { alertAllDayGenRow.setBackgroundColor(Color.WHITE); } if(busCarTrainGen.getSelectedItem().toString().equals("")){ busCarTrainGenRow.setBackgroundColor(Color.YELLOW); } else { busCarTrainGenRow.setBackgroundColor(Color.WHITE); } if(realizedGen.getSelectedItem().toString().equals("")){ realizedGenRow.setBackgroundColor(Color.YELLOW); } else { realizedGenRow.setBackgroundColor(Color.WHITE); } if(wholeDayGen.getSelectedItem().toString().equals("")){ wholeDayGenRow.setBackgroundColor(Color.YELLOW); } else { wholeDayGenRow.setBackgroundColor(Color.WHITE); } AlertDialog.Builder builder = new AlertDialog.Builder(SleepinessGeneral.this); builder.setTitle("Please answer all questions before submitting") .setMessage("Unanswered questions are highlighted") .setCancelable(false) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //do things dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); //With all the questions answered, make a connection to the Google Form and //send the answers to the spreadsheet //Instructions for getting Google Form URL and entry code can be found here: //http://www.youtube.com/watch?v=GyuJ2GtpZd0 } else { String fullUrl = "https://docs.google.com/a/uci.edu/forms/d/1x-YIb5tAnkImWDLaw0YtNIyqa0AXCroq26ogf_2yS9o/formResponse"; HttpRequest mReq = new HttpRequest(); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String participant = sp.getString("Participant", ""); String entryType = sp.getString("ManualSurveys", ""); data = "entry_1794600332=" + URLEncoder.encode(participant) + "&" + "entry_2039569836=" + URLEncoder.encode(morningGen.getSelectedItem().toString()) + "&" + "entry_633281223=" + URLEncoder.encode(wholeDayGen.getSelectedItem().toString()) + "&" + "entry_84773151=" + URLEncoder.encode(laterDayGen.getSelectedItem().toString()) + "&" + "entry_1236987037=" + URLEncoder.encode(carGen.getSelectedItem().toString()) + "&" + "entry_1480764914=" + URLEncoder.encode(awakeWholeDayGen.getSelectedItem().toString()) + "&" + "entry_581428323=" + URLEncoder.encode(alertAllDayGen.getSelectedItem().toString()) + "&" + "entry_502584888=" + URLEncoder.encode(busCarTrainGen.getSelectedItem().toString()) + "&" + "entry_1297174710=" + URLEncoder.encode(realizedGen.getSelectedItem().toString()) + "&" + "entry_12534346=" + URLEncoder.encode(entryType); // String response = mReq.sendPost(fullUrl, data); // System.out.println("postData response: " + response); UploadFormData doItNow = new UploadFormData(); doItNow.execute(fullUrl); savePrefs("sleepinessSurveyIgnored","NO"); // finish(); Intent surveyPage = new Intent(SleepinessGeneral.this,FeelRightNow.class); surveyPage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); SleepinessGeneral.this.startActivity(surveyPage); } } private class UploadFormData extends AsyncTask<String, Void, String>{ @Override protected String doInBackground(String... urls) { // TODO Auto-generated method stub String response = ""; for (String url : urls){ try{ HttpRequest mReq = new HttpRequest(); String mdata = data; System.out.print(url); response = mReq.sendPost(url, mdata); }catch (Exception e){ e.printStackTrace(); } } return response; } protected void onPostExecute(String result){ Context context = getApplicationContext(); CharSequence text = "Sleepiness Form data submitted."; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } } private void savePrefs(String key, String value) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); Editor edit = sp.edit(); edit.putString(key, value); edit.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_sleepiness, menu); return true; } }
10,052
0.718166
0.70762
273
35.820515
28.5597
122
false
false
0
0
0
0
0
0
2.868132
false
false
3
75f53d3bc7c4cdb41c08ba1613b4e5162771ce12
1,511,828,543,895
8551522d125a3aea9645a9f6631390658a735ef7
/hscard/src/hscard/model/SuperDao.java
80a169d2b7524c9dfa21fcf6322bc58253722fc5
[]
no_license
cjseop/hscard
https://github.com/cjseop/hscard
d636aaffb7913720b7b7e2df824dd61a81fde894
4351b2656c6997602b50aafd4983e913b5a816d6
refs/heads/master
2021-07-19T11:35:38.968000
2017-10-26T08:56:42
2017-10-26T08:56:42
104,972,089
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hscard.model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class SuperDao { //Instance protected Connection conn = null; private final String DB_URL = "jdbc:oracle:thin:@127.0.0.1:1521:orcl"; private final String DB_USR = "pman"; private final String DB_PASSWORD = "oracle"; private final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver"; //Constructor public SuperDao() { try { Class.forName(DB_DRIVER); this.conn = getConnection(); if (conn != null) { //System.out.println("DB_OKAY"); } else { System.out.println("DB_ERROR"); } } catch (ClassNotFoundException e) { System.out.println("check oracle jar file"); e.printStackTrace(); } } //Method protected Connection getConnection(){ try { return DriverManager.getConnection(DB_URL, DB_USR, DB_PASSWORD); } catch (SQLException e) { e.printStackTrace(); return null; } } public void closeConnection(){ if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
UTF-8
Java
1,160
java
SuperDao.java
Java
[ { "context": "\tprivate final String DB_URL = \"jdbc:oracle:thin:@127.0.0.1:1521:orcl\";\r\n\tprivate final String DB_USR = \"pman", "end": 252, "score": 0.999725878238678, "start": 243, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": ".0.1:1521:orcl\";\r\n\tprivate final String DB_USR = \"pman\";\r\n\tprivate final String DB_PASSWORD = \"oracle\";\r", "end": 302, "score": 0.9813565015792847, "start": 298, "tag": "USERNAME", "value": "pman" }, { "context": "R = \"pman\";\r\n\tprivate final String DB_PASSWORD = \"oracle\";\r\n\tprivate final String DB_DRIVER = \"oracle.jdbc", "end": 349, "score": 0.9994986057281494, "start": 343, "tag": "PASSWORD", "value": "oracle" } ]
null
[]
package hscard.model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class SuperDao { //Instance protected Connection conn = null; private final String DB_URL = "jdbc:oracle:thin:@127.0.0.1:1521:orcl"; private final String DB_USR = "pman"; private final String DB_PASSWORD = "<PASSWORD>"; private final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver"; //Constructor public SuperDao() { try { Class.forName(DB_DRIVER); this.conn = getConnection(); if (conn != null) { //System.out.println("DB_OKAY"); } else { System.out.println("DB_ERROR"); } } catch (ClassNotFoundException e) { System.out.println("check oracle jar file"); e.printStackTrace(); } } //Method protected Connection getConnection(){ try { return DriverManager.getConnection(DB_URL, DB_USR, DB_PASSWORD); } catch (SQLException e) { e.printStackTrace(); return null; } } public void closeConnection(){ if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
1,164
0.634483
0.625862
51
20.745098
17.980211
71
false
false
0
0
0
0
0
0
2.254902
false
false
3
5c20b4eaf37b1d3e2cee889320815cb755022c74
26,792,006,010,894
e2bb32fb7b7241fd33c41dcbe85416ff8a3b551b
/src/main/java/io/muic/ssc/project/backend/auth/AuthenticationController.java
9ab73056eddd2ebe9ff89ade8e35dad732fc1ac0
[]
no_license
PattakarnC/NewSSC_Project
https://github.com/PattakarnC/NewSSC_Project
527022b50064cb578b1a6251d85cd664d4d561e9
55cca1e37b8fab21caf2fed161d5545c3f99e07b
refs/heads/master
2023-06-18T16:36:47.318000
2021-07-19T15:10:17
2021-07-19T15:10:17
386,279,946
0
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.muic.ssc.project.backend.auth; import io.muic.ssc.project.backend.SimpleResponseDTO; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.security.core.context.SecurityContextHolder; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @RestController public class AuthenticationController { @GetMapping("/home") public String test(){ return "If this message is shown, it means login is successful because we didn't set to permit this path "; } @PostMapping("/api/login") public SimpleResponseDTO login(HttpServletRequest request){ String username = request.getParameter("username"); String password = request.getParameter("password"); try { // check if there is a current user logged in, if so log that user out first Object principle = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principle != null && principle instanceof org.springframework.security.core.userdetails.User) { request.logout(); } request.login(username, password); return SimpleResponseDTO .builder() .success(true) .message("You are logged in successfully") .build(); } catch(SecurityException | ServletException e){ return SimpleResponseDTO .builder() .success(false) .message("Incorrect username or password") .build(); } } @GetMapping("/api/logout") public SimpleResponseDTO logout(HttpServletRequest request){ try { request.logout(); return SimpleResponseDTO .builder() .success(true) .message("You are successfully logged out") .build(); } catch (ServletException e) { return SimpleResponseDTO .builder() .success(false) .message(e.getMessage()) .build(); } } }
UTF-8
Java
2,336
java
AuthenticationController.java
Java
[ { "context": "{\n String username = request.getParameter(\"username\");\n String password = request.getParameter", "end": 820, "score": 0.9969449639320374, "start": 812, "tag": "USERNAME", "value": "username" } ]
null
[]
package io.muic.ssc.project.backend.auth; import io.muic.ssc.project.backend.SimpleResponseDTO; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.security.core.context.SecurityContextHolder; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @RestController public class AuthenticationController { @GetMapping("/home") public String test(){ return "If this message is shown, it means login is successful because we didn't set to permit this path "; } @PostMapping("/api/login") public SimpleResponseDTO login(HttpServletRequest request){ String username = request.getParameter("username"); String password = request.getParameter("password"); try { // check if there is a current user logged in, if so log that user out first Object principle = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principle != null && principle instanceof org.springframework.security.core.userdetails.User) { request.logout(); } request.login(username, password); return SimpleResponseDTO .builder() .success(true) .message("You are logged in successfully") .build(); } catch(SecurityException | ServletException e){ return SimpleResponseDTO .builder() .success(false) .message("Incorrect username or password") .build(); } } @GetMapping("/api/logout") public SimpleResponseDTO logout(HttpServletRequest request){ try { request.logout(); return SimpleResponseDTO .builder() .success(true) .message("You are successfully logged out") .build(); } catch (ServletException e) { return SimpleResponseDTO .builder() .success(false) .message(e.getMessage()) .build(); } } }
2,336
0.600171
0.600171
62
36.677418
26.464689
115
false
false
0
0
0
0
0
0
0.370968
false
false
3
68cbbf52e83855435c837c6d9548de2850638254
19,172,734,040,916
f570def9ad91c347a8d340c3e26c1146fa422af1
/src/test/java/InMemoryPersistenceTest.java
812c38c8ed986d2d80ac7a0fa4c23526ee9cb391
[]
no_license
darm145/CinemaIII
https://github.com/darm145/CinemaIII
520bd5bf6332fed2dc74393d6c5b9f3d08f9bca6
52b3f133a3915b3e260529bff4edac5d1ea06bbd
refs/heads/master
2020-04-28T23:07:23.972000
2019-03-21T06:47:41
2019-03-21T06:47:41
175,643,267
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import edu.eci.arsw.cinema.model.Cinema; import edu.eci.arsw.cinema.model.CinemaFunction; import edu.eci.arsw.cinema.model.Movie; import edu.eci.arsw.cinema.persistence.CinemaException; import edu.eci.arsw.cinema.persistence.CinemaPersistenceException; import edu.eci.arsw.cinema.persistence.impl.InMemoryCinemaPersistence; import edu.eci.arsw.cinema.services.CinemaServices; import java.util.ArrayList; import java.util.List; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author cristian */ public class InMemoryPersistenceTest { ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml"); @Test public void saveNewAndLoadTest() throws CinemaPersistenceException{ InMemoryCinemaPersistence ipct=new InMemoryCinemaPersistence(); String functionDate = "2018-12-18 15:30"; List<CinemaFunction> functions= new ArrayList<>(); CinemaFunction funct1 = new CinemaFunction(new Movie("SuperHeroes Movie 2","Action"),functionDate); CinemaFunction funct2 = new CinemaFunction(new Movie("The Night 2","Horror"),functionDate); functions.add(funct1); functions.add(funct2); Cinema c=new Cinema("Movies Bogotá",functions); ipct.saveCinema(c); assertNotNull("Loading a previously stored cinema returned null.",ipct.getCinema(c.getName())); assertEquals("Loading a previously stored cinema returned a different cinema.",ipct.getCinema(c.getName()), c); } @Test public void saveExistingCinemaTest() { InMemoryCinemaPersistence ipct=new InMemoryCinemaPersistence(); String functionDate = "2018-12-18 15:30"; List<CinemaFunction> functions= new ArrayList<>(); CinemaFunction funct1 = new CinemaFunction(new Movie("SuperHeroes Movie 2","Action"),functionDate); CinemaFunction funct2 = new CinemaFunction(new Movie("The Night 2","Horror"),functionDate); functions.add(funct1); functions.add(funct2); Cinema c=new Cinema("Movies Bogotá",functions); try { ipct.saveCinema(c); } catch (CinemaPersistenceException ex) { fail("Cinema persistence failed inserting the first cinema."); } List<CinemaFunction> functions2= new ArrayList<>(); CinemaFunction funct12 = new CinemaFunction(new Movie("SuperHeroes Movie 3","Action"),functionDate); CinemaFunction funct22 = new CinemaFunction(new Movie("The Night 3","Horror"),functionDate); functions.add(funct12); functions.add(funct22); Cinema c2=new Cinema("Movies Bogotá",functions2); try{ ipct.saveCinema(c2); fail("An exception was expected after saving a second cinema with the same name"); } catch (CinemaPersistenceException ex){ } } @Test public void BuyTicketsTest1() { try { CinemaServices cn=ac.getBean(CinemaServices.class); cn.buyTicket(4, 4, "cinemaX", "2018-12-18 15:30", "The Night"); cn.buyTicket(4, 4, "cinemaX", "2018-12-18 15:30", "The Night"); } catch(CinemaException e){ assertEquals(e.getMessage(),"Seat booked"); } catch(CinemaPersistenceException e) { } } @Test public void BuyTicketsTest2() { try { CinemaServices cn=ac.getBean(CinemaServices.class); cn.buyTicket(4, 4, "cinemax", "2018-12-18 15:30", "The Night"); } catch(CinemaException e){ } catch(CinemaPersistenceException e) { assertEquals(e.getMessage(),"No existe el cinema cinemax"); } } @Test public void BuyTicketsTest3() { try { CinemaServices cn=ac.getBean(CinemaServices.class); cn.buyTicket(4, 4, "cinemaX", "2018-12-18 15:30", "The night"); } catch(CinemaException e){ } catch(CinemaPersistenceException e) { assertEquals(e.getMessage(),"No existe una pelicula con el nombre The night en el cinema cinemaX"); } } @Test public void GetFunctionByCinemaAndDateTest1() { try { CinemaServices cn=ac.getBean(CinemaServices.class); cn.getFunctionsbyCinemaAndDate("cinemax", "2018-12-18 15:30"); } catch(CinemaPersistenceException e) { assertEquals(e.getMessage(),"No existe el cinema cinemax"); } } @Test public void GetFunctionByCinemaAndDateTest2() { try { CinemaServices cn=ac.getBean(CinemaServices.class); List<CinemaFunction> ar=cn.getFunctionsbyCinemaAndDate("cinemaX", "2018-12-18 15:30"); Set<Cinema> cines=cn.getAllCinemas(); for(Object c: cines.toArray()) { //if (c.) } //assertEquals(.,ar.size() ); } catch(CinemaPersistenceException e) { } } @Test public void GetFunctionByCinemaAndDateTest3() { try { CinemaServices cn=ac.getBean(CinemaServices.class); List<CinemaFunction> ar=cn.getFunctionsbyCinemaAndDate("cinemaX", "2018-12-18 15:40"); assertEquals(0,ar.size() ); } catch(CinemaPersistenceException e) { } } }
UTF-8
Java
5,590
java
InMemoryPersistenceTest.java
Java
[ { "context": "the template in the editor.\n */\n\n/**\n *\n * @author cristian\n */\npublic class InMemoryPersistenceTest {\n\tAppli", "end": 989, "score": 0.9563010334968567, "start": 981, "tag": "NAME", "value": "cristian" } ]
null
[]
import edu.eci.arsw.cinema.model.Cinema; import edu.eci.arsw.cinema.model.CinemaFunction; import edu.eci.arsw.cinema.model.Movie; import edu.eci.arsw.cinema.persistence.CinemaException; import edu.eci.arsw.cinema.persistence.CinemaPersistenceException; import edu.eci.arsw.cinema.persistence.impl.InMemoryCinemaPersistence; import edu.eci.arsw.cinema.services.CinemaServices; import java.util.ArrayList; import java.util.List; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author cristian */ public class InMemoryPersistenceTest { ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml"); @Test public void saveNewAndLoadTest() throws CinemaPersistenceException{ InMemoryCinemaPersistence ipct=new InMemoryCinemaPersistence(); String functionDate = "2018-12-18 15:30"; List<CinemaFunction> functions= new ArrayList<>(); CinemaFunction funct1 = new CinemaFunction(new Movie("SuperHeroes Movie 2","Action"),functionDate); CinemaFunction funct2 = new CinemaFunction(new Movie("The Night 2","Horror"),functionDate); functions.add(funct1); functions.add(funct2); Cinema c=new Cinema("Movies Bogotá",functions); ipct.saveCinema(c); assertNotNull("Loading a previously stored cinema returned null.",ipct.getCinema(c.getName())); assertEquals("Loading a previously stored cinema returned a different cinema.",ipct.getCinema(c.getName()), c); } @Test public void saveExistingCinemaTest() { InMemoryCinemaPersistence ipct=new InMemoryCinemaPersistence(); String functionDate = "2018-12-18 15:30"; List<CinemaFunction> functions= new ArrayList<>(); CinemaFunction funct1 = new CinemaFunction(new Movie("SuperHeroes Movie 2","Action"),functionDate); CinemaFunction funct2 = new CinemaFunction(new Movie("The Night 2","Horror"),functionDate); functions.add(funct1); functions.add(funct2); Cinema c=new Cinema("Movies Bogotá",functions); try { ipct.saveCinema(c); } catch (CinemaPersistenceException ex) { fail("Cinema persistence failed inserting the first cinema."); } List<CinemaFunction> functions2= new ArrayList<>(); CinemaFunction funct12 = new CinemaFunction(new Movie("SuperHeroes Movie 3","Action"),functionDate); CinemaFunction funct22 = new CinemaFunction(new Movie("The Night 3","Horror"),functionDate); functions.add(funct12); functions.add(funct22); Cinema c2=new Cinema("Movies Bogotá",functions2); try{ ipct.saveCinema(c2); fail("An exception was expected after saving a second cinema with the same name"); } catch (CinemaPersistenceException ex){ } } @Test public void BuyTicketsTest1() { try { CinemaServices cn=ac.getBean(CinemaServices.class); cn.buyTicket(4, 4, "cinemaX", "2018-12-18 15:30", "The Night"); cn.buyTicket(4, 4, "cinemaX", "2018-12-18 15:30", "The Night"); } catch(CinemaException e){ assertEquals(e.getMessage(),"Seat booked"); } catch(CinemaPersistenceException e) { } } @Test public void BuyTicketsTest2() { try { CinemaServices cn=ac.getBean(CinemaServices.class); cn.buyTicket(4, 4, "cinemax", "2018-12-18 15:30", "The Night"); } catch(CinemaException e){ } catch(CinemaPersistenceException e) { assertEquals(e.getMessage(),"No existe el cinema cinemax"); } } @Test public void BuyTicketsTest3() { try { CinemaServices cn=ac.getBean(CinemaServices.class); cn.buyTicket(4, 4, "cinemaX", "2018-12-18 15:30", "The night"); } catch(CinemaException e){ } catch(CinemaPersistenceException e) { assertEquals(e.getMessage(),"No existe una pelicula con el nombre The night en el cinema cinemaX"); } } @Test public void GetFunctionByCinemaAndDateTest1() { try { CinemaServices cn=ac.getBean(CinemaServices.class); cn.getFunctionsbyCinemaAndDate("cinemax", "2018-12-18 15:30"); } catch(CinemaPersistenceException e) { assertEquals(e.getMessage(),"No existe el cinema cinemax"); } } @Test public void GetFunctionByCinemaAndDateTest2() { try { CinemaServices cn=ac.getBean(CinemaServices.class); List<CinemaFunction> ar=cn.getFunctionsbyCinemaAndDate("cinemaX", "2018-12-18 15:30"); Set<Cinema> cines=cn.getAllCinemas(); for(Object c: cines.toArray()) { //if (c.) } //assertEquals(.,ar.size() ); } catch(CinemaPersistenceException e) { } } @Test public void GetFunctionByCinemaAndDateTest3() { try { CinemaServices cn=ac.getBean(CinemaServices.class); List<CinemaFunction> ar=cn.getFunctionsbyCinemaAndDate("cinemaX", "2018-12-18 15:40"); assertEquals(0,ar.size() ); } catch(CinemaPersistenceException e) { } } }
5,590
0.67675
0.650081
169
32.053253
29.822008
119
false
false
0
0
0
0
0
0
1.502959
false
false
3
8609a886bed5e7562b00e783e0412c4e090e6179
19,172,734,041,447
09d0ddd512472a10bab82c912b66cbb13113fcbf
/TestApplications/TF-BETA-THERMATK-v5.7.1/DecompiledCode/Procyon/src/main/java/com/airbnb/lottie/model/animatable/AnimatableTextProperties.java
395679d89e480116bde09067c2710799ed7654ce
[]
no_license
sgros/activity_flow_plugin
https://github.com/sgros/activity_flow_plugin
bde2de3745d95e8097c053795c9e990c829a88f4
9e59f8b3adacf078946990db9c58f4965a5ccb48
refs/heads/master
2020-06-19T02:39:13.865000
2019-07-08T20:17:28
2019-07-08T20:17:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// // Decompiled by Procyon v0.5.34 // package com.airbnb.lottie.model.animatable; public class AnimatableTextProperties { public final AnimatableColorValue color; public final AnimatableColorValue stroke; public final AnimatableFloatValue strokeWidth; public final AnimatableFloatValue tracking; public AnimatableTextProperties(final AnimatableColorValue color, final AnimatableColorValue stroke, final AnimatableFloatValue strokeWidth, final AnimatableFloatValue tracking) { this.color = color; this.stroke = stroke; this.strokeWidth = strokeWidth; this.tracking = tracking; } }
UTF-8
Java
646
java
AnimatableTextProperties.java
Java
[]
null
[]
// // Decompiled by Procyon v0.5.34 // package com.airbnb.lottie.model.animatable; public class AnimatableTextProperties { public final AnimatableColorValue color; public final AnimatableColorValue stroke; public final AnimatableFloatValue strokeWidth; public final AnimatableFloatValue tracking; public AnimatableTextProperties(final AnimatableColorValue color, final AnimatableColorValue stroke, final AnimatableFloatValue strokeWidth, final AnimatableFloatValue tracking) { this.color = color; this.stroke = stroke; this.strokeWidth = strokeWidth; this.tracking = tracking; } }
646
0.752322
0.74613
20
31.299999
39.400635
183
false
false
0
0
0
0
0
0
0.6
false
false
3
3c2bdf3393d797b460886cc874e1b95652895c8f
17,557,826,333,121
30f39d6ac4848e87d07c3f5afbc8900e4ca18b0b
/src/com/playground/kid/Ticket.java
2bb1850ad68492e831158b38e5a6e306fed7f7a3
[]
no_license
Rammjalg/Swedbank
https://github.com/Rammjalg/Swedbank
1ef43b6556bce7e28998543ab1b0305832904207
01cbc8e41602b4d698f6b3060d9346755c834cd9
refs/heads/master
2021-05-14T01:45:34.783000
2018-01-10T12:34:19
2018-01-10T12:34:19
116,574,350
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.playground.kid; public class Ticket { public int number; public int vipJumps; public Ticket(int number, int vip) { super(); this.number = number; this.vipJumps = vip; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public int isVip() { return vipJumps; } public void setVip(int vip) { this.vipJumps = vip; } }
UTF-8
Java
443
java
Ticket.java
Java
[]
null
[]
package com.playground.kid; public class Ticket { public int number; public int vipJumps; public Ticket(int number, int vip) { super(); this.number = number; this.vipJumps = vip; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public int isVip() { return vipJumps; } public void setVip(int vip) { this.vipJumps = vip; } }
443
0.61851
0.61851
28
13.821428
11.931512
37
false
false
0
0
0
0
0
0
1.5
false
false
3
a8f57a6c4074298276d7d0b43c85ac4cc6dc9133
17,557,826,335,188
e13b2079c3448f251d1f663422b56013d5c5fbd4
/app/src/main/java/com/android/and0701/yasaandroid/Ch05_ViewFlipper.java
0e4345bfa95fce0556e2209c89ede2abda05ac28
[]
no_license
rohei67/YasashiiAndroid
https://github.com/rohei67/YasashiiAndroid
6900f19f1ab1eb225c8fd9afa8b703eea30ec189
945b5ae82d2f3f461cc212341e688ac77c3f6e92
refs/heads/master
2021-01-10T21:36:12.264000
2015-09-16T05:48:30
2015-09-16T05:48:30
42,552,645
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.android.and0701.yasaandroid; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.os.Bundle; import android.support.annotation.NonNull; import android.util.Log; import android.view.Display; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.ViewFlipper; import java.util.ArrayList; import java.util.Random; /** * Created by 0701AND on 2015/09/09. */ public class Ch05_ViewFlipper extends Activity { static final int NUM = 100; ViewFlipper vf; SampleView[] sv = new SampleView[3]; FrameLayout[] fl = new FrameLayout[3]; float x, y; private int ViewWidth = 0, ViewHeight = 0; final int FLICK_LENGTH = 150; LinearLayout llp; TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); llp = new LinearLayout(this); setContentView(llp); vf = new ViewFlipper(this); TextView[] tv = new TextView[3]; for (int i = 0; i < sv.length; i++) { fl[i] = new FrameLayout(this); sv[i] = new SampleView(this); fl[i].addView(sv[i]); tv[i] = new TextView(this); tv[i].setText("This is Frame No." + (i + 1)); fl[i].addView(tv[i]); vf.addView(fl[i]); } llp.addView(vf); setContentView(llp); llp.setOnTouchListener(new SampleTouchListener()); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); ViewWidth = sv[0].getWidth(); ViewHeight = sv[0].getHeight(); } class SampleTouchListener implements View.OnTouchListener { private boolean isAnimationEnd = true; @Override public boolean onTouch(View v, MotionEvent event) { // Log.v("Sample", "x:"+ViewWidth+" y:"+ViewHeight); if (!isAnimationEnd) return true; if (event.getAction() == MotionEvent.ACTION_DOWN) { x = event.getX(); y = event.getY(); } else if (event.getAction() == MotionEvent.ACTION_UP) { setAnimation(event); } return true; } private void setAnimation(MotionEvent event) { TranslateAnimation outanim; if (x + FLICK_LENGTH < event.getX()) { outanim = setAnimationX(false); } else if (x - FLICK_LENGTH > event.getX()) { outanim = setAnimationX(true); } else if (y + FLICK_LENGTH < event.getY()) { outanim = setAnimationY(true); } else if (y - FLICK_LENGTH > event.getY()) { outanim = setAnimationY(false); } else { return; } outanim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { isAnimationEnd = false; } @Override public void onAnimationEnd(Animation animation) { isAnimationEnd = true; } @Override public void onAnimationRepeat(Animation animation) { } }); } private TranslateAnimation setAnimationY(boolean isNext) { TranslateAnimation inanim; TranslateAnimation outanim; int h = sv[0].getHeight(); inanim = new TranslateAnimation(0, 0, (isNext) ? -h : h, 0); inanim.setDuration(1000); outanim = new TranslateAnimation(0, 0, 0, (isNext) ? h : -h); outanim.setDuration(1000); vf.setInAnimation(inanim); vf.setOutAnimation(outanim); if (isNext) vf.showNext(); else vf.showPrevious(); return outanim; } @NonNull private TranslateAnimation setAnimationX(boolean isNext) { TranslateAnimation inanim; TranslateAnimation outanim; int w = sv[0].getWidth(); inanim = new TranslateAnimation((isNext) ? w : -w, 0, 0, 0); inanim.setDuration(1000); outanim = new TranslateAnimation(0, (isNext) ? -w : w, 0, 0); outanim.setDuration(1000); vf.setInAnimation(inanim); vf.setOutAnimation(outanim); if (isNext) vf.showNext(); else vf.showPrevious(); return outanim; } } class SampleView extends View { ArrayList<Ball> bl; Paint p; public SampleView(Context context) { super(context); bl = new ArrayList<>(); Random rn = new Random(); p = new Paint(); WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); Display disp = wm.getDefaultDisplay(); Point p = new Point(); disp.getSize(p); // Log.v("Sample", "DispX:"+p.x+" DispY:"+p.y); for (int i = 0; i < NUM; i++) { Ball b = new Ball(); b.x = rn.nextInt(p.x - 60) + 30; b.y = rn.nextInt(p.y - 120) + 30; b.r = rn.nextInt(256); b.g = rn.nextInt(256); b.b = rn.nextInt(256); bl.add(b); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); for (int i = 0; i < NUM; i++) { Ball b = bl.get(i); p.setColor(Color.rgb(b.r, b.g, b.b)); p.setStyle(Paint.Style.FILL); canvas.drawCircle(b.x, b.y, 30, p); } Log.v("ViewFlip", "" + vf.getDisplayedChild()); } } class Ball { public int x, y, r, g, b; } }
UTF-8
Java
5,149
java
Ch05_ViewFlipper.java
Java
[ { "context": "List;\nimport java.util.Random;\n\n/**\n * Created by 0701AND on 2015/09/09.\n */\npublic class Ch05_ViewFlipper ", "end": 754, "score": 0.993890643119812, "start": 747, "tag": "USERNAME", "value": "0701AND" } ]
null
[]
package com.android.and0701.yasaandroid; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.os.Bundle; import android.support.annotation.NonNull; import android.util.Log; import android.view.Display; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.ViewFlipper; import java.util.ArrayList; import java.util.Random; /** * Created by 0701AND on 2015/09/09. */ public class Ch05_ViewFlipper extends Activity { static final int NUM = 100; ViewFlipper vf; SampleView[] sv = new SampleView[3]; FrameLayout[] fl = new FrameLayout[3]; float x, y; private int ViewWidth = 0, ViewHeight = 0; final int FLICK_LENGTH = 150; LinearLayout llp; TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); llp = new LinearLayout(this); setContentView(llp); vf = new ViewFlipper(this); TextView[] tv = new TextView[3]; for (int i = 0; i < sv.length; i++) { fl[i] = new FrameLayout(this); sv[i] = new SampleView(this); fl[i].addView(sv[i]); tv[i] = new TextView(this); tv[i].setText("This is Frame No." + (i + 1)); fl[i].addView(tv[i]); vf.addView(fl[i]); } llp.addView(vf); setContentView(llp); llp.setOnTouchListener(new SampleTouchListener()); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); ViewWidth = sv[0].getWidth(); ViewHeight = sv[0].getHeight(); } class SampleTouchListener implements View.OnTouchListener { private boolean isAnimationEnd = true; @Override public boolean onTouch(View v, MotionEvent event) { // Log.v("Sample", "x:"+ViewWidth+" y:"+ViewHeight); if (!isAnimationEnd) return true; if (event.getAction() == MotionEvent.ACTION_DOWN) { x = event.getX(); y = event.getY(); } else if (event.getAction() == MotionEvent.ACTION_UP) { setAnimation(event); } return true; } private void setAnimation(MotionEvent event) { TranslateAnimation outanim; if (x + FLICK_LENGTH < event.getX()) { outanim = setAnimationX(false); } else if (x - FLICK_LENGTH > event.getX()) { outanim = setAnimationX(true); } else if (y + FLICK_LENGTH < event.getY()) { outanim = setAnimationY(true); } else if (y - FLICK_LENGTH > event.getY()) { outanim = setAnimationY(false); } else { return; } outanim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { isAnimationEnd = false; } @Override public void onAnimationEnd(Animation animation) { isAnimationEnd = true; } @Override public void onAnimationRepeat(Animation animation) { } }); } private TranslateAnimation setAnimationY(boolean isNext) { TranslateAnimation inanim; TranslateAnimation outanim; int h = sv[0].getHeight(); inanim = new TranslateAnimation(0, 0, (isNext) ? -h : h, 0); inanim.setDuration(1000); outanim = new TranslateAnimation(0, 0, 0, (isNext) ? h : -h); outanim.setDuration(1000); vf.setInAnimation(inanim); vf.setOutAnimation(outanim); if (isNext) vf.showNext(); else vf.showPrevious(); return outanim; } @NonNull private TranslateAnimation setAnimationX(boolean isNext) { TranslateAnimation inanim; TranslateAnimation outanim; int w = sv[0].getWidth(); inanim = new TranslateAnimation((isNext) ? w : -w, 0, 0, 0); inanim.setDuration(1000); outanim = new TranslateAnimation(0, (isNext) ? -w : w, 0, 0); outanim.setDuration(1000); vf.setInAnimation(inanim); vf.setOutAnimation(outanim); if (isNext) vf.showNext(); else vf.showPrevious(); return outanim; } } class SampleView extends View { ArrayList<Ball> bl; Paint p; public SampleView(Context context) { super(context); bl = new ArrayList<>(); Random rn = new Random(); p = new Paint(); WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); Display disp = wm.getDefaultDisplay(); Point p = new Point(); disp.getSize(p); // Log.v("Sample", "DispX:"+p.x+" DispY:"+p.y); for (int i = 0; i < NUM; i++) { Ball b = new Ball(); b.x = rn.nextInt(p.x - 60) + 30; b.y = rn.nextInt(p.y - 120) + 30; b.r = rn.nextInt(256); b.g = rn.nextInt(256); b.b = rn.nextInt(256); bl.add(b); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); for (int i = 0; i < NUM; i++) { Ball b = bl.get(i); p.setColor(Color.rgb(b.r, b.g, b.b)); p.setStyle(Paint.Style.FILL); canvas.drawCircle(b.x, b.y, 30, p); } Log.v("ViewFlip", "" + vf.getDisplayedChild()); } } class Ball { public int x, y, r, g, b; } }
5,149
0.671198
0.65469
202
24.490099
18.262726
92
false
false
0
0
0
0
0
0
2.737624
false
false
3
9cdbcd1d90000a52d618888dcc78f673e93b798b
22,754,736,750,947
f4c3df730714831c12136588042a3ff7c70e8258
/src/main/java/com/boot/service/CategoryService.java
b933acdf0050371a45183b881ecc8f583582b308
[]
no_license
ExsisDev/WeMakeTattoosBack_Java
https://github.com/ExsisDev/WeMakeTattoosBack_Java
47bbbe303b8ea1899f863effdb0f227a2829c2c2
603362ed6b6724119af950adb14c8ad1a9afc3d0
refs/heads/master
2020-08-01T20:16:18.656000
2019-10-04T22:29:49
2019-10-04T22:29:49
206,346,060
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.boot.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.boot.commons.Response; import com.boot.model.entities.Category; import com.boot.model.repositories.CategoryRepository; import com.boot.service.interfaces.ICategoryService; @Service public class CategoryService implements ICategoryService { @Autowired private CategoryRepository _categoryActions; @Override @Transactional public Response<Category> getAll(){ Iterable<Category> allCategories; try { allCategories = _categoryActions.findAll(); return new Response<Category>(null, null, true, null, allCategories); } catch (Exception e) { return new Response<Category>(e, null, false, null, null); } } }
UTF-8
Java
848
java
CategoryService.java
Java
[]
null
[]
package com.boot.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.boot.commons.Response; import com.boot.model.entities.Category; import com.boot.model.repositories.CategoryRepository; import com.boot.service.interfaces.ICategoryService; @Service public class CategoryService implements ICategoryService { @Autowired private CategoryRepository _categoryActions; @Override @Transactional public Response<Category> getAll(){ Iterable<Category> allCategories; try { allCategories = _categoryActions.findAll(); return new Response<Category>(null, null, true, null, allCategories); } catch (Exception e) { return new Response<Category>(e, null, false, null, null); } } }
848
0.786557
0.786557
31
26.354839
23.989983
72
false
false
0
0
0
0
0
0
1.612903
false
false
3
5a06a556ae4cdaeb308f7a06d487d2e63664b64b
7,361,573,975,156
5089b7962d32f62c96c7dcf7898f16b90a7fb312
/jcg-engine/src/main/java/ir.sk.jcg.jcgengine/model/project/enums/OutputComponentType.java
8a0b4c687e275156cd363302ed8b45d80fc5753f
[]
no_license
skayvanfar/jcg
https://github.com/skayvanfar/jcg
27d90736b4664944b1136cbc3568548b6f3c2c44
147fd972cf5f477839e0c34fab253f0813438608
refs/heads/master
2023-07-03T22:25:20.428000
2021-08-08T08:25:55
2021-08-08T08:25:55
393,901,776
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ir.sk.jcg.jcgengine.model.project.enums; import ir.sk.jcg.jcgcommon.enums.EnumBase; import ir.sk.jcg.jcgengine.model.project.Component; import ir.sk.jcg.jcgengine.model.project.component.Label; import ir.sk.jcg.jcgengine.model.project.component.Link; import ir.sk.jcg.jcgengine.model.project.component.LinkList; import java.util.Objects; /** * @author <a href="kayvanfar.sj@gmail.com">Saeed Kayvanfar</a> on 7/8/2016 */ public enum OutputComponentType implements EnumBase { LABEL(0, "Label"), LINK(1, "Link"), LINK_LIST(2, "LinkList"); private Integer value; private String desc; OutputComponentType(Integer value, String desc) { this.value = value; this.desc = desc; } @Override public Integer getValue() { return value; } @Override public String getDescription() { return desc; } public static OutputComponentType valueOf(Integer type) { for (OutputComponentType code : OutputComponentType.values()) { if (Objects.equals(type, code.getValue())) { return code; } } return null; } public Component createComponent() { Component component = null; switch (this) { case LABEL: component = new Label(); break; case LINK: component = new Link(); break; case LINK_LIST: component = new LinkList(); break; } return component; } @Override public String toString() { return desc; } }
UTF-8
Java
1,644
java
OutputComponentType.java
Java
[ { "context": "mport java.util.Objects;\n\n/**\n * @author <a href=\"kayvanfar.sj@gmail.com\">Saeed Kayvanfar</a> on 7/8/2016\n */\npublic enum ", "end": 395, "score": 0.9999305605888367, "start": 373, "tag": "EMAIL", "value": "kayvanfar.sj@gmail.com" }, { "context": "\n\n/**\n * @author <a href=\"kayvanfar.sj@gmail.com\">Saeed Kayvanfar</a> on 7/8/2016\n */\npublic enum OutputComponentTy", "end": 412, "score": 0.9998922944068909, "start": 397, "tag": "NAME", "value": "Saeed Kayvanfar" } ]
null
[]
package ir.sk.jcg.jcgengine.model.project.enums; import ir.sk.jcg.jcgcommon.enums.EnumBase; import ir.sk.jcg.jcgengine.model.project.Component; import ir.sk.jcg.jcgengine.model.project.component.Label; import ir.sk.jcg.jcgengine.model.project.component.Link; import ir.sk.jcg.jcgengine.model.project.component.LinkList; import java.util.Objects; /** * @author <a href="<EMAIL>"><NAME></a> on 7/8/2016 */ public enum OutputComponentType implements EnumBase { LABEL(0, "Label"), LINK(1, "Link"), LINK_LIST(2, "LinkList"); private Integer value; private String desc; OutputComponentType(Integer value, String desc) { this.value = value; this.desc = desc; } @Override public Integer getValue() { return value; } @Override public String getDescription() { return desc; } public static OutputComponentType valueOf(Integer type) { for (OutputComponentType code : OutputComponentType.values()) { if (Objects.equals(type, code.getValue())) { return code; } } return null; } public Component createComponent() { Component component = null; switch (this) { case LABEL: component = new Label(); break; case LINK: component = new Link(); break; case LINK_LIST: component = new LinkList(); break; } return component; } @Override public String toString() { return desc; } }
1,620
0.591241
0.585766
67
23.537313
19.836893
75
false
false
0
0
0
0
0
0
0.477612
false
false
3
c641d910fbd2fe6376c6e581bb95f2d47ed2cff3
7,980,049,267,803
61e47d107ada681abdccb7dba1c8f832a6189b76
/StrategyAI/src/main/java/wad/service/Poliitikko.java
3631fd7a5c40e24b71142673fd43905fdea719b7
[]
no_license
jippo444/SuperStrategyAI
https://github.com/jippo444/SuperStrategyAI
f5021a68ff9f4cb423e500bd3008d876e20f97a6
0dd310fb2514695d8223c91522af631d8818eb7d
refs/heads/master
2021-01-22T07:57:43.811000
2017-05-27T10:15:20
2017-05-27T10:15:20
92,588,843
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package wad.service; import java.util.Random; import org.springframework.stereotype.Service; import wad.domain.Message; @Service public class Poliitikko { private final String[] lentavatLauseet = { "EU on kuin playboyn avioliitto: vielä kasassa, mutta valhetta täynnä.", "EU:n halu suojella susia on ymmärrettävää, onhan se susi itsekin.", "On yhtä todennäköistä pystyä istuttamaan kookospähkinälle aivot kuin saada EU toimimaan.", "Pienelle kansalle riittää pieni valhe – suurelle kansanjoukolle tarvitaan jo EU.", "Meidän asioistamme päättää entistä enemmän kreikkalainen kommunisti, italialainen fasisti, saksalainen pankkiiri ja ranskalainen sosialisti.", "EU on järjestelmä, jossa punasilmäiset tekevät Brysselissä päätöksiä, joita sinisilmäiset Helsingissä toteuttavat.", "Suomen maatiloista on tullut EU-plantaaseja. Voimattomina katselevat entiset isännät peltosarkojaan, joiden pientareilla Brysselin tarkastajat astelevat omistajan elkein kuin kuovit.", "Kotimaisia ruumiita ulkomaisista sodista! Ja kenen luvalla? Ei ainakaan äitien.", "Sinkkiarkussa on hiljaista. Enää ei kuulu omantunnon ääni.", "Demarit voisivat ajaa rahayksikön muutosta eurosta demariksi. Yksi demari olisi sata tunaria.", "Nyt ei enää kuku kepun käki – sen jo Suomen kansa näki.", "Kemijärvi-kepu on tämän päivän Valco-Sorsa.", "Omilla aivoilla ajattelu on kepun ja SDP:n eduskuntaryhmissä rangaistava teko. Laula siis ryhmässä vaikka kuinka tyhmässä.", "Valtaa EU:ssa käyttävät sosialistit ja euro-kokoomus. Kansallinen kokoomus on historiallinen ekomerkki, jolla kerätään apteekkarien äänet.", "Kyllä kokoomus tuntee tien Suomen kansan takataskulle.", "Samansukuisia olentoja ovat selkärankainen vihreä, rehellinen autokauppias, hymyilevä fasisti, onnellinen kommunisti ja tyytyväinen feministi.", "Jos kaikki eläisivät kuin Jörn Donner, ratikat eivät kulkisi ajoissa.", "RKP on politiikan Hannu Hanhi, joka säästä ja vaalituloksesta huolimatta kelpaa kärrynrasvaksi porvarihallituksen vankkureihin. Se on historian sitkeä surkastuma, jonka kuivumista odotan innolla.", "Olen uskon ja aatteen mies, heteromies, lihansyöjä, isä, aviomies, ravimies ja näköistaiteen ystävä.", "Jos opetuslapset olisivat uskoneet konsensukseen, siinä olisi jäänyt evankeliumi levittämättä.", "Politiikka ei ole yksinkertaista, mutta se ei merkitse, etteikö poliitikko voisi olla yksinkertainen.", "Optio on sileäkätisen saavutettu etu.", "Seteliselkärankainen poliitikko ja optioselkärankainen yritysjohtaja ovat saman puun hedelmiä.", "Mikään yhteiskunta ei ole köyhtynyt köyhiä auttamalla.", "Säännöllisin väliajoin taloushistoriassa koittaa aika, jolloin hölmöt erotetaan heidän rahoistaan.", "Joosefin maailman ensimmäinen suhdanneoppi seitsemästä lihavasta ja seitsemästä laihasta vuodesta on vielä tänäänkin kestävää tavaraa.", "Kukkahattu ja gepardihattu kuuluvat samaan ravintoketjuun. Molemmilla on käsi sinun taskussasi.", "En ymmärrä feministejä, eivätkä he minua. Tästä meillä on yhteisymmärrys.", "Hedelmällisyyshoitoa vihanneksille. Rajansa kaikella, sanoi rusketus pakaralla.", "Ike lähti, Ikenet tulivat.", "Alexin juttu on EU, tuttu juttu, mätä huttu."}; public Message getMessage() { Message msg = new Message(); msg.setContent(lentavatLauseet[new Random().nextInt(lentavatLauseet.length)]); msg.setUsername("TS"); return msg; } }
UTF-8
Java
3,750
java
Poliitikko.java
Java
[ { "context": "en feministi.\",\n \"Jos kaikki eläisivät kuin Jörn Donner, ratikat eivät kulkisi ajoissa.\",\n \"RKP on", "end": 1965, "score": 0.9997953176498413, "start": 1954, "tag": "NAME", "value": "Jörn Donner" }, { "context": "ivät kulkisi ajoissa.\",\n \"RKP on politiikan Hannu Hanhi, joka säästä ja vaalituloksesta huolimatta kelpaa", "end": 2038, "score": 0.9995250701904297, "start": 2027, "tag": "NAME", "value": "Hannu Hanhi" }, { "context": "\",\n \"Ike lähti, Ikenet tulivat.\",\n \"Alexin juttu on EU, tuttu juttu, mätä huttu.\"};\n\n pub", "end": 3351, "score": 0.6681480407714844, "start": 3345, "tag": "NAME", "value": "Alexin" }, { "context": "ntavatLauseet.length)]);\n msg.setUsername(\"TS\");\n return msg;\n }\n}\n", "end": 3579, "score": 0.9732058048248291, "start": 3577, "tag": "USERNAME", "value": "TS" } ]
null
[]
package wad.service; import java.util.Random; import org.springframework.stereotype.Service; import wad.domain.Message; @Service public class Poliitikko { private final String[] lentavatLauseet = { "EU on kuin playboyn avioliitto: vielä kasassa, mutta valhetta täynnä.", "EU:n halu suojella susia on ymmärrettävää, onhan se susi itsekin.", "On yhtä todennäköistä pystyä istuttamaan kookospähkinälle aivot kuin saada EU toimimaan.", "Pienelle kansalle riittää pieni valhe – suurelle kansanjoukolle tarvitaan jo EU.", "Meidän asioistamme päättää entistä enemmän kreikkalainen kommunisti, italialainen fasisti, saksalainen pankkiiri ja ranskalainen sosialisti.", "EU on järjestelmä, jossa punasilmäiset tekevät Brysselissä päätöksiä, joita sinisilmäiset Helsingissä toteuttavat.", "Suomen maatiloista on tullut EU-plantaaseja. Voimattomina katselevat entiset isännät peltosarkojaan, joiden pientareilla Brysselin tarkastajat astelevat omistajan elkein kuin kuovit.", "Kotimaisia ruumiita ulkomaisista sodista! Ja kenen luvalla? Ei ainakaan äitien.", "Sinkkiarkussa on hiljaista. Enää ei kuulu omantunnon ääni.", "Demarit voisivat ajaa rahayksikön muutosta eurosta demariksi. Yksi demari olisi sata tunaria.", "Nyt ei enää kuku kepun käki – sen jo Suomen kansa näki.", "Kemijärvi-kepu on tämän päivän Valco-Sorsa.", "Omilla aivoilla ajattelu on kepun ja SDP:n eduskuntaryhmissä rangaistava teko. Laula siis ryhmässä vaikka kuinka tyhmässä.", "Valtaa EU:ssa käyttävät sosialistit ja euro-kokoomus. Kansallinen kokoomus on historiallinen ekomerkki, jolla kerätään apteekkarien äänet.", "Kyllä kokoomus tuntee tien Suomen kansan takataskulle.", "Samansukuisia olentoja ovat selkärankainen vihreä, rehellinen autokauppias, hymyilevä fasisti, onnellinen kommunisti ja tyytyväinen feministi.", "Jos kaikki eläisivät kuin <NAME>, ratikat eivät kulkisi ajoissa.", "RKP on politiikan <NAME>, joka säästä ja vaalituloksesta huolimatta kelpaa kärrynrasvaksi porvarihallituksen vankkureihin. Se on historian sitkeä surkastuma, jonka kuivumista odotan innolla.", "Olen uskon ja aatteen mies, heteromies, lihansyöjä, isä, aviomies, ravimies ja näköistaiteen ystävä.", "Jos opetuslapset olisivat uskoneet konsensukseen, siinä olisi jäänyt evankeliumi levittämättä.", "Politiikka ei ole yksinkertaista, mutta se ei merkitse, etteikö poliitikko voisi olla yksinkertainen.", "Optio on sileäkätisen saavutettu etu.", "Seteliselkärankainen poliitikko ja optioselkärankainen yritysjohtaja ovat saman puun hedelmiä.", "Mikään yhteiskunta ei ole köyhtynyt köyhiä auttamalla.", "Säännöllisin väliajoin taloushistoriassa koittaa aika, jolloin hölmöt erotetaan heidän rahoistaan.", "Joosefin maailman ensimmäinen suhdanneoppi seitsemästä lihavasta ja seitsemästä laihasta vuodesta on vielä tänäänkin kestävää tavaraa.", "Kukkahattu ja gepardihattu kuuluvat samaan ravintoketjuun. Molemmilla on käsi sinun taskussasi.", "En ymmärrä feministejä, eivätkä he minua. Tästä meillä on yhteisymmärrys.", "Hedelmällisyyshoitoa vihanneksille. Rajansa kaikella, sanoi rusketus pakaralla.", "Ike lähti, Ikenet tulivat.", "Alexin juttu on EU, tuttu juttu, mätä huttu."}; public Message getMessage() { Message msg = new Message(); msg.setContent(lentavatLauseet[new Random().nextInt(lentavatLauseet.length)]); msg.setUsername("TS"); return msg; } }
3,739
0.752977
0.752977
49
72.693878
51.348034
206
false
false
0
0
0
0
0
0
1.367347
false
false
3
57202941292bb33f72c2f1afbbfff2c55bbf8c4f
29,472,065,600,634
3a32a7c18be8010bcd52c214318a6ad53ec92dd3
/factorial of the num.java
82470a3f57576e5b6212bd6c7eb451f750f7a8fc
[]
no_license
Aravind1125/beginner-2
https://github.com/Aravind1125/beginner-2
a4f1a5c33a8f64e1cd3e0a61595db33be4adeb2a
144d2ab4d4d77c27cd0e68d07e6613d52beff392
refs/heads/master
2020-12-02T08:13:44.410000
2017-07-14T18:44:45
2017-07-14T18:44:45
96,790,578
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class java { public static void main (String[] args) { int i,a; double sum = 1; Scanner s = new Scanner(System.in); System.out.println("Enter value here..."); a = s.nextInt(); for (i = 1; i <= a; i++) { sum = sum*i; } System.out.println("Factorial of the num is :" +sum); } }
UTF-8
Java
344
java
factorial of the num.java
Java
[]
null
[]
class java { public static void main (String[] args) { int i,a; double sum = 1; Scanner s = new Scanner(System.in); System.out.println("Enter value here..."); a = s.nextInt(); for (i = 1; i <= a; i++) { sum = sum*i; } System.out.println("Factorial of the num is :" +sum); } }
344
0.5
0.494186
17
18.294117
15.528966
55
false
false
0
0
0
0
0
0
1.176471
false
false
3
94c85d44b28b973d8d8470686747ca8478ddc41e
26,491,358,303,851
1d9c89bedb892d3cc390c67ab6161b42623aca27
/src/main/java/com/boot/computer/model/Computer.java
52f0dc04bba19afb875285e349e45d2745013069
[]
no_license
tylerDurdenHg/computer
https://github.com/tylerDurdenHg/computer
af84d8ddb47b0fe04fed46c17fa7e78ffa4d2ce1
b3d86ffbc15a89ce4d7ba553405871ebf6b1b905
refs/heads/main
2021-01-06T12:36:41.939000
2020-10-03T10:51:44
2020-10-03T10:51:44
241,324,156
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.boot.computer.model; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.validation.constraints.NotEmpty; @Entity @Table(name = "COMPUTER") public class Computer { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column private Long id; @NotEmpty @Column private String name; @OneToOne private Cpu cpu; @ManyToMany(mappedBy ="computer", cascade = CascadeType.ALL) private Set<Producer> producer; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Cpu getCpu() { return cpu; } public void setCpu(Cpu cpu) { this.cpu = cpu; } public Set<Producer> getProducer() { return producer; } public void setProducer(Set<Producer> producer) { this.producer = producer; } }
UTF-8
Java
1,285
java
Computer.java
Java
[]
null
[]
package com.boot.computer.model; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.validation.constraints.NotEmpty; @Entity @Table(name = "COMPUTER") public class Computer { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column private Long id; @NotEmpty @Column private String name; @OneToOne private Cpu cpu; @ManyToMany(mappedBy ="computer", cascade = CascadeType.ALL) private Set<Producer> producer; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Cpu getCpu() { return cpu; } public void setCpu(Cpu cpu) { this.cpu = cpu; } public Set<Producer> getProducer() { return producer; } public void setProducer(Set<Producer> producer) { this.producer = producer; } }
1,285
0.747082
0.747082
71
17.098591
15.924253
61
false
false
0
0
0
0
0
0
1.056338
false
false
3
db0c616b4799aa364e053b37bd27df5dc6e687cc
22,419,729,326,918
ceffc536a6e4e9cb2b4f6145cf32ed42ca595848
/src/test/java/com/github/daddo/validation/tests/RegistrationBeanTest.java
1d7ca9f1c9d9d47407a8c12842278dea2e20a061
[ "Apache-2.0" ]
permissive
daddo/advanced-validation
https://github.com/daddo/advanced-validation
13e26a2d98469cd58193c07ad2922ffb4a04e982
fb9e4185b36ebcfe1c18aa9de17b61b59d0d1366
refs/heads/master
2016-08-11T14:06:03.966000
2015-11-23T16:53:34
2015-11-23T16:53:34
46,033,085
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright 2015 Daniele Monesi * * 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.daddo.validation.tests; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.daddo.validation.testbeans.RegistrationBean; /** * * @author Daniele Monesi - monesidn AT gmail.com */ public class RegistrationBeanTest { private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationBeanTest.class); private static Validator validator; @BeforeClass public static final void beforeClass(){ ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); } /** * Fields empty test. 1 violation expected. */ @Test public void testRegistration_test1(){ RegistrationBean bean = new RegistrationBean(); bean.setName("Name"); bean.setSurname("Surname"); Set<ConstraintViolation<RegistrationBean>> violations = validator.validate(bean); LOGGER.debug("Violations: {}", violations); Assert.assertEquals(1, violations.size()); } /** * Mobile phone set. 0 violations expected. */ @Test public void testRegistration_test2(){ RegistrationBean bean = new RegistrationBean(); bean.setMobile("000000000"); bean.setName("Name"); bean.setSurname("Surname"); Set<ConstraintViolation<RegistrationBean>> violations = validator.validate(bean); LOGGER.debug("Violations: {}", violations); Assert.assertEquals(0, violations.size()); } }
UTF-8
Java
2,243
java
RegistrationBeanTest.java
Java
[ { "context": "/**\n * Copyright 2015 Daniele Monesi\n * \n * Licensed under the Apache License, Version", "end": 36, "score": 0.9998801350593567, "start": 22, "tag": "NAME", "value": "Daniele Monesi" }, { "context": "on.testbeans.RegistrationBean;\n\n/**\n * \n * @author Daniele Monesi - monesidn AT gmail.com\n */\npublic class Registra", "end": 1061, "score": 0.9998810887336731, "start": 1047, "tag": "NAME", "value": "Daniele Monesi" }, { "context": ");\n\t\tbean.setMobile(\"000000000\");\n\t\tbean.setName(\"Name\");\n\t\tbean.setSurname(\"Surname\");\n\t\t\n\t\tSet<Constra", "end": 2023, "score": 0.9538068771362305, "start": 2019, "tag": "NAME", "value": "Name" }, { "context": "000\");\n\t\tbean.setName(\"Name\");\n\t\tbean.setSurname(\"Surname\");\n\t\t\n\t\tSet<ConstraintViolation<RegistrationBean>", "end": 2053, "score": 0.8837158679962158, "start": 2046, "tag": "NAME", "value": "Surname" } ]
null
[]
/** * Copyright 2015 <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.daddo.validation.tests; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.daddo.validation.testbeans.RegistrationBean; /** * * @author <NAME> - monesidn AT gmail.com */ public class RegistrationBeanTest { private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationBeanTest.class); private static Validator validator; @BeforeClass public static final void beforeClass(){ ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); } /** * Fields empty test. 1 violation expected. */ @Test public void testRegistration_test1(){ RegistrationBean bean = new RegistrationBean(); bean.setName("Name"); bean.setSurname("Surname"); Set<ConstraintViolation<RegistrationBean>> violations = validator.validate(bean); LOGGER.debug("Violations: {}", violations); Assert.assertEquals(1, violations.size()); } /** * Mobile phone set. 0 violations expected. */ @Test public void testRegistration_test2(){ RegistrationBean bean = new RegistrationBean(); bean.setMobile("000000000"); bean.setName("Name"); bean.setSurname("Surname"); Set<ConstraintViolation<RegistrationBean>> violations = validator.validate(bean); LOGGER.debug("Violations: {}", violations); Assert.assertEquals(0, violations.size()); } }
2,227
0.748997
0.737851
79
27.392405
25.124207
90
false
false
0
0
0
0
0
0
1.227848
false
false
3
d000f147f8b706831ed71f65e8d7bc5c58dd8a00
19,980,187,893,145
c0289392cfba7ea2b261d8e5310c1a32fd8964a5
/src/main/java/com/valuation/model/ValuationSpringDAO.java
fa151cf1d865083479ef223dc0ad32390fd1a90d
[]
no_license
RayHo8224/ePOS
https://github.com/RayHo8224/ePOS
4dd6f528b54d4fab8429e5490c1fadd95775a916
83ba8269a64ff046aa889f63ab9b1f58c9bcdbaa
refs/heads/master
2018-10-21T06:22:56.063000
2018-08-15T17:34:48
2018-08-15T17:34:48
116,552,327
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.valuation.model; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.hibernate.Query; import org.hibernate.Session; import org.springframework.orm.hibernate5.HibernateTemplate; import com.order_detail.model.Order_DetailVO; import com.valuation_detail.model.Valuation_DetailVO; import com.order.model.OrderVO; import hibernate.util.HibernateUtil; public class ValuationSpringDAO implements Valuation_Interface { private HibernateTemplate hibernateTemplate; public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } @Override public ValuationVO Select_vlt_id(String vlt_id) throws Exception { ValuationVO valuationVO = null; valuationVO = (ValuationVO) hibernateTemplate.get(ValuationVO.class,vlt_id); return valuationVO; } private static final String GET_ONE_STMT_VALUATIONDATE = "from ValuationVO where vlt_date between ? and ?"; @Override public List Select_vlt_date(Date s_vlt_date, Date e_vlt_date) throws Exception { List<OrderVO> list = null; list= (List<OrderVO>) hibernateTemplate.find(GET_ONE_STMT_VALUATIONDATE,new Object[]{s_vlt_date,e_vlt_date}); return list; } @Override public ValuationVO addVltList(ValuationVO valuationVO, List<Valuation_DetailVO> valuation_detailVO_list) throws Exception { hibernateTemplate.save(valuationVO); return valuationVO; } @Override public ValuationVO update(ValuationVO valuationVO, List<Valuation_DetailVO> valuation_detailVO_list) throws Exception { return null; } @Override public void delete(String vlt_id) throws Exception { ValuationVO valuationVO = (ValuationVO) hibernateTemplate.get(ValuationVO.class, vlt_id); hibernateTemplate.delete(valuationVO); } private static final String GET_ALL_STMT = "from ValuationVO order by vlt_id"; @Override public List<ValuationVO> getAll() throws Exception { List<ValuationVO> list = null; list= (List<ValuationVO>) hibernateTemplate.find(GET_ALL_STMT); return list; } private static final String GET_ALL_STMT_BY_N = "from ValuationVO where status = 'N' order by vlt_id "; @Override public List<ValuationVO> getAllByN() throws Exception { List<ValuationVO> list = null; list= (List<ValuationVO>) hibernateTemplate.find(GET_ALL_STMT_BY_N); return list; } @Override public void setStatus(String status, String vlt_id) throws Exception { // hibernateTemplate.bulkUpdate("update ValuationVO set status='"+status+"'where vlt_id='"+vlt_id+"'"); hibernateTemplate.bulkUpdate("update ValuationVO set status=? where vlt_id=?",new Object[]{status,vlt_id}); } }
UTF-8
Java
2,855
java
ValuationSpringDAO.java
Java
[]
null
[]
package com.valuation.model; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.hibernate.Query; import org.hibernate.Session; import org.springframework.orm.hibernate5.HibernateTemplate; import com.order_detail.model.Order_DetailVO; import com.valuation_detail.model.Valuation_DetailVO; import com.order.model.OrderVO; import hibernate.util.HibernateUtil; public class ValuationSpringDAO implements Valuation_Interface { private HibernateTemplate hibernateTemplate; public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } @Override public ValuationVO Select_vlt_id(String vlt_id) throws Exception { ValuationVO valuationVO = null; valuationVO = (ValuationVO) hibernateTemplate.get(ValuationVO.class,vlt_id); return valuationVO; } private static final String GET_ONE_STMT_VALUATIONDATE = "from ValuationVO where vlt_date between ? and ?"; @Override public List Select_vlt_date(Date s_vlt_date, Date e_vlt_date) throws Exception { List<OrderVO> list = null; list= (List<OrderVO>) hibernateTemplate.find(GET_ONE_STMT_VALUATIONDATE,new Object[]{s_vlt_date,e_vlt_date}); return list; } @Override public ValuationVO addVltList(ValuationVO valuationVO, List<Valuation_DetailVO> valuation_detailVO_list) throws Exception { hibernateTemplate.save(valuationVO); return valuationVO; } @Override public ValuationVO update(ValuationVO valuationVO, List<Valuation_DetailVO> valuation_detailVO_list) throws Exception { return null; } @Override public void delete(String vlt_id) throws Exception { ValuationVO valuationVO = (ValuationVO) hibernateTemplate.get(ValuationVO.class, vlt_id); hibernateTemplate.delete(valuationVO); } private static final String GET_ALL_STMT = "from ValuationVO order by vlt_id"; @Override public List<ValuationVO> getAll() throws Exception { List<ValuationVO> list = null; list= (List<ValuationVO>) hibernateTemplate.find(GET_ALL_STMT); return list; } private static final String GET_ALL_STMT_BY_N = "from ValuationVO where status = 'N' order by vlt_id "; @Override public List<ValuationVO> getAllByN() throws Exception { List<ValuationVO> list = null; list= (List<ValuationVO>) hibernateTemplate.find(GET_ALL_STMT_BY_N); return list; } @Override public void setStatus(String status, String vlt_id) throws Exception { // hibernateTemplate.bulkUpdate("update ValuationVO set status='"+status+"'where vlt_id='"+vlt_id+"'"); hibernateTemplate.bulkUpdate("update ValuationVO set status=? where vlt_id=?",new Object[]{status,vlt_id}); } }
2,855
0.752014
0.751664
107
25.682243
31.542168
111
false
false
0
0
0
0
0
0
1.476635
false
false
3
2394f4c6bb2d38a338a80dffa3fd86fe9cfe1fc3
12,137,577,618,063
18a42e4646db05da24d656fea963098c33ab28f2
/src/main/java/fr/gwenzy/discord/electroid/events/ResistorCommandsListener.java
56ddc6b89342a68fe6235a81514e172f5d4d076b
[]
no_license
Gwenzy/Electroid
https://github.com/Gwenzy/Electroid
b4182e2c74e2ed13a24cd69a055b08af6470b199
41504db08c760fa1fcb47ea55f042a50e61c10e4
refs/heads/master
2021-01-22T11:15:58.310000
2017-08-11T17:22:49
2017-08-11T17:22:49
92,676,835
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.gwenzy.discord.electroid.events; import fr.gwenzy.discord.electroid.Main; import sx.blah.discord.api.events.IListener; import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent; import sx.blah.discord.handle.obj.IEmoji; import sx.blah.discord.util.EmbedBuilder; import java.awt.*; public class ResistorCommandsListener implements IListener<MessageReceivedEvent> { public void handle(MessageReceivedEvent messageReceivedEvent) { if(messageReceivedEvent.getMessage().getFormattedContent().startsWith("@Electroid ")){ String[] args = messageReceivedEvent.getMessage().getFormattedContent().split(" "); if(args.length>1) { if(args[1].equalsIgnoreCase("color")){ if(args.length>3){ //String to int value System.out.println("Value Command"); boolean ok = true; long value=0; double percent=0.0; try{ value = Long.parseLong(args[2]); } catch(Exception e){ try{ double val = Double.parseDouble(args[2].substring(0, args[2].length()-1)); switch(args[2].toUpperCase().charAt(args[2].length()-1)){ case 'K': value=(long) (val*1000); break; case 'M': value=(long) (val*1000000); break; case 'G': value=(long) (val*1000000000); break; } } catch(Exception ex){ messageReceivedEvent.getChannel().sendMessage("Value error"); ok = false; } } try{ if(args[3].endsWith("%")) percent = Double.parseDouble(args[3].substring(0, args[3].length()-1)); else{ messageReceivedEvent.getChannel().sendMessage("Percentage error"); ok = false; } } catch(Exception e){ ok= false; messageReceivedEvent.getChannel().sendMessage("Percentage error"); } if(ok){ System.out.println("Calculating with "+value+"..."); String r1, r2, r3, r4; String[] colors={"black", "brown", "red", "orange", "yellow","green", "blue", "purple", "grey", "white", "silver", "gold"}; IEmoji tolerance = null; System.out.println(args.length+":"+args[3]); r1 = colors[Integer.parseInt(String.valueOf(String.valueOf(value).charAt(0)))]; r2 = colors[Integer.parseInt(String.valueOf(String.valueOf(value).charAt(1)))]; r3 = (args.length>4 && args[4].equalsIgnoreCase("5"))?colors[Integer.parseInt(String.valueOf(String.valueOf(value).charAt(2)))]:""; r4 = (args.length>4 && args[4].equalsIgnoreCase("5"))?colors[String.valueOf(value).length()-3]:colors[String.valueOf(value).length()-2]; String s = String.valueOf(percent); if (s.equals("0.05")) { tolerance = messageReceivedEvent.getGuild().getEmojiByName("grey"); } else if (s.equals("0.10")) { tolerance = messageReceivedEvent.getGuild().getEmojiByName("purple"); } else if (s.equals("0.1")) { tolerance = messageReceivedEvent.getGuild().getEmojiByName("purple"); } else if (s.equals("0.25")) { tolerance = messageReceivedEvent.getGuild().getEmojiByName("blue"); } else if (s.equals("0.5")) { tolerance = messageReceivedEvent.getGuild().getEmojiByName("green"); } else if (s.equals("1.0")) { tolerance = messageReceivedEvent.getGuild().getEmojiByName("brown"); } else if (s.equals("2.0")) { tolerance = messageReceivedEvent.getGuild().getEmojiByName("red"); } else if (s.equals("5.0")) { tolerance = messageReceivedEvent.getGuild().getEmojiByName("gold"); } else if (s.equals("10.0")) { tolerance = messageReceivedEvent.getGuild().getEmojiByName("silver"); } EmbedBuilder eb = new EmbedBuilder(); eb.withColor(Color.GREEN); eb.withDesc("Resistor color code request"); eb.appendField("Value", args[2]+"Ω", true); eb.appendField("Tolerance", percent+"%", true); eb.appendField("Color code", ""+messageReceivedEvent.getGuild().getEmojiByName("resist1")+messageReceivedEvent.getGuild().getEmojiByName(r1)+messageReceivedEvent.getGuild().getEmojiByName(r2)+(!r3.equals("")?messageReceivedEvent.getGuild().getEmojiByName(r3):"")+messageReceivedEvent.getGuild().getEmojiByName(r4)+tolerance+messageReceivedEvent.getGuild().getEmojiByName("resist2"), true); messageReceivedEvent.getChannel().sendMessage(eb.build()); } } else{ messageReceivedEvent.getChannel().sendMessage("Please use the correct syntax"); } } else if(args[1].equalsIgnoreCase("value")) { String message = messageReceivedEvent.getMessage().getFormattedContent(); if(args.length>1){ try{ String colorCode; colorCode = message.replaceAll(" ", "").substring(15).replaceAll("><", "-").replace(":", "").replaceAll("resist1", "").replaceAll("resist2", ""); colorCode = colorCode.replaceAll("[^A-Za-z \\-]", ""); if(colorCode.startsWith("-")){ colorCode = colorCode.substring(1, colorCode.length()-1); } System.out.println("color code : "+colorCode); String[] colors = colorCode.toLowerCase().split("-"); System.out.println("Working with "+message.replaceAll(" ", "").substring(15).replaceAll("::", "-").replace(":", "").replaceAll("resist1", "").replaceAll("resist2", "")+" : "+colors[0]+", "+colors[1]+", "+colors[2]+", "+colors[3]); String emValue=""+ messageReceivedEvent.getGuild().getEmojiByName("resist1"); String valueStr = "0"; int value = 0; int multiplier = 0; Double tolerance = 0.0; int i = 0; if(colors.length==4){ for(String color : colors){ emValue+=messageReceivedEvent.getGuild().getEmojiByName(color); System.out.println("New color for i="+i+": "+color); if(i<=1){ valueStr+=Main.resistorValues.get(color); } else if(i==2){ multiplier = (int) Math.pow(10, Main.resistorValues.get(color)); } else if(i==3){ tolerance = Main.resistorTolerances.get(color); } i++; } } else{ for(String color : colors){ emValue+=messageReceivedEvent.getGuild().getEmojiByName(color); System.out.println("New color for i="+i+": "+color); if(i<=2){ valueStr+=Main.resistorValues.get(color); } else if(i==3){ multiplier = (int) Math.pow(10, Main.resistorValues.get(color)); } else if(i==4){ tolerance = Main.resistorTolerances.get(color); } i++; } } emValue+=messageReceivedEvent.getGuild().getEmojiByName("resist2"); value = Integer.parseInt(valueStr)*multiplier; String valueDisp = ""; if(value>=1000){ if(value>=1000000){ valueDisp = String.valueOf(Double.valueOf(value)/1000000)+"M"; } else{ valueDisp = String.valueOf(Double.valueOf(value)/1000)+"k"; } } else valueDisp = String.valueOf(value); //ggme.getChannel().sendMessage("Resistance value is : "+valueDisp.replace(".0", "")+"Ω - "+tolerance+"%").complete(); EmbedBuilder eb = new EmbedBuilder(); eb.withColor(Color.GREEN); eb.withDesc("Resistor value request"); eb.appendField("Color code", emValue+" ",true); eb.appendField("Value", valueDisp.replace(".0", "")+"Ω",true); eb.appendField("Tolerance", tolerance+"%" ,true); messageReceivedEvent.getChannel().sendMessage(eb.build()); }catch(Exception e){ e.printStackTrace(); messageReceivedEvent.getChannel().sendMessage("An error has occured, please check your color code syntax"); } } } } } } }
UTF-8
Java
11,734
java
ResistorCommandsListener.java
Java
[]
null
[]
package fr.gwenzy.discord.electroid.events; import fr.gwenzy.discord.electroid.Main; import sx.blah.discord.api.events.IListener; import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent; import sx.blah.discord.handle.obj.IEmoji; import sx.blah.discord.util.EmbedBuilder; import java.awt.*; public class ResistorCommandsListener implements IListener<MessageReceivedEvent> { public void handle(MessageReceivedEvent messageReceivedEvent) { if(messageReceivedEvent.getMessage().getFormattedContent().startsWith("@Electroid ")){ String[] args = messageReceivedEvent.getMessage().getFormattedContent().split(" "); if(args.length>1) { if(args[1].equalsIgnoreCase("color")){ if(args.length>3){ //String to int value System.out.println("Value Command"); boolean ok = true; long value=0; double percent=0.0; try{ value = Long.parseLong(args[2]); } catch(Exception e){ try{ double val = Double.parseDouble(args[2].substring(0, args[2].length()-1)); switch(args[2].toUpperCase().charAt(args[2].length()-1)){ case 'K': value=(long) (val*1000); break; case 'M': value=(long) (val*1000000); break; case 'G': value=(long) (val*1000000000); break; } } catch(Exception ex){ messageReceivedEvent.getChannel().sendMessage("Value error"); ok = false; } } try{ if(args[3].endsWith("%")) percent = Double.parseDouble(args[3].substring(0, args[3].length()-1)); else{ messageReceivedEvent.getChannel().sendMessage("Percentage error"); ok = false; } } catch(Exception e){ ok= false; messageReceivedEvent.getChannel().sendMessage("Percentage error"); } if(ok){ System.out.println("Calculating with "+value+"..."); String r1, r2, r3, r4; String[] colors={"black", "brown", "red", "orange", "yellow","green", "blue", "purple", "grey", "white", "silver", "gold"}; IEmoji tolerance = null; System.out.println(args.length+":"+args[3]); r1 = colors[Integer.parseInt(String.valueOf(String.valueOf(value).charAt(0)))]; r2 = colors[Integer.parseInt(String.valueOf(String.valueOf(value).charAt(1)))]; r3 = (args.length>4 && args[4].equalsIgnoreCase("5"))?colors[Integer.parseInt(String.valueOf(String.valueOf(value).charAt(2)))]:""; r4 = (args.length>4 && args[4].equalsIgnoreCase("5"))?colors[String.valueOf(value).length()-3]:colors[String.valueOf(value).length()-2]; String s = String.valueOf(percent); if (s.equals("0.05")) { tolerance = messageReceivedEvent.getGuild().getEmojiByName("grey"); } else if (s.equals("0.10")) { tolerance = messageReceivedEvent.getGuild().getEmojiByName("purple"); } else if (s.equals("0.1")) { tolerance = messageReceivedEvent.getGuild().getEmojiByName("purple"); } else if (s.equals("0.25")) { tolerance = messageReceivedEvent.getGuild().getEmojiByName("blue"); } else if (s.equals("0.5")) { tolerance = messageReceivedEvent.getGuild().getEmojiByName("green"); } else if (s.equals("1.0")) { tolerance = messageReceivedEvent.getGuild().getEmojiByName("brown"); } else if (s.equals("2.0")) { tolerance = messageReceivedEvent.getGuild().getEmojiByName("red"); } else if (s.equals("5.0")) { tolerance = messageReceivedEvent.getGuild().getEmojiByName("gold"); } else if (s.equals("10.0")) { tolerance = messageReceivedEvent.getGuild().getEmojiByName("silver"); } EmbedBuilder eb = new EmbedBuilder(); eb.withColor(Color.GREEN); eb.withDesc("Resistor color code request"); eb.appendField("Value", args[2]+"Ω", true); eb.appendField("Tolerance", percent+"%", true); eb.appendField("Color code", ""+messageReceivedEvent.getGuild().getEmojiByName("resist1")+messageReceivedEvent.getGuild().getEmojiByName(r1)+messageReceivedEvent.getGuild().getEmojiByName(r2)+(!r3.equals("")?messageReceivedEvent.getGuild().getEmojiByName(r3):"")+messageReceivedEvent.getGuild().getEmojiByName(r4)+tolerance+messageReceivedEvent.getGuild().getEmojiByName("resist2"), true); messageReceivedEvent.getChannel().sendMessage(eb.build()); } } else{ messageReceivedEvent.getChannel().sendMessage("Please use the correct syntax"); } } else if(args[1].equalsIgnoreCase("value")) { String message = messageReceivedEvent.getMessage().getFormattedContent(); if(args.length>1){ try{ String colorCode; colorCode = message.replaceAll(" ", "").substring(15).replaceAll("><", "-").replace(":", "").replaceAll("resist1", "").replaceAll("resist2", ""); colorCode = colorCode.replaceAll("[^A-Za-z \\-]", ""); if(colorCode.startsWith("-")){ colorCode = colorCode.substring(1, colorCode.length()-1); } System.out.println("color code : "+colorCode); String[] colors = colorCode.toLowerCase().split("-"); System.out.println("Working with "+message.replaceAll(" ", "").substring(15).replaceAll("::", "-").replace(":", "").replaceAll("resist1", "").replaceAll("resist2", "")+" : "+colors[0]+", "+colors[1]+", "+colors[2]+", "+colors[3]); String emValue=""+ messageReceivedEvent.getGuild().getEmojiByName("resist1"); String valueStr = "0"; int value = 0; int multiplier = 0; Double tolerance = 0.0; int i = 0; if(colors.length==4){ for(String color : colors){ emValue+=messageReceivedEvent.getGuild().getEmojiByName(color); System.out.println("New color for i="+i+": "+color); if(i<=1){ valueStr+=Main.resistorValues.get(color); } else if(i==2){ multiplier = (int) Math.pow(10, Main.resistorValues.get(color)); } else if(i==3){ tolerance = Main.resistorTolerances.get(color); } i++; } } else{ for(String color : colors){ emValue+=messageReceivedEvent.getGuild().getEmojiByName(color); System.out.println("New color for i="+i+": "+color); if(i<=2){ valueStr+=Main.resistorValues.get(color); } else if(i==3){ multiplier = (int) Math.pow(10, Main.resistorValues.get(color)); } else if(i==4){ tolerance = Main.resistorTolerances.get(color); } i++; } } emValue+=messageReceivedEvent.getGuild().getEmojiByName("resist2"); value = Integer.parseInt(valueStr)*multiplier; String valueDisp = ""; if(value>=1000){ if(value>=1000000){ valueDisp = String.valueOf(Double.valueOf(value)/1000000)+"M"; } else{ valueDisp = String.valueOf(Double.valueOf(value)/1000)+"k"; } } else valueDisp = String.valueOf(value); //ggme.getChannel().sendMessage("Resistance value is : "+valueDisp.replace(".0", "")+"Ω - "+tolerance+"%").complete(); EmbedBuilder eb = new EmbedBuilder(); eb.withColor(Color.GREEN); eb.withDesc("Resistor value request"); eb.appendField("Color code", emValue+" ",true); eb.appendField("Value", valueDisp.replace(".0", "")+"Ω",true); eb.appendField("Tolerance", tolerance+"%" ,true); messageReceivedEvent.getChannel().sendMessage(eb.build()); }catch(Exception e){ e.printStackTrace(); messageReceivedEvent.getChannel().sendMessage("An error has occured, please check your color code syntax"); } } } } } } }
11,734
0.405592
0.392891
218
51.811928
46.329262
417
false
false
0
0
0
0
0
0
0.66055
false
false
3
b548fe24c12e1761b608181f550c2894140382b6
20,263,655,728,826
5ec69fc365e69148c131aacbe80148f2f4d741cf
/BackEnd/UsersApp/src/main/java/com/microservice/usersapp/entity/MortgagesAccount.java
d66efc6e90445534c94d5e7012e7b9e0a8bba126
[]
no_license
neelsgupta/FEYENORD-ROTTERDAM
https://github.com/neelsgupta/FEYENORD-ROTTERDAM
642179452a06072926fd46d23bb5130b0386ef9c
c3265e609c7ee5fad3267bd706a3149063e764cc
refs/heads/master
2023-01-12T07:14:47.362000
2020-02-20T17:20:06
2020-02-20T17:20:06
241,832,020
0
0
null
false
2023-01-05T07:50:15
2020-02-20T08:33:19
2020-02-20T17:20:28
2023-01-05T07:50:14
2,541
0
0
21
Java
false
false
package com.microservice.usersapp.entity; public class MortgagesAccount { }
UTF-8
Java
80
java
MortgagesAccount.java
Java
[]
null
[]
package com.microservice.usersapp.entity; public class MortgagesAccount { }
80
0.7875
0.7875
5
15
17.787636
41
false
false
0
0
0
0
0
0
0.6
false
false
3
cfcd201fc413797f89ffe52bf5951ec9836126cc
28,707,561,429,511
f23de1a7cf253d7277a4353d6bedf007bf616b45
/src/com/mark/service/productService.java
10ddb5271836a70bb9491cefaaa84d0a1806083c
[]
no_license
littlemilk/shopDemo
https://github.com/littlemilk/shopDemo
6a05fd98a0ac9dc75d0ef7a8bffc95b31d753150
53372d0bbc38b1aaf7cb43e21837ca50bc76a997
refs/heads/master
2021-07-05T23:15:12.211000
2017-09-29T07:35:57
2017-09-29T07:36:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mark.service; import java.sql.SQLException; import java.util.List; import com.mark.bean.Page; import com.mark.bean.Product; import com.mark.constant.Constant; import com.mark.dao.productDao; public class productService { public Product findById(String pid) throws SQLException { productDao productDao = new productDao(); return productDao.findById(pid); } public Page<Product> findByCategoryIdAndPage(String cid, int curPage) throws Exception { productDao productDao = new productDao(); int curSize = Constant.PRODUCTS_IN_PAGE; int count = productDao.countByCid(cid); int sumPage = 0; if(count % curSize == 0){ sumPage = count / curSize; }else{ sumPage = count / curSize + 1; } int b = curSize; int a = (curPage -1)*b; List<Product> list = productDao.findByCid(a, b, cid); //1. 创建PageBean 封装 Page<Product> pageBean = new Page<Product>(); //1.1 封装当前页码 pageBean.setCurPage(curPage); //1.2 封装一页显示的数量 pageBean.setCurSize(curSize); //1.3 封装总数量(查询数据库 count(*)) pageBean.setCount(count); //1.4 封装总页码(算的) pageBean.setSumPage(sumPage); //1.5 封装商品的集合 list pageBean.setList(list); return pageBean; } //关键字查找商品 public List<Product> findByKeyword(String keyword) throws SQLException { productDao dao = new productDao(); List<Product> list = dao.findByKeyword(keyword); return list; } }
GB18030
Java
1,522
java
productService.java
Java
[]
null
[]
package com.mark.service; import java.sql.SQLException; import java.util.List; import com.mark.bean.Page; import com.mark.bean.Product; import com.mark.constant.Constant; import com.mark.dao.productDao; public class productService { public Product findById(String pid) throws SQLException { productDao productDao = new productDao(); return productDao.findById(pid); } public Page<Product> findByCategoryIdAndPage(String cid, int curPage) throws Exception { productDao productDao = new productDao(); int curSize = Constant.PRODUCTS_IN_PAGE; int count = productDao.countByCid(cid); int sumPage = 0; if(count % curSize == 0){ sumPage = count / curSize; }else{ sumPage = count / curSize + 1; } int b = curSize; int a = (curPage -1)*b; List<Product> list = productDao.findByCid(a, b, cid); //1. 创建PageBean 封装 Page<Product> pageBean = new Page<Product>(); //1.1 封装当前页码 pageBean.setCurPage(curPage); //1.2 封装一页显示的数量 pageBean.setCurSize(curSize); //1.3 封装总数量(查询数据库 count(*)) pageBean.setCount(count); //1.4 封装总页码(算的) pageBean.setSumPage(sumPage); //1.5 封装商品的集合 list pageBean.setList(list); return pageBean; } //关键字查找商品 public List<Product> findByKeyword(String keyword) throws SQLException { productDao dao = new productDao(); List<Product> list = dao.findByKeyword(keyword); return list; } }
1,522
0.684951
0.674402
54
24.333334
19.115633
89
false
false
0
0
0
0
0
0
1.944444
false
false
3
c1166ab018fe9dc6e4b89cca2f88509b5798afbe
14,413,910,260,109
2b8d8c021904a1caaea7a38869fb7acf572ac2c1
/src/test/java/com/packt/webstore/controller/CartRestControllerTest.java
01ecb7ce7b306c61dc79638c21abcc7f50ee063b
[]
no_license
kyao233/Spring_MVC
https://github.com/kyao233/Spring_MVC
b862c24e1d59cddb40ba6e2bc89343aa7ad82f4c
a0af8dbdbd60c24a07358f1618f75f1b66e5cfe8
refs/heads/master
2020-03-12T10:49:21.972000
2019-03-26T15:52:57
2019-03-26T15:52:57
130,582,004
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.packt.webstore.controller; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; import org.codehaus.jackson.map.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpSession; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.packt.webstore.domain.Cart; import com.packt.webstore.domain.CartItem; import com.packt.webstore.domain.Product; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("test-DispatcherServlet-context.xml") @WebAppConfiguration public class CartRestControllerTest { @Autowired private WebApplicationContext wac; @Autowired MockHttpSession session; private MockMvc mockMvc; private ObjectMapper mapper; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); this.mapper = new ObjectMapper(); } @Test public void read_method_should_return_correct_cart_Json_object() throws Exception { //Arrange this.mockMvc.perform(put("/rest/cart/add/P1234").session(session)) .andExpect(status().is(204)); //Act this.mockMvc.perform(get("/rest/cart/" + session.getId()).session(session)) .andExpect(status().isOk()) .andExpect(jsonPath("$.cartItems.P1234.product.productId").value("P1234")); } @Test public void create_method_should_return_same_cart() throws Exception { //Arrange Cart cart = new Cart("C12345"); String cartStr = this.mapper.writeValueAsString(cart); //Act this.mockMvc.perform(post("/rest/cart").content(cartStr).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.cartId").value("C12345")); } @Test public void update_method_should_return_updated_cart() throws Exception { //Arrange Cart cart = new Cart("C123456"); String cartStr = this.mapper.writeValueAsString(cart); Cart updatedCart = new Cart("C123456"); Product product = new Product("P1234", "iphone 5s", new BigDecimal(500)); CartItem cartItem = new CartItem(product); Map<String, CartItem> cartItems = new HashMap<String, CartItem>(); cartItems.put("P1234", cartItem); updatedCart.setCartItems(cartItems); String updatedCartStr = this.mapper.writeValueAsString(updatedCart); this.mockMvc.perform(post("/rest/cart").content(cartStr).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); //act this.mockMvc.perform(put("/rest/cart/C123456").content(updatedCartStr).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().is2xxSuccessful()); //Assert this.mockMvc.perform(get("/rest/cart/C123456")) .andExpect(status().isOk()) .andExpect(jsonPath("$.cartItems.P1234.product.productId").value("P1234")); } @Test public void delete_method_should_delete_cart() throws Exception { //Arrange this.mockMvc.perform(put("/rest/cart/add/P1234").session(session)) .andExpect(status().is(204)); //Act this.mockMvc.perform(delete("/rest/cart/" + session.getId())) .andExpect(status().is(204)); //Assert this.mockMvc.perform(get("/rest/cart/" + session.getId())) .andExpect(status().isOk()) .andExpect(content().string("")); } }
UTF-8
Java
4,336
java
CartRestControllerTest.java
Java
[]
null
[]
package com.packt.webstore.controller; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; import org.codehaus.jackson.map.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpSession; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.packt.webstore.domain.Cart; import com.packt.webstore.domain.CartItem; import com.packt.webstore.domain.Product; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("test-DispatcherServlet-context.xml") @WebAppConfiguration public class CartRestControllerTest { @Autowired private WebApplicationContext wac; @Autowired MockHttpSession session; private MockMvc mockMvc; private ObjectMapper mapper; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); this.mapper = new ObjectMapper(); } @Test public void read_method_should_return_correct_cart_Json_object() throws Exception { //Arrange this.mockMvc.perform(put("/rest/cart/add/P1234").session(session)) .andExpect(status().is(204)); //Act this.mockMvc.perform(get("/rest/cart/" + session.getId()).session(session)) .andExpect(status().isOk()) .andExpect(jsonPath("$.cartItems.P1234.product.productId").value("P1234")); } @Test public void create_method_should_return_same_cart() throws Exception { //Arrange Cart cart = new Cart("C12345"); String cartStr = this.mapper.writeValueAsString(cart); //Act this.mockMvc.perform(post("/rest/cart").content(cartStr).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.cartId").value("C12345")); } @Test public void update_method_should_return_updated_cart() throws Exception { //Arrange Cart cart = new Cart("C123456"); String cartStr = this.mapper.writeValueAsString(cart); Cart updatedCart = new Cart("C123456"); Product product = new Product("P1234", "iphone 5s", new BigDecimal(500)); CartItem cartItem = new CartItem(product); Map<String, CartItem> cartItems = new HashMap<String, CartItem>(); cartItems.put("P1234", cartItem); updatedCart.setCartItems(cartItems); String updatedCartStr = this.mapper.writeValueAsString(updatedCart); this.mockMvc.perform(post("/rest/cart").content(cartStr).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); //act this.mockMvc.perform(put("/rest/cart/C123456").content(updatedCartStr).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().is2xxSuccessful()); //Assert this.mockMvc.perform(get("/rest/cart/C123456")) .andExpect(status().isOk()) .andExpect(jsonPath("$.cartItems.P1234.product.productId").value("P1234")); } @Test public void delete_method_should_delete_cart() throws Exception { //Arrange this.mockMvc.perform(put("/rest/cart/add/P1234").session(session)) .andExpect(status().is(204)); //Act this.mockMvc.perform(delete("/rest/cart/" + session.getId())) .andExpect(status().is(204)); //Assert this.mockMvc.perform(get("/rest/cart/" + session.getId())) .andExpect(status().isOk()) .andExpect(content().string("")); } }
4,336
0.765683
0.746541
133
31.601503
29.580511
113
false
false
0
0
0
0
0
0
1.578947
false
false
3
4c22291aad7cf183815397b1cb658ac74ed3e64a
14,413,910,257,863
352581e5698f8b7ac35032429dfad9d3359873be
/easyexcel-plus-export/src/main/java/com/gongbo/excel/export/core/ExportHandlers.java
2c6b4156c0d1e517f62d328432d6558b894dfef9
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
gongbox/easy-excel-plus
https://github.com/gongbox/easy-excel-plus
6995e383b8383e367a6b124eb011d644ecdcf33e
ec1df3ca6ca2edd9fb52b8473c22c797bf5fe008
refs/heads/master
2023-05-12T06:00:55.290000
2022-05-19T09:43:12
2022-05-19T09:43:12
375,875,721
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gongbo.excel.export.core; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.springframework.beans.BeanUtils; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @NoArgsConstructor(access = AccessLevel.PRIVATE) public class ExportHandlers { /** * Cache */ private static final Map<Class<?>, Object> handlerCache = new ConcurrentHashMap<>(); /** * @param clazz * @param <T> * @return */ public static <T> T of(Class<T> clazz) { return (T) handlerCache.computeIfAbsent(clazz, BeanUtils::instantiateClass); } }
UTF-8
Java
620
java
ExportHandlers.java
Java
[]
null
[]
package com.gongbo.excel.export.core; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.springframework.beans.BeanUtils; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @NoArgsConstructor(access = AccessLevel.PRIVATE) public class ExportHandlers { /** * Cache */ private static final Map<Class<?>, Object> handlerCache = new ConcurrentHashMap<>(); /** * @param clazz * @param <T> * @return */ public static <T> T of(Class<T> clazz) { return (T) handlerCache.computeIfAbsent(clazz, BeanUtils::instantiateClass); } }
620
0.68871
0.68871
26
22.846153
24.01713
88
false
false
0
0
0
0
0
0
0.384615
false
false
3
b6037654b8fa6afc90abdde5470d6c42162abdb5
17,806,934,445,077
40c99c840dae66089416358d13fe899cf8334083
/DHLQMSEJB/com/qms/setup/java/ZoneCodeMasterDOB.java
3bdbec5add3ce003c5d10138ba198cc5aae19187
[]
no_license
diliproutkewill/QMS
https://github.com/diliproutkewill/QMS
59f44389a2f6665b4911f7eaa3c853b34a83747c
234a64bdb8fe15c7f354696183b35d3326b2ddce
refs/heads/master
2016-08-05T00:30:15.389000
2015-11-25T08:34:59
2015-11-25T08:34:59
41,022,965
0
0
null
false
2015-11-25T08:35:00
2015-08-19T08:41:15
2015-08-19T08:54:22
2015-11-25T08:34:59
128,475
0
0
0
Java
null
null
package com.qms.setup.java; import java.io.Serializable; import java.util.ArrayList; public class ZoneCodeMasterDOB implements Serializable { private String originLocation = null; private String city = null; private String state = null; private String zipCode = null; private String zoneCode = null; private String remarks = null; private String terminalId = null; private ArrayList zoneList = null; private String shipmentMode; private String consoleType; private int rowId; public ZoneCodeMasterDOB() { } public ZoneCodeMasterDOB(String originLocation,String terminalId,String city,String state,String zipCode) { this.originLocation = originLocation; this.terminalId = terminalId; this.city = city; this.state = state; this.zipCode = zipCode; //this.port = port; } public void setOriginLocation(String originLocation) { this.originLocation = originLocation; } public String getOriginLocation() { return originLocation; } public void setCity(String city) { this.city = city; } public String getCity() { return city; } public void setState(String state) { this.state = state; } public String getState() { return state; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getZipCode() { return zipCode; } public void setZoneCode(String zoneCode) { this.zoneCode = zoneCode; } public String getZoneCode() { return zoneCode; } public void setZoneCodeList(ArrayList zoneList) { this.zoneList = zoneList; } public ArrayList getZoneCodeList() { return zoneList; } public void setRemarks(String remarks) { this.remarks = remarks; } public String getRemarks() { return remarks; } public void setTerminalId(String terminalId) { this.terminalId = terminalId; } public String getTerminalId() { return terminalId; } public String getShipmentMode() { return shipmentMode; } public void setShipmentMode(String shipmentMode) { this.shipmentMode = shipmentMode; } public String getConsoleType() { return consoleType; } public void setConsoleType(String consoleType) { this.consoleType = consoleType; } public int getRowId() { return rowId; } public void setRowId(int rowId) { this.rowId = rowId; } }
UTF-8
Java
2,652
java
ZoneCodeMasterDOB.java
Java
[]
null
[]
package com.qms.setup.java; import java.io.Serializable; import java.util.ArrayList; public class ZoneCodeMasterDOB implements Serializable { private String originLocation = null; private String city = null; private String state = null; private String zipCode = null; private String zoneCode = null; private String remarks = null; private String terminalId = null; private ArrayList zoneList = null; private String shipmentMode; private String consoleType; private int rowId; public ZoneCodeMasterDOB() { } public ZoneCodeMasterDOB(String originLocation,String terminalId,String city,String state,String zipCode) { this.originLocation = originLocation; this.terminalId = terminalId; this.city = city; this.state = state; this.zipCode = zipCode; //this.port = port; } public void setOriginLocation(String originLocation) { this.originLocation = originLocation; } public String getOriginLocation() { return originLocation; } public void setCity(String city) { this.city = city; } public String getCity() { return city; } public void setState(String state) { this.state = state; } public String getState() { return state; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getZipCode() { return zipCode; } public void setZoneCode(String zoneCode) { this.zoneCode = zoneCode; } public String getZoneCode() { return zoneCode; } public void setZoneCodeList(ArrayList zoneList) { this.zoneList = zoneList; } public ArrayList getZoneCodeList() { return zoneList; } public void setRemarks(String remarks) { this.remarks = remarks; } public String getRemarks() { return remarks; } public void setTerminalId(String terminalId) { this.terminalId = terminalId; } public String getTerminalId() { return terminalId; } public String getShipmentMode() { return shipmentMode; } public void setShipmentMode(String shipmentMode) { this.shipmentMode = shipmentMode; } public String getConsoleType() { return consoleType; } public void setConsoleType(String consoleType) { this.consoleType = consoleType; } public int getRowId() { return rowId; } public void setRowId(int rowId) { this.rowId = rowId; } }
2,652
0.622549
0.622549
135
18.651852
19.094431
107
false
false
0
0
0
0
0
0
0.340741
false
false
3
387df85a0a2f67052dd746d9d9e7c1e0e1189e85
10,359,461,143,708
369270a14e669687b5b506b35895ef385dad11ab
/javafx.graphics/com/sun/prism/sw/SWResourceFactory.java
e4665f174b7a2242679133a270011d61b9fe5c69
[]
no_license
zcc888/Java9Source
https://github.com/zcc888/Java9Source
39254262bd6751203c2002d9fc020da533f78731
7776908d8053678b0b987101a50d68995c65b431
refs/heads/master
2021-09-10T05:49:56.469000
2018-03-20T06:26:03
2018-03-20T06:26:03
125,970,208
3
3
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.prism.sw; import com.sun.glass.ui.Screen; import com.sun.prism.Image; import com.sun.prism.MediaFrame; import com.sun.prism.Mesh; import com.sun.prism.MeshView; import com.sun.prism.PhongMaterial; import com.sun.prism.PixelFormat; import com.sun.prism.Presentable; import com.sun.prism.PresentableState; import com.sun.prism.ResourceFactory; import com.sun.prism.RTTexture; import com.sun.prism.Texture; import com.sun.prism.Texture.Usage; import com.sun.prism.Texture.WrapMode; import com.sun.prism.impl.BaseResourceFactory; import com.sun.prism.impl.PrismSettings; import com.sun.prism.impl.TextureResourcePool; import com.sun.prism.impl.shape.BasicRoundRectRep; import com.sun.prism.impl.shape.BasicShapeRep; import com.sun.prism.shape.ShapeRep; import java.util.Map; import java.util.WeakHashMap; final class SWResourceFactory extends BaseResourceFactory implements ResourceFactory { private static final Map<Image,Texture> clampTexCache = new WeakHashMap<>(); private static final Map<Image,Texture> repeatTexCache = new WeakHashMap<>(); private static final Map<Image,Texture> mipmapTexCache = new WeakHashMap<>(); private static final ShapeRep theRep = new BasicShapeRep(); private static final ShapeRep rectRep = new BasicRoundRectRep(); private Screen screen; private final SWContext context; public SWResourceFactory(Screen screen) { super(clampTexCache, repeatTexCache, mipmapTexCache); this.screen = screen; this.context = new SWContext(this); } public TextureResourcePool getTextureResourcePool() { return SWTexturePool.instance; } public Screen getScreen() { return screen; } SWContext getContext() { return context; } @Override public void dispose() { context.dispose(); } @Override public ShapeRep createArcRep() { return theRep; } @Override public ShapeRep createEllipseRep() { return theRep; } @Override public ShapeRep createRoundRectRep() { return rectRep; } @Override public ShapeRep createPathRep() { return theRep; } @Override public Presentable createPresentable(PresentableState pState) { if (PrismSettings.debug) { System.out.println("+ SWRF.createPresentable()"); } return new SWPresentable(pState, this); } public int getRTTWidth(int w, WrapMode wrapMode) { return w; } public int getRTTHeight(int h, WrapMode wrapMode) { return h; } @Override public boolean isCompatibleTexture(Texture tex) { return tex instanceof SWTexture; } @Override public RTTexture createRTTexture(int width, int height, WrapMode wrapMode, boolean msaa) { return createRTTexture(width, height, wrapMode); } @Override public RTTexture createRTTexture(int width, int height, WrapMode wrapMode) { SWTexturePool pool = SWTexturePool.instance; long size = pool.estimateRTTextureSize(width, height, false); if (!pool.prepareForAllocation(size)) { return null; } return new SWRTTexture(this, width, height); } @Override public int getMaximumTextureSize() { return Integer.MAX_VALUE; } @Override public boolean isFormatSupported(PixelFormat format) { switch (format) { case BYTE_RGB: case BYTE_GRAY: case INT_ARGB_PRE: case BYTE_BGRA_PRE: return true; case BYTE_ALPHA: case BYTE_APPLE_422: case MULTI_YCbCr_420: case FLOAT_XYZW: default: return false; } } @Override protected boolean canClampToZero() { return false; } @Override public Texture createTexture(MediaFrame vdb) { return new SWArgbPreTexture(this, WrapMode.CLAMP_TO_EDGE, vdb.getWidth(), vdb.getHeight()); } @Override public Texture createTexture(PixelFormat formatHint, Usage usageHint, WrapMode wrapMode, int w, int h) { SWTexturePool pool = SWTexturePool.instance; long size = pool.estimateTextureSize(w, h, formatHint); if (!pool.prepareForAllocation(size)) { return null; } return SWTexture.create(this, formatHint, wrapMode, w, h); } @Override public Texture createTexture(PixelFormat formatHint, Usage usageHint, WrapMode wrapMode, int w, int h, boolean useMipmap) { return createTexture(formatHint, usageHint, wrapMode, w, h); } public PhongMaterial createPhongMaterial() { throw new UnsupportedOperationException("Not supported yet."); } public MeshView createMeshView(Mesh mesh) { throw new UnsupportedOperationException("Not supported yet."); } public Mesh createMesh() { throw new UnsupportedOperationException("Not supported yet."); } }
UTF-8
Java
5,372
java
SWResourceFactory.java
Java
[]
null
[]
/* * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.prism.sw; import com.sun.glass.ui.Screen; import com.sun.prism.Image; import com.sun.prism.MediaFrame; import com.sun.prism.Mesh; import com.sun.prism.MeshView; import com.sun.prism.PhongMaterial; import com.sun.prism.PixelFormat; import com.sun.prism.Presentable; import com.sun.prism.PresentableState; import com.sun.prism.ResourceFactory; import com.sun.prism.RTTexture; import com.sun.prism.Texture; import com.sun.prism.Texture.Usage; import com.sun.prism.Texture.WrapMode; import com.sun.prism.impl.BaseResourceFactory; import com.sun.prism.impl.PrismSettings; import com.sun.prism.impl.TextureResourcePool; import com.sun.prism.impl.shape.BasicRoundRectRep; import com.sun.prism.impl.shape.BasicShapeRep; import com.sun.prism.shape.ShapeRep; import java.util.Map; import java.util.WeakHashMap; final class SWResourceFactory extends BaseResourceFactory implements ResourceFactory { private static final Map<Image,Texture> clampTexCache = new WeakHashMap<>(); private static final Map<Image,Texture> repeatTexCache = new WeakHashMap<>(); private static final Map<Image,Texture> mipmapTexCache = new WeakHashMap<>(); private static final ShapeRep theRep = new BasicShapeRep(); private static final ShapeRep rectRep = new BasicRoundRectRep(); private Screen screen; private final SWContext context; public SWResourceFactory(Screen screen) { super(clampTexCache, repeatTexCache, mipmapTexCache); this.screen = screen; this.context = new SWContext(this); } public TextureResourcePool getTextureResourcePool() { return SWTexturePool.instance; } public Screen getScreen() { return screen; } SWContext getContext() { return context; } @Override public void dispose() { context.dispose(); } @Override public ShapeRep createArcRep() { return theRep; } @Override public ShapeRep createEllipseRep() { return theRep; } @Override public ShapeRep createRoundRectRep() { return rectRep; } @Override public ShapeRep createPathRep() { return theRep; } @Override public Presentable createPresentable(PresentableState pState) { if (PrismSettings.debug) { System.out.println("+ SWRF.createPresentable()"); } return new SWPresentable(pState, this); } public int getRTTWidth(int w, WrapMode wrapMode) { return w; } public int getRTTHeight(int h, WrapMode wrapMode) { return h; } @Override public boolean isCompatibleTexture(Texture tex) { return tex instanceof SWTexture; } @Override public RTTexture createRTTexture(int width, int height, WrapMode wrapMode, boolean msaa) { return createRTTexture(width, height, wrapMode); } @Override public RTTexture createRTTexture(int width, int height, WrapMode wrapMode) { SWTexturePool pool = SWTexturePool.instance; long size = pool.estimateRTTextureSize(width, height, false); if (!pool.prepareForAllocation(size)) { return null; } return new SWRTTexture(this, width, height); } @Override public int getMaximumTextureSize() { return Integer.MAX_VALUE; } @Override public boolean isFormatSupported(PixelFormat format) { switch (format) { case BYTE_RGB: case BYTE_GRAY: case INT_ARGB_PRE: case BYTE_BGRA_PRE: return true; case BYTE_ALPHA: case BYTE_APPLE_422: case MULTI_YCbCr_420: case FLOAT_XYZW: default: return false; } } @Override protected boolean canClampToZero() { return false; } @Override public Texture createTexture(MediaFrame vdb) { return new SWArgbPreTexture(this, WrapMode.CLAMP_TO_EDGE, vdb.getWidth(), vdb.getHeight()); } @Override public Texture createTexture(PixelFormat formatHint, Usage usageHint, WrapMode wrapMode, int w, int h) { SWTexturePool pool = SWTexturePool.instance; long size = pool.estimateTextureSize(w, h, formatHint); if (!pool.prepareForAllocation(size)) { return null; } return SWTexture.create(this, formatHint, wrapMode, w, h); } @Override public Texture createTexture(PixelFormat formatHint, Usage usageHint, WrapMode wrapMode, int w, int h, boolean useMipmap) { return createTexture(formatHint, usageHint, wrapMode, w, h); } public PhongMaterial createPhongMaterial() { throw new UnsupportedOperationException("Not supported yet."); } public MeshView createMeshView(Mesh mesh) { throw new UnsupportedOperationException("Not supported yet."); } public Mesh createMesh() { throw new UnsupportedOperationException("Not supported yet."); } }
5,372
0.645756
0.64315
196
26.408163
25.178885
104
false
false
0
0
0
0
0
0
0.545918
false
false
3
ea7f4df7496d5c617bce77a729402c1b13102da6
13,907,104,137,462
08bda930c52d532c6f66a17f8b0c88fca90bc7e0
/src/Controle/Forno/AlterarFornoCtrl.java
c2c7d6a4a7173ba9b42586cb23b9fdd4b30295a5
[]
no_license
breakx/ProjetoMadeiraCarvao
https://github.com/breakx/ProjetoMadeiraCarvao
0a6040b9977cb9d891fe4928817942a6c8f11511
748688b0a30c383e4d9d27101860c8ec618f1b71
refs/heads/master
2021-01-17T14:29:11.931000
2017-07-13T18:21:19
2017-07-13T18:21:19
54,673,671
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 Controle.Forno; import Controle.ControleForno; import Modelo.ExecutarSql; /** * * @author Cristiano GD */ public class AlterarFornoCtrl { public AlterarFornoCtrl(ControleForno forno) { String query = "UPDATE forno SET " + "`nome_forno` = '"+forno.getNome_forno() + "', `volume_maximo_forno` = '"+forno.getVolume_maximo_forno() + "', `situacao_forno` = '"+forno.getSituacao_forno() + "', `upc_forno` = '"+forno.getUpc_forno() + "', `data_alteracao` = '"+forno.getData_alteracao() + "', `usuario_alt` = '"+forno.getUsuario_alt() + "' WHERE id_forno = "+forno.getId_forno(); ExecutarSql execut = new ExecutarSql(); execut.executar(query); } }
UTF-8
Java
987
java
AlterarFornoCtrl.java
Java
[ { "context": "rno;\nimport Modelo.ExecutarSql;\n\n/**\n *\n * @author Cristiano GD\n */\npublic class AlterarFornoCtrl {\n\n public A", "end": 299, "score": 0.9993055462837219, "start": 287, "tag": "NAME", "value": "Cristiano GD" } ]
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 Controle.Forno; import Controle.ControleForno; import Modelo.ExecutarSql; /** * * @author <NAME> */ public class AlterarFornoCtrl { public AlterarFornoCtrl(ControleForno forno) { String query = "UPDATE forno SET " + "`nome_forno` = '"+forno.getNome_forno() + "', `volume_maximo_forno` = '"+forno.getVolume_maximo_forno() + "', `situacao_forno` = '"+forno.getSituacao_forno() + "', `upc_forno` = '"+forno.getUpc_forno() + "', `data_alteracao` = '"+forno.getData_alteracao() + "', `usuario_alt` = '"+forno.getUsuario_alt() + "' WHERE id_forno = "+forno.getId_forno(); ExecutarSql execut = new ExecutarSql(); execut.executar(query); } }
981
0.588652
0.588652
29
33.034481
26.708494
79
false
false
0
0
0
0
0
0
0.482759
false
false
3
d9bd00373057d1c5f837edaf91acf58ccd337929
29,429,115,954,039
9d7cd22532126b67f34d5b25f631a762d8fd4fbe
/src/java/br/com/melkran/drefc/bean/EmpresaMB.java
b9e78bcd0662e5dfe1600712fc9cada94f1da853
[]
no_license
jaaday/drefc
https://github.com/jaaday/drefc
81de8baad8637391dff5c460f1484438c8f6207e
c48a756a619e9c380fff669d734af9f96b615198
refs/heads/master
2021-01-10T10:31:51.863000
2015-11-24T12:42:45
2015-11-24T12:42:45
46,454,142
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 br.com.melkran.drefc.bean; import br.com.melkran.drefc.dao.EmpresaJpaController; import br.com.melkran.drefc.dao.util.JPAUtil; import br.com.melkran.drefc.model.Empresa; import java.util.List; import org.primefaces.event.SelectEvent; /** * * @author sephi_000 */ public class EmpresaMB { /** * Creates a new instance of EmpresaMB */ private EmpresaJpaController dao; private Empresa empresa; private String estado; private List<Empresa> filteredEmpresas; public EmpresaMB() { dao = new EmpresaJpaController(JPAUtil.EMF); empresa = new Empresa(); estado = "INSERIR"; } public void acao(){ try { switch (estado) { case "INSERIR": inserir(); break; case "ATUALIZAR": atualizar(); break; } empresa = new Empresa(); } catch (Exception e) { } } public void inserir(){ try { dao.create(empresa); estado = "INSERIR"; } catch (Exception e) { } } public void atualizar(){ try { dao.edit(empresa); estado = "INSERIR"; } catch (Exception e) { } } public void remover(Empresa emp){ try { dao.destroy(emp.getId()); } catch (Exception e) { } } public Empresa getEmpresa() { return empresa; } public void setEmpresa(Empresa empresa) { this.empresa = empresa; } public List<Empresa> getEmpresas(){ return dao.findEmpresaEntities(); } public void onRowSelect(SelectEvent event) { this.setEmpresa((Empresa) event.getObject()); estado = "ATUALIZAR"; } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } }
UTF-8
Java
2,280
java
EmpresaMB.java
Java
[ { "context": "imefaces.event.SelectEvent;\r\n\r\n/**\r\n *\r\n * @author sephi_000\r\n */\r\npublic class EmpresaMB {\r\n\r\n /**\r\n * C", "end": 471, "score": 0.9538024067878723, "start": 462, "tag": "USERNAME", "value": "sephi_000" } ]
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 br.com.melkran.drefc.bean; import br.com.melkran.drefc.dao.EmpresaJpaController; import br.com.melkran.drefc.dao.util.JPAUtil; import br.com.melkran.drefc.model.Empresa; import java.util.List; import org.primefaces.event.SelectEvent; /** * * @author sephi_000 */ public class EmpresaMB { /** * Creates a new instance of EmpresaMB */ private EmpresaJpaController dao; private Empresa empresa; private String estado; private List<Empresa> filteredEmpresas; public EmpresaMB() { dao = new EmpresaJpaController(JPAUtil.EMF); empresa = new Empresa(); estado = "INSERIR"; } public void acao(){ try { switch (estado) { case "INSERIR": inserir(); break; case "ATUALIZAR": atualizar(); break; } empresa = new Empresa(); } catch (Exception e) { } } public void inserir(){ try { dao.create(empresa); estado = "INSERIR"; } catch (Exception e) { } } public void atualizar(){ try { dao.edit(empresa); estado = "INSERIR"; } catch (Exception e) { } } public void remover(Empresa emp){ try { dao.destroy(emp.getId()); } catch (Exception e) { } } public Empresa getEmpresa() { return empresa; } public void setEmpresa(Empresa empresa) { this.empresa = empresa; } public List<Empresa> getEmpresas(){ return dao.findEmpresaEntities(); } public void onRowSelect(SelectEvent event) { this.setEmpresa((Empresa) event.getObject()); estado = "ATUALIZAR"; } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } }
2,280
0.525439
0.524123
97
21.505156
16.935368
79
false
false
0
0
0
0
0
0
0.340206
false
false
3
038ce58babc481430a98411fd92d27ba35788c7d
19,035,295,089,326
85cb8717d157e7bfbb20e083f962fad03581029b
/src/com/qa/conditionals/Result.java
ea05d6b6311c2e76944ec8809877bb4141de88dd
[]
no_license
TigistBekele/Java_beginner
https://github.com/TigistBekele/Java_beginner
a50946e57fce21bf4acc516d3768a24e80fad3fe
52965abadeb9c0bec8df06ab55fc41e03442f924
refs/heads/main
2023-05-03T00:35:02.868000
2021-05-25T16:23:09
2021-05-25T16:23:09
369,066,122
0
0
null
false
2021-05-25T16:23:10
2021-05-20T03:18:45
2021-05-24T06:01:02
2021-05-25T16:23:09
42
0
0
0
Java
false
false
package com.qa.conditionals; public class Result { public static double Physics = 130; public static double Chemistry = 100; public static double Biology = 110; public static double total = Physics + Chemistry + Biology; public static double percentage; public static double passmarkPhy = Physics * 100 / 150; public static double passmarkChem = Chemistry * 100 / 150; public static double passmarkBio = Biology * 100 / 150; public static void displayResults() { // TODO Auto-generated method stub System.out.println("Physics Marks: " + Physics); System.out.println("Physics Marks: " + Chemistry); System.out.println("Physics Marks: " + Biology); System.out.println("overall MArk : " + total); } public static void displayExamOverall() { System.out.println("persentage of all : " + total * 100 / 450); } public static void displayPassMark() { System.out.println("PassMark of Physics is : " + passmarkPhy); System.out.println("PassMark of Physics is : " + passmarkChem); System.out.println("PassMark of Physics is : " + passmarkBio); } public static void displayOverallPassMark() { if ((passmarkPhy > 60) && (passmarkChem > 60) && (passmarkBio > 60)) { System.out.println("You pass all exam"); } else { System.out.println("You fail"); } // ****************************OR********************************** // if((passmarkPhy < 60) || (passmarkChem < 60) || (passmarkBio < 60)) { // System.out.println( "You fail "); // }else { // System.out.println("You pass all exam"); // } // } }
UTF-8
Java
1,605
java
Result.java
Java
[]
null
[]
package com.qa.conditionals; public class Result { public static double Physics = 130; public static double Chemistry = 100; public static double Biology = 110; public static double total = Physics + Chemistry + Biology; public static double percentage; public static double passmarkPhy = Physics * 100 / 150; public static double passmarkChem = Chemistry * 100 / 150; public static double passmarkBio = Biology * 100 / 150; public static void displayResults() { // TODO Auto-generated method stub System.out.println("Physics Marks: " + Physics); System.out.println("Physics Marks: " + Chemistry); System.out.println("Physics Marks: " + Biology); System.out.println("overall MArk : " + total); } public static void displayExamOverall() { System.out.println("persentage of all : " + total * 100 / 450); } public static void displayPassMark() { System.out.println("PassMark of Physics is : " + passmarkPhy); System.out.println("PassMark of Physics is : " + passmarkChem); System.out.println("PassMark of Physics is : " + passmarkBio); } public static void displayOverallPassMark() { if ((passmarkPhy > 60) && (passmarkChem > 60) && (passmarkBio > 60)) { System.out.println("You pass all exam"); } else { System.out.println("You fail"); } // ****************************OR********************************** // if((passmarkPhy < 60) || (passmarkChem < 60) || (passmarkBio < 60)) { // System.out.println( "You fail "); // }else { // System.out.println("You pass all exam"); // } // } }
1,605
0.629283
0.601246
57
26.157894
25.449495
72
false
false
0
0
0
0
0
0
1.421053
false
false
3
ee13498e345e8642082f59b6cac04f55c4e3ff47
33,294,586,498,597
9ed47d3266b29f11ee119b2ab4e56f7b9d82899a
/Mission-Web-Spring/src/main/java/kr/co/mlec/member/controller/MemberController.java
9bd5588a233420cc996e21173f5c4ae811d02a38
[]
no_license
crystal710/Spring0513
https://github.com/crystal710/Spring0513
ac9e6600a7c9b75886aae84a370ab544e4fa4195
ae520fd179d37eb57793bfee307d1971fdfb8e1d
refs/heads/master
2023-05-04T08:32:24.706000
2021-05-27T01:36:47
2021-05-27T01:36:47
366,922,243
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kr.co.mlec.member.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus; import org.springframework.web.servlet.ModelAndView; import kr.co.mlec.member.service.MemberService; import kr.co.mlec.member.vo.MemberVO; @SessionAttributes({"userVO"}) @Controller public class MemberController { @Autowired private MemberService service; // @RequestMapping(value ="/login", method = RequestMethod.GET) @GetMapping("/login") public String login() { return "login/login"; } @PostMapping("/login") public ModelAndView loginProcess(MemberVO loginVO) { MemberVO member = service.login(loginVO); ModelAndView mav = new ModelAndView(); if(member==null) { mav.setViewName("redirect:/login"); }else { mav.setViewName("redirect:/"); mav.addObject("userVO",member); } return mav; } @GetMapping("/logout") public String logout(SessionStatus status) { status.setComplete(); return "redirect:/"; } @RequestMapping("/member") public String list(HttpServletRequest request) { List<MemberVO> memberList = service.selectAllMember(); request.setAttribute("memberList", memberList); return "member/memberList"; } @GetMapping("/register") public String memberRegister(Model model) { MemberVO member = new MemberVO(); model.addAttribute("MemberVO", member); return "member/memberRegister"; } @PostMapping("/register") public String memberRegister(@Valid MemberVO member, BindingResult result) { if(result.hasErrors()) { return "member/memberRegister"; } service.insertMember(member); return "redirect:/"; } // 회원가입 post /* * @RequestMapping(value = "/register", method = RequestMethod.POST) * * public String postRegister(MemberVO vo) throws Exception { * * logger.info("post register"); * * int result = service.idChk(vo); * * try { * * if(result == 1) { * * return "/member/register"; * * }else if(result == 0) { * * service.register(vo); * * } * * // 요기에서~ 입력된 아이디가 존재한다면 -> 다시 회원가입 페이지로 돌아가기 * * // 존재하지 않는다면 -> register * * } catch (Exception e) { * * throw new RuntimeException(); * * } * * return "redirect:/"; * * } */ }
UTF-8
Java
3,071
java
MemberController.java
Java
[]
null
[]
package kr.co.mlec.member.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus; import org.springframework.web.servlet.ModelAndView; import kr.co.mlec.member.service.MemberService; import kr.co.mlec.member.vo.MemberVO; @SessionAttributes({"userVO"}) @Controller public class MemberController { @Autowired private MemberService service; // @RequestMapping(value ="/login", method = RequestMethod.GET) @GetMapping("/login") public String login() { return "login/login"; } @PostMapping("/login") public ModelAndView loginProcess(MemberVO loginVO) { MemberVO member = service.login(loginVO); ModelAndView mav = new ModelAndView(); if(member==null) { mav.setViewName("redirect:/login"); }else { mav.setViewName("redirect:/"); mav.addObject("userVO",member); } return mav; } @GetMapping("/logout") public String logout(SessionStatus status) { status.setComplete(); return "redirect:/"; } @RequestMapping("/member") public String list(HttpServletRequest request) { List<MemberVO> memberList = service.selectAllMember(); request.setAttribute("memberList", memberList); return "member/memberList"; } @GetMapping("/register") public String memberRegister(Model model) { MemberVO member = new MemberVO(); model.addAttribute("MemberVO", member); return "member/memberRegister"; } @PostMapping("/register") public String memberRegister(@Valid MemberVO member, BindingResult result) { if(result.hasErrors()) { return "member/memberRegister"; } service.insertMember(member); return "redirect:/"; } // 회원가입 post /* * @RequestMapping(value = "/register", method = RequestMethod.POST) * * public String postRegister(MemberVO vo) throws Exception { * * logger.info("post register"); * * int result = service.idChk(vo); * * try { * * if(result == 1) { * * return "/member/register"; * * }else if(result == 0) { * * service.register(vo); * * } * * // 요기에서~ 입력된 아이디가 존재한다면 -> 다시 회원가입 페이지로 돌아가기 * * // 존재하지 않는다면 -> register * * } catch (Exception e) { * * throw new RuntimeException(); * * } * * return "redirect:/"; * * } */ }
3,071
0.700033
0.699364
130
21.976923
20.722885
77
false
false
0
0
0
0
0
0
1.723077
false
false
3
006c05c0135808f73ee4c19d1ddf1a0fc3043772
11,819,750,050,612
b701a2f316441d59906d4341b8c7c235d2a62f3e
/src/test/java/org/w3c/domts/level2/core/importNode10.java
cfb8d03abc378bad8a31cfe4ff1bed89c6a7f144
[ "W3C", "GPL-1.0-or-later", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.0-or-later", "LGPL-3.0-only", "LGPL-2.1-or-later", "MPL-1.1", "MPL-2.0", "MIT" ]
permissive
apache/xmlbeans
https://github.com/apache/xmlbeans
826547e0f386481cbfd4319a0dee537a98aa7cba
99d86814497f29a5ae7aa8e85d4db04a23eaae06
refs/heads/trunk
2023-08-22T08:16:22.853000
2023-08-18T09:55:35
2023-08-18T09:55:35
270,479
39
58
Apache-2.0
false
2023-05-26T18:52:27
2009-08-06T08:06:50
2023-05-12T07:34:32
2023-05-26T16:54:48
66,116
44
54
1
Java
false
false
/* This Java source file was generated by test-to-java.xsl and is a derived work from the source document. The source document contained the following notice: Copyright (c) 2001 World Wide Web Consortium, (Massachusetts Institute of Technology, Institut National de Recherche en Informatique et en Automatique, Keio University). All Rights Reserved. This program is distributed under the W3C's Software Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.domts.level2.core; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.EntityReference; import org.w3c.dom.Node; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.w3c.domts.DOMTest.assertURIEquals; import static org.w3c.domts.DOMTest.load; /** * The "importNode(importedNode,deep)" method for a * Document should import the given importedNode into that Document. * The importedNode is of type Entity_Reference. * Only the EntityReference is copied, regardless of deep's value. * Create an entity reference whose name is "entRef1" in a different document. * Give it value "entRef1Value". * Invoke method importNode(importedNode,deep) on this document with importedNode * being "entRef1". * Method should return a node of type Entity_Reference (whose value is null) that * belongs to this document whose systemId is "staff.dtd". * * @see <a href="http://www.w3.org/TR/DOM-Level-2-Core/core#Core-Document-importNode">http://www.w3.org/TR/DOM-Level-2-Core/core#Core-Document-importNode</a> */ public class importNode10 { @Test @Disabled public void testRun() throws Throwable { Document doc = load("staffNS", true); Document aNewDoc = load("staffNS", true); EntityReference entRef = aNewDoc.createEntityReference("entRef1"); entRef.setNodeValue("entRef1Value"); Node aNode = doc.importNode(entRef, false); Document ownerDocument = aNode.getOwnerDocument(); DocumentType docType = ownerDocument.getDoctype(); String system = docType.getSystemId(); assertURIEquals("systemId", "staffNS.dtd", system); String name = aNode.getNodeName(); assertEquals("entRef1", name, "nodeName"); } /** * Gets URI that identifies the test * * @return uri identifier of test */ public String getTargetURI() { return "http://www.w3.org/2001/DOM-Test-Suite/level2/core/importNode10"; } }
UTF-8
Java
2,847
java
importNode10.java
Java
[]
null
[]
/* This Java source file was generated by test-to-java.xsl and is a derived work from the source document. The source document contained the following notice: Copyright (c) 2001 World Wide Web Consortium, (Massachusetts Institute of Technology, Institut National de Recherche en Informatique et en Automatique, Keio University). All Rights Reserved. This program is distributed under the W3C's Software Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.domts.level2.core; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.EntityReference; import org.w3c.dom.Node; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.w3c.domts.DOMTest.assertURIEquals; import static org.w3c.domts.DOMTest.load; /** * The "importNode(importedNode,deep)" method for a * Document should import the given importedNode into that Document. * The importedNode is of type Entity_Reference. * Only the EntityReference is copied, regardless of deep's value. * Create an entity reference whose name is "entRef1" in a different document. * Give it value "entRef1Value". * Invoke method importNode(importedNode,deep) on this document with importedNode * being "entRef1". * Method should return a node of type Entity_Reference (whose value is null) that * belongs to this document whose systemId is "staff.dtd". * * @see <a href="http://www.w3.org/TR/DOM-Level-2-Core/core#Core-Document-importNode">http://www.w3.org/TR/DOM-Level-2-Core/core#Core-Document-importNode</a> */ public class importNode10 { @Test @Disabled public void testRun() throws Throwable { Document doc = load("staffNS", true); Document aNewDoc = load("staffNS", true); EntityReference entRef = aNewDoc.createEntityReference("entRef1"); entRef.setNodeValue("entRef1Value"); Node aNode = doc.importNode(entRef, false); Document ownerDocument = aNode.getOwnerDocument(); DocumentType docType = ownerDocument.getDoctype(); String system = docType.getSystemId(); assertURIEquals("systemId", "staffNS.dtd", system); String name = aNode.getNodeName(); assertEquals("entRef1", name, "nodeName"); } /** * Gets URI that identifies the test * * @return uri identifier of test */ public String getTargetURI() { return "http://www.w3.org/2001/DOM-Test-Suite/level2/core/importNode10"; } }
2,847
0.713734
0.70144
77
34.974026
30.044977
157
false
false
0
0
0
0
0
0
0.480519
false
false
3
9d4435fbfc1b12bfe60b6d5a0678560aac90e183
3,100,966,423,541
68b801a185c1e9a9f29e1c9850c644183e26ca0d
/src/main/java/dp/classical/Problem07.java
93ff08dccfe251d276f1cf8dc0389a0011c6feac
[]
no_license
avishekgurung/algo
https://github.com/avishekgurung/algo
c081f8fbd11d22eed87d17a6db7e6f5aa52c0706
c63f86634d94bb4b74dbb17f4b51129bcc7b7e17
refs/heads/master
2021-08-03T00:08:25.868000
2021-07-27T05:43:07
2021-07-27T05:43:07
155,651,748
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dp.classical; import java.util.HashSet; import java.util.Set; /** * Ref: https://www.youtube.com/watch?v=s6FhG--P7z0&t=481s */ public class Problem07 { public static void subsetSum(int elements[], int s) { int sum[] = new int[s + 1]; for(int i=0; i < sum.length; i++) sum[i] = i; boolean dp[][] = new boolean[elements.length][s + 1]; for(int i=0; i < elements.length; i++) { dp[i][0] = true; } for(int j=1; j < sum.length; j++) { if(sum[j] == elements[0]) { dp[0][j] = true; } else { dp[0][j] = false; } } //creating DP table for(int i=1; i < elements.length; i++) { for(int j=1; j < sum.length; j++) { if(elements[i] > sum[j]) { //keep the value same as the above row dp[i][j] = dp[i-1][j]; } else { if(elements[i] == sum[j] || dp[i-1][j]) { dp[i][j] = true; } else { dp[i][j] = dp[i-1][j-elements[i]]; } } } } //finding subset Set<Integer> subset = new HashSet<Integer>(); int i = dp.length - 1; int j = dp[0].length - 1; while(i !=0 && j != 0) { if(dp[i][j]) { i--; } else { int element = elements[i+1]; j = j - element; subset.add(element); } } if(dp[elements.length-1][sum.length - 1]) { System.out.println("The sum " + s + " CAN be formed from the subset"); System.out.println("The subset is " + subset); } else { System.out.println("The sum " + s + " CANNOT be formed from the subset"); } System.out.println(""); } //We might have to sort the array first. public static void main(String[] args) { subsetSum(new int[]{2, 3, 7, 8, 10}, 11); } }
UTF-8
Java
1,809
java
Problem07.java
Java
[]
null
[]
package dp.classical; import java.util.HashSet; import java.util.Set; /** * Ref: https://www.youtube.com/watch?v=s6FhG--P7z0&t=481s */ public class Problem07 { public static void subsetSum(int elements[], int s) { int sum[] = new int[s + 1]; for(int i=0; i < sum.length; i++) sum[i] = i; boolean dp[][] = new boolean[elements.length][s + 1]; for(int i=0; i < elements.length; i++) { dp[i][0] = true; } for(int j=1; j < sum.length; j++) { if(sum[j] == elements[0]) { dp[0][j] = true; } else { dp[0][j] = false; } } //creating DP table for(int i=1; i < elements.length; i++) { for(int j=1; j < sum.length; j++) { if(elements[i] > sum[j]) { //keep the value same as the above row dp[i][j] = dp[i-1][j]; } else { if(elements[i] == sum[j] || dp[i-1][j]) { dp[i][j] = true; } else { dp[i][j] = dp[i-1][j-elements[i]]; } } } } //finding subset Set<Integer> subset = new HashSet<Integer>(); int i = dp.length - 1; int j = dp[0].length - 1; while(i !=0 && j != 0) { if(dp[i][j]) { i--; } else { int element = elements[i+1]; j = j - element; subset.add(element); } } if(dp[elements.length-1][sum.length - 1]) { System.out.println("The sum " + s + " CAN be formed from the subset"); System.out.println("The subset is " + subset); } else { System.out.println("The sum " + s + " CANNOT be formed from the subset"); } System.out.println(""); } //We might have to sort the array first. public static void main(String[] args) { subsetSum(new int[]{2, 3, 7, 8, 10}, 11); } }
1,809
0.487562
0.466556
79
21.898735
20.319969
79
false
false
0
0
0
0
0
0
0.531646
false
false
3
868e9e575c4d4b477446ed9d571427d4a8e52896
23,347,442,276,353
ce192d94ddfcbd5a04f8f4a5b9f57fdd10092bce
/0543_DiameterOfBinaryTree_best.java
7ea70c9a0e5d6752c2f3a030b7abbe46ad26283e
[]
no_license
ynwc2006/leetcode
https://github.com/ynwc2006/leetcode
d9302dbde3fdbf08852cbab96f1cb6d58ad5dc1e
aa431ce128d3857a1cd9cdfb14ad01f1f1979253
refs/heads/master
2021-03-13T19:57:20.540000
2020-08-02T13:43:05
2020-08-02T13:43:05
246,706,302
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { int ans=0; public int diameterOfBinaryTree(TreeNode root) { ans=1; depth(root); return ans-1; } private int depth(TreeNode n){ if(n==null) return 0; int leftDepth=depth(n.left); int rightDepth=depth(n.right); ans=Math.max(ans, leftDepth+rightDepth+1); return Math.max(leftDepth+1,rightDepth+1); } }
UTF-8
Java
575
java
0543_DiameterOfBinaryTree_best.java
Java
[]
null
[]
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { int ans=0; public int diameterOfBinaryTree(TreeNode root) { ans=1; depth(root); return ans-1; } private int depth(TreeNode n){ if(n==null) return 0; int leftDepth=depth(n.left); int rightDepth=depth(n.right); ans=Math.max(ans, leftDepth+rightDepth+1); return Math.max(leftDepth+1,rightDepth+1); } }
575
0.572174
0.56
24
22.958334
15.52546
52
false
false
0
0
0
0
0
0
0.625
false
false
3
1cd821a0b6f386432f77b0f88bfd6788466c3f72
32,701,881,011,131
c83a457e05aaf9cfd2a72e11e53f0de2c300bd21
/ace/ace-portal/ace-portal-service/src/main/java/com/huacainfo/ace/portal/dao/EvaluatDataDao.java
122606e6c9847ac63b495a922ef7d859be83c4b7
[]
no_license
249134995/ace
https://github.com/249134995/ace
b058fb3c007657da7ed21f93f0debe48dd907fe3
995597b935d4bde1d2da8524fc965a9f8cf8b315
refs/heads/master
2020-02-28T06:35:58.514000
2020-02-14T05:51:07
2020-02-14T05:51:07
87,175,606
11
13
null
false
2020-10-16T10:55:21
2017-04-04T10:48:42
2020-07-11T07:03:53
2020-10-16T10:55:19
804,196
9
16
39
JavaScript
false
false
package com.huacainfo.ace.portal.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.huacainfo.ace.portal.model.EvaluatData; import com.huacainfo.ace.portal.vo.EvaluatDataQVo; import com.huacainfo.ace.portal.vo.EvaluatDataVo; public interface EvaluatDataDao { int deleteByPrimaryKey(String EvaluatDataId); int deleteByEvaluatTplId(String evaluatTplId); int insertSelective(EvaluatData record); EvaluatDataVo selectByPrimaryKey(String EvaluatDataId); int updateByPrimaryKeySelective(EvaluatData record); List<EvaluatDataVo> findList(@Param("condition") EvaluatDataQVo condition, @Param("start") int start, @Param("limit") int limit, @Param("orderBy") String orderBy); EvaluatData latestResults(@Param("condition") EvaluatData condition); List<EvaluatDataVo> findDataList(@Param("condition") EvaluatDataQVo condition, @Param("start") int start, @Param("limit") int limit, @Param("orderBy") String orderBy); int findCount(@Param("condition") EvaluatDataQVo condition); int getRanking(@Param("condition") EvaluatData condition); int getTotal(@Param("condition") EvaluatData condition); int isExit(EvaluatData record); List<Map<String,Object>> getList(Map<String,Object> params); Map<String,Object> getById(String id); }
UTF-8
Java
1,480
java
EvaluatDataDao.java
Java
[]
null
[]
package com.huacainfo.ace.portal.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.huacainfo.ace.portal.model.EvaluatData; import com.huacainfo.ace.portal.vo.EvaluatDataQVo; import com.huacainfo.ace.portal.vo.EvaluatDataVo; public interface EvaluatDataDao { int deleteByPrimaryKey(String EvaluatDataId); int deleteByEvaluatTplId(String evaluatTplId); int insertSelective(EvaluatData record); EvaluatDataVo selectByPrimaryKey(String EvaluatDataId); int updateByPrimaryKeySelective(EvaluatData record); List<EvaluatDataVo> findList(@Param("condition") EvaluatDataQVo condition, @Param("start") int start, @Param("limit") int limit, @Param("orderBy") String orderBy); EvaluatData latestResults(@Param("condition") EvaluatData condition); List<EvaluatDataVo> findDataList(@Param("condition") EvaluatDataQVo condition, @Param("start") int start, @Param("limit") int limit, @Param("orderBy") String orderBy); int findCount(@Param("condition") EvaluatDataQVo condition); int getRanking(@Param("condition") EvaluatData condition); int getTotal(@Param("condition") EvaluatData condition); int isExit(EvaluatData record); List<Map<String,Object>> getList(Map<String,Object> params); Map<String,Object> getById(String id); }
1,480
0.692568
0.692568
48
29.854166
30.331495
90
false
false
0
0
0
0
0
0
0.6875
false
false
3
e454e12abd512b4e0799edca03f829186e81ccc1
29,789,893,211,723
4b84660ea7df69873b0ee2091874fab747429946
/src/dsr/QuadCurveTransformer.java
5ec8d01861ca0c3c9b9a37f6b9c31dd37661df10
[]
no_license
ReactionNetworks/dsrgraph
https://github.com/ReactionNetworks/dsrgraph
401d85dc541e0a8db1831ba8deec8f5e3938c9ab
e8164262fff8c42f0d0d3d85f6b945a5ca12095e
refs/heads/master
2020-07-14T21:56:33.891000
2019-08-30T15:48:30
2019-08-30T15:48:30
205,411,794
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dsr; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.CubicCurve2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.QuadCurve2D; import dsr.Util.LineType; import edu.uci.ics.jung.algorithms.layout.Layout; import edu.uci.ics.jung.graph.Graph; import edu.uci.ics.jung.graph.util.Context; import edu.uci.ics.jung.graph.util.Pair; import edu.uci.ics.jung.visualization.Layer; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.decorators.EdgeShape.QuadCurve; import edu.uci.ics.jung.visualization.transform.MutableTransformer; public class QuadCurveTransformer extends QuadCurve<Vertex,Edge> { VisualizationViewer<Vertex,Edge> v; public QuadCurveTransformer(){ super(); //this.v=v; } public void setVV(VisualizationViewer<Vertex,Edge> vv){ v=vv; } public QuadCurveTransformer(VisualizationViewer<Vertex,Edge> v){ super(); this.v=v; } public Point2D affineTransform(Edge edge, Point2D p){ //transforms from 0 - 1 to real position Layout<Vertex,Edge> layout = v.getModel().getGraphLayout(); Pair<Vertex> endpoints=Util.g.getEndpoints(edge); Vertex v1 = endpoints.getFirst(); Vertex v2 = endpoints.getSecond(); Point2D p1 = layout.transform(v1); Point2D p2 = layout.transform(v2); // p1=v.getRenderContext().getMultiLayerTransformer() p1 = v.getRenderContext().getMultiLayerTransformer().transform(Layer.LAYOUT, p1); p2 = v.getRenderContext().getMultiLayerTransformer().transform(Layer.LAYOUT, p2); float x1 = (float) p1.getX(); float y1 = (float) p1.getY(); float x2 = (float) p2.getX(); float y2 = (float) p2.getY(); AffineTransform xform = AffineTransform.getTranslateInstance(x1, y1); float dx = x2-x1; float dy = y2-y1; float thetaRadians = (float) Math.atan2(dy, dx); xform.rotate(thetaRadians); float dist = (float) Math.sqrt(dx*dx + dy*dy); xform.scale(dist, 1.0); Point2D pp=new Point2D.Double(); return xform.transform(p, pp); } public Shape transform(Context<Graph<Vertex,Edge>,Edge> context){ Layout<Vertex,Edge> layout = v.getModel().getGraphLayout(); Graph<Vertex,Edge> graph = context.graph; QuadCurve2D old=new QuadCurve2D.Float(); Edge edge = (Edge)context.element; if(Util.vv.getPickedEdgeState().getPicked().contains(edge)) {edge.edited=true;edge.isLine=false;edge.lineType=Util.LineType.quadType; if (((Util.ctrl3.getEdge()!=null) &&(!(Util.ctrl3.getEdge().equals(edge)))) || (Util.ctrl3.getEdge()==null)) //there isn't any edge that is controled by the points { Point2D currCtrl3 = new Point2D.Double(); Util.ctrl3.setEdge(edge);//the current edge for editing currCtrl3=affineTransform(edge, edge.ctrl3); layout.setLocation(Util.ctrl3, currCtrl3); } else { Point2D currCtrl3 = new Point2D.Double(); currCtrl3=affineTransform(edge, edge.ctrl3); if(((Util.ctrl3.getEdge().equals(edge)) & (!(Util.vv.getPickedVertexState().getPicked().contains(Util.ctrl3))) )) {layout.setLocation(Util.ctrl3, currCtrl3); } }} if (edge.lineType.equals(Util.LineType.quadType)) {old.setCurve(0.0,0.0, edge.ctrl3.getX(), edge.ctrl3.getY(), 1.0,0.0); return old; } else if(edge.isMultiple && edge.lineType.equals(LineType.quadType)) { old.setCurve(0.0,0.0, edge.ctrl3.getX(), edge.ctrl3.getY(), 1.0,0.0); return old; } else if(edge.lineType.equals(Util.LineType.cubicType)) { CubicCurve2D oldc=new CubicCurve2D.Float(); oldc.setCurve(0.0f, 0.0f, edge.ctrl1.getX(),edge.ctrl1.getY(),edge.ctrl2.getX(), edge.ctrl2.getY(), 1.0f,0.0f); return oldc; } return new Line2D.Float(0.0f, 0.0f, 1.0f, 0.0f); } }
UTF-8
Java
3,673
java
QuadCurveTransformer.java
Java
[]
null
[]
package dsr; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.CubicCurve2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.QuadCurve2D; import dsr.Util.LineType; import edu.uci.ics.jung.algorithms.layout.Layout; import edu.uci.ics.jung.graph.Graph; import edu.uci.ics.jung.graph.util.Context; import edu.uci.ics.jung.graph.util.Pair; import edu.uci.ics.jung.visualization.Layer; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.decorators.EdgeShape.QuadCurve; import edu.uci.ics.jung.visualization.transform.MutableTransformer; public class QuadCurveTransformer extends QuadCurve<Vertex,Edge> { VisualizationViewer<Vertex,Edge> v; public QuadCurveTransformer(){ super(); //this.v=v; } public void setVV(VisualizationViewer<Vertex,Edge> vv){ v=vv; } public QuadCurveTransformer(VisualizationViewer<Vertex,Edge> v){ super(); this.v=v; } public Point2D affineTransform(Edge edge, Point2D p){ //transforms from 0 - 1 to real position Layout<Vertex,Edge> layout = v.getModel().getGraphLayout(); Pair<Vertex> endpoints=Util.g.getEndpoints(edge); Vertex v1 = endpoints.getFirst(); Vertex v2 = endpoints.getSecond(); Point2D p1 = layout.transform(v1); Point2D p2 = layout.transform(v2); // p1=v.getRenderContext().getMultiLayerTransformer() p1 = v.getRenderContext().getMultiLayerTransformer().transform(Layer.LAYOUT, p1); p2 = v.getRenderContext().getMultiLayerTransformer().transform(Layer.LAYOUT, p2); float x1 = (float) p1.getX(); float y1 = (float) p1.getY(); float x2 = (float) p2.getX(); float y2 = (float) p2.getY(); AffineTransform xform = AffineTransform.getTranslateInstance(x1, y1); float dx = x2-x1; float dy = y2-y1; float thetaRadians = (float) Math.atan2(dy, dx); xform.rotate(thetaRadians); float dist = (float) Math.sqrt(dx*dx + dy*dy); xform.scale(dist, 1.0); Point2D pp=new Point2D.Double(); return xform.transform(p, pp); } public Shape transform(Context<Graph<Vertex,Edge>,Edge> context){ Layout<Vertex,Edge> layout = v.getModel().getGraphLayout(); Graph<Vertex,Edge> graph = context.graph; QuadCurve2D old=new QuadCurve2D.Float(); Edge edge = (Edge)context.element; if(Util.vv.getPickedEdgeState().getPicked().contains(edge)) {edge.edited=true;edge.isLine=false;edge.lineType=Util.LineType.quadType; if (((Util.ctrl3.getEdge()!=null) &&(!(Util.ctrl3.getEdge().equals(edge)))) || (Util.ctrl3.getEdge()==null)) //there isn't any edge that is controled by the points { Point2D currCtrl3 = new Point2D.Double(); Util.ctrl3.setEdge(edge);//the current edge for editing currCtrl3=affineTransform(edge, edge.ctrl3); layout.setLocation(Util.ctrl3, currCtrl3); } else { Point2D currCtrl3 = new Point2D.Double(); currCtrl3=affineTransform(edge, edge.ctrl3); if(((Util.ctrl3.getEdge().equals(edge)) & (!(Util.vv.getPickedVertexState().getPicked().contains(Util.ctrl3))) )) {layout.setLocation(Util.ctrl3, currCtrl3); } }} if (edge.lineType.equals(Util.LineType.quadType)) {old.setCurve(0.0,0.0, edge.ctrl3.getX(), edge.ctrl3.getY(), 1.0,0.0); return old; } else if(edge.isMultiple && edge.lineType.equals(LineType.quadType)) { old.setCurve(0.0,0.0, edge.ctrl3.getX(), edge.ctrl3.getY(), 1.0,0.0); return old; } else if(edge.lineType.equals(Util.LineType.cubicType)) { CubicCurve2D oldc=new CubicCurve2D.Float(); oldc.setCurve(0.0f, 0.0f, edge.ctrl1.getX(),edge.ctrl1.getY(),edge.ctrl2.getX(), edge.ctrl2.getY(), 1.0f,0.0f); return oldc; } return new Line2D.Float(0.0f, 0.0f, 1.0f, 0.0f); } }
3,673
0.722298
0.693711
126
28.15873
29.06135
164
false
false
0
0
0
0
0
0
1.81746
false
false
3
7661855e54138627da4c4fab190dd89ceab13b3f
20,572,893,392,050
621c0a88e990ea675e792fbabede2cb387116706
/src/test/java/com/kh/myapp/memberServiceTest.java
80e04ee2e2b27d15534d5a286d3f703e98d92cff
[]
no_license
SUZY0925/SpringEdu
https://github.com/SUZY0925/SpringEdu
6dc4d2387ca6b9ed28cdab5385ee3ada839bbd27
134ffe04187b8829f17ed5b76c8ac69717842666
refs/heads/master
2020-03-18T09:04:00.321000
2018-07-19T01:33:08
2018-07-19T01:33:08
134,236,618
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kh.myapp; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.kh.myapp.member.service.MemberService; import com.kh.myapp.member.vo.MemberVO; // 테스트환경 @RunWith(SpringJUnit4ClassRunner.class) // Runwith : 환경을 가져가겠다 .여기선 스프링프레임워크에서 테스트하는 환경을 가져가겠다는 말임. @ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/root-context.xml" }) // 이걸로 인해서 스프링프레임워크를 실행을 안해도 테스트 할 수 있음 // ----------- public class memberServiceTest { private static final Logger logger = LoggerFactory.getLogger(loginTest.class); @Autowired DefaultListableBeanFactory df; @Test public void beans() { for(String name : df.getBeanDefinitionNames()) { logger.info(name + "\t " + df.getBean(name).getClass().getName()); } } /* @Autowired @Qualifier("memberServiceImpl") MemberService memberService; // 컨테이너상에서는 memberSerivceImpl이 올라갔지만 상위타입으로 받을 수 있음ㅎㅎㅎㅎ @Test public void test() { MemberVO memberVO = memberService.getByMemberId("admin@kh.com"); Logger.info(memberVO.toString()); }*/ }
UTF-8
Java
1,617
java
memberServiceTest.java
Java
[ { "context": "\tMemberVO memberVO = memberService.getByMemberId(\"admin@kh.com\");\n\t\tLogger.info(memberVO.toString());\n\t}*/\n}\n", "end": 1372, "score": 0.9999211430549622, "start": 1360, "tag": "EMAIL", "value": "admin@kh.com" } ]
null
[]
package com.kh.myapp; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.kh.myapp.member.service.MemberService; import com.kh.myapp.member.vo.MemberVO; // 테스트환경 @RunWith(SpringJUnit4ClassRunner.class) // Runwith : 환경을 가져가겠다 .여기선 스프링프레임워크에서 테스트하는 환경을 가져가겠다는 말임. @ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/root-context.xml" }) // 이걸로 인해서 스프링프레임워크를 실행을 안해도 테스트 할 수 있음 // ----------- public class memberServiceTest { private static final Logger logger = LoggerFactory.getLogger(loginTest.class); @Autowired DefaultListableBeanFactory df; @Test public void beans() { for(String name : df.getBeanDefinitionNames()) { logger.info(name + "\t " + df.getBean(name).getClass().getName()); } } /* @Autowired @Qualifier("memberServiceImpl") MemberService memberService; // 컨테이너상에서는 memberSerivceImpl이 올라갔지만 상위타입으로 받을 수 있음ㅎㅎㅎㅎ @Test public void test() { MemberVO memberVO = memberService.getByMemberId("<EMAIL>"); Logger.info(memberVO.toString()); }*/ }
1,612
0.773784
0.770261
42
32.785713
32.088074
133
false
false
0
0
0
0
0
0
1.095238
false
false
3
c91d02e7ed71ef75ebbfce3dfa3fbc31d91b59e7
28,492,813,097,423
cf5f95fb930a984862015d448cf8ed66c66740ce
/src/main/java/com/roasted/bean/JvmMetricsView.java
212f1b786df0f85c5a5c4fe7593121a97f6ceb8b
[]
no_license
yukorengan/yava30
https://github.com/yukorengan/yava30
00fdbcf6792d7283a84879f42329ddd7bf10b6f0
da1ade81bc7a8be9aa014385f412d3fda5c6b9d1
refs/heads/master
2020-09-14T09:18:17.289000
2020-01-08T10:27:14
2020-01-08T10:27:14
223,087,686
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.roasted.bean; import java.io.Serializable; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import org.jboss.logging.Logger; import org.primefaces.model.charts.ChartData; import org.primefaces.model.charts.donut.DonutChartDataSet; import org.primefaces.model.charts.donut.DonutChartModel; import com.roasted.ejb.JvmAmbariJMXUtil; import com.roasted.ejb.JvmMetricsRestClient; import com.roasted.model.JvmMetrics; @ManagedBean @RequestScoped public class JvmMetricsView implements Serializable { static final long serialVersionUID = 1237l; private DonutChartModel donutModel; String _percentageJvmMetrics; static Logger logger = Logger.getLogger(JvmMetricsView.class); static String host = "192.168.3.132"; static String port = "50075"; private List<JvmMetrics> _bbs_; JvmMetricsRestClient _client = new JvmMetricsRestClient(host, port); JvmMetrics _jvm = new JvmMetrics(); @PostConstruct public void init() { getJSON(); createDonutModel(); } public void getJSON() { try { String _url = "http://192.168.3.132:50075/jmx?qry=Hadoop:name=JvmMetrics,service=DataNode"; String json = _client.ambari_plain_client(_url); _bbs_ = JvmAmbariJMXUtil.json2JvmMetrics(json); _bbs_.size(); for (JvmMetrics i : _bbs_) { _jvm = i; } } catch (Exception e) { logger.error(e); } } public void createDonutModel() { donutModel = new DonutChartModel(); ChartData data = new ChartData(); DonutChartDataSet dataSet = new DonutChartDataSet(); List<Number> values = new ArrayList<>(); Double heapUsed = _jvm.getMemHeapUsedM(); Double heapMax = _jvm.getMemHeapMaxM(); Double heapNonUsed = heapMax - heapUsed; Double percentageJvm = (heapUsed / heapMax) * 100; DecimalFormat dfP = new DecimalFormat("#"); percentageJvm = Double.valueOf(dfP.format(percentageJvm)); _percentageJvmMetrics = percentageJvm.toString() + "%"; values.add(heapUsed); values.add(heapNonUsed); dataSet.setData(values); List<String> bgColors = new ArrayList<>(); bgColors.add("rgb(1, 155, 0)"); bgColors.add("rgb(191, 191, 191)"); dataSet.setBackgroundColor(bgColors); data.addChartDataSet(dataSet); List<String> labels = new ArrayList<>(); // labels.add("Capacity"); labels.add("Heap Used"); labels.add("Heap Free"); data.setLabels(labels); donutModel.setData(data); } public String get_percentageJvmMetrics() { return _percentageJvmMetrics; } public void set_percentageJvmMetrics(String _percentageJvmMetrics) { this._percentageJvmMetrics = _percentageJvmMetrics; } public DonutChartModel getDonutModel() { return donutModel; } public void setDonutModel(DonutChartModel donutModel) { this.donutModel = donutModel; } public List<JvmMetrics> get_bbs_() { return _bbs_; } public void set_bbs_(List<JvmMetrics> _bbs_) { this._bbs_ = _bbs_; } }
UTF-8
Java
3,016
java
JvmMetricsView.java
Java
[ { "context": "er(JvmMetricsView.class);\n\n\tstatic String host = \"192.168.3.132\";\n\tstatic String port = \"50075\";\n\n\tprivate List<J", "end": 879, "score": 0.9997167587280273, "start": 866, "tag": "IP_ADDRESS", "value": "192.168.3.132" }, { "context": "id getJSON() {\n\n\t\ttry {\n\n\t\t\tString _url = \"http://192.168.3.132:50075/jmx?qry=Hadoop:name=JvmMetrics,service=Data", "end": 1207, "score": 0.9997026920318604, "start": 1194, "tag": "IP_ADDRESS", "value": "192.168.3.132" } ]
null
[]
package com.roasted.bean; import java.io.Serializable; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import org.jboss.logging.Logger; import org.primefaces.model.charts.ChartData; import org.primefaces.model.charts.donut.DonutChartDataSet; import org.primefaces.model.charts.donut.DonutChartModel; import com.roasted.ejb.JvmAmbariJMXUtil; import com.roasted.ejb.JvmMetricsRestClient; import com.roasted.model.JvmMetrics; @ManagedBean @RequestScoped public class JvmMetricsView implements Serializable { static final long serialVersionUID = 1237l; private DonutChartModel donutModel; String _percentageJvmMetrics; static Logger logger = Logger.getLogger(JvmMetricsView.class); static String host = "192.168.3.132"; static String port = "50075"; private List<JvmMetrics> _bbs_; JvmMetricsRestClient _client = new JvmMetricsRestClient(host, port); JvmMetrics _jvm = new JvmMetrics(); @PostConstruct public void init() { getJSON(); createDonutModel(); } public void getJSON() { try { String _url = "http://192.168.3.132:50075/jmx?qry=Hadoop:name=JvmMetrics,service=DataNode"; String json = _client.ambari_plain_client(_url); _bbs_ = JvmAmbariJMXUtil.json2JvmMetrics(json); _bbs_.size(); for (JvmMetrics i : _bbs_) { _jvm = i; } } catch (Exception e) { logger.error(e); } } public void createDonutModel() { donutModel = new DonutChartModel(); ChartData data = new ChartData(); DonutChartDataSet dataSet = new DonutChartDataSet(); List<Number> values = new ArrayList<>(); Double heapUsed = _jvm.getMemHeapUsedM(); Double heapMax = _jvm.getMemHeapMaxM(); Double heapNonUsed = heapMax - heapUsed; Double percentageJvm = (heapUsed / heapMax) * 100; DecimalFormat dfP = new DecimalFormat("#"); percentageJvm = Double.valueOf(dfP.format(percentageJvm)); _percentageJvmMetrics = percentageJvm.toString() + "%"; values.add(heapUsed); values.add(heapNonUsed); dataSet.setData(values); List<String> bgColors = new ArrayList<>(); bgColors.add("rgb(1, 155, 0)"); bgColors.add("rgb(191, 191, 191)"); dataSet.setBackgroundColor(bgColors); data.addChartDataSet(dataSet); List<String> labels = new ArrayList<>(); // labels.add("Capacity"); labels.add("Heap Used"); labels.add("Heap Free"); data.setLabels(labels); donutModel.setData(data); } public String get_percentageJvmMetrics() { return _percentageJvmMetrics; } public void set_percentageJvmMetrics(String _percentageJvmMetrics) { this._percentageJvmMetrics = _percentageJvmMetrics; } public DonutChartModel getDonutModel() { return donutModel; } public void setDonutModel(DonutChartModel donutModel) { this.donutModel = donutModel; } public List<JvmMetrics> get_bbs_() { return _bbs_; } public void set_bbs_(List<JvmMetrics> _bbs_) { this._bbs_ = _bbs_; } }
3,016
0.728448
0.711207
130
22.200001
20.994286
94
false
false
0
0
0
0
0
0
1.553846
false
false
3
3bb4ebae869f1e75dd233ded4469ee9f6940ae60
18,906,446,086,102
9d7e041e5c1e65279b6a49c1ce1a9ca06817588b
/KGenerator/src/main/java/transaction/ParamsTrans.java
e0b9880c0194267b8326b54c109f9f176324e64b
[]
no_license
KermitSun/utils
https://github.com/KermitSun/utils
f0ef51d71923971f2621272938494c834810e0e1
b79f8bcd25f1f47daef72271093ace1269f4e370
refs/heads/master
2022-06-22T12:14:51.704000
2019-06-08T04:55:58
2019-06-08T04:55:58
182,935,079
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package transaction; import entity.ColumnParams; import entity.TableParams; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @Date: 0:44 2019/6/8 * @Author: Kermit Sun * @Description: 将TableParams转换为模板识别的key-value */ public class ParamsTrans { public static Map<String, String> trans(TableParams tableParams){ /*Map<String, String> tableMap = new HashMap(); tableMap.putAll(tableParams.getParams()); tableMap.put("tableName", tableParams.getName()); tableMap.put("tableRemark", tableParams.getRemark()); List<Map<String, String>> list = new ArrayList<Map<String, String>>(); for (ColumnParams column : tableParams.getColumns()) { Map<String, String> columnMap = new HashMap(); columnMap.put("name",column.getColumnName()); columnMap.put("package", column.getImportPackage()); columnMap.put("typeNmae", column.getTypeName()); columnMap.put("remark", column.getRemark()); list.add(columnMap); } return tableMap;*/ return null; } }
UTF-8
Java
1,161
java
ParamsTrans.java
Java
[ { "context": "util.Map;\n\n/**\n * @Date: 0:44 2019/6/8\n * @Author: Kermit Sun\n * @Description: 将TableParams转换为模板识别的key-value\n *", "end": 228, "score": 0.9997596740722656, "start": 218, "tag": "NAME", "value": "Kermit Sun" } ]
null
[]
package transaction; import entity.ColumnParams; import entity.TableParams; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @Date: 0:44 2019/6/8 * @Author: <NAME> * @Description: 将TableParams转换为模板识别的key-value */ public class ParamsTrans { public static Map<String, String> trans(TableParams tableParams){ /*Map<String, String> tableMap = new HashMap(); tableMap.putAll(tableParams.getParams()); tableMap.put("tableName", tableParams.getName()); tableMap.put("tableRemark", tableParams.getRemark()); List<Map<String, String>> list = new ArrayList<Map<String, String>>(); for (ColumnParams column : tableParams.getColumns()) { Map<String, String> columnMap = new HashMap(); columnMap.put("name",column.getColumnName()); columnMap.put("package", column.getImportPackage()); columnMap.put("typeNmae", column.getTypeName()); columnMap.put("remark", column.getRemark()); list.add(columnMap); } return tableMap;*/ return null; } }
1,157
0.652668
0.644794
34
32.64706
23.266844
78
false
false
0
0
0
0
0
0
0.911765
false
false
3
e7aa41cd3daab06591ed818db88ecf0a64a49445
2,310,692,461,466
d8a19a90bf33c89978fe81c46aa8b0883148ca40
/TGP Code/docroot/WEB-INF/src/java/com/tgp/procurement/transaction/web/controller/reviewcheckoutbasket/TGPReviewCheckoutBasketController.java
a0855ae5571a9d65cc73ee419c9391fdd1968096
[]
no_license
liferayjedi/liferaywork
https://github.com/liferayjedi/liferaywork
cba9d01125129a04306059dbc59dbfd06e510165
9e2491baa2023e27c5904d5b5990cea6653cf799
refs/heads/master
2016-08-09T23:30:26.292000
2016-01-17T16:28:42
2016-01-17T16:28:42
49,152,363
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tgp.procurement.transaction.web.controller.reviewcheckoutbasket; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.portlet.bind.annotation.RenderMapping; import com.liferay.portal.kernel.util.PropsUtil; import com.tgp.procurement.common.constants.TGPProcurementConstants; import com.tgp.procurement.common.exception.TGPProcurementException; import com.tgp.procurement.common.liferay.service.TGPLiferayEmailService; import com.tgp.procurement.common.transaction.vo.reviewcheckoutbasket.TGPReviewCheckOutBasketListVO; import com.tgp.procurement.common.transaction.vo.reviewcheckoutbasket.TGPReviewCheckOutBasketVO; import com.tgp.procurement.common.util.TGPGeneralUtil; import com.tgp.procurement.common.util.TGPObjectUtil; import com.tgp.procurement.common.util.TGPProcurementPropertiesUtil; import com.tgp.procurement.common.vo.TGPMessage; import com.tgp.procurement.transaction.framework.business.delegate.reviewcheckoutbasket.TGPReviewCheckOutBasketDelegate; import com.tgp.procurement.transaction.web.controller.common.TGPProcurementBaseController; @Controller("tgpReviewCheckOutController") @RequestMapping(value = "VIEW") public class TGPReviewCheckoutBasketController extends TGPProcurementBaseController{ /** * */ private static final long serialVersionUID = 2145167073062791670L; @RenderMapping public String showHomePage(RenderRequest request, RenderResponse response) { String renderPage = reviewAndCheckOutBasketPage; tgpMessage.setErrorMessage(request.getParameter(TGPProcurementConstants.ERROR_MESSAGE)); tgpMessage.setSuccessMessage(request.getParameter(TGPProcurementConstants.SUCCESS_MESSAGE)); return renderPage; } @ModelAttribute(tgpReviewCheckOutListVOString) public TGPReviewCheckOutBasketListVO getTransactionList(RenderRequest request,RenderResponse response){ String userId = request.getRemoteUser(); try { tgpReviewCheckOutListVO=tgpReviewCheckoutBasketDelegate.getReviewCheckOutBasketList(Long.valueOf(userId)); }catch (TGPProcurementException tgpExcp) { tgpMessage.setErrorMessage(tgpExcp.getErrorCode()); }catch (Exception ex){ tgpMessage.setErrorMessage(ex.getMessage()); } return tgpReviewCheckOutListVO; } @RenderMapping(params="formAction=removefromBasket") public String removefromBasket(@RequestParam String index,Model model,RenderRequest request,RenderResponse response){ tgpReviewCheckOutBasketVO = tgpReviewCheckOutListVO.getTgpReviewCheckoutList().get(Integer.parseInt(index)); tgpMessage.setSuccessMessage(null); tgpMessage.setErrorMessage(null); String userId = request.getRemoteUser(); TGPReviewCheckOutBasketListVO tgpRemovefromBasketList =new TGPReviewCheckOutBasketListVO(); tgpRemovefromBasketList.getTgpReviewCheckoutList().add(tgpReviewCheckOutBasketVO); try { tgpReviewCheckOutListVO = tgpReviewCheckoutBasketDelegate.removeFromBasket(tgpRemovefromBasketList.getTgpReviewCheckoutList(),Long.valueOf(userId)); //tgpReviewCheckOutListVO.getTgpReviewCheckoutList().remove(Integer.parseInt(index)); tgpMessage.setSuccessMessage(TGPProcurementConstants.TGP_REVIEW_CHECKOUT_REMOVE_FROM_BASKET); } catch (TGPProcurementException tgpexp) { tgpMessage.setErrorMessage(TGPProcurementConstants.TGP_REVIEW_CHECKOUT_REMOVE_FROM_BASKET_ERROR); } model.addAttribute(tgpReviewCheckOutListVOString, tgpReviewCheckOutListVO); model.addAttribute(tgpMessageString, tgpMessage); return reviewAndCheckOutBasketPage; } @RenderMapping(params="formAction=checkOutBasket") public String checkOutBasket(Model model,RenderRequest request,RenderResponse response){ tgpMessage.setSuccessMessage(null); tgpMessage.setErrorMessage(null); StringBuilder mailBody = new StringBuilder(); String rowStart=TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_BASKET_MAIL_TABLE_TD_START); String rowBtw = TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_BASKET_MAIL_BODY_TABLE_TD_BETWEEN); String rowEnd=TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_BASKET_MAIL_BODY_TABLE_TD_END); String userId = request.getRemoteUser(); try { tgpReviewCheckoutBasketDelegate.checkOutBasket(tgpReviewCheckOutListVO.getTgpReviewCheckoutList()); String customerEmailId = tgpReviewCheckoutBasketDelegate.getCustomerEmailId(tgpReviewCheckOutListVO.getTgpReviewCheckoutList().get(0).getCustomerUserId()); String customerName = tgpReviewCheckoutBasketDelegate.getCustomerName(tgpReviewCheckOutListVO.getTgpReviewCheckoutList().get(0).getCustomerUserId()); String userEmailId = tgpReviewCheckoutBasketDelegate.getUserEmailId(request.getRemoteUser()); List<String> toList = new ArrayList<String>(); toList.add(customerEmailId); toList.add(userEmailId); String customerEmailSubject = TGPProcurementPropertiesUtil. getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_CUSTOMER_EMAIL_SUBJECT); String customerEmailBody = TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_CUSTOMER_EMAIL_BODY); String customerEmailFooter =TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_BASKET_MAIL_BODY_TEXT_BOTTOM); for(TGPReviewCheckOutBasketVO tgpReviewCheckoutVO : tgpReviewCheckOutListVO.getTgpReviewCheckoutList() ){ String commodityName = tgpReviewCheckoutVO.getCommodityName(); String productQty = tgpReviewCheckoutVO.getQuantity(); mailBody = new StringBuilder(mailBody).append(rowStart).append(TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_VIEW_ALL_TRANSACTION_SATUS_PENDING)).append(rowBtw); mailBody = new StringBuilder(mailBody).append(commodityName).append(rowBtw); mailBody = new StringBuilder(mailBody).append(customerName).append(rowBtw); mailBody = new StringBuilder(mailBody).append(tgpReviewCheckoutVO.getProductName()).append(rowBtw); mailBody = new StringBuilder(mailBody).append(productQty).append(rowBtw); mailBody = new StringBuilder(mailBody).append(tgpReviewCheckoutVO.getTransactionType()).append(rowBtw); mailBody = new StringBuilder(mailBody).append(tgpReviewCheckoutVO.getPrice()); mailBody = new StringBuilder(mailBody).append(rowEnd); } mailBody = new StringBuilder(mailBody).append(TGPProcurementPropertiesUtil. getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_BASKET_MAIL_BODY_TABLE_FOOTER)); String finalcustomerEmailBody = customerEmailBody+ TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_BASKET_CUSTOMER_EMAIL_TABLE_HEADER) + mailBody + customerEmailFooter; TGPLiferayEmailService.sendEmail(TGPProcurementPropertiesUtil. getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_SENDER_ID), toList, customerEmailSubject, finalcustomerEmailBody); String supplierEmailDL = TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_SUPPLIER_DL); toList.clear(); for(String temp:Arrays.asList(supplierEmailDL.split(","))){ temp.trim(); toList.add(temp); } String supplierEmailSubject = TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_SUPPLIER_EMAIL_SUBJECT); String supplierEmailBody = TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_SUPPLIER_EMAIL_BODY); mailBody =new StringBuilder(); String supplierEmailFooter =TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_BASKET_MAIL_BODY_PORTAL_LINK); for(TGPReviewCheckOutBasketVO tgpReviewCheckoutVO : tgpReviewCheckOutListVO.getTgpReviewCheckoutList() ){ String commodityName = tgpReviewCheckoutVO.getCommodityName(); String productQty = tgpReviewCheckoutVO.getQuantity(); mailBody = new StringBuilder(mailBody).append(rowStart).append(TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_VIEW_ALL_TRANSACTION_SATUS_PENDING)).append(rowBtw); mailBody = new StringBuilder(mailBody).append(commodityName).append(rowBtw); mailBody = new StringBuilder(mailBody).append(customerName).append(rowBtw); mailBody = new StringBuilder(mailBody).append(tgpReviewCheckoutVO.getProductName()).append(rowBtw); mailBody = new StringBuilder(mailBody).append(productQty).append(rowBtw); mailBody = new StringBuilder(mailBody).append(tgpReviewCheckoutVO.getTransactionType()).append(rowBtw); mailBody = new StringBuilder(mailBody).append(tgpReviewCheckoutVO.getMarketPrice()).append(rowBtw); mailBody = new StringBuilder(mailBody).append(tgpReviewCheckoutVO.getPrice()); mailBody = new StringBuilder(mailBody).append(rowEnd); } String supplierPortalLink = ""; if(TGPObjectUtil.isDefined(PropsUtil.get("TGPSupplierTranPage"))){ supplierPortalLink = "<br/><br/><a href=\"" + PropsUtil.get("TGPSupplierTranPage") + "\"> TGP Procurement Portal Link </a>"; } mailBody = new StringBuilder(mailBody).append(TGPProcurementPropertiesUtil. getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_BASKET_MAIL_BODY_TABLE_FOOTER)); String finalsupplierEmailBody = supplierEmailBody + TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_BASKET_SUPPLIER_EMAIL_TABLE_HEADER) + mailBody + supplierEmailFooter + supplierPortalLink; TGPLiferayEmailService.sendEmail(TGPProcurementPropertiesUtil. getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_SENDER_ID), toList, supplierEmailSubject, finalsupplierEmailBody); tgpReviewCheckOutListVO.getTgpReviewCheckoutList().removeAll(tgpReviewCheckOutListVO.getTgpReviewCheckoutList()); tgpReviewCheckOutListVO=tgpReviewCheckoutBasketDelegate.getReviewCheckOutBasketList(Long.valueOf(userId)); tgpMessage.setSuccessMessage(TGPProcurementConstants.TGP_REVIEW_CHECKOUT_CHECKED_OUT); } catch (TGPProcurementException tgpExp) { tgpMessage.setErrorMessage(tgpExp.getErrorCode()); } catch (Exception exp){ tgpMessage.setErrorMessage(exp.getMessage()); } model.addAttribute(tgpReviewCheckOutListVOString, tgpReviewCheckOutListVO); model.addAttribute(tgpMessageString, tgpMessage); return reviewAndCheckOutBasketPage; } public TGPReviewCheckOutBasketListVO getTgpReviewCheckOutListVO() { return tgpReviewCheckOutListVO; } public void setTgpReviewCheckOutListVO( TGPReviewCheckOutBasketListVO tgpReviewCheckOutListVO) { this.tgpReviewCheckOutListVO = tgpReviewCheckOutListVO; } public TGPReviewCheckOutBasketVO getTgpReviewCheckOutBasketVO() { return tgpReviewCheckOutBasketVO; } public void setTgpReviewCheckOutBasketVO( TGPReviewCheckOutBasketVO tgpReviewCheckOutBasketVO) { this.tgpReviewCheckOutBasketVO = tgpReviewCheckOutBasketVO; } public void setTgpMessage(TGPMessage tgpMessage) { this.tgpMessage = tgpMessage; } public void setTgpReviewCheckoutBasketDelegate( TGPReviewCheckOutBasketDelegate tgpReviewCheckoutBasketDelegate) { this.tgpReviewCheckoutBasketDelegate = tgpReviewCheckoutBasketDelegate; } private TGPReviewCheckOutBasketListVO tgpReviewCheckOutListVO = new TGPReviewCheckOutBasketListVO() ; private TGPMessage tgpMessage = new TGPMessage(); private TGPReviewCheckOutBasketVO tgpReviewCheckOutBasketVO; @Autowired private TGPReviewCheckOutBasketDelegate tgpReviewCheckoutBasketDelegate; private static final String tgpMessageString = "tgpMessage"; private static final String tgpReviewCheckOutListVOString = "tgpReviewCheckOutListVO"; private static final String reviewAndCheckOutBasketPage = "reviewAndCheckOutBasket/tgpReviewAndCheckoutBasket"; }
UTF-8
Java
12,148
java
TGPReviewCheckoutBasketController.java
Java
[]
null
[]
package com.tgp.procurement.transaction.web.controller.reviewcheckoutbasket; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.portlet.bind.annotation.RenderMapping; import com.liferay.portal.kernel.util.PropsUtil; import com.tgp.procurement.common.constants.TGPProcurementConstants; import com.tgp.procurement.common.exception.TGPProcurementException; import com.tgp.procurement.common.liferay.service.TGPLiferayEmailService; import com.tgp.procurement.common.transaction.vo.reviewcheckoutbasket.TGPReviewCheckOutBasketListVO; import com.tgp.procurement.common.transaction.vo.reviewcheckoutbasket.TGPReviewCheckOutBasketVO; import com.tgp.procurement.common.util.TGPGeneralUtil; import com.tgp.procurement.common.util.TGPObjectUtil; import com.tgp.procurement.common.util.TGPProcurementPropertiesUtil; import com.tgp.procurement.common.vo.TGPMessage; import com.tgp.procurement.transaction.framework.business.delegate.reviewcheckoutbasket.TGPReviewCheckOutBasketDelegate; import com.tgp.procurement.transaction.web.controller.common.TGPProcurementBaseController; @Controller("tgpReviewCheckOutController") @RequestMapping(value = "VIEW") public class TGPReviewCheckoutBasketController extends TGPProcurementBaseController{ /** * */ private static final long serialVersionUID = 2145167073062791670L; @RenderMapping public String showHomePage(RenderRequest request, RenderResponse response) { String renderPage = reviewAndCheckOutBasketPage; tgpMessage.setErrorMessage(request.getParameter(TGPProcurementConstants.ERROR_MESSAGE)); tgpMessage.setSuccessMessage(request.getParameter(TGPProcurementConstants.SUCCESS_MESSAGE)); return renderPage; } @ModelAttribute(tgpReviewCheckOutListVOString) public TGPReviewCheckOutBasketListVO getTransactionList(RenderRequest request,RenderResponse response){ String userId = request.getRemoteUser(); try { tgpReviewCheckOutListVO=tgpReviewCheckoutBasketDelegate.getReviewCheckOutBasketList(Long.valueOf(userId)); }catch (TGPProcurementException tgpExcp) { tgpMessage.setErrorMessage(tgpExcp.getErrorCode()); }catch (Exception ex){ tgpMessage.setErrorMessage(ex.getMessage()); } return tgpReviewCheckOutListVO; } @RenderMapping(params="formAction=removefromBasket") public String removefromBasket(@RequestParam String index,Model model,RenderRequest request,RenderResponse response){ tgpReviewCheckOutBasketVO = tgpReviewCheckOutListVO.getTgpReviewCheckoutList().get(Integer.parseInt(index)); tgpMessage.setSuccessMessage(null); tgpMessage.setErrorMessage(null); String userId = request.getRemoteUser(); TGPReviewCheckOutBasketListVO tgpRemovefromBasketList =new TGPReviewCheckOutBasketListVO(); tgpRemovefromBasketList.getTgpReviewCheckoutList().add(tgpReviewCheckOutBasketVO); try { tgpReviewCheckOutListVO = tgpReviewCheckoutBasketDelegate.removeFromBasket(tgpRemovefromBasketList.getTgpReviewCheckoutList(),Long.valueOf(userId)); //tgpReviewCheckOutListVO.getTgpReviewCheckoutList().remove(Integer.parseInt(index)); tgpMessage.setSuccessMessage(TGPProcurementConstants.TGP_REVIEW_CHECKOUT_REMOVE_FROM_BASKET); } catch (TGPProcurementException tgpexp) { tgpMessage.setErrorMessage(TGPProcurementConstants.TGP_REVIEW_CHECKOUT_REMOVE_FROM_BASKET_ERROR); } model.addAttribute(tgpReviewCheckOutListVOString, tgpReviewCheckOutListVO); model.addAttribute(tgpMessageString, tgpMessage); return reviewAndCheckOutBasketPage; } @RenderMapping(params="formAction=checkOutBasket") public String checkOutBasket(Model model,RenderRequest request,RenderResponse response){ tgpMessage.setSuccessMessage(null); tgpMessage.setErrorMessage(null); StringBuilder mailBody = new StringBuilder(); String rowStart=TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_BASKET_MAIL_TABLE_TD_START); String rowBtw = TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_BASKET_MAIL_BODY_TABLE_TD_BETWEEN); String rowEnd=TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_BASKET_MAIL_BODY_TABLE_TD_END); String userId = request.getRemoteUser(); try { tgpReviewCheckoutBasketDelegate.checkOutBasket(tgpReviewCheckOutListVO.getTgpReviewCheckoutList()); String customerEmailId = tgpReviewCheckoutBasketDelegate.getCustomerEmailId(tgpReviewCheckOutListVO.getTgpReviewCheckoutList().get(0).getCustomerUserId()); String customerName = tgpReviewCheckoutBasketDelegate.getCustomerName(tgpReviewCheckOutListVO.getTgpReviewCheckoutList().get(0).getCustomerUserId()); String userEmailId = tgpReviewCheckoutBasketDelegate.getUserEmailId(request.getRemoteUser()); List<String> toList = new ArrayList<String>(); toList.add(customerEmailId); toList.add(userEmailId); String customerEmailSubject = TGPProcurementPropertiesUtil. getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_CUSTOMER_EMAIL_SUBJECT); String customerEmailBody = TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_CUSTOMER_EMAIL_BODY); String customerEmailFooter =TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_BASKET_MAIL_BODY_TEXT_BOTTOM); for(TGPReviewCheckOutBasketVO tgpReviewCheckoutVO : tgpReviewCheckOutListVO.getTgpReviewCheckoutList() ){ String commodityName = tgpReviewCheckoutVO.getCommodityName(); String productQty = tgpReviewCheckoutVO.getQuantity(); mailBody = new StringBuilder(mailBody).append(rowStart).append(TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_VIEW_ALL_TRANSACTION_SATUS_PENDING)).append(rowBtw); mailBody = new StringBuilder(mailBody).append(commodityName).append(rowBtw); mailBody = new StringBuilder(mailBody).append(customerName).append(rowBtw); mailBody = new StringBuilder(mailBody).append(tgpReviewCheckoutVO.getProductName()).append(rowBtw); mailBody = new StringBuilder(mailBody).append(productQty).append(rowBtw); mailBody = new StringBuilder(mailBody).append(tgpReviewCheckoutVO.getTransactionType()).append(rowBtw); mailBody = new StringBuilder(mailBody).append(tgpReviewCheckoutVO.getPrice()); mailBody = new StringBuilder(mailBody).append(rowEnd); } mailBody = new StringBuilder(mailBody).append(TGPProcurementPropertiesUtil. getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_BASKET_MAIL_BODY_TABLE_FOOTER)); String finalcustomerEmailBody = customerEmailBody+ TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_BASKET_CUSTOMER_EMAIL_TABLE_HEADER) + mailBody + customerEmailFooter; TGPLiferayEmailService.sendEmail(TGPProcurementPropertiesUtil. getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_SENDER_ID), toList, customerEmailSubject, finalcustomerEmailBody); String supplierEmailDL = TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_SUPPLIER_DL); toList.clear(); for(String temp:Arrays.asList(supplierEmailDL.split(","))){ temp.trim(); toList.add(temp); } String supplierEmailSubject = TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_SUPPLIER_EMAIL_SUBJECT); String supplierEmailBody = TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_SUPPLIER_EMAIL_BODY); mailBody =new StringBuilder(); String supplierEmailFooter =TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_BASKET_MAIL_BODY_PORTAL_LINK); for(TGPReviewCheckOutBasketVO tgpReviewCheckoutVO : tgpReviewCheckOutListVO.getTgpReviewCheckoutList() ){ String commodityName = tgpReviewCheckoutVO.getCommodityName(); String productQty = tgpReviewCheckoutVO.getQuantity(); mailBody = new StringBuilder(mailBody).append(rowStart).append(TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_VIEW_ALL_TRANSACTION_SATUS_PENDING)).append(rowBtw); mailBody = new StringBuilder(mailBody).append(commodityName).append(rowBtw); mailBody = new StringBuilder(mailBody).append(customerName).append(rowBtw); mailBody = new StringBuilder(mailBody).append(tgpReviewCheckoutVO.getProductName()).append(rowBtw); mailBody = new StringBuilder(mailBody).append(productQty).append(rowBtw); mailBody = new StringBuilder(mailBody).append(tgpReviewCheckoutVO.getTransactionType()).append(rowBtw); mailBody = new StringBuilder(mailBody).append(tgpReviewCheckoutVO.getMarketPrice()).append(rowBtw); mailBody = new StringBuilder(mailBody).append(tgpReviewCheckoutVO.getPrice()); mailBody = new StringBuilder(mailBody).append(rowEnd); } String supplierPortalLink = ""; if(TGPObjectUtil.isDefined(PropsUtil.get("TGPSupplierTranPage"))){ supplierPortalLink = "<br/><br/><a href=\"" + PropsUtil.get("TGPSupplierTranPage") + "\"> TGP Procurement Portal Link </a>"; } mailBody = new StringBuilder(mailBody).append(TGPProcurementPropertiesUtil. getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_BASKET_MAIL_BODY_TABLE_FOOTER)); String finalsupplierEmailBody = supplierEmailBody + TGPProcurementPropertiesUtil.getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_BASKET_SUPPLIER_EMAIL_TABLE_HEADER) + mailBody + supplierEmailFooter + supplierPortalLink; TGPLiferayEmailService.sendEmail(TGPProcurementPropertiesUtil. getProperty(TGPProcurementConstants.TGP_EMAIL_REVIEW_CHECKOUT_SENDER_ID), toList, supplierEmailSubject, finalsupplierEmailBody); tgpReviewCheckOutListVO.getTgpReviewCheckoutList().removeAll(tgpReviewCheckOutListVO.getTgpReviewCheckoutList()); tgpReviewCheckOutListVO=tgpReviewCheckoutBasketDelegate.getReviewCheckOutBasketList(Long.valueOf(userId)); tgpMessage.setSuccessMessage(TGPProcurementConstants.TGP_REVIEW_CHECKOUT_CHECKED_OUT); } catch (TGPProcurementException tgpExp) { tgpMessage.setErrorMessage(tgpExp.getErrorCode()); } catch (Exception exp){ tgpMessage.setErrorMessage(exp.getMessage()); } model.addAttribute(tgpReviewCheckOutListVOString, tgpReviewCheckOutListVO); model.addAttribute(tgpMessageString, tgpMessage); return reviewAndCheckOutBasketPage; } public TGPReviewCheckOutBasketListVO getTgpReviewCheckOutListVO() { return tgpReviewCheckOutListVO; } public void setTgpReviewCheckOutListVO( TGPReviewCheckOutBasketListVO tgpReviewCheckOutListVO) { this.tgpReviewCheckOutListVO = tgpReviewCheckOutListVO; } public TGPReviewCheckOutBasketVO getTgpReviewCheckOutBasketVO() { return tgpReviewCheckOutBasketVO; } public void setTgpReviewCheckOutBasketVO( TGPReviewCheckOutBasketVO tgpReviewCheckOutBasketVO) { this.tgpReviewCheckOutBasketVO = tgpReviewCheckOutBasketVO; } public void setTgpMessage(TGPMessage tgpMessage) { this.tgpMessage = tgpMessage; } public void setTgpReviewCheckoutBasketDelegate( TGPReviewCheckOutBasketDelegate tgpReviewCheckoutBasketDelegate) { this.tgpReviewCheckoutBasketDelegate = tgpReviewCheckoutBasketDelegate; } private TGPReviewCheckOutBasketListVO tgpReviewCheckOutListVO = new TGPReviewCheckOutBasketListVO() ; private TGPMessage tgpMessage = new TGPMessage(); private TGPReviewCheckOutBasketVO tgpReviewCheckOutBasketVO; @Autowired private TGPReviewCheckOutBasketDelegate tgpReviewCheckoutBasketDelegate; private static final String tgpMessageString = "tgpMessage"; private static final String tgpReviewCheckOutListVOString = "tgpReviewCheckOutListVO"; private static final String reviewAndCheckOutBasketPage = "reviewAndCheckOutBasket/tgpReviewAndCheckoutBasket"; }
12,148
0.830178
0.828449
210
56.847618
45.972305
214
false
false
0
0
0
0
0
0
2.585714
false
false
3
d409d926c7b1f759959e25b2da2109799c24e0a2
2,310,692,461,104
a199322a6da71e6a258964cbcb9c9df3d4fe9196
/com.dubture.doctrine.core/src/com/dubture/doctrine/core/model/DoctrineModelAccess.java
574f44463c547ec79dd3c0c1136ff2408d6351ae
[]
no_license
pulse00/Doctrine-Eclipse-Plugin
https://github.com/pulse00/Doctrine-Eclipse-Plugin
86dc9820300058f0cd5a5d6ca0d34112cd57eb77
2cda219e94b7f48a2e28681d85160ed537925624
refs/heads/master
2021-12-23T00:22:59.263000
2020-05-13T10:38:45
2020-05-13T10:38:45
2,581,313
7
4
null
false
2014-03-06T08:38:27
2011-10-15T10:55:12
2014-03-06T08:38:27
2014-03-06T08:38:27
2,140
10
3
3
Java
null
null
package com.dubture.doctrine.core.model; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.Platform; import org.eclipse.dltk.core.IScriptProject; import org.eclipse.dltk.core.ISourceModule; import org.eclipse.dltk.core.IType; import org.eclipse.dltk.core.index2.search.ISearchEngine; import org.eclipse.dltk.core.index2.search.ISearchEngine.MatchRule; import org.eclipse.dltk.core.index2.search.ISearchEngine.SearchFor; import org.eclipse.dltk.core.index2.search.ISearchRequestor; import org.eclipse.dltk.core.index2.search.ModelAccess; import org.eclipse.dltk.core.search.IDLTKSearchScope; import org.eclipse.dltk.core.search.SearchEngine; import org.eclipse.dltk.internal.core.util.LRUCache; import org.eclipse.php.internal.core.PHPLanguageToolkit; import org.eclipse.php.internal.core.model.PHPModelAccess; import com.dubture.doctrine.core.goals.IEntityResolver; import com.dubture.doctrine.core.index.ICleanListener; import com.dubture.doctrine.core.log.Logger; /** * * Access to the doctrine model. * * * @author Robert Gruendler <r.gruendler@gmail.com> * */ @SuppressWarnings("restriction") public class DoctrineModelAccess extends PHPModelAccess implements ICleanListener { private static final String ENTITYRESOLVER_ID = "com.dubture.doctrine.core.entityResolvers"; private static DoctrineModelAccess modelInstance = null; private List<IEntityResolver> resolvers = null; private LRUCache entityCache = new LRUCache(10); private final String NULL_RESULT = "__NOT_FOUND__"; public static DoctrineModelAccess getDefault() { if (modelInstance == null) modelInstance = new DoctrineModelAccess(); return modelInstance; } /** * * Find the repositoryClass for a doctrine entity * * @param className * @param project * @return */ public String getRepositoryClass(String className, String qualifier, IScriptProject project) { if (className == null ) { return null; } String key = project.getElementName() + "/" + className; IDLTKSearchScope scope = SearchEngine.createSearchScope(project); if (scope == null) { return null; } ISearchEngine engine = ModelAccess.getSearchEngine(PHPLanguageToolkit.getDefault()); final List<String> repos = new ArrayList<String>(); engine.search(IDoctrineModelElement.REPOSITORY_CLASS, qualifier, className, 0, 0, 100, SearchFor.REFERENCES, MatchRule.EXACT, scope, new ISearchRequestor() { public void match(int elementType, int flags, int offset, int length, int nameOffset, int nameLength, String elementName, String metadata, String doc, String qualifier, String parent, ISourceModule sourceModule, boolean isReference) { if (metadata != null) { repos.add(metadata); } } }, null); if (repos.size() == 1) { String repo = repos.get(0); return repo; } return null; } public List<Entity> getEntities(IScriptProject project) { IDLTKSearchScope scope = SearchEngine.createSearchScope(project); if (scope == null) { return null; } ISearchEngine engine = ModelAccess.getSearchEngine(PHPLanguageToolkit.getDefault()); final List<Entity> entities = new ArrayList<Entity>(); engine.search(IDoctrineModelElement.ENTITY, null, null, 0, 0, 100, SearchFor.REFERENCES, MatchRule.PREFIX, scope, new ISearchRequestor() { public void match(int elementType, int flags, int offset, int length, int nameOffset, int nameLength, String elementName, String metadata, String doc, String qualifier, String parent, ISourceModule sourceModule, boolean isReference) { String name = ""; if (qualifier != null) name = qualifier + "\\"; name += elementName; Entity e = new Entity(null, name); entities.add(e); } }, null); return entities; } /** * Resolve a classname via registered entityResolver extensions. * * @param classname * @param project * @return */ public IType getExtensionType(String classname, IScriptProject project) { String key = classname + project.getElementName(); Object object = entityCache.get(key); if (object != null && object.equals(NULL_RESULT)) { return null; } else if (object instanceof IType) { return (IType) object; } for (IEntityResolver resolver : getResolvers()) { IType type = resolver.resolve(classname, project); // first extension wins if (type != null) { entityCache.put(key, type); return type; } } entityCache.put(classname, NULL_RESULT); return null; } private List<IEntityResolver> getResolvers() { if (resolvers != null) { return resolvers; } resolvers = new ArrayList<IEntityResolver>(); IConfigurationElement[] config = Platform.getExtensionRegistry().getConfigurationElementsFor(ENTITYRESOLVER_ID); try { for (IConfigurationElement element : config) { final Object extension = element.createExecutableExtension("class"); if (extension instanceof IEntityResolver) { resolvers.add((IEntityResolver) extension); } } } catch (Exception e1) { Logger.logException(e1); } return resolvers; } public void clean() { entityCache.flush(); } }
UTF-8
Java
5,239
java
DoctrineModelAccess.java
Java
[ { "context": "\n * Access to the doctrine model.\n *\n *\n * @author Robert Gruendler <r.gruendler@gmail.com>\n *\n */\n@SuppressWarnings(", "end": 1131, "score": 0.9998780488967896, "start": 1115, "tag": "NAME", "value": "Robert Gruendler" }, { "context": "octrine model.\n *\n *\n * @author Robert Gruendler <r.gruendler@gmail.com>\n *\n */\n@SuppressWarnings(\"restriction\")\npublic c", "end": 1154, "score": 0.9999226331710815, "start": 1133, "tag": "EMAIL", "value": "r.gruendler@gmail.com" }, { "context": "ll ) {\n\t\t\treturn null;\n\t\t}\n\n\t\tString key = project.getElementName() + \"/\" + className;\n\n\t\tIDLTKSearchScope scope = SearchEngine.createS", "end": 2066, "score": 0.9005535840988159, "start": 2032, "tag": "KEY", "value": "getElementName() + \"/\" + className" } ]
null
[]
package com.dubture.doctrine.core.model; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.Platform; import org.eclipse.dltk.core.IScriptProject; import org.eclipse.dltk.core.ISourceModule; import org.eclipse.dltk.core.IType; import org.eclipse.dltk.core.index2.search.ISearchEngine; import org.eclipse.dltk.core.index2.search.ISearchEngine.MatchRule; import org.eclipse.dltk.core.index2.search.ISearchEngine.SearchFor; import org.eclipse.dltk.core.index2.search.ISearchRequestor; import org.eclipse.dltk.core.index2.search.ModelAccess; import org.eclipse.dltk.core.search.IDLTKSearchScope; import org.eclipse.dltk.core.search.SearchEngine; import org.eclipse.dltk.internal.core.util.LRUCache; import org.eclipse.php.internal.core.PHPLanguageToolkit; import org.eclipse.php.internal.core.model.PHPModelAccess; import com.dubture.doctrine.core.goals.IEntityResolver; import com.dubture.doctrine.core.index.ICleanListener; import com.dubture.doctrine.core.log.Logger; /** * * Access to the doctrine model. * * * @author <NAME> <<EMAIL>> * */ @SuppressWarnings("restriction") public class DoctrineModelAccess extends PHPModelAccess implements ICleanListener { private static final String ENTITYRESOLVER_ID = "com.dubture.doctrine.core.entityResolvers"; private static DoctrineModelAccess modelInstance = null; private List<IEntityResolver> resolvers = null; private LRUCache entityCache = new LRUCache(10); private final String NULL_RESULT = "__NOT_FOUND__"; public static DoctrineModelAccess getDefault() { if (modelInstance == null) modelInstance = new DoctrineModelAccess(); return modelInstance; } /** * * Find the repositoryClass for a doctrine entity * * @param className * @param project * @return */ public String getRepositoryClass(String className, String qualifier, IScriptProject project) { if (className == null ) { return null; } String key = project.getElementName() + "/" + className; IDLTKSearchScope scope = SearchEngine.createSearchScope(project); if (scope == null) { return null; } ISearchEngine engine = ModelAccess.getSearchEngine(PHPLanguageToolkit.getDefault()); final List<String> repos = new ArrayList<String>(); engine.search(IDoctrineModelElement.REPOSITORY_CLASS, qualifier, className, 0, 0, 100, SearchFor.REFERENCES, MatchRule.EXACT, scope, new ISearchRequestor() { public void match(int elementType, int flags, int offset, int length, int nameOffset, int nameLength, String elementName, String metadata, String doc, String qualifier, String parent, ISourceModule sourceModule, boolean isReference) { if (metadata != null) { repos.add(metadata); } } }, null); if (repos.size() == 1) { String repo = repos.get(0); return repo; } return null; } public List<Entity> getEntities(IScriptProject project) { IDLTKSearchScope scope = SearchEngine.createSearchScope(project); if (scope == null) { return null; } ISearchEngine engine = ModelAccess.getSearchEngine(PHPLanguageToolkit.getDefault()); final List<Entity> entities = new ArrayList<Entity>(); engine.search(IDoctrineModelElement.ENTITY, null, null, 0, 0, 100, SearchFor.REFERENCES, MatchRule.PREFIX, scope, new ISearchRequestor() { public void match(int elementType, int flags, int offset, int length, int nameOffset, int nameLength, String elementName, String metadata, String doc, String qualifier, String parent, ISourceModule sourceModule, boolean isReference) { String name = ""; if (qualifier != null) name = qualifier + "\\"; name += elementName; Entity e = new Entity(null, name); entities.add(e); } }, null); return entities; } /** * Resolve a classname via registered entityResolver extensions. * * @param classname * @param project * @return */ public IType getExtensionType(String classname, IScriptProject project) { String key = classname + project.getElementName(); Object object = entityCache.get(key); if (object != null && object.equals(NULL_RESULT)) { return null; } else if (object instanceof IType) { return (IType) object; } for (IEntityResolver resolver : getResolvers()) { IType type = resolver.resolve(classname, project); // first extension wins if (type != null) { entityCache.put(key, type); return type; } } entityCache.put(classname, NULL_RESULT); return null; } private List<IEntityResolver> getResolvers() { if (resolvers != null) { return resolvers; } resolvers = new ArrayList<IEntityResolver>(); IConfigurationElement[] config = Platform.getExtensionRegistry().getConfigurationElementsFor(ENTITYRESOLVER_ID); try { for (IConfigurationElement element : config) { final Object extension = element.createExecutableExtension("class"); if (extension instanceof IEntityResolver) { resolvers.add((IEntityResolver) extension); } } } catch (Exception e1) { Logger.logException(e1); } return resolvers; } public void clean() { entityCache.flush(); } }
5,215
0.726093
0.722084
195
25.871796
28.069857
114
false
false
0
0
0
0
0
0
2.158974
false
false
3
41d14870ffa8bf7cdcb6ca6fb4572beb57526318
5,970,004,595,224
29b6e415a41576153b055117e6315bdb81880430
/Client/Android/Scrumer/app/src/main/java/com/tanyixiu/scrumer/http/VolleyHelper.java
6850c1e611c6a07c8876f77563c0b0bf63acfc3d
[]
no_license
csc0211/Scrumer
https://github.com/csc0211/Scrumer
c01602375c1f1e8595c41fc89d7b44b19169e997
4e4968bcf429e05b6e8eccb54fdbde976223f32e
refs/heads/master
2020-12-30T18:37:52.495000
2015-08-22T05:58:00
2015-08-22T05:58:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tanyixiu.scrumer.http; import android.util.Log; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.tanyixiu.scrumer.App; import java.net.URLEncoder; /** * Created by Mimo on 2015/8/18. */ public class VolleyHelper { private static final String SERVER_ADDRESS = "http://192.168.0.104/scrumer/web/index.php/store/sql?sql=%s"; public interface RequestListener<T> extends Response.Listener<T>, Response.ErrorListener { } public static void requestServer(String param, RequestListener listener) { try { param = URLEncoder.encode(param, "UTF-8"); String url = String.format(SERVER_ADDRESS, param); Log.d("TEST", url); StringRequest request = new StringRequest(url, listener, listener); App.getRequestQueue().add(request); } catch (Exception e) { e.printStackTrace(); listener.onErrorResponse(new VolleyError(e.getMessage())); } } }
UTF-8
Java
1,059
java
VolleyHelper.java
Java
[ { "context": "p;\n\nimport java.net.URLEncoder;\n\n/**\n * Created by Mimo on 2015/8/18.\n */\npublic class VolleyHelper {\n", "end": 268, "score": 0.4798450171947479, "start": 267, "tag": "NAME", "value": "M" }, { "context": "\n\nimport java.net.URLEncoder;\n\n/**\n * Created by Mimo on 2015/8/18.\n */\npublic class VolleyHelper {\n\n ", "end": 271, "score": 0.7714760303497314, "start": 268, "tag": "USERNAME", "value": "imo" }, { "context": "vate static final String SERVER_ADDRESS = \"http://192.168.0.104/scrumer/web/index.php/store/sql?sql=%s\";\n\n pub", "end": 389, "score": 0.9997711181640625, "start": 376, "tag": "IP_ADDRESS", "value": "192.168.0.104" } ]
null
[]
package com.tanyixiu.scrumer.http; import android.util.Log; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.tanyixiu.scrumer.App; import java.net.URLEncoder; /** * Created by Mimo on 2015/8/18. */ public class VolleyHelper { private static final String SERVER_ADDRESS = "http://192.168.0.104/scrumer/web/index.php/store/sql?sql=%s"; public interface RequestListener<T> extends Response.Listener<T>, Response.ErrorListener { } public static void requestServer(String param, RequestListener listener) { try { param = URLEncoder.encode(param, "UTF-8"); String url = String.format(SERVER_ADDRESS, param); Log.d("TEST", url); StringRequest request = new StringRequest(url, listener, listener); App.getRequestQueue().add(request); } catch (Exception e) { e.printStackTrace(); listener.onErrorResponse(new VolleyError(e.getMessage())); } } }
1,059
0.674221
0.657224
35
29.285715
29.669197
111
false
false
0
0
0
0
0
0
0.628571
false
false
3
afdebefe93e1dcb92b63cda054528361da9b478f
30,571,577,273,524
26b7d2d6f5aec50a8264577ec18d4179aabca87f
/src/main/java/com/crs/utils/Token.java
08ac585ee09e161ef1143f53d24e58fac4924bf3
[]
no_license
chrisrsipes/json2java
https://github.com/chrisrsipes/json2java
815e5130790081cea6608442a2b103e1c2703b77
07ef4a8751054f0c6919a3ebcb386427408466ca
refs/heads/master
2020-03-25T19:34:17.196000
2018-08-09T00:10:55
2018-08-09T00:10:55
144,089,410
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.crs.utils; /** * Created by crs on 8/8/18. */ public class Token { private String key; private String jsonBody; public Token() { } public Token(String key, String jsonBody) { this.key = key; this.jsonBody = jsonBody; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getJsonBody() { return jsonBody; } public void setJsonBody(String jsonBody) { this.jsonBody = jsonBody; } }
UTF-8
Java
559
java
Token.java
Java
[ { "context": "package com.crs.utils;\n\n/**\n * Created by crs on 8/8/18.\n */\npublic class Token {\n\n private ", "end": 45, "score": 0.9993807077407837, "start": 42, "tag": "USERNAME", "value": "crs" } ]
null
[]
package com.crs.utils; /** * Created by crs on 8/8/18. */ public class Token { private String key; private String jsonBody; public Token() { } public Token(String key, String jsonBody) { this.key = key; this.jsonBody = jsonBody; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getJsonBody() { return jsonBody; } public void setJsonBody(String jsonBody) { this.jsonBody = jsonBody; } }
559
0.568873
0.561717
36
14.527778
14.547788
47
false
false
0
0
0
0
0
0
0.277778
false
false
3
7ac3beac28f33e8da9fcea52adeca06db0991a9d
11,055,245,874,936
3597cd5aea263ea4d640edd384daf31371f0d7e4
/src/main/java/factory/pizzaaf/GoatCheese.java
a9bfaa2bd68464155a74e199a39115add7d9aad5
[]
no_license
derekberger/Head-First-Design-Patterns
https://github.com/derekberger/Head-First-Design-Patterns
b1b48fba75d84aafcef1e8803a0e41f5d0a141bf
a1a2cfc9d1017871526880979b8f4c4c1ce82a25
refs/heads/master
2021-06-17T09:26:58.933000
2019-03-28T16:01:09
2019-03-28T16:01:09
155,777,786
0
1
null
true
2019-03-28T16:01:10
2018-11-01T21:25:33
2019-03-28T14:18:27
2019-03-28T16:01:10
174
0
1
0
Java
false
null
package factory.pizzaaf; public class GoatCheese implements Cheese { public String toString(){ return "Goat Cheese"; } }
UTF-8
Java
143
java
GoatCheese.java
Java
[]
null
[]
package factory.pizzaaf; public class GoatCheese implements Cheese { public String toString(){ return "Goat Cheese"; } }
143
0.657343
0.657343
8
16.875
15.455076
43
false
false
0
0
0
0
0
0
0.25
false
false
3
321bee5f797f026bf6f284e167d4109b7c744250
29,686,813,996,636
ddd7c8e1478791babe56f0a24563f02cab790cf3
/src/main/java/Secteur.java
55af0d4e60ce7c797ecee50ed009185fd166fa04
[]
no_license
Jean-Philippe21/TP_1_API_POO_ensim
https://github.com/Jean-Philippe21/TP_1_API_POO_ensim
4b74d6a64ba31b60809de8365d9586d4c23a56c8
404bb657e8083ef4b74840bca55a08c467e8b3c5
refs/heads/master
2023-08-24T21:03:29.707000
2021-11-09T14:54:27
2021-11-09T14:54:27
423,922,404
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.List; public class Secteur { private TypeAnimal typeAnimauxDansSecteur; private List<Animal> animauxDansSecteur; //******************************************************************************** // * MES GETTERS ET SETTERS * //******************************************************************************** public TypeAnimal getTypeAnimauxDansSecteur() { return typeAnimauxDansSecteur; } public void setTypeAnimauxDansSecteur(TypeAnimal typeAnimauxDansSecteur) { this.typeAnimauxDansSecteur = typeAnimauxDansSecteur; } public List<Animal> getAnimauxDansSecteur() { return animauxDansSecteur; } public void setAnimauxDansSecteur(List<Animal> animauxDansSecteur) { this.animauxDansSecteur = animauxDansSecteur; } //******************************************************************************** // * Fin GETTERS ET SETTERS * //******************************************************************************** public void ajouterAnimal(Animal animal){ } public int getNombreAnimaux(){ return 0; } public Enum obtenirType(){ return typeAnimauxDansSecteur; } }
UTF-8
Java
1,331
java
Secteur.java
Java
[]
null
[]
import java.util.List; public class Secteur { private TypeAnimal typeAnimauxDansSecteur; private List<Animal> animauxDansSecteur; //******************************************************************************** // * MES GETTERS ET SETTERS * //******************************************************************************** public TypeAnimal getTypeAnimauxDansSecteur() { return typeAnimauxDansSecteur; } public void setTypeAnimauxDansSecteur(TypeAnimal typeAnimauxDansSecteur) { this.typeAnimauxDansSecteur = typeAnimauxDansSecteur; } public List<Animal> getAnimauxDansSecteur() { return animauxDansSecteur; } public void setAnimauxDansSecteur(List<Animal> animauxDansSecteur) { this.animauxDansSecteur = animauxDansSecteur; } //******************************************************************************** // * Fin GETTERS ET SETTERS * //******************************************************************************** public void ajouterAnimal(Animal animal){ } public int getNombreAnimaux(){ return 0; } public Enum obtenirType(){ return typeAnimauxDansSecteur; } }
1,331
0.456799
0.456048
44
29.25
31.325363
86
false
false
0
0
0
0
0
0
0.204545
false
false
3
16fe160f963247863173f7080e2992d4e2ae68d4
33,328,946,227,459
a1d3edbe4a9d810b3f6b35fc9f9f3226fa8e5107
/app/src/main/java/com/systemonline/fanscoupon/Model/Brand.java
2b8f72474c43c48b15d1e92a9f5769b24a33ab43
[]
no_license
graduation18/fans
https://github.com/graduation18/fans
84eead2dde6d66b9bd0b12d259cad0450fc3443a
a82a6ec7ce1f20cb1021e13e51aa385bf8636c59
refs/heads/master
2020-04-23T18:41:16.487000
2019-02-19T00:24:33
2019-02-19T00:24:33
171,376,433
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.systemonline.fanscoupon.Model; import java.util.ArrayList; public class Brand implements Cloneable { private String brandName, brandDesc, brandSlug, brandImage, brandCover, brandRatingStarsCount = "null"; private int brandID, brandFansCount, brandCouponsCount; private ArrayList<Brand> brandAlliances; private ArrayList<BrandBranch> brandBranches; private ArrayList<SocialNetwork> brandSocialNetworks; private ArrayList<Fan> brandFans; private boolean likedByCurrentUser = false, hasLoyalty; private ArrayList<CustomerType> brandCustomerTypes; private ArrayList<Coupon> loyaltyCoupons, specialOfferCoupons; private ArrayList<Comment> brandEvaluations; private Comment currentFanComment; public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } public String getBrandSlug() { return brandSlug; } public void setBrandSlug(String brandSlug) { this.brandSlug = brandSlug; } public String getBrandImage() { return brandImage; } public void setBrandImage(String brandImage) { this.brandImage = brandImage; } public String getBrandCover() { return brandCover; } public void setBrandCover(String brandCover) { this.brandCover = brandCover; } public int getBrandCouponsCount() { return brandCouponsCount; } public void setBrandCouponsCount(int brandCouponsCount) { this.brandCouponsCount = brandCouponsCount; } public Integer getBrandID() { return brandID; } public void setBrandID(Integer brandID) { this.brandID = brandID; } public int getBrandFansCount() { return brandFansCount; } public void setBrandFansCount(int brandFansCount) { this.brandFansCount = brandFansCount; } public String getBrandRatingStarsCount() { return brandRatingStarsCount; } public void setBrandRatingStarsCount(String brandRatingStarsCount) { this.brandRatingStarsCount = brandRatingStarsCount; } public ArrayList<Brand> getBrandAlliances() { return brandAlliances; } public void setBrandAlliances(ArrayList<Brand> brandAlliances) { this.brandAlliances = brandAlliances; } public ArrayList<BrandBranch> getBrandBranches() { return brandBranches; } public void setBrandBranches(ArrayList<BrandBranch> brandBranches) { this.brandBranches = brandBranches; } public ArrayList<SocialNetwork> getBrandSocialNetworks() { return brandSocialNetworks; } public void setBrandSocialNetworks(ArrayList<SocialNetwork> brandSocialNetworks) { this.brandSocialNetworks = brandSocialNetworks; } public boolean getLikedByCurrentUser() { return likedByCurrentUser; } public void setLikedByCurrentUser(boolean likedByCurrentUser) { this.likedByCurrentUser = likedByCurrentUser; } public ArrayList<Fan> getBrandFans() { return brandFans; } public void setBrandFans(ArrayList<Fan> brandFans) { this.brandFans = brandFans; } public boolean isHasLoyalty() { return hasLoyalty; } public void setHasLoyalty(boolean hasLoyalty) { this.hasLoyalty = hasLoyalty; } public Object clone() throws CloneNotSupportedException { return super.clone(); } public ArrayList<CustomerType> getBrandCustomerTypes() { return brandCustomerTypes; } public void setBrandCustomerTypes(ArrayList<CustomerType> brandCustomerTypes) { this.brandCustomerTypes = brandCustomerTypes; } public ArrayList<Coupon> getLoyaltyCoupons() { return loyaltyCoupons; } public void setLoyaltyCoupons(ArrayList<Coupon> loyaltyCoupons) { this.loyaltyCoupons = loyaltyCoupons; } public ArrayList<Coupon> getSpecialOfferCoupons() { return specialOfferCoupons; } public void setSpecialOfferCoupons(ArrayList<Coupon> specialOfferCoupons) { this.specialOfferCoupons = specialOfferCoupons; } public ArrayList<Comment> getBrandEvaluations() { return brandEvaluations; } public void setBrandEvaluations(ArrayList<Comment> brandEvaluations) { this.brandEvaluations = brandEvaluations; } public String getBrandDesc() { return brandDesc; } public void setBrandDesc(String brandDesc) { this.brandDesc = brandDesc; } public Comment getCurrentFanComment() { return currentFanComment; } public void setCurrentFanComment(Comment currentFanComment) { this.currentFanComment = currentFanComment; } }
UTF-8
Java
4,807
java
Brand.java
Java
[]
null
[]
package com.systemonline.fanscoupon.Model; import java.util.ArrayList; public class Brand implements Cloneable { private String brandName, brandDesc, brandSlug, brandImage, brandCover, brandRatingStarsCount = "null"; private int brandID, brandFansCount, brandCouponsCount; private ArrayList<Brand> brandAlliances; private ArrayList<BrandBranch> brandBranches; private ArrayList<SocialNetwork> brandSocialNetworks; private ArrayList<Fan> brandFans; private boolean likedByCurrentUser = false, hasLoyalty; private ArrayList<CustomerType> brandCustomerTypes; private ArrayList<Coupon> loyaltyCoupons, specialOfferCoupons; private ArrayList<Comment> brandEvaluations; private Comment currentFanComment; public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } public String getBrandSlug() { return brandSlug; } public void setBrandSlug(String brandSlug) { this.brandSlug = brandSlug; } public String getBrandImage() { return brandImage; } public void setBrandImage(String brandImage) { this.brandImage = brandImage; } public String getBrandCover() { return brandCover; } public void setBrandCover(String brandCover) { this.brandCover = brandCover; } public int getBrandCouponsCount() { return brandCouponsCount; } public void setBrandCouponsCount(int brandCouponsCount) { this.brandCouponsCount = brandCouponsCount; } public Integer getBrandID() { return brandID; } public void setBrandID(Integer brandID) { this.brandID = brandID; } public int getBrandFansCount() { return brandFansCount; } public void setBrandFansCount(int brandFansCount) { this.brandFansCount = brandFansCount; } public String getBrandRatingStarsCount() { return brandRatingStarsCount; } public void setBrandRatingStarsCount(String brandRatingStarsCount) { this.brandRatingStarsCount = brandRatingStarsCount; } public ArrayList<Brand> getBrandAlliances() { return brandAlliances; } public void setBrandAlliances(ArrayList<Brand> brandAlliances) { this.brandAlliances = brandAlliances; } public ArrayList<BrandBranch> getBrandBranches() { return brandBranches; } public void setBrandBranches(ArrayList<BrandBranch> brandBranches) { this.brandBranches = brandBranches; } public ArrayList<SocialNetwork> getBrandSocialNetworks() { return brandSocialNetworks; } public void setBrandSocialNetworks(ArrayList<SocialNetwork> brandSocialNetworks) { this.brandSocialNetworks = brandSocialNetworks; } public boolean getLikedByCurrentUser() { return likedByCurrentUser; } public void setLikedByCurrentUser(boolean likedByCurrentUser) { this.likedByCurrentUser = likedByCurrentUser; } public ArrayList<Fan> getBrandFans() { return brandFans; } public void setBrandFans(ArrayList<Fan> brandFans) { this.brandFans = brandFans; } public boolean isHasLoyalty() { return hasLoyalty; } public void setHasLoyalty(boolean hasLoyalty) { this.hasLoyalty = hasLoyalty; } public Object clone() throws CloneNotSupportedException { return super.clone(); } public ArrayList<CustomerType> getBrandCustomerTypes() { return brandCustomerTypes; } public void setBrandCustomerTypes(ArrayList<CustomerType> brandCustomerTypes) { this.brandCustomerTypes = brandCustomerTypes; } public ArrayList<Coupon> getLoyaltyCoupons() { return loyaltyCoupons; } public void setLoyaltyCoupons(ArrayList<Coupon> loyaltyCoupons) { this.loyaltyCoupons = loyaltyCoupons; } public ArrayList<Coupon> getSpecialOfferCoupons() { return specialOfferCoupons; } public void setSpecialOfferCoupons(ArrayList<Coupon> specialOfferCoupons) { this.specialOfferCoupons = specialOfferCoupons; } public ArrayList<Comment> getBrandEvaluations() { return brandEvaluations; } public void setBrandEvaluations(ArrayList<Comment> brandEvaluations) { this.brandEvaluations = brandEvaluations; } public String getBrandDesc() { return brandDesc; } public void setBrandDesc(String brandDesc) { this.brandDesc = brandDesc; } public Comment getCurrentFanComment() { return currentFanComment; } public void setCurrentFanComment(Comment currentFanComment) { this.currentFanComment = currentFanComment; } }
4,807
0.696692
0.696692
183
25.267759
24.594179
107
false
false
0
0
0
0
0
0
0.344262
false
false
3
cb30fd52c50ee2785d7739045287599dfd7b6af3
712,964,591,075
e184d31afaa7de3f1c942bb90fca11403f05426e
/Connexion/app/src/main/java/com/openclassrooms/connexion/client/photo/Photo.java
50e76e644e8e869b6967fb4974e1d62179153582
[]
no_license
imane-077/AppMob
https://github.com/imane-077/AppMob
658a40a926981327cbd6ef74e2be8b660ac58f08
c4ca9845f0a436bf9b465bd6231751d305a5e968
refs/heads/master
2023-03-29T15:47:55.593000
2021-03-21T23:23:37
2021-03-21T23:23:37
350,145,658
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.openclassrooms.connexion.client.photo; import android.content.ContentResolver; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.MimeTypeMap; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.OnProgressListener; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.StorageTask; import com.google.firebase.storage.UploadTask; import com.openclassrooms.connexion.Accueil; import com.openclassrooms.connexion.R; import com.openclassrooms.connexion.navigation; import static android.app.Activity.RESULT_OK; public class Photo extends Fragment { private static final int PICK_IMAGE_REQUEST = 1; Button BtnChoisirImage; Button Btntelecharger; TextView TextAccesPhoto; ImageView mImageView; ProgressBar mProgressBar; private Uri mImageUri; private StorageReference mStorageRef; private DatabaseReference mDatabaseRef; private StorageTask mUploadTask; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_photo, container, false); BtnChoisirImage = root.findViewById(R.id.btnChoisirImg); Btntelecharger = root.findViewById(R.id.btnTelecharger); TextAccesPhoto = root.findViewById(R.id.textAccesPhoto); mImageView = root.findViewById(R.id.img); mProgressBar = root.findViewById(R.id.progressBar); mStorageRef = FirebaseStorage.getInstance().getReference("Photo"); // mettre dans le dossier photo mDatabaseRef = FirebaseDatabase.getInstance().getReference("Photo"); BtnChoisirImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { choisirImage(); } }); Btntelecharger.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mUploadTask != null && mUploadTask.isInProgress()) { Toast.makeText(getActivity(), "En cours de téléchargement", Toast.LENGTH_SHORT).show(); } else { uploadFile(); } } }); TextAccesPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); return root; } // permet de choisir l'image private void choisirImage() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, PICK_IMAGE_REQUEST); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { mImageUri = data.getData(); mImageView.setImageURI(mImageUri); } } //enregistrer image choisit dans la base private String getFileExtension(Uri uri) { ContentResolver cR = getActivity().getContentResolver(); MimeTypeMap mime = MimeTypeMap.getSingleton(); return mime.getExtensionFromMimeType(cR.getType(uri)); } private void uploadFile() { if (mImageUri != null) { StorageReference fileReference = mStorageRef.child(System.currentTimeMillis() + "." + getFileExtension(mImageUri)); mUploadTask = fileReference.putFile(mImageUri) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { mProgressBar.setProgress(0); } }, 500); Toast.makeText(getActivity(), "Téléchargement réussi !", Toast.LENGTH_LONG).show(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show(); } }) .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { @Override public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount()); mProgressBar.setProgress((int) progress); } }); } else { Toast.makeText(getActivity(), "Aucune image ", Toast.LENGTH_SHORT).show(); } } }
UTF-8
Java
6,129
java
Photo.java
Java
[]
null
[]
package com.openclassrooms.connexion.client.photo; import android.content.ContentResolver; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.MimeTypeMap; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.OnProgressListener; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.StorageTask; import com.google.firebase.storage.UploadTask; import com.openclassrooms.connexion.Accueil; import com.openclassrooms.connexion.R; import com.openclassrooms.connexion.navigation; import static android.app.Activity.RESULT_OK; public class Photo extends Fragment { private static final int PICK_IMAGE_REQUEST = 1; Button BtnChoisirImage; Button Btntelecharger; TextView TextAccesPhoto; ImageView mImageView; ProgressBar mProgressBar; private Uri mImageUri; private StorageReference mStorageRef; private DatabaseReference mDatabaseRef; private StorageTask mUploadTask; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_photo, container, false); BtnChoisirImage = root.findViewById(R.id.btnChoisirImg); Btntelecharger = root.findViewById(R.id.btnTelecharger); TextAccesPhoto = root.findViewById(R.id.textAccesPhoto); mImageView = root.findViewById(R.id.img); mProgressBar = root.findViewById(R.id.progressBar); mStorageRef = FirebaseStorage.getInstance().getReference("Photo"); // mettre dans le dossier photo mDatabaseRef = FirebaseDatabase.getInstance().getReference("Photo"); BtnChoisirImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { choisirImage(); } }); Btntelecharger.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mUploadTask != null && mUploadTask.isInProgress()) { Toast.makeText(getActivity(), "En cours de téléchargement", Toast.LENGTH_SHORT).show(); } else { uploadFile(); } } }); TextAccesPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); return root; } // permet de choisir l'image private void choisirImage() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, PICK_IMAGE_REQUEST); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { mImageUri = data.getData(); mImageView.setImageURI(mImageUri); } } //enregistrer image choisit dans la base private String getFileExtension(Uri uri) { ContentResolver cR = getActivity().getContentResolver(); MimeTypeMap mime = MimeTypeMap.getSingleton(); return mime.getExtensionFromMimeType(cR.getType(uri)); } private void uploadFile() { if (mImageUri != null) { StorageReference fileReference = mStorageRef.child(System.currentTimeMillis() + "." + getFileExtension(mImageUri)); mUploadTask = fileReference.putFile(mImageUri) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { mProgressBar.setProgress(0); } }, 500); Toast.makeText(getActivity(), "Téléchargement réussi !", Toast.LENGTH_LONG).show(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show(); } }) .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { @Override public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount()); mProgressBar.setProgress((int) progress); } }); } else { Toast.makeText(getActivity(), "Aucune image ", Toast.LENGTH_SHORT).show(); } } }
6,129
0.60614
0.60467
153
38.039215
27.728582
126
false
false
0
0
0
0
0
0
0.607843
false
false
3
08cb57c7729e3c1392d07e5353d0048b9a665b21
13,572,096,716,973
f558f054f9e5866553631bf077d99aa351ea9819
/Dsup/src/main/java/com/dsup/chat/controller/RpController.java
05dd6e9b7607368c01c9f2842a9a54cc12c11001
[]
no_license
sh910312/Dsup
https://github.com/sh910312/Dsup
49f06b5ebd6e041f8c9b5769b18a9276cdd1eb5d
ec63ddc8bbd39557b249114663aab646dc86191c
refs/heads/master
2022-12-21T02:27:48.809000
2019-11-25T00:20:36
2019-11-25T00:20:36
215,730,622
0
1
null
false
2022-12-16T10:01:39
2019-10-17T07:32:38
2019-11-25T00:20:54
2022-12-16T10:01:35
16,076
0
0
4
JavaScript
false
false
package com.dsup.chat.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; 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 com.dsup.chat.ChatVO; import com.dsup.chat.ReVO; import com.dsup.chat.RpVO; import com.dsup.chat.SearchVO; import com.dsup.chat.service.ChatService; import com.dsup.chat.service.ReService; import com.dsup.chat.service.RpService; import com.dsup.chat.service.SearchService; import com.dsup.member.MemberVO; @Controller public class RpController { @Autowired RpService rpService; @Autowired ReService reService; @Autowired SearchService searchService; @Autowired ChatService chatService; // 신고 @RequestMapping("getRp") public String getRpsearch(HttpSession session,HttpServletRequest request, Model model, SearchVO svo, ReVO revo, RpVO rpvo, ChatVO cvo) { MemberVO member = (MemberVO) session.getAttribute("member"); rpvo.setUserId(member.getUserId()); // 0번 게시글 if (svo.getSearchId() != 0) { model.addAttribute("rpType", 0); model.addAttribute("search", searchService.getSearch(svo)); rpvo.setRpType(0); rpvo.setBoardNum(svo.getSearchId()); model.addAttribute("checkRp", rpService.checkRp(rpvo)); // 1번 댓글 }else if(revo.getReId() != 0) { model.addAttribute("rpType", 1); model.addAttribute("re",reService.getRe(revo)); rpvo.setRpType(1); rpvo.setBoardNum(revo.getReId()); model.addAttribute("checkRp", rpService.checkRp(rpvo)); System.out.println(revo); // 2번 채팅신고 }else if(cvo.getChatId() != 0) { model.addAttribute("rpType", 2); model.addAttribute("chat",chatService.getChat(cvo)); rpvo.setRpType(2); rpvo.setBoardNum(cvo.getChatId()); model.addAttribute("checkRp", rpService.checkRp(rpvo)); } return "chat/report/inRp"; } // 신고처리 @RequestMapping("/RpOk") public String insertSearch(RpVO vo, HttpServletRequest request, HttpSession session) { MemberVO member = (MemberVO) session.getAttribute("member"); vo.setUserId(member.getUserId()); rpService.inRp(vo); return "redirect:/SearchMap"; // 이쪽으로 이동 // redirech 안에는 requestmapping 내용을 넣는다 } }
UTF-8
Java
2,437
java
RpController.java
Java
[]
null
[]
package com.dsup.chat.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; 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 com.dsup.chat.ChatVO; import com.dsup.chat.ReVO; import com.dsup.chat.RpVO; import com.dsup.chat.SearchVO; import com.dsup.chat.service.ChatService; import com.dsup.chat.service.ReService; import com.dsup.chat.service.RpService; import com.dsup.chat.service.SearchService; import com.dsup.member.MemberVO; @Controller public class RpController { @Autowired RpService rpService; @Autowired ReService reService; @Autowired SearchService searchService; @Autowired ChatService chatService; // 신고 @RequestMapping("getRp") public String getRpsearch(HttpSession session,HttpServletRequest request, Model model, SearchVO svo, ReVO revo, RpVO rpvo, ChatVO cvo) { MemberVO member = (MemberVO) session.getAttribute("member"); rpvo.setUserId(member.getUserId()); // 0번 게시글 if (svo.getSearchId() != 0) { model.addAttribute("rpType", 0); model.addAttribute("search", searchService.getSearch(svo)); rpvo.setRpType(0); rpvo.setBoardNum(svo.getSearchId()); model.addAttribute("checkRp", rpService.checkRp(rpvo)); // 1번 댓글 }else if(revo.getReId() != 0) { model.addAttribute("rpType", 1); model.addAttribute("re",reService.getRe(revo)); rpvo.setRpType(1); rpvo.setBoardNum(revo.getReId()); model.addAttribute("checkRp", rpService.checkRp(rpvo)); System.out.println(revo); // 2번 채팅신고 }else if(cvo.getChatId() != 0) { model.addAttribute("rpType", 2); model.addAttribute("chat",chatService.getChat(cvo)); rpvo.setRpType(2); rpvo.setBoardNum(cvo.getChatId()); model.addAttribute("checkRp", rpService.checkRp(rpvo)); } return "chat/report/inRp"; } // 신고처리 @RequestMapping("/RpOk") public String insertSearch(RpVO vo, HttpServletRequest request, HttpSession session) { MemberVO member = (MemberVO) session.getAttribute("member"); vo.setUserId(member.getUserId()); rpService.inRp(vo); return "redirect:/SearchMap"; // 이쪽으로 이동 // redirech 안에는 requestmapping 내용을 넣는다 } }
2,437
0.720793
0.715732
79
28.037975
24.381172
137
false
false
0
0
0
0
0
0
2
false
false
3
c492772311d8027cae6fc33e61eb2a9b3fa75113
28,922,309,833,206
77bd398dd85c7a87ced915c2574b188127f4b830
/src/main/java/client/HttpClient.java
02b41660ebd05a749ec5a8e2d7b7dd0a4f469c8a
[]
no_license
wxkskynet/HowTomcatWorks
https://github.com/wxkskynet/HowTomcatWorks
b1118964f036828750cd0bf99ffebf3521ce3f1d
8fe54d71406fcf4262bfb2f15ccccb25be6a8b4e
refs/heads/master
2020-04-10T05:06:49.899000
2019-02-13T07:41:11
2019-02-13T07:41:11
160,817,927
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package client; import java.io.*; import java.net.InetSocketAddress; import java.net.Socket; /** * @author wxk */ public class HttpClient { private boolean trouble = false; public boolean postHttpRequestDemo(String address, int port, boolean autoFlush) { if (isWrongHost(address)) { return trouble; } Socket socket = null; OutputStream output = null; InputStream input; try { socket = new Socket(); socket.connect(new InetSocketAddress(address, port), 15000); output = socket.getOutputStream(); input = socket.getInputStream(); } catch (IOException e) { closeSocket(socket); closeStream(output); // no need to close input stream return true; } PrintWriter out = new PrintWriter(output, autoFlush); BufferedReader in = new BufferedReader(new InputStreamReader(input)); // send an HTTP request to the web server out.println("GET / HTTP/1.1"); out.println("Host: " + address + ":" + port); out.println("Connection: Close"); out.println(); // read the response boolean loop = true; StringBuffer sb = new StringBuffer(8192); while (loop) { try { if (in.ready()) { int i = 0; while (i != -1) { i = in.read(); sb.append((char) i); } loop = false; } Thread.sleep(50); } catch (Exception e) { e.printStackTrace(); closeSocket(socket); closeStream(in); closeStream(out); return true; } } /// keep console clean // display the response to the out console // System.out.println(sb.toString()); closeSocket(socket); closeStream(in); closeStream(out); return trouble; } private void closeSocket(Socket socket) { if (socket == null) { return; } try { socket.close(); } catch (IOException ie) { trouble = true; } } private void closeStream(Closeable closeable) { if (closeable == null) { return; } try { closeable.close(); } catch (IOException e) { trouble = true; } } private boolean isWrongHost(String address) { if (address == null || address.isEmpty()) { trouble = true; return true; } else { return false; } } }
UTF-8
Java
2,780
java
HttpClient.java
Java
[ { "context": "etAddress;\nimport java.net.Socket;\n\n/**\n * @author wxk\n */\npublic class HttpClient {\n private boolean", "end": 113, "score": 0.999610424041748, "start": 110, "tag": "USERNAME", "value": "wxk" } ]
null
[]
package client; import java.io.*; import java.net.InetSocketAddress; import java.net.Socket; /** * @author wxk */ public class HttpClient { private boolean trouble = false; public boolean postHttpRequestDemo(String address, int port, boolean autoFlush) { if (isWrongHost(address)) { return trouble; } Socket socket = null; OutputStream output = null; InputStream input; try { socket = new Socket(); socket.connect(new InetSocketAddress(address, port), 15000); output = socket.getOutputStream(); input = socket.getInputStream(); } catch (IOException e) { closeSocket(socket); closeStream(output); // no need to close input stream return true; } PrintWriter out = new PrintWriter(output, autoFlush); BufferedReader in = new BufferedReader(new InputStreamReader(input)); // send an HTTP request to the web server out.println("GET / HTTP/1.1"); out.println("Host: " + address + ":" + port); out.println("Connection: Close"); out.println(); // read the response boolean loop = true; StringBuffer sb = new StringBuffer(8192); while (loop) { try { if (in.ready()) { int i = 0; while (i != -1) { i = in.read(); sb.append((char) i); } loop = false; } Thread.sleep(50); } catch (Exception e) { e.printStackTrace(); closeSocket(socket); closeStream(in); closeStream(out); return true; } } /// keep console clean // display the response to the out console // System.out.println(sb.toString()); closeSocket(socket); closeStream(in); closeStream(out); return trouble; } private void closeSocket(Socket socket) { if (socket == null) { return; } try { socket.close(); } catch (IOException ie) { trouble = true; } } private void closeStream(Closeable closeable) { if (closeable == null) { return; } try { closeable.close(); } catch (IOException e) { trouble = true; } } private boolean isWrongHost(String address) { if (address == null || address.isEmpty()) { trouble = true; return true; } else { return false; } } }
2,780
0.488129
0.482734
106
25.226416
17.779722
85
false
false
0
0
0
0
0
0
0.518868
false
false
3
d2b885b503256bfbca364b641cfe11200f76b4be
10,995,116,323,891
07fd062ce48a98e9bfbc02c61076c25451a0950e
/test/TestReadXML/src/ReadXML.java
70cd4a81fe435f54d0d55bde433cde596faf7ec5
[]
no_license
codywsy/MyJavaTestingCode
https://github.com/codywsy/MyJavaTestingCode
5336d00e38b10ad8941d9c7bdcccb77f64721ca6
30a01eb3790241da528de9ff6b07f220dd4a28ca
refs/heads/master
2021-01-22T10:51:37.006000
2017-09-30T11:36:17
2017-09-30T11:36:17
92,659,660
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class ReadXML { public static void main(String[] args) { try { //DOM DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new File("languages.xml")); Element root = document.getDocumentElement(); NodeList list = root.getElementsByTagName("lan"); for(int i=0; i<list.getLength(); i++){ Element lan = (Element) list.item(i); System.out.println("---------------"); System.out.println("id=" + lan.getAttribute("id")); NodeList clist = lan.getChildNodes(); for(int j=0; j<clist.hashCode(); j++){ Node c = clist.item(j); if(c instanceof Element){ System.out.println(c.getNodeName() + "=" + c.getTextContent()); } } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
UTF-8
Java
1,310
java
ReadXML.java
Java
[]
null
[]
import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class ReadXML { public static void main(String[] args) { try { //DOM DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new File("languages.xml")); Element root = document.getDocumentElement(); NodeList list = root.getElementsByTagName("lan"); for(int i=0; i<list.getLength(); i++){ Element lan = (Element) list.item(i); System.out.println("---------------"); System.out.println("id=" + lan.getAttribute("id")); NodeList clist = lan.getChildNodes(); for(int j=0; j<clist.hashCode(); j++){ Node c = clist.item(j); if(c instanceof Element){ System.out.println(c.getNodeName() + "=" + c.getTextContent()); } } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
1,310
0.683969
0.679389
46
27.47826
20.033384
69
false
false
0
0
0
0
0
0
2.565217
false
false
3
defb49a090554b38e511b2eace5edc6d774babc5
10,187,662,463,250
61a2b02d866232d92d0fd76becac48e9f3cc6f60
/Spring/src/main/java/com/dollarkiller/ioc/demo5/SpringDemo5.java
f89bc0e3e564de5132ad5fe718df39473e69e15c
[]
no_license
dollarkillerx/SpringStudy
https://github.com/dollarkillerx/SpringStudy
4b521d2132ec3c3c91971bdb8f09d8f7994654e0
71bfcc077c80907d73f1536688c32374abaf3e84
refs/heads/master
2020-05-16T11:35:22.978000
2019-05-20T14:31:01
2019-05-20T14:31:01
183,019,499
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dollarkiller.ioc.demo5; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created with IntelliJ IDEA. * User: dollarkiller * Date: 19-5-1 * Time: 下午4:07 * Description: No Description */ public class SpringDemo5 { @Test public void demo1() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); CollectionBean collectionBean = (CollectionBean) applicationContext.getBean("collectionBean"); System.out.println(collectionBean); } }
UTF-8
Java
647
java
SpringDemo5.java
Java
[ { "context": "text;\n\n/**\n * Created with IntelliJ IDEA.\n * User: dollarkiller\n * Date: 19-5-1\n * Time: 下午4:07\n * Description: N", "end": 247, "score": 0.9996758699417114, "start": 235, "tag": "USERNAME", "value": "dollarkiller" } ]
null
[]
package com.dollarkiller.ioc.demo5; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created with IntelliJ IDEA. * User: dollarkiller * Date: 19-5-1 * Time: 下午4:07 * Description: No Description */ public class SpringDemo5 { @Test public void demo1() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); CollectionBean collectionBean = (CollectionBean) applicationContext.getBean("collectionBean"); System.out.println(collectionBean); } }
647
0.757387
0.741835
21
29.619047
30.805807
109
false
false
0
0
0
0
0
0
0.333333
false
false
3
b6b57a7a26cb97cb86004b482b4e4a546c062202
32,676,111,223,635
c7e63b658840a7e243d85c93c2d79bfe45a33570
/spring-birt-integration-example/src/main/java/org/eclipse/birt/spring/example/MasterActionHandler.java
d7d803710fe1c2c6f130aee125e678c3a57716a1
[]
no_license
joshlong/spring-birt
https://github.com/joshlong/spring-birt
1a158aeb880212511d84485372f2f3f4b52b87b3
10bb8af7ab1bd8481c30e66ff5715ec5c03a22a0
refs/heads/master
2016-09-05T20:04:49.516000
2012-07-09T00:45:36
2012-07-09T00:45:36
4,813,718
18
15
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.eclipse.birt.spring.example; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; import java.util.Map; import org.eclipse.birt.report.engine.api.IAction; import org.eclipse.birt.report.engine.api.script.IReportContext; import org.eclipse.birt.spring.core.SimpleRequestParameterActionHandler; public class MasterActionHandler extends SimpleRequestParameterActionHandler { public MasterActionHandler(String reportNameKey, String formatKey) { super(reportNameKey, formatKey); } public MasterActionHandler() { super(null, null); } @Override public String getURL(IAction actionDefn, IReportContext context) { if( actionDefn.getType() == IAction.ACTION_DRILLTHROUGH ){ //"/orders/{orderId}.html" StringBuilder link = new StringBuilder(); String baseURL = null; if (context != null) { baseURL = context.getRenderOption().getBaseURL(); } if (baseURL == null) { baseURL = ""; } link.append( baseURL ); link.append("/orders/"); Object ordern = actionDefn.getParameterBindings().get("order"); if (ordern != null) { Object[] values; if (ordern instanceof List) { ordern = ((List) ordern).toArray(); values = (Object[]) ordern; } else { values = new Object[1]; values[0] = ordern; } if( values[0] != null )link.append( values[0]); link.append(".html"); } return link.toString(); }else{ return super.getURL(actionDefn, context); } } }
UTF-8
Java
1,505
java
MasterActionHandler.java
Java
[]
null
[]
package org.eclipse.birt.spring.example; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; import java.util.Map; import org.eclipse.birt.report.engine.api.IAction; import org.eclipse.birt.report.engine.api.script.IReportContext; import org.eclipse.birt.spring.core.SimpleRequestParameterActionHandler; public class MasterActionHandler extends SimpleRequestParameterActionHandler { public MasterActionHandler(String reportNameKey, String formatKey) { super(reportNameKey, formatKey); } public MasterActionHandler() { super(null, null); } @Override public String getURL(IAction actionDefn, IReportContext context) { if( actionDefn.getType() == IAction.ACTION_DRILLTHROUGH ){ //"/orders/{orderId}.html" StringBuilder link = new StringBuilder(); String baseURL = null; if (context != null) { baseURL = context.getRenderOption().getBaseURL(); } if (baseURL == null) { baseURL = ""; } link.append( baseURL ); link.append("/orders/"); Object ordern = actionDefn.getParameterBindings().get("order"); if (ordern != null) { Object[] values; if (ordern instanceof List) { ordern = ((List) ordern).toArray(); values = (Object[]) ordern; } else { values = new Object[1]; values[0] = ordern; } if( values[0] != null )link.append( values[0]); link.append(".html"); } return link.toString(); }else{ return super.getURL(actionDefn, context); } } }
1,505
0.69103
0.688372
62
23.274193
22.289278
78
false
false
0
0
0
0
0
0
2.33871
false
false
3
456e068118af5178ce02376e0a9aa21b965ac93f
16,595,753,650,781
6f559e2550161a04758513044dc776073d1bf987
/src/TestMethod.java
d722d9474ca9bed15722c5c12b30ace8dd138fd4
[]
no_license
Lattjolajban/Uppgift-3-test
https://github.com/Lattjolajban/Uppgift-3-test
7155808691f535c1aa69f146253d1b7d01d419e3
4762445c85b6f6fe0667bfbb6c29e228c1d5d808
refs/heads/master
2021-05-15T06:25:59.757000
2017-12-20T10:23:15
2017-12-20T10:23:15
114,790,002
0
0
null
false
2018-01-12T09:49:01
2017-12-19T16:55:42
2017-12-19T17:10:58
2018-01-11T14:05:51
95
0
0
2
Java
false
null
public class TestMethod { public static void main(String[] args) { ProductRegister pReg = new ProductRegister(); CustomerRegister cReg = new CustomerRegister(); Product p1 = new Product(); OrderLine line1 = new OrderLine(); OrderLine line2 = new OrderLine(); Order order1 = new Order(); Customer customer1 = new Customer(); p1.setName("Pågatåg"); p1.setPrice(2000); p1.setCategory("Tåg"); Product p2 = new Product(); p2.setName("Pågatåg vagn"); p2.setPrice(500); p2.setCategory("Vagnar"); Unit exp1 = new Unit(); exp1.setSerialNumber("1"); exp1.setProduct(p1); p1.addUnit(exp1); Unit exp2 = new Unit(); exp2.setSerialNumber("2"); exp2.setProduct(p1); p1.addUnit(exp2); Unit exp3 = new Unit(); exp3.setSerialNumber("3"); exp3.setProduct(p2); p2.addUnit(exp3); Unit exp4 = new Unit(); exp3.setSerialNumber("4"); exp3.setProduct(p2); p2.addUnit(exp4); pReg.addProduct(p1); pReg.addProduct(p2); line1.setNumber("1"); line1.setProduct(p1); line1.setQuantity(2); line1.setOrder(order1); line2.setNumber("2"); line2.setProduct(p2); line2.setQuantity(2); line2.setOrder(order1); order1.setOrderID("order1"); order1.setDeliveryDate("Röv"); order1.addOrderLine(line1); order1.addOrderLine(line2); order1.setCustomerOrder(customer1); customer1.setName("Olof"); customer1.setCustomerNumber("1"); customer1.setAddress("Universitetsgatan 2"); customer1.addOrder(order1); cReg.addCustomer(customer1); System.out.println(customer1.summeraOrder("order1")); line1.PlusOnequantity(3); System.out.println ("Hello World!"); } }
ISO-8859-1
Java
1,643
java
TestMethod.java
Java
[ { "context": "stomer customer1 = new Customer();\n\n\t\tp1.setName(\"Pågatåg\");\n\t\tp1.setPrice(2000);\n\t\tp1.setCategory(\"Tåg\");\n", "end": 364, "score": 0.9998680353164673, "start": 357, "tag": "NAME", "value": "Pågatåg" }, { "context": "g\");\n\n\t\tProduct p2 = new Product();\n\t\tp2.setName(\"Pågatåg vagn\");\n\t\tp2.setPrice(500);\n\t\tp2.setCategory(\"Vagnar\")", "end": 471, "score": 0.9998571276664734, "start": 459, "tag": "NAME", "value": "Pågatåg vagn" } ]
null
[]
public class TestMethod { public static void main(String[] args) { ProductRegister pReg = new ProductRegister(); CustomerRegister cReg = new CustomerRegister(); Product p1 = new Product(); OrderLine line1 = new OrderLine(); OrderLine line2 = new OrderLine(); Order order1 = new Order(); Customer customer1 = new Customer(); p1.setName("Pågatåg"); p1.setPrice(2000); p1.setCategory("Tåg"); Product p2 = new Product(); p2.setName("<NAME>"); p2.setPrice(500); p2.setCategory("Vagnar"); Unit exp1 = new Unit(); exp1.setSerialNumber("1"); exp1.setProduct(p1); p1.addUnit(exp1); Unit exp2 = new Unit(); exp2.setSerialNumber("2"); exp2.setProduct(p1); p1.addUnit(exp2); Unit exp3 = new Unit(); exp3.setSerialNumber("3"); exp3.setProduct(p2); p2.addUnit(exp3); Unit exp4 = new Unit(); exp3.setSerialNumber("4"); exp3.setProduct(p2); p2.addUnit(exp4); pReg.addProduct(p1); pReg.addProduct(p2); line1.setNumber("1"); line1.setProduct(p1); line1.setQuantity(2); line1.setOrder(order1); line2.setNumber("2"); line2.setProduct(p2); line2.setQuantity(2); line2.setOrder(order1); order1.setOrderID("order1"); order1.setDeliveryDate("Röv"); order1.addOrderLine(line1); order1.addOrderLine(line2); order1.setCustomerOrder(customer1); customer1.setName("Olof"); customer1.setCustomerNumber("1"); customer1.setAddress("Universitetsgatan 2"); customer1.addOrder(order1); cReg.addCustomer(customer1); System.out.println(customer1.summeraOrder("order1")); line1.PlusOnequantity(3); System.out.println ("Hello World!"); } }
1,635
0.690287
0.637752
74
21.135136
13.933553
55
false
false
0
0
0
0
0
0
2.256757
false
false
3
ce5a9ef53c4c7ce2ab517f4a92e95f00894ea034
10,428,180,611,232
c8b7b6dfa76ca52a89b84c09aa9c471d45bfecde
/src/test/java/com/example/gradle_example/MessageServiceTest.java
27125b1da3826cdbe01bc3064496ae4553beaa68
[]
no_license
HuntMark/my-gradle-example
https://github.com/HuntMark/my-gradle-example
cf8ea616e6db3538a766451eeb7e7092d4efc1c6
b4547a3bfec603eaaed277c3945f2243b9bde3e9
refs/heads/master
2019-01-21T17:53:09.833000
2017-03-18T11:42:01
2017-03-18T11:42:01
85,208,537
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.gradle_example; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * @author Rinat Zalyaletdinov. */ public class MessageServiceTest { private MessageService service; @Before public void setUp() { service = new MessageService(); } @Test public void getMessage() throws Exception { assertEquals(MessageService.MESSAGE, service.getMessage()); } }
UTF-8
Java
450
java
MessageServiceTest.java
Java
[ { "context": "\nimport static org.junit.Assert.*;\n\n/**\n * @author Rinat Zalyaletdinov.\n */\npublic class MessageServiceTest {\n privat", "end": 155, "score": 0.9998632073402405, "start": 136, "tag": "NAME", "value": "Rinat Zalyaletdinov" } ]
null
[]
package com.example.gradle_example; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * @author <NAME>. */ public class MessageServiceTest { private MessageService service; @Before public void setUp() { service = new MessageService(); } @Test public void getMessage() throws Exception { assertEquals(MessageService.MESSAGE, service.getMessage()); } }
437
0.686667
0.686667
23
18.608696
18.414879
67
false
false
0
0
0
0
0
0
0.347826
false
false
3
c76181a2eecf2842a8a9aa8850f06c5ce01957c7
8,366,596,297,244
1a2daf068134c5e04c6d180a8bf678a76d579b70
/com/ifmo/jjd/lesson9/App.java
615e732dc608c9947ddee4708005f53edece6804
[]
no_license
Shipiguzov/Java
https://github.com/Shipiguzov/Java
9b1b5810ba286cc8d4881d088bf9145cc2173046
aebca9a761c6e5eb4f23f22e708e41f15219661b
refs/heads/master
2023-01-30T05:05:15.886000
2020-12-18T08:20:08
2020-12-18T08:20:08
300,535,026
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ifmo.jjd.lesson9; import java.util.Objects; public class App { public static void main(String[] args) { Author ivan = new Author("Иван", "Петров"); Author anna = new Author("Анна", "Гришкова"); ColouringBook cars = new ColouringBook("Машинки", 23, 15); cars.setAuthor(ivan); ColouringBook robots = new ColouringBook("Роботы", 38, 19); robots.setAuthor(ivan); ColouringBook flowers = new ColouringBook("Цветы", 12, 10); flowers.setAuthor(anna); //Все классы наследуются от класса Object Object obj = new Object(); Object author = new Author("Иван", "Петров"); //toString() System.out.println(flowers.toString()); //equals() и hashCode() исользуются для сравнения объектов Author author1 = new Author("Михаил", "Петров"); Author author2 = new Author("Михаил", "Петров"); // == сравнивает ссылки на объект и вернёт true, если System.out.println(author1 == author2); //false //метод equals() используется для сравнения объектов //equals() по умолчанию сравнивает ссылки на объект System.out.println(author1.equals(author2)); //true //instanceof проверяет принадлежность объекта к указанному типу //equals() //1. объект всегда равен самому себе (рефлективность) //2. если a.equals(b), то и b.equals(a) (симметричность) //3. если a.equals(b), и b.equals(c), то и a.equals(c) (транзитивность) //4. сколько бы раз не вызывался equals без изменения состояния объекта, результат должен оставаться неизменным (консистентноть) //hashCode() //hashCode - не адрес в памяти //1. если объекты равны по equals, то hashCode должен вернуть одинаковое значание для обоих объектов //2. если объекты не равны по equals, то hashCode может верныть одинаковое значение для обоих объектов //3. если состояние объекта не именяется, то hashCode должен возвращать одинаковый результат System.out.println(author1.hashCode()); System.out.println(author2.hashCode()); ColouringBook colouring1 = new ColouringBook("Роботы", 38, 19); colouring1.setAuthor(ivan); ColouringBook colouring2 = new ColouringBook("Роботы", 38, 19); colouring2.setAuthor(ivan); System.out.println(colouring1.equals(colouring2));//false //Objects.hash(picCount) - вернет hashCode объекта //clone() //модификатор доступа - protected //возвращает Object //super.clone() - не создаёт копии объектов //super.clone() обязывет метод выбрасывать CloneNotSupportedException, но нужно будет написать свою реализацию //(создание нового объекта) ColouringBook cloneColouting = colouring1; ivan = new Author("Иван", "Петров"); //Author copyIvan = ivan.clone(); ColouringBook cloneColouring = colouring1.clone(); System.out.println(cloneColouring == colouring1); //класс Objects - набор статических методов для работы с объектами //Objects.requireNonNull(null, "Is NULL"); //Objects.requireNonNull(null); } }
UTF-8
Java
4,101
java
App.java
Java
[ { "context": "tring[] args) {\n Author ivan = new Author(\"Иван\", \"Петров\");\n Author anna = new Author(\"Ан", "end": 160, "score": 0.9998697638511658, "start": 156, "tag": "NAME", "value": "Иван" }, { "context": "args) {\n Author ivan = new Author(\"Иван\", \"Петров\");\n Author anna = new Author(\"Анна\", \"Гриш", "end": 170, "score": 0.9997842311859131, "start": 164, "tag": "NAME", "value": "Петров" }, { "context": "ан\", \"Петров\");\n Author anna = new Author(\"Анна\", \"Гришкова\");\n\n ColouringBook cars = new ", "end": 212, "score": 0.9998645782470703, "start": 208, "tag": "NAME", "value": "Анна" }, { "context": "тров\");\n Author anna = new Author(\"Анна\", \"Гришкова\");\n\n ColouringBook cars = new ColouringBoo", "end": 224, "score": 0.9998599886894226, "start": 216, "tag": "NAME", "value": "Гришкова" }, { "context": "new Object();\n Object author = new Author(\"Иван\", \"Петров\");\n\n //toString()\n System", "end": 655, "score": 0.9998685717582703, "start": 651, "tag": "NAME", "value": "Иван" }, { "context": "ct();\n Object author = new Author(\"Иван\", \"Петров\");\n\n //toString()\n System.out.print", "end": 665, "score": 0.9997577667236328, "start": 659, "tag": "NAME", "value": "Петров" }, { "context": "ия объектов\n\n Author author1 = new Author(\"Михаил\", \"Петров\");\n Author author2 = new Author(", "end": 851, "score": 0.9998756051063538, "start": 845, "tag": "NAME", "value": "Михаил" }, { "context": "в\n\n Author author1 = new Author(\"Михаил\", \"Петров\");\n Author author2 = new Author(\"Михаил\", ", "end": 861, "score": 0.9997646808624268, "start": 855, "tag": "NAME", "value": "Петров" }, { "context": ", \"Петров\");\n Author author2 = new Author(\"Михаил\", \"Петров\");\n // == сравнивает ссылки на о", "end": 908, "score": 0.9998708367347717, "start": 902, "tag": "NAME", "value": "Михаил" }, { "context": ");\n Author author2 = new Author(\"Михаил\", \"Петров\");\n // == сравнивает ссылки на объект и ве", "end": 918, "score": 0.9997416138648987, "start": 912, "tag": "NAME", "value": "Петров" }, { "context": "k(\"Роботы\", 38, 19);\n colouring1.setAuthor(ivan);\n\n ColouringBook colouring2 = new Colouri", "end": 2240, "score": 0.5418165922164917, "start": 2236, "tag": "NAME", "value": "ivan" }, { "context": "olouting = colouring1;\n ivan = new Author(\"Иван\", \"Петров\");\n //Author copyIvan = ivan.clo", "end": 2856, "score": 0.9998598098754883, "start": 2852, "tag": "NAME", "value": "Иван" }, { "context": " = colouring1;\n ivan = new Author(\"Иван\", \"Петров\");\n //Author copyIvan = ivan.clone();\n ", "end": 2866, "score": 0.999851405620575, "start": 2860, "tag": "NAME", "value": "Петров" } ]
null
[]
package com.ifmo.jjd.lesson9; import java.util.Objects; public class App { public static void main(String[] args) { Author ivan = new Author("Иван", "Петров"); Author anna = new Author("Анна", "Гришкова"); ColouringBook cars = new ColouringBook("Машинки", 23, 15); cars.setAuthor(ivan); ColouringBook robots = new ColouringBook("Роботы", 38, 19); robots.setAuthor(ivan); ColouringBook flowers = new ColouringBook("Цветы", 12, 10); flowers.setAuthor(anna); //Все классы наследуются от класса Object Object obj = new Object(); Object author = new Author("Иван", "Петров"); //toString() System.out.println(flowers.toString()); //equals() и hashCode() исользуются для сравнения объектов Author author1 = new Author("Михаил", "Петров"); Author author2 = new Author("Михаил", "Петров"); // == сравнивает ссылки на объект и вернёт true, если System.out.println(author1 == author2); //false //метод equals() используется для сравнения объектов //equals() по умолчанию сравнивает ссылки на объект System.out.println(author1.equals(author2)); //true //instanceof проверяет принадлежность объекта к указанному типу //equals() //1. объект всегда равен самому себе (рефлективность) //2. если a.equals(b), то и b.equals(a) (симметричность) //3. если a.equals(b), и b.equals(c), то и a.equals(c) (транзитивность) //4. сколько бы раз не вызывался equals без изменения состояния объекта, результат должен оставаться неизменным (консистентноть) //hashCode() //hashCode - не адрес в памяти //1. если объекты равны по equals, то hashCode должен вернуть одинаковое значание для обоих объектов //2. если объекты не равны по equals, то hashCode может верныть одинаковое значение для обоих объектов //3. если состояние объекта не именяется, то hashCode должен возвращать одинаковый результат System.out.println(author1.hashCode()); System.out.println(author2.hashCode()); ColouringBook colouring1 = new ColouringBook("Роботы", 38, 19); colouring1.setAuthor(ivan); ColouringBook colouring2 = new ColouringBook("Роботы", 38, 19); colouring2.setAuthor(ivan); System.out.println(colouring1.equals(colouring2));//false //Objects.hash(picCount) - вернет hashCode объекта //clone() //модификатор доступа - protected //возвращает Object //super.clone() - не создаёт копии объектов //super.clone() обязывет метод выбрасывать CloneNotSupportedException, но нужно будет написать свою реализацию //(создание нового объекта) ColouringBook cloneColouting = colouring1; ivan = new Author("Иван", "Петров"); //Author copyIvan = ivan.clone(); ColouringBook cloneColouring = colouring1.clone(); System.out.println(cloneColouring == colouring1); //класс Objects - набор статических методов для работы с объектами //Objects.requireNonNull(null, "Is NULL"); //Objects.requireNonNull(null); } }
4,101
0.656572
0.642523
75
41.720001
31.07692
136
false
false
0
0
0
0
0
0
0.76
false
false
3
d61934ab0aaf3627eb8037bbb3a01df2d080b2ea
14,173,392,142,138
a74f99c8e3d22544e3c73783bad02805cd94bd40
/library/src/main/java/support/im/leanclound/SupportClientEventHandler.java
53600a830c1972d258994f2f09443a53077e99fc
[]
no_license
qijitech/support-im
https://github.com/qijitech/support-im
a82e1dfa87f84dee8773ac03a7de8ce1d396392e
0baa66efc964291963077dc884cc2809f48776c8
refs/heads/master
2021-01-21T13:30:19.444000
2016-05-19T12:38:40
2016-05-19T12:38:40
55,222,776
16
2
null
false
2016-04-21T13:43:10
2016-04-01T10:04:51
2016-04-07T08:45:46
2016-04-21T13:43:10
8,402
2
0
0
Java
null
null
package support.im.leanclound; import com.avos.avoscloud.im.v2.AVIMClient; import com.avos.avoscloud.im.v2.AVIMClientEventHandler; import de.greenrobot.event.EventBus; import support.im.leanclound.event.ConnectionChangeEvent; public class SupportClientEventHandler extends AVIMClientEventHandler { private static SupportClientEventHandler eventHandler; public static synchronized SupportClientEventHandler getInstance() { if (null == eventHandler) { eventHandler = new SupportClientEventHandler(); } return eventHandler; } private SupportClientEventHandler() { } private volatile boolean connect = false; /** * 是否连上聊天服务 */ public boolean isConnect() { return connect; } public void setConnectAndNotify(boolean isConnect) { connect = isConnect; EventBus.getDefault().post(new ConnectionChangeEvent(connect)); } @Override public void onConnectionPaused(AVIMClient avimClient) { setConnectAndNotify(false); } @Override public void onConnectionResume(AVIMClient avimClient) { setConnectAndNotify(true); } @Override public void onClientOffline(AVIMClient avimClient, int i) { } }
UTF-8
Java
1,181
java
SupportClientEventHandler.java
Java
[]
null
[]
package support.im.leanclound; import com.avos.avoscloud.im.v2.AVIMClient; import com.avos.avoscloud.im.v2.AVIMClientEventHandler; import de.greenrobot.event.EventBus; import support.im.leanclound.event.ConnectionChangeEvent; public class SupportClientEventHandler extends AVIMClientEventHandler { private static SupportClientEventHandler eventHandler; public static synchronized SupportClientEventHandler getInstance() { if (null == eventHandler) { eventHandler = new SupportClientEventHandler(); } return eventHandler; } private SupportClientEventHandler() { } private volatile boolean connect = false; /** * 是否连上聊天服务 */ public boolean isConnect() { return connect; } public void setConnectAndNotify(boolean isConnect) { connect = isConnect; EventBus.getDefault().post(new ConnectionChangeEvent(connect)); } @Override public void onConnectionPaused(AVIMClient avimClient) { setConnectAndNotify(false); } @Override public void onConnectionResume(AVIMClient avimClient) { setConnectAndNotify(true); } @Override public void onClientOffline(AVIMClient avimClient, int i) { } }
1,181
0.757082
0.755365
47
23.787233
25.242598
71
false
false
0
0
0
0
0
0
0.319149
false
false
3
3c91df2b494f6e5cb671e62bc792f37d4cd5be69
15,504,831,991,742
cb281aabbbea27a6d8338a5a3aa0a55d7af6ce0b
/ContactApplication/src/main/java/org/full/controller/Login.java
960d2a85fd20022d5013699501d7679ae9ed94a3
[]
no_license
Praveen-Surya/FullCreative1
https://github.com/Praveen-Surya/FullCreative1
6a4d5555f8bd26a90dbeb35b6bde73b344c34626
3e17d722431b400f12d03610350c2a9dcf05194c
refs/heads/main
2023-01-06T19:50:33.853000
2020-10-31T11:19:39
2020-10-31T11:19:39
300,611,101
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.full.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; @Controller public class Login { ModelAndView mv = new ModelAndView(); @RequestMapping(value = "/Login", method = RequestMethod.POST) public ModelAndView add(HttpServletRequest request, HttpServletResponse response) { String userName = request.getParameter("UserName"); String password = request.getParameter("Password"); DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Query q = new Query("User"); PreparedQuery pq = ds.prepare(q); for (Entity u1 : pq.asIterable()) { if (userName.equals(u1.getProperty("UserName").toString()) && password.equals(u1.getProperty("Password").toString())) { HttpSession session = request.getSession(); session.setMaxInactiveInterval(1800); session.setAttribute("User1", u1.getProperty("UserId").toString()); mv.setViewName("Home"); return mv; } } mv.setViewName("Error"); return mv; } }
UTF-8
Java
1,675
java
Login.java
Java
[ { "context": "nse) {\n\n\t\tString userName = request.getParameter(\"UserName\");\n\t\tString password = request.getParameter(\"Pass", "end": 1050, "score": 0.8312057852745056, "start": 1042, "tag": "USERNAME", "value": "UserName" }, { "context": "able()) {\n\n\t\t\tif (userName.equals(u1.getProperty(\"UserName\").toString())\n\t\t\t\t\t&& password.equals(u1.getPrope", "end": 1334, "score": 0.7242154479026794, "start": 1326, "tag": "USERNAME", "value": "UserName" } ]
null
[]
package org.full.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; @Controller public class Login { ModelAndView mv = new ModelAndView(); @RequestMapping(value = "/Login", method = RequestMethod.POST) public ModelAndView add(HttpServletRequest request, HttpServletResponse response) { String userName = request.getParameter("UserName"); String password = request.getParameter("Password"); DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Query q = new Query("User"); PreparedQuery pq = ds.prepare(q); for (Entity u1 : pq.asIterable()) { if (userName.equals(u1.getProperty("UserName").toString()) && password.equals(u1.getProperty("Password").toString())) { HttpSession session = request.getSession(); session.setMaxInactiveInterval(1800); session.setAttribute("User1", u1.getProperty("UserId").toString()); mv.setViewName("Home"); return mv; } } mv.setViewName("Error"); return mv; } }
1,675
0.779701
0.774328
49
33.183674
25.28989
84
false
false
0
0
0
0
0
0
1.714286
false
false
3
02f52d23be30f761bc55186a9c69a866ae048b09
14,534,169,399,934
f4b958644697e3690de91c52a7c09f9735735c81
/AutoDealer/src/Vehicle.java
6d425fc9d8d7a8410fdd086c2ee2c78d7faa302b
[ "MIT" ]
permissive
bill-neely/COSC1336-06-Fall2017
https://github.com/bill-neely/COSC1336-06-Fall2017
6e8bc97e49fbc502f5a09c030db4b5d92e2248ed
b45222b942e63d7111d7545c679a90bcabb9aa23
refs/heads/master
2021-08-30T18:02:23.223000
2017-12-18T23:03:42
2017-12-18T23:03:42
104,070,006
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Vehicle { private String make; private String model; private int doors; private float price; private int quantity; public Vehicle(String make, String model, int doors, float price, int quantity) { this.make = make; this.model = model; this.doors = doors; this.price = price; this.quantity = quantity; } public String make() { return this.make; } public String model() { return this.model; } public int doors() { return this.doors; } public float price() { return this.price; } public int quantity() { return this.quantity; } public Vehicle clone(int quantity) { return new Vehicle(this.make, this.model, this.doors, this.price, quantity); } public boolean removeQty(int quantityToRemove) { if (this.quantity >= quantityToRemove) { this.quantity -= quantityToRemove; return true; } return false; } }
UTF-8
Java
878
java
Vehicle.java
Java
[]
null
[]
public class Vehicle { private String make; private String model; private int doors; private float price; private int quantity; public Vehicle(String make, String model, int doors, float price, int quantity) { this.make = make; this.model = model; this.doors = doors; this.price = price; this.quantity = quantity; } public String make() { return this.make; } public String model() { return this.model; } public int doors() { return this.doors; } public float price() { return this.price; } public int quantity() { return this.quantity; } public Vehicle clone(int quantity) { return new Vehicle(this.make, this.model, this.doors, this.price, quantity); } public boolean removeQty(int quantityToRemove) { if (this.quantity >= quantityToRemove) { this.quantity -= quantityToRemove; return true; } return false; } }
878
0.689066
0.689066
49
16.897959
18.104284
82
false
false
0
0
0
0
0
0
1.673469
false
false
3
5150b6fe0babf0bf1c8b29b7a8d7022ee4f014c9
2,851,858,327,500
f5cf3990c0d9bb0e294cf5de6dc765ea0221f1d6
/gt-fhir2-jpabase/src/main/java/edu/gatech/chai/omopv5/jpa/dao/ConceptDao.java
7cdec356a2ecad57b39b072a320bcbb8dcdf3df5
[ "Apache-2.0" ]
permissive
soto14/GT-FHIR2
https://github.com/soto14/GT-FHIR2
5d72d336b89ae33fd475f35fbbe9af0562bac905
6b9f4ecf370355f56ec94aacfd019c42a158ab3b
refs/heads/master
2021-01-25T12:19:21.386000
2018-03-01T20:57:31
2018-03-01T20:57:31
123,463,544
0
0
null
true
2018-03-01T16:46:38
2018-03-01T16:46:38
2018-02-03T01:20:10
2018-02-26T22:08:13
172
0
0
0
null
false
null
package edu.gatech.chai.omopv5.jpa.dao; import org.springframework.stereotype.Repository; import edu.gatech.chai.omopv5.jpa.entity.Concept; @Repository public class ConceptDao extends BaseEntityDao<Concept> { @Override public void add(Concept baseEntity) { // Concept table is read-only. } @Override public void merge(Concept baseEntity) { // Concept table is read-only. } @Override public void update(Concept baseEntity) { // Concept table is read-only. } @Override public Concept findById(Long id) { return getEntityManager().find(Concept.class, id); } @Override public void delete(Long id) { // Concept table is read-only. } }
UTF-8
Java
664
java
ConceptDao.java
Java
[]
null
[]
package edu.gatech.chai.omopv5.jpa.dao; import org.springframework.stereotype.Repository; import edu.gatech.chai.omopv5.jpa.entity.Concept; @Repository public class ConceptDao extends BaseEntityDao<Concept> { @Override public void add(Concept baseEntity) { // Concept table is read-only. } @Override public void merge(Concept baseEntity) { // Concept table is read-only. } @Override public void update(Concept baseEntity) { // Concept table is read-only. } @Override public Concept findById(Long id) { return getEntityManager().find(Concept.class, id); } @Override public void delete(Long id) { // Concept table is read-only. } }
664
0.733434
0.730422
35
17.971428
18.858095
56
false
false
0
0
0
0
0
0
0.857143
false
false
3
451614ecfed8d76698f275468f8aca288d9e70f6
5,901,285,132,226
c3115f960d968d5b1d06f849e16c9345d9623eee
/CalculatorWeb/app/src/main/java/com/example/hossainkabir/calculatorweb/MainActivity.java
cc4d7628e59f0e02713776cc2468fc312fe94341
[]
no_license
HossainKabir/Android-Work
https://github.com/HossainKabir/Android-Work
5d66440f2413a80d5d45e3372adf90008caa4fef
63a77adb1635073cc9a588b2ff1524282480dded
refs/heads/master
2021-08-11T05:48:26.407000
2017-11-13T07:07:45
2017-11-13T07:07:45
110,512,345
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.hossainkabir.calculatorweb; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { WebView viewWeb; WebSettings webSettings; ConnectivityManager conman; WifiManager wifiManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewWeb=(WebView)findViewById(R.id.webView); conman = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); wifiManager=(WifiManager)getSystemService(Context.WIFI_SERVICE); if (conman.getActiveNetworkInfo() == null) { viewWeb.loadUrl("file:///android_asset/index.html"); } else { viewWeb.loadUrl("file:///android_asset/VIP2.html"); } webSettings = viewWeb.getSettings(); webSettings.setJavaScriptEnabled(true); WebViewInterface webAppInterface = new WebViewInterface(this); viewWeb.addJavascriptInterface(webAppInterface,"Android"); viewWeb.getSettings().setBuiltInZoomControls(true); } }
UTF-8
Java
1,441
java
MainActivity.java
Java
[ { "context": "package com.example.hossainkabir.calculatorweb;\n\nimport android.content.Context;\ni", "end": 32, "score": 0.9942660331726074, "start": 20, "tag": "USERNAME", "value": "hossainkabir" } ]
null
[]
package com.example.hossainkabir.calculatorweb; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { WebView viewWeb; WebSettings webSettings; ConnectivityManager conman; WifiManager wifiManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewWeb=(WebView)findViewById(R.id.webView); conman = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); wifiManager=(WifiManager)getSystemService(Context.WIFI_SERVICE); if (conman.getActiveNetworkInfo() == null) { viewWeb.loadUrl("file:///android_asset/index.html"); } else { viewWeb.loadUrl("file:///android_asset/VIP2.html"); } webSettings = viewWeb.getSettings(); webSettings.setJavaScriptEnabled(true); WebViewInterface webAppInterface = new WebViewInterface(this); viewWeb.addJavascriptInterface(webAppInterface,"Android"); viewWeb.getSettings().setBuiltInZoomControls(true); } }
1,441
0.734212
0.732824
42
33.309525
23.47287
86
false
false
0
0
0
0
0
0
0.666667
false
false
3
a59088a453f7a3c318644038367adc9998c34c4f
9,552,007,268,856
ae2ee449bfafd343bd57390ca72cf5880507b50e
/game-ai/src/main/java/com/jzy/game/ai/nav/node/KPolygon.java
0ad3735e97c01ddab4e4f9cfd9204ed61ec753a6
[]
no_license
youboyTizzyT/game-server
https://github.com/youboyTizzyT/game-server
1ff1d9121f85a58e7f1af733682afb12aea746dd
eacdc71364123c3753a2f9989a2dea0ae1674463
refs/heads/master
2020-04-23T01:01:34.356000
2019-02-15T04:08:19
2019-02-15T04:08:19
170,800,145
2
1
null
true
2019-02-15T04:07:30
2019-02-15T04:07:30
2019-02-15T04:07:27
2019-01-25T06:34:10
29,014
0
0
0
null
false
null
package com.jzy.game.ai.nav.node; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import com.jzy.game.engine.math.Vector3; /** * 自定义多边形,包括三角形<br> * 封装了在java2D图像显示,多边形可凸或凹,但不能相交 * * @author JiangZhiYong * @date 2017年12月3日 * @mail 359135103@qq.com */ public class KPolygon implements Serializable, Cloneable, PolygonHolder, Shape { private static final long serialVersionUID = 1L; private List<Vector3> points; // 顶点坐标 protected boolean counterClockWise; // 多边形顶点是否为逆时针 protected double area; // 面积 protected Vector3 center; // 中心坐标 protected double radius; // 半径,中点到顶点的最大距离 protected float y = -1; // 多边形的平均y轴高度 protected double radiusSq; // 半径的平方 /** * @param pointsList * 顶点坐标 */ public KPolygon(List<Vector3> pointsList) { this(pointsList, true); } /** * @param pointsList * 顶点坐标 * @param copyPoints * true否复制坐标点 */ public KPolygon(List<Vector3> pointsList, boolean copyPoints) { if (pointsList.size() < 3) { throw new RuntimeException("最少需要三个顶点,当前为 " + pointsList.size()); } this.points = new ArrayList<>(pointsList.size()); for (int i = 0; i < pointsList.size(); i++) { Vector3 existingPoint = pointsList.get(i); if (copyPoints) { points.add(new Vector3(existingPoint)); } else { points.add(existingPoint); } } this.calcAll(); } /** * 复制创建 * * @param polygon */ public KPolygon(KPolygon polygon) { points = new ArrayList<>(polygon.getPoints().size()); for (int i = 0; i < polygon.getPoints().size(); i++) { Vector3 existingPoint = polygon.getPoints().get(i); points.add(new Vector3(existingPoint)); } area = polygon.getArea(); counterClockWise = polygon.isCounterClockWise(); radius = polygon.getRadius(); radiusSq = polygon.getRadiusSq(); center = new Vector3(polygon.getCenter()); } /** * @ 计算面积,中心点,半径 */ public void calcAll() { this.calcArea(); this.calcCenter(); this.calcRadius(); } /** * 计算面积 */ public void calcArea() { double signedArea = getAndCalcSignedArea(); if (signedArea < 0) { counterClockWise = false; } else { counterClockWise = true; } area = Math.abs(signedArea); } /** * 中心点 */ public void calcCenter() { if (center == null) { center = new Vector3(); } if (getArea() == 0) { center.x = points.get(0).x; center.z = points.get(0).z; return; } float cx = 0.0f; float cz = 0.0f; Vector3 pointIBefore = (!points.isEmpty() ? points.get(points.size() - 1) : null); for (int i = 0; i < points.size(); i++) { Vector3 pointI = points.get(i); double multiplier = (pointIBefore.z * pointI.x - pointIBefore.x * pointI.z); cx += (pointIBefore.x + pointI.x) * multiplier; cz += (pointIBefore.z + pointI.z) * multiplier; pointIBefore = pointI; } cx /= (6 * getArea()); cz /= (6 * getArea()); if (counterClockWise == true) { cx *= -1; cz *= -1; } center.x = cx; center.z = cz; } /** * 半径,中点到顶点的最大距离 */ public void calcRadius() { if (center == null) { calcCenter(); } double maxRadiusSq = -1; int furthestPointIndex = 0; for (int i = 0; i < points.size(); i++) { double currentRadiusSq = (center.dst2(points.get(i))); if (currentRadiusSq > maxRadiusSq) { maxRadiusSq = currentRadiusSq; furthestPointIndex = i; } } radius = (center.dst(points.get(furthestPointIndex))); radiusSq = radius * radius; } /** * 计算多边形面积 * * @return 面积 负数标示顺时针,正数顶点逆时针 */ public double getAndCalcSignedArea() { double totalArea = 0; for (int i = 0; i < points.size() - 1; i++) { totalArea += ((points.get(i).x - points.get(i + 1).x) * (points.get(i + 1).z + (points.get(i).z - points.get(i + 1).z) / 2)); } // need to do points[point.length-1] and points[0]. totalArea += ((points.get(points.size() - 1).x - points.get(0).x) * (points.get(0).z + (points.get(points.size() - 1).z - points.get(0).z) / 2)); return totalArea; } /** * 倒置坐标点的顺序 */ public void reversePointOrder() { counterClockWise = !counterClockWise; List<Vector3> tempPoints = new ArrayList<>(points.size()); for (int i = points.size() - 1; i >= 0; i--) { tempPoints.add(points.get(i)); } points.clear(); points.addAll(tempPoints); } /** * 获取坐标点 * * @param i * 序号 * @return */ public Vector3 getPoint(int i) { return getPoints().get(i); } /** * 克隆复制 * * @return */ public KPolygon copy() { KPolygon polygon = new KPolygon(this); return polygon; } public List<Vector3> getPoints() { return points; } public boolean isCounterClockWise() { return counterClockWise; } public Vector3 getCenter() { return center; } public double getRadius() { return radius; } public float getY() { return y; } public double getRadiusSq() { return radiusSq; } public double getArea() { return area; } /** * @ 坐标p是否在多边形内 * * @param p * 顶点坐标 * @return */ public boolean contains(Vector3 p) { return contains(p.x, p.z); } /** * 点p1 p2所在线段和多边形是否相交 * * @param p1 * @param p2 * @return */ public boolean intersectionPossible(Vector3 p1, Vector3 p2) { return intersectionPossible(p1.x, p1.z, p2.x, p2.z); } /** * 点p1 p2所在线段和多边形是否相交 * * @param x1 * @param z1 * @param x2 * @param z2 * @return */ public boolean intersectionPossible(double x1, double z1, double x2, double z2) { if (center.ptSegDistSq(x1, z1, x2, z2) > radiusSq) { // 中心点到线段的距离大于半径,不相交,不能绝对确定,由于中心点的计算可能有误差, return false; } return true; } /** * 是否为相交线 * * @param p1 * @param p2 * @return */ public boolean intersectsLine(Vector3 p1, Vector3 p2) { return intersectsLine(p1.x, p1.z, p2.x, p2.z); } /** * 坐标点和多边形否线性相交 * * @param x1 * @param z1 * @param x2 * @param z2 * @return */ public boolean intersectsLine(double x1, double z1, double x2, double z2) { // Sometimes this method fails if the 'lines' // start and end on the same point, so here we check for that. if (x1 == x2 && z1 == z2) { return false; } double ax = x2 - x1; double ay = z2 - z1; Vector3 pointIBefore = points.get(points.size() - 1); for (int i = 0; i < points.size(); i++) { Vector3 pointI = points.get(i); double x3 = pointIBefore.x; double z3 = pointIBefore.z; double x4 = pointI.x; double y4 = pointI.z; double bx = x3 - x4; double by = z3 - y4; double cx = x1 - x3; double cy = z1 - z3; double alphaNumerator = by * cx - bx * cy; double commonDenominator = ay * bx - ax * by; if (commonDenominator > 0) { if (alphaNumerator < 0 || alphaNumerator > commonDenominator) { pointIBefore = pointI; continue; } } else if (commonDenominator < 0) { if (alphaNumerator > 0 || alphaNumerator < commonDenominator) { pointIBefore = pointI; continue; } } double betaNumerator = ax * cy - ay * cx; if (commonDenominator > 0) { if (betaNumerator < 0 || betaNumerator > commonDenominator) { pointIBefore = pointI; continue; } } else if (commonDenominator < 0) { if (betaNumerator > 0 || betaNumerator < commonDenominator) { pointIBefore = pointI; continue; } } if (commonDenominator == 0) { // This code wasn't in Franklin Antonio's method. It was added // by Keith Woodward. // The lines are parallel. // Check if they're collinear. double collinearityTestForP3 = x1 * (z2 - z3) + x2 * (z3 - z1) + x3 * (z1 - z2); // see // http://mathworld.wolfram.com/Collinear.html // If p3 is collinear with p1 and p2 then p4 will also be // collinear, since p1-p2 is parallel with p3-p4 if (collinearityTestForP3 == 0) { // The lines are collinear. Now check if they overlap. if (x1 >= x3 && x1 <= x4 || x1 <= x3 && x1 >= x4 || x2 >= x3 && x2 <= x4 || x2 <= x3 && x2 >= x4 || x3 >= x1 && x3 <= x2 || x3 <= x1 && x3 >= x2) { if (z1 >= z3 && z1 <= y4 || z1 <= z3 && z1 >= y4 || z2 >= z3 && z2 <= y4 || z2 <= z3 && z2 >= y4 || z3 >= z1 && z3 <= z2 || z3 <= z1 && z3 >= z2) { return true; } } } pointIBefore = pointI; continue; } return true; } return false; } /** * 获取最靠近边界的点 * @param p * @return */ public Vector3 getBoundaryPointClosestTo(Vector3 p) { return getBoundaryPointClosestTo(p.x, p.z); } /** * 获取最靠近边界的点 * @param x * @param z * @return */ public Vector3 getBoundaryPointClosestTo(float x, float z) { double closestDistanceSq = Double.MAX_VALUE; int closestIndex = -1; int closestNextIndex = -1; int nextI; for (int i = 0; i < points.size(); i++) { //获取点到多边形边最近的两个点 nextI = (i + 1 == points.size() ? 0 : i + 1); Vector3 p = this.getPoints().get(i); Vector3 pNext = this.getPoints().get(nextI); double ptSegDistSq = Vector3.ptSegDistSq(p.x, p.z, pNext.x, pNext.z, x, z); if (ptSegDistSq < closestDistanceSq) { closestDistanceSq = ptSegDistSq; closestIndex = i; closestNextIndex = nextI; } } Vector3 p = this.getPoints().get(closestIndex); Vector3 pNext = this.getPoints().get(closestNextIndex); return Vector3.getClosestPointOnSegment(p.x, p.z, pNext.x, pNext.z, x, z); } public double[] getBoundsArray() { return getBoundsArray(new double[4]); } public double[] getBoundsArray(double[] bounds) { double leftX = Double.MAX_VALUE; double botY = Double.MAX_VALUE; double rightX = -Double.MAX_VALUE; double topY = -Double.MAX_VALUE; for (int i = 0; i < points.size(); i++) { if (points.get(i).x < leftX) { leftX = points.get(i).x; } if (points.get(i).x > rightX) { rightX = points.get(i).x; } if (points.get(i).z < botY) { botY = points.get(i).z; } if (points.get(i).z > topY) { topY = points.get(i).z; } } bounds[0] = leftX; bounds[1] = botY; bounds[2] = rightX; bounds[3] = topY; return bounds; } // ===========java图像显示============== @Override public Rectangle getBounds() { double[] bounds = getBoundsArray(); return new Rectangle((int) (bounds[0]), (int) (bounds[1]), (int) Math.ceil(bounds[2]), (int) Math.ceil(bounds[3])); } @Override public Rectangle2D getBounds2D() { double[] bounds = getBoundsArray(); return new Rectangle2D.Double(bounds[0], bounds[1], bounds[2], bounds[3]); } // The essence of the ray-crossing method is as follows. Think of standing // inside a field with a fence representing the polygon. Then walk north. If // you have to jump the fence you know you are now outside the poly. If you // have to cross again you know you are now inside again; i.e., if you were // inside the field to start with, the total number of fence jumps you would // make will be odd, whereas if you were ouside the jumps will be even. // The code below is from Wm. Randolph Franklin <wrf@ecse.rpi.edu> with some // minor modifications for speed. It returns 1 for strictly interior points, // 0 for strictly exterior, and 0 or 1 for points on the boundary. The // boundary behavior is complex but determined; | in particular, for a // partition of a region into polygons, each point | is "in" exactly one // polygon. See the references below for more detail // The code may be further accelerated, at some loss in clarity, by avoiding // the central computation when the inequality can be deduced, and by // replacing the division by a multiplication for those processors with slow // divides. // References: @Override public boolean contains(double x, double z) { Vector3 pointIBefore = (points.size() != 0 ? points.get(points.size() - 1) : null); int crossings = 0; for (int i = 0; i < points.size(); i++) { Vector3 pointI = points.get(i); if (((pointIBefore.z <= z && z < pointI.z) || (pointI.z <= z && z < pointIBefore.z)) && x < ((pointI.x - pointIBefore.x) / (pointI.z - pointIBefore.z) * (z - pointIBefore.z) + pointIBefore.x)) { crossings++; } pointIBefore = pointI; } return (crossings % 2 != 0); } @Override public boolean contains(Point2D p) { return contains(p.getX(), p.getY()); } @Override public boolean intersects(double x, double z, double w, double h) { if (x + w < center.x - radius || x > center.x + radius || z + h < center.z - radius || z > center.z + radius) { return false; } for (int i = 0; i < points.size(); i++) { int nextI = (i + 1 >= points.size() ? 0 : i + 1); if (Vector3.linesIntersect(x, z, x + w, z, points.get(i).x, points.get(i).z, points.get(nextI).x, points.get(nextI).z) || Vector3.linesIntersect(x, z, x, z + h, points.get(i).x, points.get(i).z, points.get(nextI).x, points.get(nextI).z) || Vector3.linesIntersect(x, z + h, x + w, z + h, points.get(i).x, points.get(i).z, points.get(nextI).x, points.get(nextI).z) || Vector3.linesIntersect(x + w, z, x + w, z + h, points.get(i).x, points.get(i).z, points.get(nextI).x, points.get(nextI).z)) { return true; } } double px = points.get(0).x; double py = points.get(0).z; if (px > x && px < x + w && py > z && py < z + h) { return true; } if (contains(x, z) == true) { return true; } return false; } @Override public boolean intersects(Rectangle2D r) { return this.intersects(r.getX(), r.getY(), r.getWidth(), r.getHeight()); } @Override public boolean contains(double x, double z, double w, double h) { if (x + w < center.x - radius || x > center.x + radius || z + h < center.z - radius || z > center.z + radius) { return false; } for (int i = 0; i < points.size(); i++) { int nextI = (i + 1 >= points.size() ? 0 : i + 1); if (Vector3.linesIntersect(x, z, x + w, z, points.get(i).x, points.get(i).z, points.get(nextI).x, points.get(nextI).z) || Vector3.linesIntersect(x, z, x, z + h, points.get(i).x, points.get(i).z, points.get(nextI).x, points.get(nextI).z) || Vector3.linesIntersect(x, z + h, x + w, z + h, points.get(i).x, points.get(i).z, points.get(nextI).x, points.get(nextI).z) || Vector3.linesIntersect(x + w, z, x + w, z + h, points.get(i).x, points.get(i).z, points.get(nextI).x, points.get(nextI).z)) { return false; } } double px = points.get(0).x; double py = points.get(0).z; if (px > x && px < x + w && py > z && py < z + h) { return false; } return contains(x, z) == true; } @Override public boolean contains(Rectangle2D r) { return this.contains(r.getX(), r.getY(), r.getWidth(), r.getHeight()); } @Override public PathIterator getPathIterator(AffineTransform at) { return new KPolygonIterator(this, at); } @Override public PathIterator getPathIterator(AffineTransform at, double flatness) { return new KPolygonIterator(this, at); } @Override public KPolygon getPolygon() { return this; } public class KPolygonIterator implements PathIterator { int type = PathIterator.SEG_MOVETO; int index = 0; KPolygon polygon; Vector3 currentPoint; AffineTransform affine; double[] singlePointSetDouble = new double[2]; KPolygonIterator(KPolygon kPolygon) { this(kPolygon, null); } KPolygonIterator(KPolygon kPolygon, AffineTransform at) { this.polygon = kPolygon; this.affine = at; currentPoint = polygon.getPoint(0); } public int getWindingRule() { return PathIterator.WIND_EVEN_ODD; } @Override public boolean isDone() { if (index == polygon.points.size() + 1) { return true; } return false; } @Override public void next() { index++; } public void assignPointAndType() { if (index == 0) { currentPoint = polygon.getPoint(0); type = PathIterator.SEG_MOVETO; } else if (index == polygon.points.size()) { type = PathIterator.SEG_CLOSE; } else { currentPoint = polygon.getPoint(index); type = PathIterator.SEG_LINETO; } } @Override public int currentSegment(float[] coords) { assignPointAndType(); if (type != PathIterator.SEG_CLOSE) { if (affine != null) { float[] singlePointSetFloat = new float[2]; singlePointSetFloat[0] = (float) currentPoint.x; singlePointSetFloat[1] = (float) currentPoint.z; affine.transform(singlePointSetFloat, 0, coords, 0, 1); } else { coords[0] = (float) currentPoint.x; coords[1] = (float) currentPoint.z; } } return type; } @Override public int currentSegment(double[] coords) { assignPointAndType(); if (type != PathIterator.SEG_CLOSE) { if (affine != null) { singlePointSetDouble[0] = currentPoint.x; singlePointSetDouble[1] = currentPoint.z; affine.transform(singlePointSetDouble, 0, coords, 0, 1); } else { coords[0] = currentPoint.x; coords[1] = currentPoint.z; } } return type; } } }
UTF-8
Java
21,974
java
KPolygon.java
Java
[ { "context": "\r\n * 封装了在java2D图像显示,多边形可凸或凹,但不能相交\r\n * \r\n * @author JiangZhiYong\r\n * @date 2017年12月3日\r\n * @mail 359135103@qq.com\r\n", "end": 446, "score": 0.9998359680175781, "start": 434, "tag": "NAME", "value": "JiangZhiYong" }, { "context": "uthor JiangZhiYong\r\n * @date 2017年12月3日\r\n * @mail 359135103@qq.com\r\n */\r\npublic class KPolygon implements Serializab", "end": 494, "score": 0.911626398563385, "start": 478, "tag": "EMAIL", "value": "359135103@qq.com" }, { "context": "onio's method. It was added\r\n // by Keith Woodward.\r\n // The lines are parallel.\r\n ", "end": 9573, "score": 0.9998405575752258, "start": 9559, "tag": "NAME", "value": "Keith Woodward" }, { "context": "mps will be even.\r\n // The code below is from Wm. Randolph Franklin <wrf@ecse.rpi.edu> with some\r\n", "end": 13945, "score": 0.5688359141349792, "start": 13944, "tag": "NAME", "value": "m" }, { "context": "s will be even.\r\n // The code below is from Wm. Randolph Franklin <wrf@ecse.rpi.edu> with some\r\n // minor modifi", "end": 13964, "score": 0.9029746055603027, "start": 13947, "tag": "NAME", "value": "Randolph Franklin" }, { "context": " // The code below is from Wm. Randolph Franklin <wrf@ecse.rpi.edu> with some\r\n // minor modifications for speed.", "end": 13982, "score": 0.9999311566352844, "start": 13966, "tag": "EMAIL", "value": "wrf@ecse.rpi.edu" } ]
null
[]
package com.jzy.game.ai.nav.node; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import com.jzy.game.engine.math.Vector3; /** * 自定义多边形,包括三角形<br> * 封装了在java2D图像显示,多边形可凸或凹,但不能相交 * * @author JiangZhiYong * @date 2017年12月3日 * @mail <EMAIL> */ public class KPolygon implements Serializable, Cloneable, PolygonHolder, Shape { private static final long serialVersionUID = 1L; private List<Vector3> points; // 顶点坐标 protected boolean counterClockWise; // 多边形顶点是否为逆时针 protected double area; // 面积 protected Vector3 center; // 中心坐标 protected double radius; // 半径,中点到顶点的最大距离 protected float y = -1; // 多边形的平均y轴高度 protected double radiusSq; // 半径的平方 /** * @param pointsList * 顶点坐标 */ public KPolygon(List<Vector3> pointsList) { this(pointsList, true); } /** * @param pointsList * 顶点坐标 * @param copyPoints * true否复制坐标点 */ public KPolygon(List<Vector3> pointsList, boolean copyPoints) { if (pointsList.size() < 3) { throw new RuntimeException("最少需要三个顶点,当前为 " + pointsList.size()); } this.points = new ArrayList<>(pointsList.size()); for (int i = 0; i < pointsList.size(); i++) { Vector3 existingPoint = pointsList.get(i); if (copyPoints) { points.add(new Vector3(existingPoint)); } else { points.add(existingPoint); } } this.calcAll(); } /** * 复制创建 * * @param polygon */ public KPolygon(KPolygon polygon) { points = new ArrayList<>(polygon.getPoints().size()); for (int i = 0; i < polygon.getPoints().size(); i++) { Vector3 existingPoint = polygon.getPoints().get(i); points.add(new Vector3(existingPoint)); } area = polygon.getArea(); counterClockWise = polygon.isCounterClockWise(); radius = polygon.getRadius(); radiusSq = polygon.getRadiusSq(); center = new Vector3(polygon.getCenter()); } /** * @ 计算面积,中心点,半径 */ public void calcAll() { this.calcArea(); this.calcCenter(); this.calcRadius(); } /** * 计算面积 */ public void calcArea() { double signedArea = getAndCalcSignedArea(); if (signedArea < 0) { counterClockWise = false; } else { counterClockWise = true; } area = Math.abs(signedArea); } /** * 中心点 */ public void calcCenter() { if (center == null) { center = new Vector3(); } if (getArea() == 0) { center.x = points.get(0).x; center.z = points.get(0).z; return; } float cx = 0.0f; float cz = 0.0f; Vector3 pointIBefore = (!points.isEmpty() ? points.get(points.size() - 1) : null); for (int i = 0; i < points.size(); i++) { Vector3 pointI = points.get(i); double multiplier = (pointIBefore.z * pointI.x - pointIBefore.x * pointI.z); cx += (pointIBefore.x + pointI.x) * multiplier; cz += (pointIBefore.z + pointI.z) * multiplier; pointIBefore = pointI; } cx /= (6 * getArea()); cz /= (6 * getArea()); if (counterClockWise == true) { cx *= -1; cz *= -1; } center.x = cx; center.z = cz; } /** * 半径,中点到顶点的最大距离 */ public void calcRadius() { if (center == null) { calcCenter(); } double maxRadiusSq = -1; int furthestPointIndex = 0; for (int i = 0; i < points.size(); i++) { double currentRadiusSq = (center.dst2(points.get(i))); if (currentRadiusSq > maxRadiusSq) { maxRadiusSq = currentRadiusSq; furthestPointIndex = i; } } radius = (center.dst(points.get(furthestPointIndex))); radiusSq = radius * radius; } /** * 计算多边形面积 * * @return 面积 负数标示顺时针,正数顶点逆时针 */ public double getAndCalcSignedArea() { double totalArea = 0; for (int i = 0; i < points.size() - 1; i++) { totalArea += ((points.get(i).x - points.get(i + 1).x) * (points.get(i + 1).z + (points.get(i).z - points.get(i + 1).z) / 2)); } // need to do points[point.length-1] and points[0]. totalArea += ((points.get(points.size() - 1).x - points.get(0).x) * (points.get(0).z + (points.get(points.size() - 1).z - points.get(0).z) / 2)); return totalArea; } /** * 倒置坐标点的顺序 */ public void reversePointOrder() { counterClockWise = !counterClockWise; List<Vector3> tempPoints = new ArrayList<>(points.size()); for (int i = points.size() - 1; i >= 0; i--) { tempPoints.add(points.get(i)); } points.clear(); points.addAll(tempPoints); } /** * 获取坐标点 * * @param i * 序号 * @return */ public Vector3 getPoint(int i) { return getPoints().get(i); } /** * 克隆复制 * * @return */ public KPolygon copy() { KPolygon polygon = new KPolygon(this); return polygon; } public List<Vector3> getPoints() { return points; } public boolean isCounterClockWise() { return counterClockWise; } public Vector3 getCenter() { return center; } public double getRadius() { return radius; } public float getY() { return y; } public double getRadiusSq() { return radiusSq; } public double getArea() { return area; } /** * @ 坐标p是否在多边形内 * * @param p * 顶点坐标 * @return */ public boolean contains(Vector3 p) { return contains(p.x, p.z); } /** * 点p1 p2所在线段和多边形是否相交 * * @param p1 * @param p2 * @return */ public boolean intersectionPossible(Vector3 p1, Vector3 p2) { return intersectionPossible(p1.x, p1.z, p2.x, p2.z); } /** * 点p1 p2所在线段和多边形是否相交 * * @param x1 * @param z1 * @param x2 * @param z2 * @return */ public boolean intersectionPossible(double x1, double z1, double x2, double z2) { if (center.ptSegDistSq(x1, z1, x2, z2) > radiusSq) { // 中心点到线段的距离大于半径,不相交,不能绝对确定,由于中心点的计算可能有误差, return false; } return true; } /** * 是否为相交线 * * @param p1 * @param p2 * @return */ public boolean intersectsLine(Vector3 p1, Vector3 p2) { return intersectsLine(p1.x, p1.z, p2.x, p2.z); } /** * 坐标点和多边形否线性相交 * * @param x1 * @param z1 * @param x2 * @param z2 * @return */ public boolean intersectsLine(double x1, double z1, double x2, double z2) { // Sometimes this method fails if the 'lines' // start and end on the same point, so here we check for that. if (x1 == x2 && z1 == z2) { return false; } double ax = x2 - x1; double ay = z2 - z1; Vector3 pointIBefore = points.get(points.size() - 1); for (int i = 0; i < points.size(); i++) { Vector3 pointI = points.get(i); double x3 = pointIBefore.x; double z3 = pointIBefore.z; double x4 = pointI.x; double y4 = pointI.z; double bx = x3 - x4; double by = z3 - y4; double cx = x1 - x3; double cy = z1 - z3; double alphaNumerator = by * cx - bx * cy; double commonDenominator = ay * bx - ax * by; if (commonDenominator > 0) { if (alphaNumerator < 0 || alphaNumerator > commonDenominator) { pointIBefore = pointI; continue; } } else if (commonDenominator < 0) { if (alphaNumerator > 0 || alphaNumerator < commonDenominator) { pointIBefore = pointI; continue; } } double betaNumerator = ax * cy - ay * cx; if (commonDenominator > 0) { if (betaNumerator < 0 || betaNumerator > commonDenominator) { pointIBefore = pointI; continue; } } else if (commonDenominator < 0) { if (betaNumerator > 0 || betaNumerator < commonDenominator) { pointIBefore = pointI; continue; } } if (commonDenominator == 0) { // This code wasn't in Franklin Antonio's method. It was added // by <NAME>. // The lines are parallel. // Check if they're collinear. double collinearityTestForP3 = x1 * (z2 - z3) + x2 * (z3 - z1) + x3 * (z1 - z2); // see // http://mathworld.wolfram.com/Collinear.html // If p3 is collinear with p1 and p2 then p4 will also be // collinear, since p1-p2 is parallel with p3-p4 if (collinearityTestForP3 == 0) { // The lines are collinear. Now check if they overlap. if (x1 >= x3 && x1 <= x4 || x1 <= x3 && x1 >= x4 || x2 >= x3 && x2 <= x4 || x2 <= x3 && x2 >= x4 || x3 >= x1 && x3 <= x2 || x3 <= x1 && x3 >= x2) { if (z1 >= z3 && z1 <= y4 || z1 <= z3 && z1 >= y4 || z2 >= z3 && z2 <= y4 || z2 <= z3 && z2 >= y4 || z3 >= z1 && z3 <= z2 || z3 <= z1 && z3 >= z2) { return true; } } } pointIBefore = pointI; continue; } return true; } return false; } /** * 获取最靠近边界的点 * @param p * @return */ public Vector3 getBoundaryPointClosestTo(Vector3 p) { return getBoundaryPointClosestTo(p.x, p.z); } /** * 获取最靠近边界的点 * @param x * @param z * @return */ public Vector3 getBoundaryPointClosestTo(float x, float z) { double closestDistanceSq = Double.MAX_VALUE; int closestIndex = -1; int closestNextIndex = -1; int nextI; for (int i = 0; i < points.size(); i++) { //获取点到多边形边最近的两个点 nextI = (i + 1 == points.size() ? 0 : i + 1); Vector3 p = this.getPoints().get(i); Vector3 pNext = this.getPoints().get(nextI); double ptSegDistSq = Vector3.ptSegDistSq(p.x, p.z, pNext.x, pNext.z, x, z); if (ptSegDistSq < closestDistanceSq) { closestDistanceSq = ptSegDistSq; closestIndex = i; closestNextIndex = nextI; } } Vector3 p = this.getPoints().get(closestIndex); Vector3 pNext = this.getPoints().get(closestNextIndex); return Vector3.getClosestPointOnSegment(p.x, p.z, pNext.x, pNext.z, x, z); } public double[] getBoundsArray() { return getBoundsArray(new double[4]); } public double[] getBoundsArray(double[] bounds) { double leftX = Double.MAX_VALUE; double botY = Double.MAX_VALUE; double rightX = -Double.MAX_VALUE; double topY = -Double.MAX_VALUE; for (int i = 0; i < points.size(); i++) { if (points.get(i).x < leftX) { leftX = points.get(i).x; } if (points.get(i).x > rightX) { rightX = points.get(i).x; } if (points.get(i).z < botY) { botY = points.get(i).z; } if (points.get(i).z > topY) { topY = points.get(i).z; } } bounds[0] = leftX; bounds[1] = botY; bounds[2] = rightX; bounds[3] = topY; return bounds; } // ===========java图像显示============== @Override public Rectangle getBounds() { double[] bounds = getBoundsArray(); return new Rectangle((int) (bounds[0]), (int) (bounds[1]), (int) Math.ceil(bounds[2]), (int) Math.ceil(bounds[3])); } @Override public Rectangle2D getBounds2D() { double[] bounds = getBoundsArray(); return new Rectangle2D.Double(bounds[0], bounds[1], bounds[2], bounds[3]); } // The essence of the ray-crossing method is as follows. Think of standing // inside a field with a fence representing the polygon. Then walk north. If // you have to jump the fence you know you are now outside the poly. If you // have to cross again you know you are now inside again; i.e., if you were // inside the field to start with, the total number of fence jumps you would // make will be odd, whereas if you were ouside the jumps will be even. // The code below is from Wm. <NAME> <<EMAIL>> with some // minor modifications for speed. It returns 1 for strictly interior points, // 0 for strictly exterior, and 0 or 1 for points on the boundary. The // boundary behavior is complex but determined; | in particular, for a // partition of a region into polygons, each point | is "in" exactly one // polygon. See the references below for more detail // The code may be further accelerated, at some loss in clarity, by avoiding // the central computation when the inequality can be deduced, and by // replacing the division by a multiplication for those processors with slow // divides. // References: @Override public boolean contains(double x, double z) { Vector3 pointIBefore = (points.size() != 0 ? points.get(points.size() - 1) : null); int crossings = 0; for (int i = 0; i < points.size(); i++) { Vector3 pointI = points.get(i); if (((pointIBefore.z <= z && z < pointI.z) || (pointI.z <= z && z < pointIBefore.z)) && x < ((pointI.x - pointIBefore.x) / (pointI.z - pointIBefore.z) * (z - pointIBefore.z) + pointIBefore.x)) { crossings++; } pointIBefore = pointI; } return (crossings % 2 != 0); } @Override public boolean contains(Point2D p) { return contains(p.getX(), p.getY()); } @Override public boolean intersects(double x, double z, double w, double h) { if (x + w < center.x - radius || x > center.x + radius || z + h < center.z - radius || z > center.z + radius) { return false; } for (int i = 0; i < points.size(); i++) { int nextI = (i + 1 >= points.size() ? 0 : i + 1); if (Vector3.linesIntersect(x, z, x + w, z, points.get(i).x, points.get(i).z, points.get(nextI).x, points.get(nextI).z) || Vector3.linesIntersect(x, z, x, z + h, points.get(i).x, points.get(i).z, points.get(nextI).x, points.get(nextI).z) || Vector3.linesIntersect(x, z + h, x + w, z + h, points.get(i).x, points.get(i).z, points.get(nextI).x, points.get(nextI).z) || Vector3.linesIntersect(x + w, z, x + w, z + h, points.get(i).x, points.get(i).z, points.get(nextI).x, points.get(nextI).z)) { return true; } } double px = points.get(0).x; double py = points.get(0).z; if (px > x && px < x + w && py > z && py < z + h) { return true; } if (contains(x, z) == true) { return true; } return false; } @Override public boolean intersects(Rectangle2D r) { return this.intersects(r.getX(), r.getY(), r.getWidth(), r.getHeight()); } @Override public boolean contains(double x, double z, double w, double h) { if (x + w < center.x - radius || x > center.x + radius || z + h < center.z - radius || z > center.z + radius) { return false; } for (int i = 0; i < points.size(); i++) { int nextI = (i + 1 >= points.size() ? 0 : i + 1); if (Vector3.linesIntersect(x, z, x + w, z, points.get(i).x, points.get(i).z, points.get(nextI).x, points.get(nextI).z) || Vector3.linesIntersect(x, z, x, z + h, points.get(i).x, points.get(i).z, points.get(nextI).x, points.get(nextI).z) || Vector3.linesIntersect(x, z + h, x + w, z + h, points.get(i).x, points.get(i).z, points.get(nextI).x, points.get(nextI).z) || Vector3.linesIntersect(x + w, z, x + w, z + h, points.get(i).x, points.get(i).z, points.get(nextI).x, points.get(nextI).z)) { return false; } } double px = points.get(0).x; double py = points.get(0).z; if (px > x && px < x + w && py > z && py < z + h) { return false; } return contains(x, z) == true; } @Override public boolean contains(Rectangle2D r) { return this.contains(r.getX(), r.getY(), r.getWidth(), r.getHeight()); } @Override public PathIterator getPathIterator(AffineTransform at) { return new KPolygonIterator(this, at); } @Override public PathIterator getPathIterator(AffineTransform at, double flatness) { return new KPolygonIterator(this, at); } @Override public KPolygon getPolygon() { return this; } public class KPolygonIterator implements PathIterator { int type = PathIterator.SEG_MOVETO; int index = 0; KPolygon polygon; Vector3 currentPoint; AffineTransform affine; double[] singlePointSetDouble = new double[2]; KPolygonIterator(KPolygon kPolygon) { this(kPolygon, null); } KPolygonIterator(KPolygon kPolygon, AffineTransform at) { this.polygon = kPolygon; this.affine = at; currentPoint = polygon.getPoint(0); } public int getWindingRule() { return PathIterator.WIND_EVEN_ODD; } @Override public boolean isDone() { if (index == polygon.points.size() + 1) { return true; } return false; } @Override public void next() { index++; } public void assignPointAndType() { if (index == 0) { currentPoint = polygon.getPoint(0); type = PathIterator.SEG_MOVETO; } else if (index == polygon.points.size()) { type = PathIterator.SEG_CLOSE; } else { currentPoint = polygon.getPoint(index); type = PathIterator.SEG_LINETO; } } @Override public int currentSegment(float[] coords) { assignPointAndType(); if (type != PathIterator.SEG_CLOSE) { if (affine != null) { float[] singlePointSetFloat = new float[2]; singlePointSetFloat[0] = (float) currentPoint.x; singlePointSetFloat[1] = (float) currentPoint.z; affine.transform(singlePointSetFloat, 0, coords, 0, 1); } else { coords[0] = (float) currentPoint.x; coords[1] = (float) currentPoint.z; } } return type; } @Override public int currentSegment(double[] coords) { assignPointAndType(); if (type != PathIterator.SEG_CLOSE) { if (affine != null) { singlePointSetDouble[0] = currentPoint.x; singlePointSetDouble[1] = currentPoint.z; affine.transform(singlePointSetDouble, 0, coords, 0, 1); } else { coords[0] = currentPoint.x; coords[1] = currentPoint.z; } } return type; } } }
21,937
0.492969
0.478391
643
31.178848
28.832289
206
false
false
0
0
0
0
0
0
0.692068
false
false
3
3f4ce11ee5abc94e927c08d625e5561ddd9cdf6d
14,628,658,676,646
7e1d4295b7f8543efee07e31189855ed66eb7e23
/ch_002/src/main/java/ru/job4j/pojo/College.java
09a4e89caeff639fcf8c2c1172669d435e561244
[ "Apache-2.0" ]
permissive
KengyRoo/old_job4j
https://github.com/KengyRoo/old_job4j
9b84810049a56644f6767967c4df202663ec62d3
095ba3c2f8958ab445486ecf61ea378d34d1d971
refs/heads/master
2021-06-25T05:21:46.943000
2019-11-22T14:23:30
2019-11-22T14:23:30
142,148,269
0
0
Apache-2.0
false
2020-10-13T04:48:55
2018-07-24T11:21:33
2019-12-05T11:14:20
2020-10-13T04:48:54
126
0
0
1
Java
false
false
package ru.job4j.pojo; import java.util.Date; public class College { public static void main(String[] args){ Student student = new Student(); student.setFio("Aleksandr Kostyuk Urievich"); student.setGroup("25A19"); student.setEnrollment(new Date()); System.out.println(student.getFio() + " group: " + student.getGroup() + " enrollement " + student.getEnrollment()); } }
UTF-8
Java
423
java
College.java
Java
[ { "context": " student = new Student();\n student.setFio(\"Aleksandr Kostyuk Urievich\");\n student.setGroup(\"25A19\");\n stu", "end": 206, "score": 0.9998762607574463, "start": 180, "tag": "NAME", "value": "Aleksandr Kostyuk Urievich" } ]
null
[]
package ru.job4j.pojo; import java.util.Date; public class College { public static void main(String[] args){ Student student = new Student(); student.setFio("<NAME>"); student.setGroup("25A19"); student.setEnrollment(new Date()); System.out.println(student.getFio() + " group: " + student.getGroup() + " enrollement " + student.getEnrollment()); } }
403
0.643026
0.631206
16
25.4375
31.056337
123
false
false
0
0
0
0
0
0
0.4375
false
false
3
ea404b17eb8bd89f39f69ddbac9603915a34fa25
20,332,375,235,646
3b1acce9b2bc5545dcbe460d8f9af179bf5c0b7f
/src/main/java/com/kenzanexample/employeedemo/domain/Employee.java
d717771f91e8a3f65912a58e650394d06601087b
[]
no_license
naulta/SpringEmployeeRESTExample
https://github.com/naulta/SpringEmployeeRESTExample
01855088e6787a270bc726eab5e11143242dc954
59843b19ca2fd7140b9d4cd13936e9d7e8faf6ff
refs/heads/master
2020-03-25T06:22:01.596000
2018-08-06T15:53:26
2018-08-06T15:53:26
143,497,154
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kenzanexample.employeedemo.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Employee { /* * Employee spec * ID - Unique identifier for an employee * FirstName - Employee first name * MiddleInitial - Employee middle initial * LastName - Employee last name * DateOfBirth - Employee birthday and year * DateOfEmployment - Employee start date * Status - ACTIVE or INACTIVE */ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", unique=true, nullable=false, length=255) private long ID; @Column(name = "first_name", unique=false, nullable=false, length=60) private String FirstName; @Column(name = "middle_initial", unique=false, nullable=true, length=1) private String MiddleInitial; @Column(name = "last_name", unique=false, nullable=false, length=60) private String LastName; @Column(name = "date_of_birth", unique=false, nullable=false, length=60) private String DateOfBirth; @Column(name = "date_of_employment", unique=false, nullable=false, length=60) private String DateOfEmployment; @Column(name = "status", unique=false, nullable=false, length=10) private String Status; public Employee () {} public Employee (Long ID, String FirstName, String MiddleInitial, String LastName, String DateOfBirth, String DateOfEmployment, String Status) { this.ID = ID; this.FirstName = FirstName; this.MiddleInitial = MiddleInitial; this.LastName = LastName; this.DateOfBirth = DateOfBirth; this.DateOfEmployment = DateOfEmployment; this.Status = Status; } public Long getID() { return ID; } public void setID(Long ID) { this.ID = ID; } public String getFirstName() { return FirstName; } public void setFirstName(String FirstName) { this.FirstName = FirstName; } public String getLastName() { return LastName; } public void setLastName(String LastName) { this.LastName = LastName; } public String getMiddleInitial() { return MiddleInitial; } public void setMiddleInitial(String MiddleInitial) { this.MiddleInitial = MiddleInitial; } public String getDateOfBirth() { return DateOfBirth; } public void setDateOfBirth(String DateOfBirth) { this.DateOfBirth = DateOfBirth; } public String getDateOfEmployment() { return DateOfEmployment; } public void setDateOfEmployment(String DateOfEmployment) { this.DateOfEmployment = DateOfEmployment; } public String getStatus() { return Status; } public void setStatus(String Status) { this.Status = Status; } @Override public String toString() { return "Employee [ID=" + ID + ", FirstName=" + FirstName + ", MiddleInitial=" + MiddleInitial + ", LastName=" + LastName + ", DateOfBirth=" + DateOfBirth + ", DateOfEmployment=" + DateOfEmployment + ", Status=" + Status + "]"; } }
UTF-8
Java
3,067
java
Employee.java
Java
[ { "context": "ing Status) {\r\n\t\tthis.ID = ID;\r\n\t\tthis.FirstName = FirstName;\r\n\t\tthis.MiddleInitial = MiddleInitial;\r\n\t\tth", "end": 1577, "score": 0.5898435115814209, "start": 1572, "tag": "NAME", "value": "First" }, { "context": ".MiddleInitial = MiddleInitial;\r\n\t\tthis.LastName = LastName;\r\n\t\tthis.DateOfBirth = DateOfBirth;\r\n\t\tthis.DateO", "end": 1649, "score": 0.7480376958847046, "start": 1641, "tag": "NAME", "value": "LastName" } ]
null
[]
package com.kenzanexample.employeedemo.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Employee { /* * Employee spec * ID - Unique identifier for an employee * FirstName - Employee first name * MiddleInitial - Employee middle initial * LastName - Employee last name * DateOfBirth - Employee birthday and year * DateOfEmployment - Employee start date * Status - ACTIVE or INACTIVE */ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", unique=true, nullable=false, length=255) private long ID; @Column(name = "first_name", unique=false, nullable=false, length=60) private String FirstName; @Column(name = "middle_initial", unique=false, nullable=true, length=1) private String MiddleInitial; @Column(name = "last_name", unique=false, nullable=false, length=60) private String LastName; @Column(name = "date_of_birth", unique=false, nullable=false, length=60) private String DateOfBirth; @Column(name = "date_of_employment", unique=false, nullable=false, length=60) private String DateOfEmployment; @Column(name = "status", unique=false, nullable=false, length=10) private String Status; public Employee () {} public Employee (Long ID, String FirstName, String MiddleInitial, String LastName, String DateOfBirth, String DateOfEmployment, String Status) { this.ID = ID; this.FirstName = FirstName; this.MiddleInitial = MiddleInitial; this.LastName = LastName; this.DateOfBirth = DateOfBirth; this.DateOfEmployment = DateOfEmployment; this.Status = Status; } public Long getID() { return ID; } public void setID(Long ID) { this.ID = ID; } public String getFirstName() { return FirstName; } public void setFirstName(String FirstName) { this.FirstName = FirstName; } public String getLastName() { return LastName; } public void setLastName(String LastName) { this.LastName = LastName; } public String getMiddleInitial() { return MiddleInitial; } public void setMiddleInitial(String MiddleInitial) { this.MiddleInitial = MiddleInitial; } public String getDateOfBirth() { return DateOfBirth; } public void setDateOfBirth(String DateOfBirth) { this.DateOfBirth = DateOfBirth; } public String getDateOfEmployment() { return DateOfEmployment; } public void setDateOfEmployment(String DateOfEmployment) { this.DateOfEmployment = DateOfEmployment; } public String getStatus() { return Status; } public void setStatus(String Status) { this.Status = Status; } @Override public String toString() { return "Employee [ID=" + ID + ", FirstName=" + FirstName + ", MiddleInitial=" + MiddleInitial + ", LastName=" + LastName + ", DateOfBirth=" + DateOfBirth + ", DateOfEmployment=" + DateOfEmployment + ", Status=" + Status + "]"; } }
3,067
0.699054
0.69449
121
23.347107
26.404892
145
false
false
0
0
0
0
0
0
1.454545
false
false
3
91183f2f79f9aae1842680f1b69be2363a556c1e
17,171,279,304,860
c9977c66ec9a0aa177ad2a2b131ae6bda4d6aa58
/src/day_01/IQ_04_LongestPalindrome.java
8e4bfa76117573409639bb90725605de8ae173ba
[]
no_license
erkandormen/interview_prep
https://github.com/erkandormen/interview_prep
f80a57829a0b756229fdb8cee5bbf9dd9b786936
736f3c1cfcb51cf21ff15b762cd96c1f90027458
refs/heads/master
2023-04-14T23:10:24.690000
2021-04-30T12:09:09
2021-04-30T12:09:09
363,129,248
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package day_01; //TODO /* * * Given a string, find the longest substring which is palindrome. For example, Input# Given string :"fortechproorphcetfor", Output# "techproorphcet" max lenght: 14 Input# Given string :"aacabbacba", Output# "cabbac" max lenght: 6 The simple approach is to check each substring whether the substring is a palindrome or not. To do this first, run three nested loops, the outer two loops pick all substrings one by one by fixing the corner characters, the inner loop checks whether the picked substring is palindrome or not. */ public class IQ_04_LongestPalindrome { public static void main(String[] args) { String str1="fortechproorphcetfor";//3,16-> 16-3=13, How many term is in that boundaries 13+1=14 longestPalindromeSubstring(str1); System.out.println("**************************************"); System.out.println("**************************************"); String str2="aacabbacba"; longestPalindromeSubstring(str2); } public static void longestPalindromeSubstring(String str) { int len = str.length(); int maxLenght=0, startingIndex=0, endingIndex=str.length()-1; int flag; //Define starting index, ending index for(int i=0; i <len; i++) { for(int j=i;j<len;j++) { flag=1;//repsents palindrome //Check palindrome for(int k=0; k<(j-i+1)/2; k++) { if(str.charAt(i+k)!=str.charAt(j-k)) { flag=0; } } // if(flag !=0 && j-i+1>maxLenght) { startingIndex=i; endingIndex=j+1; maxLenght=endingIndex-startingIndex; } } } System.out.println("The given string:"+str); System.out.println("--------------------"); System.out.println("The longest palindrome sub-string is: "+str.substring(startingIndex, endingIndex)); //print max lenght of the sub-string System.out.println("Max lenght of the sub-string is:"+maxLenght); } }
UTF-8
Java
1,888
java
IQ_04_LongestPalindrome.java
Java
[]
null
[]
package day_01; //TODO /* * * Given a string, find the longest substring which is palindrome. For example, Input# Given string :"fortechproorphcetfor", Output# "techproorphcet" max lenght: 14 Input# Given string :"aacabbacba", Output# "cabbac" max lenght: 6 The simple approach is to check each substring whether the substring is a palindrome or not. To do this first, run three nested loops, the outer two loops pick all substrings one by one by fixing the corner characters, the inner loop checks whether the picked substring is palindrome or not. */ public class IQ_04_LongestPalindrome { public static void main(String[] args) { String str1="fortechproorphcetfor";//3,16-> 16-3=13, How many term is in that boundaries 13+1=14 longestPalindromeSubstring(str1); System.out.println("**************************************"); System.out.println("**************************************"); String str2="aacabbacba"; longestPalindromeSubstring(str2); } public static void longestPalindromeSubstring(String str) { int len = str.length(); int maxLenght=0, startingIndex=0, endingIndex=str.length()-1; int flag; //Define starting index, ending index for(int i=0; i <len; i++) { for(int j=i;j<len;j++) { flag=1;//repsents palindrome //Check palindrome for(int k=0; k<(j-i+1)/2; k++) { if(str.charAt(i+k)!=str.charAt(j-k)) { flag=0; } } // if(flag !=0 && j-i+1>maxLenght) { startingIndex=i; endingIndex=j+1; maxLenght=endingIndex-startingIndex; } } } System.out.println("The given string:"+str); System.out.println("--------------------"); System.out.println("The longest palindrome sub-string is: "+str.substring(startingIndex, endingIndex)); //print max lenght of the sub-string System.out.println("Max lenght of the sub-string is:"+maxLenght); } }
1,888
0.647246
0.628178
72
25.222221
26.210272
105
false
false
0
0
0
0
0
0
2.152778
false
false
3
ef1d868ad8da3d66d77bff15a9ce4091d6aa608a
28,784,870,885,121
4c18ef55211126fc5a170ec6ff241968bb6112b8
/src/com/company/Game/PaneGame/Bom/BomBig.java
93877767eaa4b4f766bef7f1bfb1cbe58e77d387
[]
no_license
DatNguyen15399/Boom
https://github.com/DatNguyen15399/Boom
49f91244243229f042350c32da5af298df6f1ec7
73c23d9679aec2fc9e882e7d14d5974212e2fd2e
refs/heads/master
2021-07-16T01:56:11.269000
2020-09-14T04:32:59
2020-09-14T04:32:59
207,462,497
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company.Game.PaneGame.Bom; import com.company.Game.PaneGame.MapGame.InputMap; import com.company.Game.SoundGame; import com.company.Library.libarary; import javax.swing.*; import java.awt.*; public class BomBig extends Bom { private int widthTrai, widthPhai, widthTren, widthDuoi; public BomBig(int x, int y) { super(x, y); } // kiem tra xem bom nổ xong chưa để remove khỏi list bom trong show game public boolean BomNo(Graphics2D g, JPanel panel) { if (frameBom <= Speed_BomNo + 1) { //vẽ trung tam g.drawImage(imageBomNo[0], ToaDoX(), ToaDoY(), panel); if (frameBom == Speed_BomNo + 1) { new SoundGame("Bom").start();// âm thanh SetWidth(); } } else { int a; if (frameBom <= Speed_BomNo + 3) { a = 0; } else { a = 1; } g.drawImage(imageBomNo[a], ToaDoX(), ToaDoY(), panel); //trai if (com.company.Game.PaneGame.MapGame.InputMap.Map[Vitri.y + 1][Vitri.x - 1] != libarary.Tuong) { g.drawImage(imageBomNo[a + 2], ToaDoX() - libarary.WidthOVuong * widthTrai, ToaDoY(), panel); // no trai } //phai if (com.company.Game.PaneGame.MapGame.InputMap.Map[Vitri.y + 1][Vitri.x + 3] != libarary.Tuong) { g.drawImage(imageBomNo[a + 4], ToaDoX() + libarary.WidthOVuong, ToaDoY(), panel);//no phai } //tren if (com.company.Game.PaneGame.MapGame.InputMap.Map[Vitri.y - 1][Vitri.x + 1] != libarary.Tuong) { g.drawImage(imageBomNo[a + 6], ToaDoX(), ToaDoY() - libarary.WidthOVuong * widthTren, panel); // no tren } //duoi if (InputMap.Map[Vitri.y + 3][Vitri.x + 1] != libarary.Tuong) { g.drawImage(imageBomNo[a + 8], ToaDoX(), ToaDoY() + libarary.WidthOVuong, panel); // no duoi } } if (frameBom == Speed_BomNo + 5) { QuetPhamViBomNo(2);// tiêu diệt mục tiêu xung quanh return true; } return false; } public void SetWidth() { widthTrai = 1; if (InputMap.Map[Vitri.y + 1][Vitri.x - 1] == libarary.DiChuyen && InputMap.Map[Vitri.y + 1][Vitri.x - 4] != libarary.Tuong) { widthTrai = 2; } widthPhai = 1; if (InputMap.Map[Vitri.y + 1][Vitri.x + 3] == libarary.DiChuyen && InputMap.Map[Vitri.y + 1][Vitri.x + 6] != libarary.Tuong) { widthPhai = 2; } widthTren = 1; if (InputMap.Map[Vitri.y - 1][Vitri.x + 1] == libarary.DiChuyen && InputMap.Map[Vitri.y - 4][Vitri.x + 1] != libarary.Tuong) { widthTren = 2; } widthDuoi = 1; if (InputMap.Map[Vitri.y + 3][Vitri.x + 1] == libarary.DiChuyen && InputMap.Map[Vitri.y + 6][Vitri.x + 1] != libarary.Tuong) { widthDuoi = 2; } imageBomNo[2] = imageBomNo[2].getScaledInstance(libarary.WidthOVuong * widthTrai, libarary.WidthOVuong, Image.SCALE_SMOOTH); imageBomNo[3] = imageBomNo[3].getScaledInstance(libarary.WidthOVuong * widthTrai, libarary.WidthOVuong, Image.SCALE_SMOOTH); imageBomNo[4] = imageBomNo[4].getScaledInstance(libarary.WidthOVuong * widthPhai, libarary.WidthOVuong, Image.SCALE_SMOOTH); imageBomNo[5] = imageBomNo[5].getScaledInstance(libarary.WidthOVuong * widthPhai, libarary.WidthOVuong, Image.SCALE_SMOOTH); imageBomNo[6] = imageBomNo[6].getScaledInstance(libarary.WidthOVuong, libarary.WidthOVuong * widthTren, Image.SCALE_SMOOTH); imageBomNo[7] = imageBomNo[7].getScaledInstance(libarary.WidthOVuong, libarary.WidthOVuong * widthTren, Image.SCALE_SMOOTH); imageBomNo[8] = imageBomNo[8].getScaledInstance(libarary.WidthOVuong, libarary.WidthOVuong * widthDuoi, Image.SCALE_SMOOTH); imageBomNo[9] = imageBomNo[9].getScaledInstance(libarary.WidthOVuong, libarary.WidthOVuong * widthDuoi, Image.SCALE_SMOOTH); } }
UTF-8
Java
4,085
java
BomBig.java
Java
[]
null
[]
package com.company.Game.PaneGame.Bom; import com.company.Game.PaneGame.MapGame.InputMap; import com.company.Game.SoundGame; import com.company.Library.libarary; import javax.swing.*; import java.awt.*; public class BomBig extends Bom { private int widthTrai, widthPhai, widthTren, widthDuoi; public BomBig(int x, int y) { super(x, y); } // kiem tra xem bom nổ xong chưa để remove khỏi list bom trong show game public boolean BomNo(Graphics2D g, JPanel panel) { if (frameBom <= Speed_BomNo + 1) { //vẽ trung tam g.drawImage(imageBomNo[0], ToaDoX(), ToaDoY(), panel); if (frameBom == Speed_BomNo + 1) { new SoundGame("Bom").start();// âm thanh SetWidth(); } } else { int a; if (frameBom <= Speed_BomNo + 3) { a = 0; } else { a = 1; } g.drawImage(imageBomNo[a], ToaDoX(), ToaDoY(), panel); //trai if (com.company.Game.PaneGame.MapGame.InputMap.Map[Vitri.y + 1][Vitri.x - 1] != libarary.Tuong) { g.drawImage(imageBomNo[a + 2], ToaDoX() - libarary.WidthOVuong * widthTrai, ToaDoY(), panel); // no trai } //phai if (com.company.Game.PaneGame.MapGame.InputMap.Map[Vitri.y + 1][Vitri.x + 3] != libarary.Tuong) { g.drawImage(imageBomNo[a + 4], ToaDoX() + libarary.WidthOVuong, ToaDoY(), panel);//no phai } //tren if (com.company.Game.PaneGame.MapGame.InputMap.Map[Vitri.y - 1][Vitri.x + 1] != libarary.Tuong) { g.drawImage(imageBomNo[a + 6], ToaDoX(), ToaDoY() - libarary.WidthOVuong * widthTren, panel); // no tren } //duoi if (InputMap.Map[Vitri.y + 3][Vitri.x + 1] != libarary.Tuong) { g.drawImage(imageBomNo[a + 8], ToaDoX(), ToaDoY() + libarary.WidthOVuong, panel); // no duoi } } if (frameBom == Speed_BomNo + 5) { QuetPhamViBomNo(2);// tiêu diệt mục tiêu xung quanh return true; } return false; } public void SetWidth() { widthTrai = 1; if (InputMap.Map[Vitri.y + 1][Vitri.x - 1] == libarary.DiChuyen && InputMap.Map[Vitri.y + 1][Vitri.x - 4] != libarary.Tuong) { widthTrai = 2; } widthPhai = 1; if (InputMap.Map[Vitri.y + 1][Vitri.x + 3] == libarary.DiChuyen && InputMap.Map[Vitri.y + 1][Vitri.x + 6] != libarary.Tuong) { widthPhai = 2; } widthTren = 1; if (InputMap.Map[Vitri.y - 1][Vitri.x + 1] == libarary.DiChuyen && InputMap.Map[Vitri.y - 4][Vitri.x + 1] != libarary.Tuong) { widthTren = 2; } widthDuoi = 1; if (InputMap.Map[Vitri.y + 3][Vitri.x + 1] == libarary.DiChuyen && InputMap.Map[Vitri.y + 6][Vitri.x + 1] != libarary.Tuong) { widthDuoi = 2; } imageBomNo[2] = imageBomNo[2].getScaledInstance(libarary.WidthOVuong * widthTrai, libarary.WidthOVuong, Image.SCALE_SMOOTH); imageBomNo[3] = imageBomNo[3].getScaledInstance(libarary.WidthOVuong * widthTrai, libarary.WidthOVuong, Image.SCALE_SMOOTH); imageBomNo[4] = imageBomNo[4].getScaledInstance(libarary.WidthOVuong * widthPhai, libarary.WidthOVuong, Image.SCALE_SMOOTH); imageBomNo[5] = imageBomNo[5].getScaledInstance(libarary.WidthOVuong * widthPhai, libarary.WidthOVuong, Image.SCALE_SMOOTH); imageBomNo[6] = imageBomNo[6].getScaledInstance(libarary.WidthOVuong, libarary.WidthOVuong * widthTren, Image.SCALE_SMOOTH); imageBomNo[7] = imageBomNo[7].getScaledInstance(libarary.WidthOVuong, libarary.WidthOVuong * widthTren, Image.SCALE_SMOOTH); imageBomNo[8] = imageBomNo[8].getScaledInstance(libarary.WidthOVuong, libarary.WidthOVuong * widthDuoi, Image.SCALE_SMOOTH); imageBomNo[9] = imageBomNo[9].getScaledInstance(libarary.WidthOVuong, libarary.WidthOVuong * widthDuoi, Image.SCALE_SMOOTH); } }
4,085
0.593904
0.578909
86
46.313953
45.478146
134
false
false
0
0
0
0
0
0
0.906977
false
false
3