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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1b6a0af05b4299d0ed2388630d855c0dc05448c3 | 6,287,832,149,338 | 44242deb6c01959cff4c9663e50edfc37a833c6c | /srp-binding/src/main/java/org/srplib/binding/Binding.java | 19e0eeadfc4d50108b5535511b3ef3937ee91d34 | [
"Apache-2.0"
] | permissive | apechinsky/srplib | https://github.com/apechinsky/srplib | b468e8f1f260349ffaf43e86fdc7a72dea9322bf | af6b69ca876f091a7eff731bb865aca739790f1b | refs/heads/master | 2023-03-23T18:41:27.176000 | 2017-09-13T10:30:11 | 2017-09-13T10:30:11 | 1,626,476 | 1 | 5 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.srplib.binding;
import org.srplib.conversion.Converter;
import org.srplib.model.ValueModel;
/**
* Binding is an association between two value models.
*
* @author Anton Pechinsky
*/
public interface Binding {
/**
* Returns source model of association.
*
* @return ValueModel value model.
*/
ValueModel getSource();
/**
* Returns target model of association.
*
* @return ValueModel value model.
*/
ValueModel getTarget();
/**
* An optional value converter between models.
*
* @return Converter a converter
*/
Converter getConverter();
}
| UTF-8 | Java | 677 | java | Binding.java | Java | [
{
"context": "ociation between two value models.\r\n *\r\n * @author Anton Pechinsky\r\n */\r\npublic interface Binding {\r\n\r\n /**\r\n ",
"end": 202,
"score": 0.9997682571411133,
"start": 187,
"tag": "NAME",
"value": "Anton Pechinsky"
}
] | null | [] | package org.srplib.binding;
import org.srplib.conversion.Converter;
import org.srplib.model.ValueModel;
/**
* Binding is an association between two value models.
*
* @author <NAME>
*/
public interface Binding {
/**
* Returns source model of association.
*
* @return ValueModel value model.
*/
ValueModel getSource();
/**
* Returns target model of association.
*
* @return ValueModel value model.
*/
ValueModel getTarget();
/**
* An optional value converter between models.
*
* @return Converter a converter
*/
Converter getConverter();
}
| 668 | 0.601182 | 0.601182 | 35 | 17.342857 | 17.172974 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.171429 | false | false | 13 |
0da17ce33983605d6a1ca94dbfd61cba6d1b172e | 15,702,400,480,149 | 81b4700cc8734cff4f915d9427f0a5cf241490a1 | /src/main/java/com/application/icafapi/common/util/AWSUtil.java | f9ad9faa59c0028f5e23ec049d230b0b5a61e385 | [] | no_license | shamoda/ICAF-api | https://github.com/shamoda/ICAF-api | 5799ad6fda01c3cb4257c0875d48a98fb5a0e2df | 680c04f245908226542af7f4bfa8f7120eb6eb96 | refs/heads/master | 2023-05-31T04:22:47.469000 | 2021-06-30T08:14:39 | 2021-06-30T08:14:39 | 366,112,228 | 1 | 0 | null | false | 2021-06-26T18:52:10 | 2021-05-10T16:46:34 | 2021-06-26T17:31:56 | 2021-06-26T18:52:09 | 163 | 0 | 0 | 0 | Java | false | false | package com.application.icafapi.common.util;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.services.s3.S3Client;
import static com.application.icafapi.common.constant.AWS.REGION;
@Service
public class AWSUtil {
private static S3Client s3Client = null;
public static S3Client getS3Client() {
if (s3Client == null) {
s3Client = S3Client.builder().region(REGION).build();
}
return s3Client;
}
private AWSUtil() {}
}
| UTF-8 | Java | 501 | java | AWSUtil.java | Java | [] | null | [] | package com.application.icafapi.common.util;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.services.s3.S3Client;
import static com.application.icafapi.common.constant.AWS.REGION;
@Service
public class AWSUtil {
private static S3Client s3Client = null;
public static S3Client getS3Client() {
if (s3Client == null) {
s3Client = S3Client.builder().region(REGION).build();
}
return s3Client;
}
private AWSUtil() {}
}
| 501 | 0.698603 | 0.678643 | 20 | 24.049999 | 22.363977 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35 | false | false | 13 |
6d3e27b7c7ca443e612c30fa6195c5e08fabd3df | 3,384,434,236,023 | 45407f3162e1657be6bd3273213fc1a444cde445 | /dbclient/src/main/java/ru/kraftn/client/models/Duty.java | ae4fca0634f8bab0cc51a33a5594703c7403ec6d | [] | no_license | kraftn/java-gui-and-database | https://github.com/kraftn/java-gui-and-database | 1912878e55cdf32c05631e48113f7fd68054a7f6 | 4a1dd10ba8bfac4114149ca8369b8d562f6d1666 | refs/heads/master | 2020-05-09T14:50:45.500000 | 2019-11-11T18:53:10 | 2019-11-11T18:53:10 | 181,210,414 | 0 | 0 | null | true | 2019-05-19T19:35:52 | 2019-04-13T18:06:36 | 2019-05-19T19:34:48 | 2019-05-19T19:34:47 | 472 | 0 | 0 | 0 | Java | false | false | package ru.kraftn.client.models;
import javax.persistence.*;
@Entity
@Table(name = "List_Of_Duties")
public class Duty implements AbleToGiveId{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private int id;
@Column(name = "Name", nullable = false)
private String name;
@Column(name = "Value_Of_Duty", nullable = false)
private double valueOfDuty;
@ManyToOne
@JoinColumn(name = "Unit_Of_Measurement", nullable = false)
private Unit unitOfMeasurement;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getValueOfDuty() {
return valueOfDuty;
}
public void setValueOfDuty(double valueOfDuty) {
this.valueOfDuty = valueOfDuty;
}
public Unit getUnitOfMeasurement() {
return unitOfMeasurement;
}
public void setUnitOfMeasurement(Unit unitOfMeasurement) {
this.unitOfMeasurement = unitOfMeasurement;
}
@Override
public String toString() {
return name;
}
}
| UTF-8 | Java | 1,222 | java | Duty.java | Java | [] | null | [] | package ru.kraftn.client.models;
import javax.persistence.*;
@Entity
@Table(name = "List_Of_Duties")
public class Duty implements AbleToGiveId{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private int id;
@Column(name = "Name", nullable = false)
private String name;
@Column(name = "Value_Of_Duty", nullable = false)
private double valueOfDuty;
@ManyToOne
@JoinColumn(name = "Unit_Of_Measurement", nullable = false)
private Unit unitOfMeasurement;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getValueOfDuty() {
return valueOfDuty;
}
public void setValueOfDuty(double valueOfDuty) {
this.valueOfDuty = valueOfDuty;
}
public Unit getUnitOfMeasurement() {
return unitOfMeasurement;
}
public void setUnitOfMeasurement(Unit unitOfMeasurement) {
this.unitOfMeasurement = unitOfMeasurement;
}
@Override
public String toString() {
return name;
}
}
| 1,222 | 0.633388 | 0.633388 | 59 | 19.711864 | 18.40049 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.305085 | false | false | 13 |
169e2e0f937d68c1f2974c772445fb4f207eb376 | 5,729,486,378,058 | 4cbcff88e1125679bd3d2a11b0e4e5b3250f5be8 | /library/src/main/java/com/qiniu/android/storage/serverConfig/ServerUserConfig.java | 32d4b4ea2c25dec7e51fe615a5e1c18db7fc5419 | [
"MIT"
] | permissive | qiniu/android-sdk | https://github.com/qiniu/android-sdk | f157c8095a84fb344e54775e0b94ca55917b4bda | 63e06c2b10d21ee243ab5653d173929f6316fe31 | refs/heads/master | 2023-08-18T15:44:43.148000 | 2023-08-07T07:01:32 | 2023-08-07T07:01:32 | 5,308,654 | 643 | 248 | MIT | false | 2023-08-07T07:01:34 | 2012-08-06T01:34:03 | 2023-07-10T01:24:37 | 2023-08-07T07:01:33 | 4,902 | 618 | 227 | 4 | Java | false | false | package com.qiniu.android.storage.serverConfig;
import com.qiniu.android.utils.Utils;
import org.json.JSONException;
import org.json.JSONObject;
public class ServerUserConfig {
private long timestamp;
private long ttl = 10;
private Boolean http3Enable;
private Boolean networkCheckEnable;
private JSONObject info;
public ServerUserConfig(JSONObject info) {
if (info == null) {
return;
}
this.info = info;
this.ttl = info.optLong("ttl", 5 * 60);
if (info.opt("timestamp") != null) {
this.timestamp = info.optLong("timestamp");
}
if (this.timestamp == 0) {
this.timestamp = Utils.currentSecondTimestamp();
try {
info.putOpt("timestamp", this.timestamp);
} catch (JSONException ignored) {
}
}
JSONObject http3 = info.optJSONObject("http3");
if (http3 != null && http3.opt("enabled") != null) {
this.http3Enable = http3.optBoolean("enabled");
}
JSONObject networkCheck = info.optJSONObject("network_check");
if (networkCheck != null && networkCheck.opt("enabled") != null) {
this.networkCheckEnable = networkCheck.optBoolean("enabled");
}
}
public Boolean getHttp3Enable() {
return http3Enable;
}
public Boolean getNetworkCheckEnable() {
return networkCheckEnable;
}
public JSONObject getInfo() {
return info;
}
public boolean isValid() {
return Utils.currentSecondTimestamp() < (this.timestamp + this.ttl);
}
}
| UTF-8 | Java | 1,638 | java | ServerUserConfig.java | Java | [] | null | [] | package com.qiniu.android.storage.serverConfig;
import com.qiniu.android.utils.Utils;
import org.json.JSONException;
import org.json.JSONObject;
public class ServerUserConfig {
private long timestamp;
private long ttl = 10;
private Boolean http3Enable;
private Boolean networkCheckEnable;
private JSONObject info;
public ServerUserConfig(JSONObject info) {
if (info == null) {
return;
}
this.info = info;
this.ttl = info.optLong("ttl", 5 * 60);
if (info.opt("timestamp") != null) {
this.timestamp = info.optLong("timestamp");
}
if (this.timestamp == 0) {
this.timestamp = Utils.currentSecondTimestamp();
try {
info.putOpt("timestamp", this.timestamp);
} catch (JSONException ignored) {
}
}
JSONObject http3 = info.optJSONObject("http3");
if (http3 != null && http3.opt("enabled") != null) {
this.http3Enable = http3.optBoolean("enabled");
}
JSONObject networkCheck = info.optJSONObject("network_check");
if (networkCheck != null && networkCheck.opt("enabled") != null) {
this.networkCheckEnable = networkCheck.optBoolean("enabled");
}
}
public Boolean getHttp3Enable() {
return http3Enable;
}
public Boolean getNetworkCheckEnable() {
return networkCheckEnable;
}
public JSONObject getInfo() {
return info;
}
public boolean isValid() {
return Utils.currentSecondTimestamp() < (this.timestamp + this.ttl);
}
}
| 1,638 | 0.59768 | 0.588523 | 62 | 25.419355 | 22.72809 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.403226 | false | false | 13 |
799ba65ca51cd1288c2225b51755c8abebfb80fd | 7,524,782,709,591 | 8c478a2ce3c1f6d69786834c11da80f6dd3876f5 | /DriverBookingApp/src/main/java/com/bookingapp/service/AdminService.java | 5aaa3e54da1cacb89606d265b0ec5bcf4b561788 | [] | no_license | rachit2402/DriverBookingApplication | https://github.com/rachit2402/DriverBookingApplication | 925d95d64617772fcd85be2fdd0964e17e60d928 | 0303f80db558b4c68d026b011041ec8d2d959f26 | refs/heads/master | 2023-04-08T09:13:58.112000 | 2021-04-18T15:19:32 | 2021-04-18T15:19:32 | 356,202,420 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bookingapp.service;
import java.util.List;
import com.bookingapp.exceptions.DriverDoesNotExistException;
import com.bookingapp.users.Admin;
public interface AdminService {
void addDriver(Admin admin);
void updateDriver(double charges,int driverId) throws DriverDoesNotExistException;
void deleteDriver(int driverId) throws DriverDoesNotExistException;
List<Admin> getAllDriver();
}
| UTF-8 | Java | 403 | java | AdminService.java | Java | [] | null | [] | package com.bookingapp.service;
import java.util.List;
import com.bookingapp.exceptions.DriverDoesNotExistException;
import com.bookingapp.users.Admin;
public interface AdminService {
void addDriver(Admin admin);
void updateDriver(double charges,int driverId) throws DriverDoesNotExistException;
void deleteDriver(int driverId) throws DriverDoesNotExistException;
List<Admin> getAllDriver();
}
| 403 | 0.828784 | 0.828784 | 14 | 27.785715 | 26.205721 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 13 |
f1ddeba82d9fc54fac03c455759c43cdbf4884f3 | 17,987,323,044,918 | 890fb079c3258115a1f6b87b672cb0494c23349a | /core/src/main/java/uk/co/pbellchambers/maceswinger/map/MapObject.java | 03787a7949be5041d950f6e6025eb682128332a8 | [
"MIT"
] | permissive | pbellchambers/Mace-Swinger | https://github.com/pbellchambers/Mace-Swinger | 22230e4b8debfab97bce85f3c9e920e4659b5dad | ac41ba049164e04b9fe130a771873e71220b06e2 | refs/heads/master | 2020-07-26T02:33:57.751000 | 2016-11-16T21:15:13 | 2016-11-16T21:15:13 | 73,637,659 | 1 | 0 | null | true | 2016-11-13T19:27:00 | 2016-11-13T19:26:57 | 2016-10-07T23:50:37 | 2014-11-20T00:25:10 | 42,940 | 0 | 0 | 0 | null | null | null | package uk.co.pbellchambers.maceswinger.map;
import org.magnos.entity.EntityList;
public interface MapObject {
public Object spawn(EntityList list, int x, int y, String... params);
}
| UTF-8 | Java | 190 | java | MapObject.java | Java | [
{
"context": "package uk.co.pbellchambers.maceswinger.map;\n\nimport org.magnos.entity.Entity",
"end": 27,
"score": 0.9955928921699524,
"start": 14,
"tag": "USERNAME",
"value": "pbellchambers"
}
] | null | [] | package uk.co.pbellchambers.maceswinger.map;
import org.magnos.entity.EntityList;
public interface MapObject {
public Object spawn(EntityList list, int x, int y, String... params);
}
| 190 | 0.757895 | 0.757895 | 8 | 22.75 | 25.508577 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 13 |
02ab4f90f279d36107799f03a691cbcf8e3b09ca | 22,067,541,971,576 | b37f05f31bd4b6961053b27e6bd69d4b705fd2e7 | /src-demo/com/weibo/sdk/android/demo/UserInfoActivity.java | b11440f82e7be25f98828243086c77a76d31d0e6 | [] | no_license | besky86/GraduationProject | https://github.com/besky86/GraduationProject | 9ca03dc606110d9ca57168fd0c03a5a1fa8dc182 | 47e71565706d7d253bc53a51a6c13b746e02f371 | refs/heads/master | 2020-06-05T02:01:00.904000 | 2013-06-01T03:07:49 | 2013-06-01T03:07:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.weibo.sdk.android.demo;
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.FriendshipsAPI;
import com.weibo.sdk.android.api.UsersAPI;
import com.weibo.sdk.android.entity.User;
import com.weibo.sdk.android.net.RequestListener;
import com.weibo.sdk.android.requestlisteners.NullRequestListener;
import com.weibo.sdk.android.util.AsynImageLoader;
import com.weibo.sdk.android.util.ImageCallback;
import com.weibo.sdk.android.util.StringUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.*;
@SuppressLint("HandlerLeak")
public class UserInfoActivity extends Activity {
private long userId = 0;
private Button btn_back;
private Button btn_home;
private ImageView user_head;
private Button btn_follow;
private LinearLayout followLayout;
private LinearLayout weiboLayout;
private LinearLayout followerLayout;
private LinearLayout favLayout;
private TextView user_name;
private TextView tv_location;
private TextView tv_description;
private TextView num_follow;
private TextView num_weibo;
private TextView num_follower;
private TextView num_fav;
private User user;
Handler h = new Handler() {
public void handleMessage(Message msg) {
try {
user = User.getUserByJSON(new JSONObject(msg.getData()
.getString("user")));
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Util.showToast(UserInfoActivity.this, "数据解析异常");
}
if (user != null) {
Drawable image = AsynImageLoader.loadDrawable(
user.getProfile_image_url(), user_head,
new ImageCallback() {
@Override
public void imageSet(Drawable drawable,
ImageView imageView) {
imageView.setImageDrawable(drawable);
}
});
if (image != null) {
user_head.setImageDrawable(image);
}
user_name.setText(user.getScreen_name());
String location = user.getLocation();
if (StringUtil.isEmpty(location)) {
tv_location.setText("其他");
}
// Log.v("userinfo",location);
else
tv_location.setText(location);
String description = user.getDescriprtion();
if (StringUtil.isEmpty(description)) {
tv_description.setText("该用户未设置任何个人说明");
}
else
tv_description.setText(description);
num_follow.setText("" + user.getFriends_count());
num_follower.setText("" + user.getFollowers_count());
num_weibo.setText("" + user.getStatuses_count());
if (user.isFollowing()) {
btn_follow
.setBackgroundResource(R.drawable.btn_unfollow_shape);
btn_follow.setText(R.string.unfollow);
}
// 当是非用户一致时,不显示关注按钮
if (!user.getIdstr().equals(
MainTabActivity.accessToken.getUid()))
btn_follow.setVisibility(View.VISIBLE);
num_fav.setText("" + user.getFavourites_count());
}
}
};
/**
* 创建一个新的实例 UserInfoActivity.
*
*/
public UserInfoActivity() {
super();
// TODO Auto-generated constructor stub
}
/**
* 创建一个新的实例 UserInfoActivity.
*
* @param userId
*/
public UserInfoActivity(long userId) {
super();
this.userId = userId;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_info);
if (userId == 0) {
userId = getIntent().getLongExtra("user_id", 0l);
Log.e("Error", "" + userId);
}
getViews();
Log.v("toke你", MainTabActivity.accessToken.getToken());
new UsersAPI(MainTabActivity.accessToken).show(userId,
new GetUserRequestListenerIn());
setListeners();
}
private void getViews() {
btn_back = (Button) findViewById(R.id.btn_back);
btn_home = (Button) findViewById(R.id.btn_home);
user_name = (TextView) findViewById(R.id.user_name);
user_head = (ImageView) findViewById(R.id.user_head);
btn_follow = (Button) findViewById(R.id.btn_follow);
followLayout = (LinearLayout) findViewById(R.id.follow_layout);;
weiboLayout = (LinearLayout) findViewById(R.id.weibo_layout);
followerLayout = (LinearLayout) findViewById(R.id.follower_layout);
favLayout = (LinearLayout) findViewById(R.id.fav_layout);
tv_location = (TextView) findViewById(R.id.tv_location);
tv_description = (TextView) findViewById(R.id.tv_despription);
num_follow = (TextView) findViewById(R.id.num_follow);
num_weibo = (TextView) findViewById(R.id.num_weibo);
num_follower = (TextView) findViewById(R.id.num_follower);
num_fav = (TextView) findViewById(R.id.num_fav);
if(userId ==Long.parseLong( MainTabActivity.accessToken.getUid())){
btn_back.setVisibility(View.INVISIBLE);
btn_home.setVisibility(View.INVISIBLE);
}
}
private void setListeners() {
btn_back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
UserInfoActivity.this.finish();
}
});
followLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(UserInfoActivity.this,
FollowingActivity.class);
intent.putExtra("user_id", user.getId());
intent.putExtra("following_num", user.getFriends_count());
startActivity(intent);
}
});
followerLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(UserInfoActivity.this,
FollowerListActivity.class);
intent.putExtra("user_id", user.getId());
intent.putExtra("follower_num", user.getFollowers_count());
startActivity(intent);
}
});
btn_follow.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (btn_follow.getText().toString().equals("关注")) {
new FriendshipsAPI(MainTabActivity.accessToken).create(
userId, user.getScreen_name(),
new NullRequestListener());
btn_follow
.setBackgroundResource(R.drawable.btn_unfollow_shape);
btn_follow.setText(R.string.unfollow);
}
else {
new FriendshipsAPI(MainTabActivity.accessToken).destroy(
userId, null, new NullRequestListener());
btn_follow
.setBackgroundResource(R.drawable.btn_follow_shape);
btn_follow.setText(R.string.follow);
}
}
});
weiboLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if (user != null && user.getId() > 0) {
// TODO Auto-generated method stub
Intent intent = new Intent(UserInfoActivity.this,
UserWeiboActivity.class);
intent.putExtra("user_id", user.getId());
// intent.putExtra("follower_num",
// user.getFollowers_count());
startActivity(intent);
}
}
});
btn_home.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(UserInfoActivity.this,
MainTabActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
}
class GetUserRequestListenerIn implements RequestListener {
@Override
public void onComplete(String response) {
Message msg = new Message();
msg.getData().putString("user", response);
UserInfoActivity.this.h.sendMessage(msg);
}
@Override
public void onIOException(IOException e) {
// TODO Auto-generated method stub
// Util.showToast(UserInfoActivity.this, "操作异常");
Toast toast = Toast.makeText(UserInfoActivity.this, "操作异常",
Toast.LENGTH_SHORT);
toast.show();
}
@Override
public void onError(WeiboException e) {
// TODO Auto-generated method stub
Log.e("Error", e.getMessage());
Util.showToast(UserInfoActivity.this, "操作失败");
}
}
}
| UTF-8 | Java | 8,422 | java | UserInfoActivity.java | Java | [] | null | [] | package com.weibo.sdk.android.demo;
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.FriendshipsAPI;
import com.weibo.sdk.android.api.UsersAPI;
import com.weibo.sdk.android.entity.User;
import com.weibo.sdk.android.net.RequestListener;
import com.weibo.sdk.android.requestlisteners.NullRequestListener;
import com.weibo.sdk.android.util.AsynImageLoader;
import com.weibo.sdk.android.util.ImageCallback;
import com.weibo.sdk.android.util.StringUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.*;
@SuppressLint("HandlerLeak")
public class UserInfoActivity extends Activity {
private long userId = 0;
private Button btn_back;
private Button btn_home;
private ImageView user_head;
private Button btn_follow;
private LinearLayout followLayout;
private LinearLayout weiboLayout;
private LinearLayout followerLayout;
private LinearLayout favLayout;
private TextView user_name;
private TextView tv_location;
private TextView tv_description;
private TextView num_follow;
private TextView num_weibo;
private TextView num_follower;
private TextView num_fav;
private User user;
Handler h = new Handler() {
public void handleMessage(Message msg) {
try {
user = User.getUserByJSON(new JSONObject(msg.getData()
.getString("user")));
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Util.showToast(UserInfoActivity.this, "数据解析异常");
}
if (user != null) {
Drawable image = AsynImageLoader.loadDrawable(
user.getProfile_image_url(), user_head,
new ImageCallback() {
@Override
public void imageSet(Drawable drawable,
ImageView imageView) {
imageView.setImageDrawable(drawable);
}
});
if (image != null) {
user_head.setImageDrawable(image);
}
user_name.setText(user.getScreen_name());
String location = user.getLocation();
if (StringUtil.isEmpty(location)) {
tv_location.setText("其他");
}
// Log.v("userinfo",location);
else
tv_location.setText(location);
String description = user.getDescriprtion();
if (StringUtil.isEmpty(description)) {
tv_description.setText("该用户未设置任何个人说明");
}
else
tv_description.setText(description);
num_follow.setText("" + user.getFriends_count());
num_follower.setText("" + user.getFollowers_count());
num_weibo.setText("" + user.getStatuses_count());
if (user.isFollowing()) {
btn_follow
.setBackgroundResource(R.drawable.btn_unfollow_shape);
btn_follow.setText(R.string.unfollow);
}
// 当是非用户一致时,不显示关注按钮
if (!user.getIdstr().equals(
MainTabActivity.accessToken.getUid()))
btn_follow.setVisibility(View.VISIBLE);
num_fav.setText("" + user.getFavourites_count());
}
}
};
/**
* 创建一个新的实例 UserInfoActivity.
*
*/
public UserInfoActivity() {
super();
// TODO Auto-generated constructor stub
}
/**
* 创建一个新的实例 UserInfoActivity.
*
* @param userId
*/
public UserInfoActivity(long userId) {
super();
this.userId = userId;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_info);
if (userId == 0) {
userId = getIntent().getLongExtra("user_id", 0l);
Log.e("Error", "" + userId);
}
getViews();
Log.v("toke你", MainTabActivity.accessToken.getToken());
new UsersAPI(MainTabActivity.accessToken).show(userId,
new GetUserRequestListenerIn());
setListeners();
}
private void getViews() {
btn_back = (Button) findViewById(R.id.btn_back);
btn_home = (Button) findViewById(R.id.btn_home);
user_name = (TextView) findViewById(R.id.user_name);
user_head = (ImageView) findViewById(R.id.user_head);
btn_follow = (Button) findViewById(R.id.btn_follow);
followLayout = (LinearLayout) findViewById(R.id.follow_layout);;
weiboLayout = (LinearLayout) findViewById(R.id.weibo_layout);
followerLayout = (LinearLayout) findViewById(R.id.follower_layout);
favLayout = (LinearLayout) findViewById(R.id.fav_layout);
tv_location = (TextView) findViewById(R.id.tv_location);
tv_description = (TextView) findViewById(R.id.tv_despription);
num_follow = (TextView) findViewById(R.id.num_follow);
num_weibo = (TextView) findViewById(R.id.num_weibo);
num_follower = (TextView) findViewById(R.id.num_follower);
num_fav = (TextView) findViewById(R.id.num_fav);
if(userId ==Long.parseLong( MainTabActivity.accessToken.getUid())){
btn_back.setVisibility(View.INVISIBLE);
btn_home.setVisibility(View.INVISIBLE);
}
}
private void setListeners() {
btn_back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
UserInfoActivity.this.finish();
}
});
followLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(UserInfoActivity.this,
FollowingActivity.class);
intent.putExtra("user_id", user.getId());
intent.putExtra("following_num", user.getFriends_count());
startActivity(intent);
}
});
followerLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(UserInfoActivity.this,
FollowerListActivity.class);
intent.putExtra("user_id", user.getId());
intent.putExtra("follower_num", user.getFollowers_count());
startActivity(intent);
}
});
btn_follow.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (btn_follow.getText().toString().equals("关注")) {
new FriendshipsAPI(MainTabActivity.accessToken).create(
userId, user.getScreen_name(),
new NullRequestListener());
btn_follow
.setBackgroundResource(R.drawable.btn_unfollow_shape);
btn_follow.setText(R.string.unfollow);
}
else {
new FriendshipsAPI(MainTabActivity.accessToken).destroy(
userId, null, new NullRequestListener());
btn_follow
.setBackgroundResource(R.drawable.btn_follow_shape);
btn_follow.setText(R.string.follow);
}
}
});
weiboLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if (user != null && user.getId() > 0) {
// TODO Auto-generated method stub
Intent intent = new Intent(UserInfoActivity.this,
UserWeiboActivity.class);
intent.putExtra("user_id", user.getId());
// intent.putExtra("follower_num",
// user.getFollowers_count());
startActivity(intent);
}
}
});
btn_home.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(UserInfoActivity.this,
MainTabActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
}
class GetUserRequestListenerIn implements RequestListener {
@Override
public void onComplete(String response) {
Message msg = new Message();
msg.getData().putString("user", response);
UserInfoActivity.this.h.sendMessage(msg);
}
@Override
public void onIOException(IOException e) {
// TODO Auto-generated method stub
// Util.showToast(UserInfoActivity.this, "操作异常");
Toast toast = Toast.makeText(UserInfoActivity.this, "操作异常",
Toast.LENGTH_SHORT);
toast.show();
}
@Override
public void onError(WeiboException e) {
// TODO Auto-generated method stub
Log.e("Error", e.getMessage());
Util.showToast(UserInfoActivity.this, "操作失败");
}
}
}
| 8,422 | 0.700531 | 0.699324 | 331 | 24.039274 | 21.119892 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.595166 | false | false | 13 |
64524944732720ace82c34abaf4ada43988070e9 | 24,215,025,621,465 | de903af69178dd689a24b3187328c11df89091e7 | /java/Counting Elements/FrogRiverOne.java | 445cc9dd49c94c9c57c5982e1ddd5aa486e93123 | [] | no_license | nwyee/Codility | https://github.com/nwyee/Codility | 7034e67e6fc5f08a7202b900a840b3bbddd97588 | d75ac072b7c65e11207d186ea3e2a019b8c8a052 | refs/heads/master | 2021-08-06T15:04:54.566000 | 2021-07-04T14:39:58 | 2021-07-04T14:39:58 | 137,974,082 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
https://app.codility.com/programmers/lessons/4-counting_elements/frog_river_one/
https://app.codility.com/demo/results/trainingWCUA4N-MFH/
*/
class Solution {
public int solution(int X, int[] A) {
// write your code in Java SE 8
int step = 0;
boolean[] hasLeaf = new boolean[X+1];
for(int i = 0 ; i < A.length; i++) {
if(!hasLeaf[A[i]] && A[i] <= X) {
hasLeaf[A[i]] = true;
step++;
}
if(step == X) return i;
}
return -1;
}
} | UTF-8 | Java | 556 | java | FrogRiverOne.java | Java | [] | null | [] | /*
https://app.codility.com/programmers/lessons/4-counting_elements/frog_river_one/
https://app.codility.com/demo/results/trainingWCUA4N-MFH/
*/
class Solution {
public int solution(int X, int[] A) {
// write your code in Java SE 8
int step = 0;
boolean[] hasLeaf = new boolean[X+1];
for(int i = 0 ; i < A.length; i++) {
if(!hasLeaf[A[i]] && A[i] <= X) {
hasLeaf[A[i]] = true;
step++;
}
if(step == X) return i;
}
return -1;
}
} | 556 | 0.496403 | 0.483813 | 23 | 23.217392 | 21.779442 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.391304 | false | false | 13 |
0ba9759bdad8a355c56684cd81a962dcb4c649f3 | 31,207,232,377,681 | 1b27d2ef93ca2374a3202673c22f4a6f8920402a | /app/src/main/java/xyz/chaisong/cskitdemo/network/response/RespEntity.java | 72aa3764e10dc0a73eef6481074b0fab7c0ff702 | [] | no_license | droison/CSKit | https://github.com/droison/CSKit | bdbeba24f1eafa0e27adeed576c0ab220e218338 | ff6d4f11e79a023dc2396ba5a435156b4be7e831 | refs/heads/master | 2020-05-21T04:28:23.798000 | 2018-07-27T15:15:02 | 2018-07-27T15:15:02 | 54,967,823 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package xyz.chaisong.cskitdemo.network.response;
import java.util.Map;
/**
* Created by song on 15/11/27.
*/
public class RespEntity<T extends RespBaseMeta> {
private T responseMeta;
private HttpResponseMeta httpResponseMeta;
private boolean isCache;
private String responseString;
public boolean isCache() {
return isCache;
}
public void setCache(boolean cache) {
isCache = cache;
}
public HttpResponseMeta getHttpResponseMeta() {
return httpResponseMeta;
}
public void setHttpResponseMeta(HttpResponseMeta httpResponseMeta) {
this.httpResponseMeta = httpResponseMeta;
}
public String getResponseString() {
return responseString;
}
public void setResponseString(String responseString) {
this.responseString = responseString;
}
public T getResponseMeta() {
return responseMeta;
}
public void setResponseMeta(T responseMeta) {
this.responseMeta = responseMeta;
}
public static class HttpResponseMeta {
public final int statusCode;
/** Response headers. */
public final Map<String, String> headers;
/** True if the server returned a 304 (Not Modified). */
public final boolean notModified;
/** Network roundtrip time in milliseconds. */
public final long networkTimeMs;
public HttpResponseMeta(int statusCode, Map<String, String> headers,
boolean notModified, long networkTimeMs) {
this.statusCode = statusCode;
this.headers = headers;
this.notModified = notModified;
this.networkTimeMs = networkTimeMs;
}
}
public RespEntity<RespBaseMeta> convertBase() {
RespEntity<RespBaseMeta> result = new RespEntity<RespBaseMeta>();
result.setResponseMeta((RespBaseMeta) responseMeta);
result.setHttpResponseMeta(httpResponseMeta);
return result;
}
} | UTF-8 | Java | 1,995 | java | RespEntity.java | Java | [
{
"context": "esponse;\n\nimport java.util.Map;\n\n/**\n * Created by song on 15/11/27.\n */\npublic class RespEntity<T extend",
"end": 95,
"score": 0.8644827604293823,
"start": 91,
"tag": "USERNAME",
"value": "song"
}
] | null | [] | package xyz.chaisong.cskitdemo.network.response;
import java.util.Map;
/**
* Created by song on 15/11/27.
*/
public class RespEntity<T extends RespBaseMeta> {
private T responseMeta;
private HttpResponseMeta httpResponseMeta;
private boolean isCache;
private String responseString;
public boolean isCache() {
return isCache;
}
public void setCache(boolean cache) {
isCache = cache;
}
public HttpResponseMeta getHttpResponseMeta() {
return httpResponseMeta;
}
public void setHttpResponseMeta(HttpResponseMeta httpResponseMeta) {
this.httpResponseMeta = httpResponseMeta;
}
public String getResponseString() {
return responseString;
}
public void setResponseString(String responseString) {
this.responseString = responseString;
}
public T getResponseMeta() {
return responseMeta;
}
public void setResponseMeta(T responseMeta) {
this.responseMeta = responseMeta;
}
public static class HttpResponseMeta {
public final int statusCode;
/** Response headers. */
public final Map<String, String> headers;
/** True if the server returned a 304 (Not Modified). */
public final boolean notModified;
/** Network roundtrip time in milliseconds. */
public final long networkTimeMs;
public HttpResponseMeta(int statusCode, Map<String, String> headers,
boolean notModified, long networkTimeMs) {
this.statusCode = statusCode;
this.headers = headers;
this.notModified = notModified;
this.networkTimeMs = networkTimeMs;
}
}
public RespEntity<RespBaseMeta> convertBase() {
RespEntity<RespBaseMeta> result = new RespEntity<RespBaseMeta>();
result.setResponseMeta((RespBaseMeta) responseMeta);
result.setHttpResponseMeta(httpResponseMeta);
return result;
}
} | 1,995 | 0.657143 | 0.652632 | 69 | 27.927536 | 22.790361 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.449275 | false | false | 13 |
2a1592d3513d0b8b1557c46e8401828fad8bae75 | 15,599,321,229,321 | e14b16cf11d20fc07a59626547902193d6c246d9 | /WAGDEV_heromancer/Setting.java.java | 8c83bfe8c706eb3c73df0761dd23acac31a71a59 | [] | no_license | yu-podong/OpenSourceDevelopment | https://github.com/yu-podong/OpenSourceDevelopment | 523c49786ec8cb41897ce9cfa77cc618a4c658a0 | ae27b5fa40ec3d37557bafef355db2df2ea81681 | refs/heads/main | 2023-01-23T12:49:00.487000 | 2020-12-04T07:28:50 | 2020-12-04T07:28:50 | 318,410,327 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wagdev.heromancer;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.Switch;
import com.wagdev.heromancer.R;
public class Setting extends AppCompatActivity {
public static boolean soundOnOff = true; //스위치 on/off 여부 저장
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//타이틀바 없애기
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_setting);
//sound on/off 관련
@SuppressLint("UseSwitchCompatOrMaterialCode") Switch sound =(Switch)findViewById(R.id.soundSwitch);
sound.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(isChecked){
soundOnOff = true;
MainActivity.mediaPlayer.start();
//게임의 모든 사운드 on
}
else{
soundOnOff = false;
MainActivity.mediaPlayer.pause();
//게임의 모든 사운드 off
}
}
});
}
@Override
public void onBackPressed() {
finish();
}
} | UTF-8 | Java | 1,737 | java | Setting.java.java | Java | [] | null | [] | package com.wagdev.heromancer;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.Switch;
import com.wagdev.heromancer.R;
public class Setting extends AppCompatActivity {
public static boolean soundOnOff = true; //스위치 on/off 여부 저장
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//타이틀바 없애기
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_setting);
//sound on/off 관련
@SuppressLint("UseSwitchCompatOrMaterialCode") Switch sound =(Switch)findViewById(R.id.soundSwitch);
sound.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(isChecked){
soundOnOff = true;
MainActivity.mediaPlayer.start();
//게임의 모든 사운드 on
}
else{
soundOnOff = false;
MainActivity.mediaPlayer.pause();
//게임의 모든 사운드 off
}
}
});
}
@Override
public void onBackPressed() {
finish();
}
} | 1,737 | 0.627615 | 0.627615 | 53 | 29.603773 | 23.69009 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.490566 | false | false | 13 |
c1b8631d464dc15a3ab4d402bc1613da1557421c | 39,247,411,172,639 | 07f2fa83cafb993cc107825223dc8279969950dd | /game_logic_server/src/main/java/com/xgame/logic/server/game/bag/entity/DeductItem.java | 339594868b5b9c4e2c6842419cb903220c72c35d | [] | no_license | hw233/x2-slg-java | https://github.com/hw233/x2-slg-java | 3f12a8ed700e88b81057bccc7431237fae2c0ff9 | 03dcdab55e94ee4450625404f6409b1361794cbf | refs/heads/master | 2020-04-27T15:42:10.982000 | 2018-09-27T08:35:27 | 2018-09-27T08:35:27 | 174,456,389 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xgame.logic.server.game.bag.entity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;
import com.xgame.config.items.ItemsPir;
import com.xgame.config.items.ItemsPirFactory;
import com.xgame.logic.server.core.gamelog.constant.GameLogSource;
import com.xgame.logic.server.core.gamelog.event.EventBus;
import com.xgame.logic.server.game.bag.converter.ItemConverter;
import com.xgame.logic.server.game.bag.entity.eventmodel.ItemChangeEventObject;
import com.xgame.logic.server.game.player.entity.Player;
import com.xgame.logic.server.game.player.entity.PlayerBag;
/**
* 道具扣减
* @author jacky.jiang
*
*/
@Component
public class DeductItem {
/**
* 判断道具是否足够
* @param tId 模板id
* @param num
* @return false 数量不足,true数量满足
*/
public boolean checkDeductItem(Player player, int tId, int num) {
ItemsPir config = ItemsPirFactory.get(tId);
if(config == null) {
return false;
}
int playerNum = player.roleInfo().getPlayerBag().getItemNum(tId);
if(playerNum < num) {
return false;
}
return true;
}
/**
* 删除玩家道具, 推包
* <ul>说明 : 扣除道具从最少的开始扣除<ul>
* @param tId
* @param num
*/
public int deductItem(Player player, int tId, int num, GameLogSource gameLogSource) {
PlayerBag bag = player.roleInfo().getPlayerBag();
List<Item> playerItem = player.roleInfo().getPlayerBag().getPlayerItem(tId);
Collections.sort(playerItem);
// 扣除道具从最少的开始扣除
List<Item> resultList = new ArrayList<>();
Iterator<Item> iterator = playerItem.iterator();
while (iterator.hasNext()) {
Item item = (Item) iterator.next();
int tmp = item.getNum();
item.setNum(item.getNum() - num);
num -= tmp;
if (item.getNum() <= 0) {
// 已使用完,从背包移除道具
bag.getItemTable().remove(item.getId());
resultList.add(Item.valueOf(item.getItemId(), 0, item.getId()));
} else {
resultList.add(item);
break;
}
}
// 推包
player.send(ItemConverter.getMsgItems(resultList));
// 记录日志
int resultNum = player.roleInfo().getPlayerBag().getItemNum(tId);
EventBus.getSelf().fireEvent(new ItemChangeEventObject(tId, player, resultNum + num, resultNum, ItemChangeEventObject.REMOVE, gameLogSource, 0,ItemChangeEventObject.ITEM_TYPE));
return num;
}
/**
* 删除玩家道具, 推包
* <ul>说明 : 扣除道具从最少的开始扣除<ul>
* @param uId
* @param num
*/
public boolean deductItem(Player player, long uId, int num, GameLogSource gameLogSource) {
PlayerBag bag = player.roleInfo().getPlayerBag();
Item item= player.roleInfo().getPlayerBag().getPlayerItem(uId);
if(item.getNum() < num) {
return false;
}
int tmp = item.getNum();
item.setNum(item.getNum() - num);
num -= tmp;
List<Item> items = new ArrayList<>();
if (item.getNum() == 0) {
// 已使用完,从背包移除道具
bag.getItemTable().remove(item.getId());
items.add(Item.valueOf(item.getItemId(), 0, item.getId()));
} else {
items.add(item);
}
// 记录日志
int resultNum = player.roleInfo().getPlayerBag().getItemNum(item.getItemId());
EventBus.getSelf().fireEvent(new ItemChangeEventObject(item.getItemId(), player, resultNum + num, resultNum, ItemChangeEventObject.REMOVE, gameLogSource, 0,ItemChangeEventObject.ITEM_TYPE));
// 推包
player.send(ItemConverter.getMsgItems(items));
return true;
}
/**
* 使用带有来源的道具
* @param player
* @param tId
* @param num
* @return
*/
public Map<Integer, Integer> deductOriginItem(Player player,int tId, int num, GameLogSource gameLogSource) {
PlayerBag bag = player.roleInfo().getPlayerBag();
List<Item> playerItem = player.roleInfo().getPlayerBag().getPlayerItem(tId);
Collections.sort(playerItem);
Collections.reverse(playerItem);
// 扣除道具从最少的开始扣除
Iterator<Item> iterator = playerItem.iterator();
Map<Integer, Integer> resultMap = new HashMap<>();
List<Item> items = new ArrayList<>();
while (iterator.hasNext()) {
Item item = (Item) iterator.next();
int tmp = item.getNum();
int deductNum = item.getNum() - num;
item.setNum(deductNum);
num -= tmp;
items.add(item);
if (item.getNum() <= 0) {
// 已使用完,从背包移除道具
bag.getItemTable().remove(item.getId());
resultMap.putAll(item.getOriginInfo());
} else {
// 处理带有来源的道具信息
int originDeductNum = deductNum;
Map<Integer, Integer> originInfo = item.getOriginInfo();
Iterator<java.util.Map.Entry<Integer, Integer>> iter = originInfo.entrySet().iterator();
while (iter.hasNext()) {
java.util.Map.Entry<Integer, Integer> entry = iter.next();
Integer count = entry.getValue();
Integer key = entry.getKey();
if (count != null && key != null) {
int check = count - originDeductNum;
originDeductNum -= count;
if (check <= 0) {
originInfo.remove(entry.getKey());
} else {
originInfo.put(key, originDeductNum);
break;
}
}
}
break;
}
}
// 记录日志
int resultNum = player.roleInfo().getPlayerBag().getItemNum(tId);
EventBus.getSelf().fireEvent(new ItemChangeEventObject(tId, player, resultNum + num, resultNum, ItemChangeEventObject.REMOVE, gameLogSource, 0,ItemChangeEventObject.ITEM_TYPE));
player.send(ItemConverter.getMsgItems(items));
return resultMap;
}
}
| UTF-8 | Java | 5,640 | java | DeductItem.java | Java | [
{
"context": "e.player.entity.PlayerBag;\n\n/**\n * 道具扣减\n * @author jacky.jiang\n *\n */\n@Component\npublic class DeductIt",
"end": 755,
"score": 0.9091859459877014,
"start": 754,
"tag": "NAME",
"value": "j"
},
{
"context": "player.entity.PlayerBag;\n\n/**\n * 道具扣减\n * @author jack... | null | [] | package com.xgame.logic.server.game.bag.entity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;
import com.xgame.config.items.ItemsPir;
import com.xgame.config.items.ItemsPirFactory;
import com.xgame.logic.server.core.gamelog.constant.GameLogSource;
import com.xgame.logic.server.core.gamelog.event.EventBus;
import com.xgame.logic.server.game.bag.converter.ItemConverter;
import com.xgame.logic.server.game.bag.entity.eventmodel.ItemChangeEventObject;
import com.xgame.logic.server.game.player.entity.Player;
import com.xgame.logic.server.game.player.entity.PlayerBag;
/**
* 道具扣减
* @author jacky.jiang
*
*/
@Component
public class DeductItem {
/**
* 判断道具是否足够
* @param tId 模板id
* @param num
* @return false 数量不足,true数量满足
*/
public boolean checkDeductItem(Player player, int tId, int num) {
ItemsPir config = ItemsPirFactory.get(tId);
if(config == null) {
return false;
}
int playerNum = player.roleInfo().getPlayerBag().getItemNum(tId);
if(playerNum < num) {
return false;
}
return true;
}
/**
* 删除玩家道具, 推包
* <ul>说明 : 扣除道具从最少的开始扣除<ul>
* @param tId
* @param num
*/
public int deductItem(Player player, int tId, int num, GameLogSource gameLogSource) {
PlayerBag bag = player.roleInfo().getPlayerBag();
List<Item> playerItem = player.roleInfo().getPlayerBag().getPlayerItem(tId);
Collections.sort(playerItem);
// 扣除道具从最少的开始扣除
List<Item> resultList = new ArrayList<>();
Iterator<Item> iterator = playerItem.iterator();
while (iterator.hasNext()) {
Item item = (Item) iterator.next();
int tmp = item.getNum();
item.setNum(item.getNum() - num);
num -= tmp;
if (item.getNum() <= 0) {
// 已使用完,从背包移除道具
bag.getItemTable().remove(item.getId());
resultList.add(Item.valueOf(item.getItemId(), 0, item.getId()));
} else {
resultList.add(item);
break;
}
}
// 推包
player.send(ItemConverter.getMsgItems(resultList));
// 记录日志
int resultNum = player.roleInfo().getPlayerBag().getItemNum(tId);
EventBus.getSelf().fireEvent(new ItemChangeEventObject(tId, player, resultNum + num, resultNum, ItemChangeEventObject.REMOVE, gameLogSource, 0,ItemChangeEventObject.ITEM_TYPE));
return num;
}
/**
* 删除玩家道具, 推包
* <ul>说明 : 扣除道具从最少的开始扣除<ul>
* @param uId
* @param num
*/
public boolean deductItem(Player player, long uId, int num, GameLogSource gameLogSource) {
PlayerBag bag = player.roleInfo().getPlayerBag();
Item item= player.roleInfo().getPlayerBag().getPlayerItem(uId);
if(item.getNum() < num) {
return false;
}
int tmp = item.getNum();
item.setNum(item.getNum() - num);
num -= tmp;
List<Item> items = new ArrayList<>();
if (item.getNum() == 0) {
// 已使用完,从背包移除道具
bag.getItemTable().remove(item.getId());
items.add(Item.valueOf(item.getItemId(), 0, item.getId()));
} else {
items.add(item);
}
// 记录日志
int resultNum = player.roleInfo().getPlayerBag().getItemNum(item.getItemId());
EventBus.getSelf().fireEvent(new ItemChangeEventObject(item.getItemId(), player, resultNum + num, resultNum, ItemChangeEventObject.REMOVE, gameLogSource, 0,ItemChangeEventObject.ITEM_TYPE));
// 推包
player.send(ItemConverter.getMsgItems(items));
return true;
}
/**
* 使用带有来源的道具
* @param player
* @param tId
* @param num
* @return
*/
public Map<Integer, Integer> deductOriginItem(Player player,int tId, int num, GameLogSource gameLogSource) {
PlayerBag bag = player.roleInfo().getPlayerBag();
List<Item> playerItem = player.roleInfo().getPlayerBag().getPlayerItem(tId);
Collections.sort(playerItem);
Collections.reverse(playerItem);
// 扣除道具从最少的开始扣除
Iterator<Item> iterator = playerItem.iterator();
Map<Integer, Integer> resultMap = new HashMap<>();
List<Item> items = new ArrayList<>();
while (iterator.hasNext()) {
Item item = (Item) iterator.next();
int tmp = item.getNum();
int deductNum = item.getNum() - num;
item.setNum(deductNum);
num -= tmp;
items.add(item);
if (item.getNum() <= 0) {
// 已使用完,从背包移除道具
bag.getItemTable().remove(item.getId());
resultMap.putAll(item.getOriginInfo());
} else {
// 处理带有来源的道具信息
int originDeductNum = deductNum;
Map<Integer, Integer> originInfo = item.getOriginInfo();
Iterator<java.util.Map.Entry<Integer, Integer>> iter = originInfo.entrySet().iterator();
while (iter.hasNext()) {
java.util.Map.Entry<Integer, Integer> entry = iter.next();
Integer count = entry.getValue();
Integer key = entry.getKey();
if (count != null && key != null) {
int check = count - originDeductNum;
originDeductNum -= count;
if (check <= 0) {
originInfo.remove(entry.getKey());
} else {
originInfo.put(key, originDeductNum);
break;
}
}
}
break;
}
}
// 记录日志
int resultNum = player.roleInfo().getPlayerBag().getItemNum(tId);
EventBus.getSelf().fireEvent(new ItemChangeEventObject(tId, player, resultNum + num, resultNum, ItemChangeEventObject.REMOVE, gameLogSource, 0,ItemChangeEventObject.ITEM_TYPE));
player.send(ItemConverter.getMsgItems(items));
return resultMap;
}
}
| 5,640 | 0.685171 | 0.683478 | 183 | 28.038252 | 30.534288 | 193 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.73224 | false | false | 13 |
0a5673439b5225183be0588d3dc7911743418508 | 25,022,479,528,354 | 5496c812de49f99119e8581d089763eabeb55b39 | /src/main/java/nl/utwente/ing/service/CategoryService.java | 28d6086c5c9eb3f8e74b55746c3945fc9b11122f | [
"BSD-2-Clause-Views"
] | permissive | agilitytestbed/Team-F1 | https://github.com/agilitytestbed/Team-F1 | 729a87bea0c592f1049683ff1720830ee421161f | 5dd362affbd7fe0c84d7352d50ab1a99db3c61cf | refs/heads/master | 2020-03-09T11:50:58.993000 | 2018-08-26T17:43:45 | 2018-08-26T17:43:45 | 128,771,138 | 0 | 0 | null | false | 2018-08-26T17:43:46 | 2018-04-09T12:51:47 | 2018-08-14T11:35:52 | 2018-08-26T17:43:46 | 204 | 0 | 0 | 0 | Java | false | null | /*
* Copyright (c) 2018, Tom Leemreize <https://github.com/oplosthee>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package nl.utwente.ing.service;
import nl.utwente.ing.model.Category;
import nl.utwente.ing.model.Session;
import nl.utwente.ing.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class CategoryService {
private final CategoryRepository categoryRepository;
@Autowired
public CategoryService(CategoryRepository categoryRepository) {
this.categoryRepository = categoryRepository;
}
@Transactional
public Category add(Category category) {
return categoryRepository.save(category);
}
@Transactional
public List<Category> findBySession(Session session) {
return categoryRepository.findBySession(session);
}
@Transactional
public Category findByIdAndSession(int id, Session session) {
return categoryRepository.findByIdAndSession(id, session);
}
@Transactional
public int update(Category category) {
return categoryRepository.setCategoryNameByIdAndSession(
category.getName(),
category.getId(),
category.getSession()
);
}
@Transactional
public int delete(int id, Session session) {
return categoryRepository.deleteByIdAndSession(id, session);
}
}
| UTF-8 | Java | 2,825 | java | CategoryService.java | Java | [
{
"context": "/*\n * Copyright (c) 2018, Tom Leemreize <https://github.com/oplosthee>\n * All rights rese",
"end": 39,
"score": 0.9998766779899597,
"start": 26,
"tag": "NAME",
"value": "Tom Leemreize"
},
{
"context": "right (c) 2018, Tom Leemreize <https://github.com/oplosthee>\n * A... | null | [] | /*
* Copyright (c) 2018, <NAME> <https://github.com/oplosthee>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package nl.utwente.ing.service;
import nl.utwente.ing.model.Category;
import nl.utwente.ing.model.Session;
import nl.utwente.ing.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class CategoryService {
private final CategoryRepository categoryRepository;
@Autowired
public CategoryService(CategoryRepository categoryRepository) {
this.categoryRepository = categoryRepository;
}
@Transactional
public Category add(Category category) {
return categoryRepository.save(category);
}
@Transactional
public List<Category> findBySession(Session session) {
return categoryRepository.findBySession(session);
}
@Transactional
public Category findByIdAndSession(int id, Session session) {
return categoryRepository.findByIdAndSession(id, session);
}
@Transactional
public int update(Category category) {
return categoryRepository.setCategoryNameByIdAndSession(
category.getName(),
category.getId(),
category.getSession()
);
}
@Transactional
public int delete(int id, Session session) {
return categoryRepository.deleteByIdAndSession(id, session);
}
}
| 2,818 | 0.747257 | 0.745133 | 74 | 37.175674 | 29.836201 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.594595 | false | false | 13 |
cd58b63908decbbc903a544f4acd00ccfdd2f5dc | 38,723,425,192,470 | 56512080a835a98040c2855abc45a77f2faa9de1 | /src/main/java/ar/nex/jpa/GastoRepuestoJpaController.java | 7f20adcaeb4dba46faa06562c8fd020972c90993 | [
"Apache-2.0"
] | permissive | renzog6/sae-app | https://github.com/renzog6/sae-app | 812e42cde1d586404950eeec20c53ea41e89471c | f44f5c23cc542809e8545a16473c2a1127e3c8a1 | refs/heads/master | 2022-06-26T21:39:01.538000 | 2020-04-29T21:02:39 | 2020-04-29T21:02:39 | 186,499,418 | 1 | 0 | Apache-2.0 | false | 2022-05-20T21:34:41 | 2019-05-13T21:40:05 | 2020-04-29T21:03:05 | 2022-05-20T21:34:40 | 850 | 0 | 0 | 6 | Java | false | false | /*
* 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 ar.nex.jpa;
import ar.nex.entity.equipo.gasto.GastoRepuesto;
import ar.nex.jpa.exceptions.NonexistentEntityException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
/**
*
* @author Renzo
*/
public class GastoRepuestoJpaController implements Serializable {
public GastoRepuestoJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(GastoRepuesto gastoRepuesto) {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(gastoRepuesto);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(GastoRepuesto gastoRepuesto) throws NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
gastoRepuesto = em.merge(gastoRepuesto);
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Long id = gastoRepuesto.getIdGasto();
if (findGastoRepuesto(id) == null) {
throw new NonexistentEntityException("The gastoRepuesto with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Long id) throws NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
GastoRepuesto gastoRepuesto;
try {
gastoRepuesto = em.getReference(GastoRepuesto.class, id);
gastoRepuesto.getIdGasto();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The gastoRepuesto with id " + id + " no longer exists.", enfe);
}
em.remove(gastoRepuesto);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public List<GastoRepuesto> findGastoRepuestoEntities() {
return findGastoRepuestoEntities(true, -1, -1);
}
public List<GastoRepuesto> findGastoRepuestoEntities(int maxResults, int firstResult) {
return findGastoRepuestoEntities(false, maxResults, firstResult);
}
private List<GastoRepuesto> findGastoRepuestoEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(GastoRepuesto.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public GastoRepuesto findGastoRepuesto(Long id) {
EntityManager em = getEntityManager();
try {
return em.find(GastoRepuesto.class, id);
} finally {
em.close();
}
}
public int getGastoRepuestoCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<GastoRepuesto> rt = cq.from(GastoRepuesto.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
| UTF-8 | Java | 4,599 | java | GastoRepuestoJpaController.java | Java | [
{
"context": ".persistence.criteria.Root;\r\n\r\n/**\r\n *\r\n * @author Renzo\r\n */\r\npublic class GastoRepuestoJpaController imp",
"end": 666,
"score": 0.9995924234390259,
"start": 661,
"tag": "NAME",
"value": "Renzo"
}
] | 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 ar.nex.jpa;
import ar.nex.entity.equipo.gasto.GastoRepuesto;
import ar.nex.jpa.exceptions.NonexistentEntityException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
/**
*
* @author Renzo
*/
public class GastoRepuestoJpaController implements Serializable {
public GastoRepuestoJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(GastoRepuesto gastoRepuesto) {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(gastoRepuesto);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(GastoRepuesto gastoRepuesto) throws NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
gastoRepuesto = em.merge(gastoRepuesto);
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Long id = gastoRepuesto.getIdGasto();
if (findGastoRepuesto(id) == null) {
throw new NonexistentEntityException("The gastoRepuesto with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Long id) throws NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
GastoRepuesto gastoRepuesto;
try {
gastoRepuesto = em.getReference(GastoRepuesto.class, id);
gastoRepuesto.getIdGasto();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The gastoRepuesto with id " + id + " no longer exists.", enfe);
}
em.remove(gastoRepuesto);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public List<GastoRepuesto> findGastoRepuestoEntities() {
return findGastoRepuestoEntities(true, -1, -1);
}
public List<GastoRepuesto> findGastoRepuestoEntities(int maxResults, int firstResult) {
return findGastoRepuestoEntities(false, maxResults, firstResult);
}
private List<GastoRepuesto> findGastoRepuestoEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(GastoRepuesto.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public GastoRepuesto findGastoRepuesto(Long id) {
EntityManager em = getEntityManager();
try {
return em.find(GastoRepuesto.class, id);
} finally {
em.close();
}
}
public int getGastoRepuestoCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<GastoRepuesto> rt = cq.from(GastoRepuesto.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
| 4,599 | 0.569906 | 0.569254 | 138 | 31.326086 | 25.109085 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.550725 | false | false | 13 |
9634578d64d12371ea16440c5a71644dad299a6c | 34,213,709,535,885 | 237e37a2358c846a08b7c5f8b49838da94dc6d6d | /src/strings/RegularExpressions.java | d72326171e726b606467d407a6ffaddee10f0ffe | [] | no_license | Lok-Aravind-Palu/PluralsightPractice | https://github.com/Lok-Aravind-Palu/PluralsightPractice | 742856b207e57b733284ec4403832fafce4a8914 | 77b6fef8688bd8656ab3fef12c329aa994e32af4 | refs/heads/master | 2020-03-19T17:32:53.163000 | 2018-06-09T23:46:05 | 2018-06-09T23:46:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package strings;
public class RegularExpressions {
public static void main(String[] args) {
String s1 ="apple,apple and orange please";
/////replaceAll method
String s2 =s1.replaceAll("ple", "ricot");
System.out.println(s2);
String s3 = s1.replaceAll("ple\\b", "ricot");
System.out.println(s3);
///////Split method and matches method
String[] parts = s1.split("\\b");
for(String st : parts){
if(st.matches("\\w+")){
System.out.print(st + "\t");
}
}
}
}
| UTF-8 | Java | 569 | java | RegularExpressions.java | Java | [] | null | [] | package strings;
public class RegularExpressions {
public static void main(String[] args) {
String s1 ="apple,apple and orange please";
/////replaceAll method
String s2 =s1.replaceAll("ple", "ricot");
System.out.println(s2);
String s3 = s1.replaceAll("ple\\b", "ricot");
System.out.println(s3);
///////Split method and matches method
String[] parts = s1.split("\\b");
for(String st : parts){
if(st.matches("\\w+")){
System.out.print(st + "\t");
}
}
}
}
| 569 | 0.537786 | 0.523726 | 26 | 20.884615 | 17.600977 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.038462 | false | false | 13 |
e6fc7b5e1926c60a716437c287a99b05963c93a3 | 34,402,688,098,491 | c6a69e4491b73ff3e1bd380c9f20788087b3f84c | /app/src/main/java/com/google/developer/bugmaster/features/details_insect/DetailsMvpPresenter.java | 6a66750685474a00622786c48078cd296d95f25e | [] | no_license | CoDCaT/Test-task-from-Google | https://github.com/CoDCaT/Test-task-from-Google | cf59c74bf3383937f41fccaf81fe3646a1897f00 | 8115b00067ddf37dadd9b4240e67594ede7893b3 | refs/heads/master | 2021-05-16T17:28:03.894000 | 2017-12-14T14:27:40 | 2017-12-23T08:41:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.developer.bugmaster.features.details_insect;
import android.content.Intent;
import android.view.MenuItem;
import com.google.developer.bugmaster.base.MvpPresenter;
public interface DetailsMvpPresenter<V extends DetailsMvpView> extends MvpPresenter<V> {
void onViewInitialized(Intent intent);
void onClickButtonMenu(MenuItem item);
}
| UTF-8 | Java | 365 | java | DetailsMvpPresenter.java | Java | [] | null | [] | package com.google.developer.bugmaster.features.details_insect;
import android.content.Intent;
import android.view.MenuItem;
import com.google.developer.bugmaster.base.MvpPresenter;
public interface DetailsMvpPresenter<V extends DetailsMvpView> extends MvpPresenter<V> {
void onViewInitialized(Intent intent);
void onClickButtonMenu(MenuItem item);
}
| 365 | 0.813699 | 0.813699 | 14 | 25.071428 | 28.434044 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 13 |
53464b6b12e8655ab09464bdc8a64ac66f816b51 | 34,041,910,844,462 | 31820a5b5cb96f3acee4eec17fbd20c4332c80f6 | /src/main/java/robots/model/field/between_cells_objects/BetweenCellObjectWithAction.java | 10fa4dca15d15dd0903ed3d9b2041d5ac68eccfd | [] | no_license | vitek999/OOP_Robots | https://github.com/vitek999/OOP_Robots | 160e74ffafb027551ed269af934c6d6212cc5bcb | 306c95ad11e08eb10171a2a76c1f0113175e6f63 | refs/heads/master | 2021-04-20T11:52:06.395000 | 2021-01-28T20:13:11 | 2021-01-28T20:13:11 | 249,681,500 | 5 | 0 | null | false | 2021-01-28T20:13:11 | 2020-03-24T10:45:15 | 2020-05-21T04:41:13 | 2021-01-28T20:13:11 | 4,175 | 2 | 0 | 0 | Java | false | false | package robots.model.field.between_cells_objects;
import robots.model.field.BetweenCellObject;
/**
* Объект, распологающийся между ячейками {@link robots.model.field.Cell}, имеющий действия.
*/
public abstract class BetweenCellObjectWithAction extends BetweenCellObject {
/**
* Выполнить действие.
*/
public abstract void perform();
/**
* Стоимость выполнения действия.
* @return стоимость выполнения действия.
*/
public abstract int actionCost();
}
| UTF-8 | Java | 617 | java | BetweenCellObjectWithAction.java | Java | [] | null | [] | package robots.model.field.between_cells_objects;
import robots.model.field.BetweenCellObject;
/**
* Объект, распологающийся между ячейками {@link robots.model.field.Cell}, имеющий действия.
*/
public abstract class BetweenCellObjectWithAction extends BetweenCellObject {
/**
* Выполнить действие.
*/
public abstract void perform();
/**
* Стоимость выполнения действия.
* @return стоимость выполнения действия.
*/
public abstract int actionCost();
}
| 617 | 0.710262 | 0.710262 | 20 | 23.85 | 26.676348 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 13 |
bb69fe13c630ab6d7c6b9fd8c590046fcb04e6c6 | 38,233,798,898,054 | 963f4f641327d85d13a2194558912194d1831789 | /src/main/java/com/xuliang/framework/async/worker/WorkResult.java | 4bb2a67caf69fe7322983a25420a75b70f5fd29f | [] | no_license | xuliang12/async | https://github.com/xuliang12/async | 31e885e0c8753956289c74b9d4a36664f2dde641 | 698bee7e75ac5b0c819f1816120f473b07c59cf0 | refs/heads/master | 2023-03-11T15:09:28.613000 | 2021-02-22T10:11:20 | 2021-02-22T10:11:20 | 283,086,440 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xuliang.framework.async.worker;
import lombok.Data;
/**
* 执行结果
*
* @author xuliang
*/
@Data
public class WorkResult<V> {
/**
* 执行结果
*/
private V result;
/**
* 结果状态
*/
private ResultState resultState;
/**
* 异常信息
*/
private Exception ex;
public WorkResult(V result, ResultState resultState) {
this(result, resultState, null);
}
public WorkResult(V result, ResultState resultState, Exception ex) {
this.result = result;
this.resultState = resultState;
this.ex = ex;
}
public static <V> WorkResult<V> defaultResult() {
return new WorkResult<>(null, ResultState.DEFAULT);
}
}
| UTF-8 | Java | 749 | java | WorkResult.java | Java | [
{
"context": ";\n\n\nimport lombok.Data;\n\n/**\n * 执行结果\n *\n * @author xuliang\n */\n@Data\npublic class WorkResult<V> {\n\n\n /**\n",
"end": 100,
"score": 0.9987399578094482,
"start": 93,
"tag": "USERNAME",
"value": "xuliang"
}
] | null | [] | package com.xuliang.framework.async.worker;
import lombok.Data;
/**
* 执行结果
*
* @author xuliang
*/
@Data
public class WorkResult<V> {
/**
* 执行结果
*/
private V result;
/**
* 结果状态
*/
private ResultState resultState;
/**
* 异常信息
*/
private Exception ex;
public WorkResult(V result, ResultState resultState) {
this(result, resultState, null);
}
public WorkResult(V result, ResultState resultState, Exception ex) {
this.result = result;
this.resultState = resultState;
this.ex = ex;
}
public static <V> WorkResult<V> defaultResult() {
return new WorkResult<>(null, ResultState.DEFAULT);
}
}
| 749 | 0.589958 | 0.589958 | 45 | 14.933333 | 18.68737 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.355556 | false | false | 13 |
6ac9a03e447a0f36a6143dfd1455041549cafa47 | 37,924,561,250,155 | e9e76843183120eaf08bcb9de5f9a86ea9e325db | /src/org/processmining/prediction/Augmentation/Hour.java | fc8f8c3a9fbb54e550adc7943cce6c30c483039a | [] | no_license | avihaigr/ConcurrentFeaturesPrediction | https://github.com/avihaigr/ConcurrentFeaturesPrediction | 0ae81cdb9fd17dbbb92d742e3dc8489df736862c | b1f1d209201562923d1fb45158cb6871489690e2 | refs/heads/master | 2021-01-02T16:04:43.217000 | 2020-02-25T21:08:34 | 2020-02-25T21:08:34 | 239,694,932 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.processmining.prediction.Augmentation;
import java.util.Date;
import org.deckfour.xes.extension.std.XTimeExtension;
import org.deckfour.xes.model.XEvent;
import org.deckfour.xes.model.XLog;
import org.deckfour.xes.model.XTrace;
public class Hour extends Augmentation{
public static final String TIMESTAMP_NAME="Activity Hour";
public Hour() {
super(TIMESTAMP_NAME);
}
public void reset(XTrace trace) {
}
public void setLog(XLog log) {
}
public Integer returnAttribute(XEvent event) {
Date timestamp=XTimeExtension.instance().extractTimestamp(event);
if (timestamp!=null){
//0 through 23
int hour = timestamp.getHours();
return hour;
}
else
return null;
}
}
| UTF-8 | Java | 718 | java | Hour.java | Java | [] | null | [] | package org.processmining.prediction.Augmentation;
import java.util.Date;
import org.deckfour.xes.extension.std.XTimeExtension;
import org.deckfour.xes.model.XEvent;
import org.deckfour.xes.model.XLog;
import org.deckfour.xes.model.XTrace;
public class Hour extends Augmentation{
public static final String TIMESTAMP_NAME="Activity Hour";
public Hour() {
super(TIMESTAMP_NAME);
}
public void reset(XTrace trace) {
}
public void setLog(XLog log) {
}
public Integer returnAttribute(XEvent event) {
Date timestamp=XTimeExtension.instance().extractTimestamp(event);
if (timestamp!=null){
//0 through 23
int hour = timestamp.getHours();
return hour;
}
else
return null;
}
}
| 718 | 0.733983 | 0.729805 | 38 | 17.894737 | 19.737474 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.289474 | false | false | 13 |
f5f8ff7433355e3c267e8ae4bd10169c215e464e | 38,929,583,590,213 | 1242c92560cd6bfe11fc028c81c16dd1c9777765 | /src/main/java/dev/atanasovski/dagscheduler/Main.java | 206dee3ab26a70e774c2612d60eb2c3cab33a46b | [] | no_license | wddllyy/DAG_Task_Scheduler | https://github.com/wddllyy/DAG_Task_Scheduler | b945efe6c0f9c935669b817102ebf2f921c92d91 | fb9c40b43099ba138404a7c1718e29c121120202 | refs/heads/main | 2023-04-19T22:32:46.237000 | 2021-05-06T22:30:40 | 2021-05-06T22:33:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dev.atanasovski.dagscheduler;
import dev.atanasovski.dagscheduler.algorithms.DummySchedulingAlgorithm;
import dev.atanasovski.dagscheduler.examples.login.LogInSchedule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by Blagoj on 24-Feb-16.
*/
public class Main {
static final Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String... args) throws InterruptedException {
Schedule schedule = new LogInSchedule("some user", "pass hash");
Scheduler s = new Scheduler(new DummySchedulingAlgorithm());
s.execute(schedule);
logger.info("Done!");
logger.info(schedule.getResults().toString());
}
} | UTF-8 | Java | 707 | java | Main.java | Java | [
{
"context": "import org.slf4j.LoggerFactory;\n\n/**\n * Created by Blagoj on 24-Feb-16.\n */\npublic class Main {\n static ",
"end": 260,
"score": 0.994625985622406,
"start": 254,
"tag": "USERNAME",
"value": "Blagoj"
}
] | null | [] | package dev.atanasovski.dagscheduler;
import dev.atanasovski.dagscheduler.algorithms.DummySchedulingAlgorithm;
import dev.atanasovski.dagscheduler.examples.login.LogInSchedule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by Blagoj on 24-Feb-16.
*/
public class Main {
static final Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String... args) throws InterruptedException {
Schedule schedule = new LogInSchedule("some user", "pass hash");
Scheduler s = new Scheduler(new DummySchedulingAlgorithm());
s.execute(schedule);
logger.info("Done!");
logger.info(schedule.getResults().toString());
}
} | 707 | 0.729844 | 0.721358 | 21 | 32.714287 | 27.46451 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 13 |
2effd5fa6069a7271cc64b206c0c8c90da5d795f | 34,823,594,887,024 | 3d33196d8950940aa29a3a569c15e6224bc400f2 | /springboot-integrate/spring/spring-ioc-di/src/main/java/vip/xjdai/ioc/xml/static_factory/DaoFactory.java | a25df3e6fa88185c0125178a2da2fd92b389be29 | [] | no_license | myliwenbo/Springboot | https://github.com/myliwenbo/Springboot | 1e2a48f344114e00defb2f954027dbbe5aa930ac | c0c90840481f206625e13328e31f8f554b01731f | refs/heads/master | 2023-03-06T23:36:05.053000 | 2022-09-16T08:17:48 | 2022-09-16T08:17:48 | 150,402,628 | 7 | 5 | null | false | 2023-02-22T08:02:02 | 2018-09-26T09:32:08 | 2021-12-29T16:34:37 | 2023-02-22T08:02:02 | 32,863 | 6 | 5 | 33 | Java | false | false | package vip.xjdai.ioc.xml.static_factory;
public class DaoFactory {
//静态工厂
public static final FactoryDao getStaticFactoryDaoImpl() {
return new StaticFacotryDaoImpl();
}
} | UTF-8 | Java | 203 | java | DaoFactory.java | Java | [] | null | [] | package vip.xjdai.ioc.xml.static_factory;
public class DaoFactory {
//静态工厂
public static final FactoryDao getStaticFactoryDaoImpl() {
return new StaticFacotryDaoImpl();
}
} | 203 | 0.707692 | 0.707692 | 8 | 23.5 | 21.406775 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 13 |
ce5c0e144574464263169cdc3b706012b4a13aea | 34,823,594,889,936 | fbf1e3006201c93115422fc2480c34a271e9c0ae | /src/main/java/gov/pnnl/aim/discovery/util/MatrixUtil.java | 11419b8d275ae32ec34f313f6a9d66d68b1badeb | [] | no_license | Tubbz-alt/aim-science-of-interaction | https://github.com/Tubbz-alt/aim-science-of-interaction | 74f1ced535f97520ed5006bf5fb4c31bd4c2d615 | 4bd1634e30f9a1db8c57a56d1ae99c0512a4813f | refs/heads/master | 2021-05-29T21:22:44.533000 | 2015-08-04T04:27:41 | 2015-08-04T04:27:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gov.pnnl.aim.discovery.util;
import gov.pnnl.jac.geom.CoordinateList;
import gov.pnnl.jac.geom.RealMatrixCoordinateList;
import gov.pnnl.jac.math.linalg.PCA;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.ArrayRealVector;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.linear.RealVector;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import com.google.common.primitives.Doubles;
public class MatrixUtil {
public static RealMatrix zScaling(final RealMatrix matrix) {
RealMatrix origMatrix = matrix.copy();
int colCount = origMatrix.getColumnDimension();
int rowCount = origMatrix.getRowDimension();
for (int col = 0; col < colCount; col++) {
double [] dist = origMatrix.getColumn(col);
for (int row = 0; row < rowCount; row++) {
matrix.setEntry(row, col, zscore(dist, origMatrix.getEntry(row, col)));
}
}
return matrix;
}
public static double zscore(double [] dist, double value) {
DescriptiveStatistics stats = new DescriptiveStatistics();
for (double v : dist) {
stats.addValue(v);
}
double mean = stats.getMean();
double stddev = stats.getStandardDeviation();
return (value - mean) / stddev;
}
public static RealMatrix computeMinMax(final CoordinateList coordList) {
final int rows = coordList.getCoordinateCount();
final int cols = coordList.getDimensionCount();
final double[] dmin = new double[cols];
final double[] dmax = new double[cols];
Arrays.fill(dmin, Double.MAX_VALUE);
Arrays.fill(dmax, -Double.MAX_VALUE);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
double d = coordList.getCoordinate(i, j);
if (Double.isNaN(d)) {
d = 0.0;
}
if (d < dmin[j]) {
dmin[j] = d;
}
if (d > dmax[j]) {
dmax[j] = d;
}
}
}
return new Array2DRowRealMatrix(new double[][] { dmin, dmax });
}
public static RealMatrix computeMinMax(final RealMatrix coordList) {
final int rows = coordList.getRowDimension();
final int cols = coordList.getColumnDimension();
final double[] dmin = new double[cols];
final double[] dmax = new double[cols];
Arrays.fill(dmin, Double.MAX_VALUE);
Arrays.fill(dmax, -Double.MAX_VALUE);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
double d = coordList.getEntry(i, j);
if (Double.isNaN(d)) {
d = 0.0;
}
if (d < dmin[j]) {
dmin[j] = d;
}
if (d > dmax[j]) {
dmax[j] = d;
}
}
}
return new Array2DRowRealMatrix(new double[][] { dmin, dmax });
}
public static RealMatrix computeGlobalMinMax(final RealMatrix coordList) {
final int rows = coordList.getRowDimension();
final int cols = coordList.getColumnDimension();
double dmin = Double.MAX_VALUE;
double dmax = -Double.MAX_VALUE;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
double d = coordList.getEntry(i, j);
if (Double.isNaN(d)) {
d = 0.0;
}
if (d < dmin) {
dmin = d;
}
if (d > dmax) {
dmax = d;
}
}
}
return new Array2DRowRealMatrix(new double[] { dmin, dmax });
}
public static void normalize2d(RealMatrix nspace) {
double min0 = Double.MAX_VALUE;
double max0 = -Double.MAX_VALUE;
double min1 = Double.MAX_VALUE;
double max1 = -Double.MAX_VALUE;
for (int i = 0; i < nspace.getColumnDimension(); i++) {
double v = nspace.getEntry(0, i);
if (v < min0) {
min0 = v;
}
if (v > max0) {
max0 = v;
}
}
for (int i = 0; i < nspace.getColumnDimension(); i++) {
double v = nspace.getEntry(1, i);
if (v < min1) {
min1 = v;
}
if (v > max1) {
max1 = v;
}
}
double rang0 = max0 - min0;
double rang1 = max1 - min1;
for (int i = 0; i < nspace.getColumnDimension(); i++) {
double v0 = nspace.getEntry(0, i);
nspace.setEntry(0, i, (v0 - min0) / rang0);
double v1 = nspace.getEntry(1, i);
nspace.setEntry(1, i, (v1 - min1) / rang1);
}
}
public static void normalizeDimensionsGlobal(RealMatrix nspace) {
normalizeDimensionsGlobal(nspace, MatrixUtil.computeGlobalMinMax(nspace));
}
public static void normalizeDimensionsGlobal(RealMatrix nspace, RealMatrix minmax) {
int rows = nspace.getRowDimension();
int cols = nspace.getColumnDimension();
double min = minmax.getEntry(0, 0);
double range = minmax.getEntry(1, 0) - minmax.getEntry(0, 0);
double[] coords = new double[cols];
for (int i = 0; i < rows; i++) {
coords = nspace.getRow(i);
for (int j = 0; j < cols; j++) {
if (range == 0.0) {
coords[j] = 0.0;
} else {
coords[j] = (coords[j] - min) / range;
}
}
nspace.setRow(i, coords);
}
}
public static void normalizeDimensions(RealMatrix nspace) {
normalizeDimensions(nspace, MatrixUtil.computeMinMax(nspace));
}
public static void normalizeDimensions(CoordinateList nspace) {
normalizeDimensions(nspace, MatrixUtil.computeMinMax(nspace));
}
public static void normalizeDimensions(CoordinateList nspace, RealMatrix minmax) {
int rows = nspace.getCoordinateCount();
int cols = nspace.getDimensionCount();
double[] dmin = new double[cols];
double[] drange = new double[cols];
for (int i = 0; i < cols; i++) {
dmin[i] = minmax.getEntry(0, i);
drange[i] = minmax.getEntry(1, i) - dmin[i];
}
double[] coords = new double[cols];
for (int i = 0; i < rows; i++) {
nspace.getCoordinates(i, coords);
for (int j = 0; j < cols; j++) {
double min = dmin[j];
double range = drange[j];
if (range == 0.0) {
coords[j] = 0.0;
} else {
coords[j] = (coords[j] - min) / range;
}
}
nspace.setCoordinates(i, coords);
}
}
public static void normalizeDimensions(RealMatrix nspace, RealMatrix minmax) {
int rows = nspace.getRowDimension();
int cols = nspace.getColumnDimension();
double[] dmin = new double[cols];
double[] drange = new double[cols];
for (int i = 0; i < cols; i++) {
dmin[i] = minmax.getEntry(0, i);
drange[i] = minmax.getEntry(1, i) - dmin[i];
}
double[] coords = new double[cols];
for (int i = 0; i < rows; i++) {
coords = nspace.getRow(i);
for (int j = 0; j < cols; j++) {
double min = dmin[j];
double range = drange[j];
if (range == 0.0) {
coords[j] = 0.0;
} else {
coords[j] = (coords[j] - min) / range;
}
}
nspace.setRow(i, coords);
}
}
static public RealMatrix computeDistanceMatrix(RealMatrix nspace) {
int size = nspace.getRowDimension();
RealMatrix distMatrix = new Array2DRowRealMatrix(size, size);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
double dist = ((i == j) ? 0.0 : (MatrixUtil.distance(nspace.getRow(i), nspace.getRow(j))));
distMatrix.setEntry(i, j, dist);
}
}
MatrixUtil.normalizeDimensions(distMatrix);
return distMatrix;
}
static private double[][] reduce(double[][] matrix) {
Array2DRowRealMatrix realMatrix = new Array2DRowRealMatrix(matrix);
PCA pca = new PCA(realMatrix, PCA.CovarianceType.COVARIANCE, 2);
RealMatrix projMatrix = pca.getPrincipalComponents();
MatrixUtil.normalizeDimensions(new RealMatrixCoordinateList(projMatrix), MatrixUtil.computeMinMax(projMatrix));
return projMatrix.getData();
// The orientation of this needs to be inverted to work with the calling code
// return MDSJ.classicalScaling(matrix);
}
public static double distance(double[] a, double[] b) {
// return new Cosine().distanceBetween(a, b);
// return new gov.pnnl.jac.geom.distance.Manhattan().distanceBetween(a, b) / 50.0;
return new gov.pnnl.jac.geom.distance.Euclidean().distanceBetween(a, b);
}
public static void printMatrix(RealMatrix matrix) {
for (int i = 0; i < matrix.getRowDimension(); i++) {
for (int j = 0; j < matrix.getColumnDimension(); j++) {
System.out.print(matrix.getEntry(i, j) + "\t");
}
System.out.println();
}
}
public static void printVector(RealVector v1Vector) {
for (int i = 0; i < v1Vector.getDimension(); i++) {
System.out.print(v1Vector.getEntry(i) + "\t");
}
System.out.println();
}
public static void printModelResponse(List<double[]> modelResponseHistory, List<String> features) {
int count = features.size();
for (int i = 0; i < count; i++) {
System.out.print(features.get(i));
for (int k = 0; k < modelResponseHistory.size(); k++) {
double [] weights = modelResponseHistory.get(k);
System.out.print("\t" + weights[i]);
}
System.out.println();
// double [] weights = modelResponseHistory.get(i);
// for (int j = 0; j < weights.length; j++) {
// System.out.print("\t" + weights[j]);
// }
}
}
public static void printCoords(final CoordinateList matrix) {
for (int i = 0; i < matrix.getCoordinateCount(); i++) {
String row = "";
for (int j = 0; j < matrix.getDimensionCount(); j++) {
row += matrix.getCoordinate(i, j) + " ";
}
System.out.println(row);
}
}
public static void printGroups(Map<Integer, Set<Integer>> groups) {
for (Map.Entry<Integer, Set<Integer>> entry : groups.entrySet()) {
System.out.print("G" + entry.getKey());
for (int member : entry.getValue()) {
System.out.print("\t" + member);
}
System.out.println();
}
}
public static List<Double> extractImageVector(RealVector row) {
List<Double> ret = new ArrayList<Double>();
double[] data = new double[500];
double[] full = row.toArray();
data = Arrays.copyOfRange(full, 201, full.length);
for( int i=0; i<data.length; i++ ) {
ret.add(data[i]);
}
return ret;
}
public static List<Double> extractTextVector(RealVector row) {
List<Double> ret = new ArrayList<Double>();
double[] data = new double[200];
double[] full = row.toArray();
data = Arrays.copyOfRange(full, 0, 200);
for( int i=0; i<data.length; i++ ) {
ret.add(data[i]);
}
return ret;
}
public static List<Double> convertToList(RealVector row) {
List<Double> list = Doubles.asList(row.toArray());
return list;
}
public static RealVector convertToRealVector(List<Double> list) {
RealVector rv = new ArrayRealVector(Doubles.toArray(list));
return rv;
}
public static void print(Set<Integer> topFeatures) {
System.out.print("Top Features: ");
for (int index : topFeatures) {
System.out.print(index + " ");
}
System.out.println();
}
/**
* Resizes a RealMatrix, copying data where available, zeroing elsewhere. This
* returns a new matrix except when the requested size matches the existing
* size, in which case the original matrix is returned.
*/
public static RealMatrix resizeMatrix(RealMatrix original, int rows, int columns) {
// Get existing size
int rowsOriginal = original.getRowDimension();
int columnsOriginal = original.getColumnDimension();
if (rows == rowsOriginal && columns == columnsOriginal) {
// No change in size, so just use the original
return original;
}
// Find how much data overlap there is
int rowsToCopy = Math.min(rowsOriginal, rows);
int columnsToCopy = Math.min(columnsOriginal, columns);
// Get the overlapping data
double[][] data = new double[rowsToCopy][columnsToCopy];
original.copySubMatrix(0, rowsToCopy - 1, 0, columnsToCopy - 1, data);
// Copy the overlapping data to a new matrix
RealMatrix resized = new Array2DRowRealMatrix(rows, columns);
resized.setSubMatrix(data, 0, 0);
return resized;
}
}
| UTF-8 | Java | 12,527 | java | MatrixUtil.java | Java | [] | null | [] | package gov.pnnl.aim.discovery.util;
import gov.pnnl.jac.geom.CoordinateList;
import gov.pnnl.jac.geom.RealMatrixCoordinateList;
import gov.pnnl.jac.math.linalg.PCA;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.ArrayRealVector;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.linear.RealVector;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import com.google.common.primitives.Doubles;
public class MatrixUtil {
public static RealMatrix zScaling(final RealMatrix matrix) {
RealMatrix origMatrix = matrix.copy();
int colCount = origMatrix.getColumnDimension();
int rowCount = origMatrix.getRowDimension();
for (int col = 0; col < colCount; col++) {
double [] dist = origMatrix.getColumn(col);
for (int row = 0; row < rowCount; row++) {
matrix.setEntry(row, col, zscore(dist, origMatrix.getEntry(row, col)));
}
}
return matrix;
}
public static double zscore(double [] dist, double value) {
DescriptiveStatistics stats = new DescriptiveStatistics();
for (double v : dist) {
stats.addValue(v);
}
double mean = stats.getMean();
double stddev = stats.getStandardDeviation();
return (value - mean) / stddev;
}
public static RealMatrix computeMinMax(final CoordinateList coordList) {
final int rows = coordList.getCoordinateCount();
final int cols = coordList.getDimensionCount();
final double[] dmin = new double[cols];
final double[] dmax = new double[cols];
Arrays.fill(dmin, Double.MAX_VALUE);
Arrays.fill(dmax, -Double.MAX_VALUE);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
double d = coordList.getCoordinate(i, j);
if (Double.isNaN(d)) {
d = 0.0;
}
if (d < dmin[j]) {
dmin[j] = d;
}
if (d > dmax[j]) {
dmax[j] = d;
}
}
}
return new Array2DRowRealMatrix(new double[][] { dmin, dmax });
}
public static RealMatrix computeMinMax(final RealMatrix coordList) {
final int rows = coordList.getRowDimension();
final int cols = coordList.getColumnDimension();
final double[] dmin = new double[cols];
final double[] dmax = new double[cols];
Arrays.fill(dmin, Double.MAX_VALUE);
Arrays.fill(dmax, -Double.MAX_VALUE);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
double d = coordList.getEntry(i, j);
if (Double.isNaN(d)) {
d = 0.0;
}
if (d < dmin[j]) {
dmin[j] = d;
}
if (d > dmax[j]) {
dmax[j] = d;
}
}
}
return new Array2DRowRealMatrix(new double[][] { dmin, dmax });
}
public static RealMatrix computeGlobalMinMax(final RealMatrix coordList) {
final int rows = coordList.getRowDimension();
final int cols = coordList.getColumnDimension();
double dmin = Double.MAX_VALUE;
double dmax = -Double.MAX_VALUE;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
double d = coordList.getEntry(i, j);
if (Double.isNaN(d)) {
d = 0.0;
}
if (d < dmin) {
dmin = d;
}
if (d > dmax) {
dmax = d;
}
}
}
return new Array2DRowRealMatrix(new double[] { dmin, dmax });
}
public static void normalize2d(RealMatrix nspace) {
double min0 = Double.MAX_VALUE;
double max0 = -Double.MAX_VALUE;
double min1 = Double.MAX_VALUE;
double max1 = -Double.MAX_VALUE;
for (int i = 0; i < nspace.getColumnDimension(); i++) {
double v = nspace.getEntry(0, i);
if (v < min0) {
min0 = v;
}
if (v > max0) {
max0 = v;
}
}
for (int i = 0; i < nspace.getColumnDimension(); i++) {
double v = nspace.getEntry(1, i);
if (v < min1) {
min1 = v;
}
if (v > max1) {
max1 = v;
}
}
double rang0 = max0 - min0;
double rang1 = max1 - min1;
for (int i = 0; i < nspace.getColumnDimension(); i++) {
double v0 = nspace.getEntry(0, i);
nspace.setEntry(0, i, (v0 - min0) / rang0);
double v1 = nspace.getEntry(1, i);
nspace.setEntry(1, i, (v1 - min1) / rang1);
}
}
public static void normalizeDimensionsGlobal(RealMatrix nspace) {
normalizeDimensionsGlobal(nspace, MatrixUtil.computeGlobalMinMax(nspace));
}
public static void normalizeDimensionsGlobal(RealMatrix nspace, RealMatrix minmax) {
int rows = nspace.getRowDimension();
int cols = nspace.getColumnDimension();
double min = minmax.getEntry(0, 0);
double range = minmax.getEntry(1, 0) - minmax.getEntry(0, 0);
double[] coords = new double[cols];
for (int i = 0; i < rows; i++) {
coords = nspace.getRow(i);
for (int j = 0; j < cols; j++) {
if (range == 0.0) {
coords[j] = 0.0;
} else {
coords[j] = (coords[j] - min) / range;
}
}
nspace.setRow(i, coords);
}
}
public static void normalizeDimensions(RealMatrix nspace) {
normalizeDimensions(nspace, MatrixUtil.computeMinMax(nspace));
}
public static void normalizeDimensions(CoordinateList nspace) {
normalizeDimensions(nspace, MatrixUtil.computeMinMax(nspace));
}
public static void normalizeDimensions(CoordinateList nspace, RealMatrix minmax) {
int rows = nspace.getCoordinateCount();
int cols = nspace.getDimensionCount();
double[] dmin = new double[cols];
double[] drange = new double[cols];
for (int i = 0; i < cols; i++) {
dmin[i] = minmax.getEntry(0, i);
drange[i] = minmax.getEntry(1, i) - dmin[i];
}
double[] coords = new double[cols];
for (int i = 0; i < rows; i++) {
nspace.getCoordinates(i, coords);
for (int j = 0; j < cols; j++) {
double min = dmin[j];
double range = drange[j];
if (range == 0.0) {
coords[j] = 0.0;
} else {
coords[j] = (coords[j] - min) / range;
}
}
nspace.setCoordinates(i, coords);
}
}
public static void normalizeDimensions(RealMatrix nspace, RealMatrix minmax) {
int rows = nspace.getRowDimension();
int cols = nspace.getColumnDimension();
double[] dmin = new double[cols];
double[] drange = new double[cols];
for (int i = 0; i < cols; i++) {
dmin[i] = minmax.getEntry(0, i);
drange[i] = minmax.getEntry(1, i) - dmin[i];
}
double[] coords = new double[cols];
for (int i = 0; i < rows; i++) {
coords = nspace.getRow(i);
for (int j = 0; j < cols; j++) {
double min = dmin[j];
double range = drange[j];
if (range == 0.0) {
coords[j] = 0.0;
} else {
coords[j] = (coords[j] - min) / range;
}
}
nspace.setRow(i, coords);
}
}
static public RealMatrix computeDistanceMatrix(RealMatrix nspace) {
int size = nspace.getRowDimension();
RealMatrix distMatrix = new Array2DRowRealMatrix(size, size);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
double dist = ((i == j) ? 0.0 : (MatrixUtil.distance(nspace.getRow(i), nspace.getRow(j))));
distMatrix.setEntry(i, j, dist);
}
}
MatrixUtil.normalizeDimensions(distMatrix);
return distMatrix;
}
static private double[][] reduce(double[][] matrix) {
Array2DRowRealMatrix realMatrix = new Array2DRowRealMatrix(matrix);
PCA pca = new PCA(realMatrix, PCA.CovarianceType.COVARIANCE, 2);
RealMatrix projMatrix = pca.getPrincipalComponents();
MatrixUtil.normalizeDimensions(new RealMatrixCoordinateList(projMatrix), MatrixUtil.computeMinMax(projMatrix));
return projMatrix.getData();
// The orientation of this needs to be inverted to work with the calling code
// return MDSJ.classicalScaling(matrix);
}
public static double distance(double[] a, double[] b) {
// return new Cosine().distanceBetween(a, b);
// return new gov.pnnl.jac.geom.distance.Manhattan().distanceBetween(a, b) / 50.0;
return new gov.pnnl.jac.geom.distance.Euclidean().distanceBetween(a, b);
}
public static void printMatrix(RealMatrix matrix) {
for (int i = 0; i < matrix.getRowDimension(); i++) {
for (int j = 0; j < matrix.getColumnDimension(); j++) {
System.out.print(matrix.getEntry(i, j) + "\t");
}
System.out.println();
}
}
public static void printVector(RealVector v1Vector) {
for (int i = 0; i < v1Vector.getDimension(); i++) {
System.out.print(v1Vector.getEntry(i) + "\t");
}
System.out.println();
}
public static void printModelResponse(List<double[]> modelResponseHistory, List<String> features) {
int count = features.size();
for (int i = 0; i < count; i++) {
System.out.print(features.get(i));
for (int k = 0; k < modelResponseHistory.size(); k++) {
double [] weights = modelResponseHistory.get(k);
System.out.print("\t" + weights[i]);
}
System.out.println();
// double [] weights = modelResponseHistory.get(i);
// for (int j = 0; j < weights.length; j++) {
// System.out.print("\t" + weights[j]);
// }
}
}
public static void printCoords(final CoordinateList matrix) {
for (int i = 0; i < matrix.getCoordinateCount(); i++) {
String row = "";
for (int j = 0; j < matrix.getDimensionCount(); j++) {
row += matrix.getCoordinate(i, j) + " ";
}
System.out.println(row);
}
}
public static void printGroups(Map<Integer, Set<Integer>> groups) {
for (Map.Entry<Integer, Set<Integer>> entry : groups.entrySet()) {
System.out.print("G" + entry.getKey());
for (int member : entry.getValue()) {
System.out.print("\t" + member);
}
System.out.println();
}
}
public static List<Double> extractImageVector(RealVector row) {
List<Double> ret = new ArrayList<Double>();
double[] data = new double[500];
double[] full = row.toArray();
data = Arrays.copyOfRange(full, 201, full.length);
for( int i=0; i<data.length; i++ ) {
ret.add(data[i]);
}
return ret;
}
public static List<Double> extractTextVector(RealVector row) {
List<Double> ret = new ArrayList<Double>();
double[] data = new double[200];
double[] full = row.toArray();
data = Arrays.copyOfRange(full, 0, 200);
for( int i=0; i<data.length; i++ ) {
ret.add(data[i]);
}
return ret;
}
public static List<Double> convertToList(RealVector row) {
List<Double> list = Doubles.asList(row.toArray());
return list;
}
public static RealVector convertToRealVector(List<Double> list) {
RealVector rv = new ArrayRealVector(Doubles.toArray(list));
return rv;
}
public static void print(Set<Integer> topFeatures) {
System.out.print("Top Features: ");
for (int index : topFeatures) {
System.out.print(index + " ");
}
System.out.println();
}
/**
* Resizes a RealMatrix, copying data where available, zeroing elsewhere. This
* returns a new matrix except when the requested size matches the existing
* size, in which case the original matrix is returned.
*/
public static RealMatrix resizeMatrix(RealMatrix original, int rows, int columns) {
// Get existing size
int rowsOriginal = original.getRowDimension();
int columnsOriginal = original.getColumnDimension();
if (rows == rowsOriginal && columns == columnsOriginal) {
// No change in size, so just use the original
return original;
}
// Find how much data overlap there is
int rowsToCopy = Math.min(rowsOriginal, rows);
int columnsToCopy = Math.min(columnsOriginal, columns);
// Get the overlapping data
double[][] data = new double[rowsToCopy][columnsToCopy];
original.copySubMatrix(0, rowsToCopy - 1, 0, columnsToCopy - 1, data);
// Copy the overlapping data to a new matrix
RealMatrix resized = new Array2DRowRealMatrix(rows, columns);
resized.setSubMatrix(data, 0, 0);
return resized;
}
}
| 12,527 | 0.599665 | 0.589048 | 438 | 27.600456 | 24.276991 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.705479 | false | false | 13 |
a70245f29fc7ca45a64435c067859fdeae40dd4c | 39,307,540,705,829 | 6adf826eb84ea3654761b0c028b918e53b3e189e | /client/StudentTrackKitKat/register/src/main/java/xchg/online/register/LookupEvent.java | 4e78a67c024acd914603177895f8117fd3861bfd | [] | no_license | rajsanka/studenttrack | https://github.com/rajsanka/studenttrack | feb9a31baf05fe54edb9faaad13dd5696a3d17db | 066afa823dad41c935624d125b43ffe054a9cc1b | refs/heads/master | 2023-02-21T00:03:12.493000 | 2017-03-23T04:52:02 | 2017-03-23T04:52:02 | 79,415,735 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package xchg.online.register;
import android.app.Activity;
import android.util.Log;
import org.anon.smart.client.SmartEvent;
import org.anon.smart.client.SmartResponseListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by rsankarx on 12/12/16.
*/
public class LookupEvent extends SmartEvent {
public interface LookupProfileListener {
public void onProfile(Map data);
public void onError(String msg);
}
public class LookupSmartListener implements SmartResponseListener {
LookupProfileListener listener;
LookupSmartListener(LookupProfileListener l) {
listener = l;
}
@Override
public void handleResponse(List list) {
List result = (List) ((Map)list.get(0)).get("result");
if ((result != null) && (result.size() > 0)) {
listener.onProfile((Map)result.get(0));
}
}
@Override
public void handleError(double code, String context) {
String message = code + ":" + context;
Log.i(TAG, "Error Searching data: " + message);
listener.onError(message);
}
@Override
public void handleNetworkError(String message) {
Log.i(TAG, "Error Searching data: " + message);
listener.onError(message);
}
}
private static final String TAG = LookupEvent.class.getSimpleName();
private static final String FLOW = "ProfileFlow";
private String email;
public LookupEvent(String e) {
super(FLOW);
email = e;
}
@Override
protected Map<String, Object> getParams() {
Map<String, Object> parms = new HashMap<>();
parms.put("group", "Profile");
parms.put("key", email);
return parms;
}
public void postTo(Activity activity, LookupProfileListener listener) {
super.postEvent(activity, new LookupSmartListener(listener), "FlowAdmin", FLOW);
}
}
| UTF-8 | Java | 2,015 | java | LookupEvent.java | Java | [
{
"context": "til.List;\nimport java.util.Map;\n\n/**\n * Created by rsankarx on 12/12/16.\n */\n\npublic class LookupEvent extend",
"end": 278,
"score": 0.9997010231018066,
"start": 270,
"tag": "USERNAME",
"value": "rsankarx"
}
] | null | [] | package xchg.online.register;
import android.app.Activity;
import android.util.Log;
import org.anon.smart.client.SmartEvent;
import org.anon.smart.client.SmartResponseListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by rsankarx on 12/12/16.
*/
public class LookupEvent extends SmartEvent {
public interface LookupProfileListener {
public void onProfile(Map data);
public void onError(String msg);
}
public class LookupSmartListener implements SmartResponseListener {
LookupProfileListener listener;
LookupSmartListener(LookupProfileListener l) {
listener = l;
}
@Override
public void handleResponse(List list) {
List result = (List) ((Map)list.get(0)).get("result");
if ((result != null) && (result.size() > 0)) {
listener.onProfile((Map)result.get(0));
}
}
@Override
public void handleError(double code, String context) {
String message = code + ":" + context;
Log.i(TAG, "Error Searching data: " + message);
listener.onError(message);
}
@Override
public void handleNetworkError(String message) {
Log.i(TAG, "Error Searching data: " + message);
listener.onError(message);
}
}
private static final String TAG = LookupEvent.class.getSimpleName();
private static final String FLOW = "ProfileFlow";
private String email;
public LookupEvent(String e) {
super(FLOW);
email = e;
}
@Override
protected Map<String, Object> getParams() {
Map<String, Object> parms = new HashMap<>();
parms.put("group", "Profile");
parms.put("key", email);
return parms;
}
public void postTo(Activity activity, LookupProfileListener listener) {
super.postEvent(activity, new LookupSmartListener(listener), "FlowAdmin", FLOW);
}
}
| 2,015 | 0.62134 | 0.616873 | 74 | 26.229731 | 23.58856 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.540541 | false | false | 13 |
b3f5310153e2013f803c4f34860e60efbec0f632 | 38,182,259,294,119 | 2079a6cdd739d332773114f379602344d1cd273e | /app/src/main/java/com/example/operacionesmteriasprimas/Adapters/ListAdapterActividades.java | 44e26dcb490ffaf6ba7ba6ce94bb2af7992b09ba | [] | no_license | ppereira123/OperacionesMateriasPrimas | https://github.com/ppereira123/OperacionesMateriasPrimas | 3eaf2a4af7548100d0250e0a36f4ad6e7dac7be9 | d754149807d18bc9555401404f0ba84f12e9c51f | refs/heads/main | 2023-07-05T00:00:27.934000 | 2021-08-31T16:46:56 | 2021-08-31T16:46:56 | 357,053,712 | 0 | 0 | null | false | 2021-08-03T15:30:33 | 2021-04-12T04:10:34 | 2021-05-14T15:54:16 | 2021-08-03T15:30:33 | 8,835 | 0 | 0 | 0 | Java | false | false | package com.example.operacionesmteriasprimas.Adapters;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.UnderlineSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.operacionesmteriasprimas.R;
import com.example.operacionesmteriasprimas.ui.reporte.ListaActividadOperadores;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ListAdapterActividades extends RecyclerView.Adapter<ListAdapterActividades.ViewHolder> {
private List<String> mdata;
private Context context;
List <Double> valores;
int posicion;
private ListaActividadOperadores instance;
Double horas;
LayoutInflater mInflater;
public ListAdapterActividades(List<String> mdata, Context context,List<Double> valores, int posicion, ListaActividadOperadores instance){
this.mInflater=LayoutInflater.from(context);
this.context=context;
this.mdata =mdata;
this.posicion=posicion;
this.instance = instance;
this.valores = valores;
}
public ListAdapterActividades(){
}
@NonNull
@Override
public ListAdapterActividades
.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= mInflater.inflate(R.layout.adaptador_reportes_diarios,null);
return new ListAdapterActividades.ViewHolder(view);
}
@Override
public void onViewRecycled(@NonNull ViewHolder holder) {
super.onViewRecycled(holder);
}
@Override
public void onBindViewHolder(@NonNull ListAdapterActividades.ViewHolder holder, int position) {
holder.binData(mdata.get(position));
}
@Override
public int getItemCount() {
return mdata.size();
}
public List<Double> getValores(){
return valores;
}
public void setValores(List<Double> valores){
this.valores=valores;
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView txtEnunciado;
TextInputEditText tietHoras;
Button btnSiguient;
Button btnAnterior;
View view;
public ViewHolder(View view) {
super(view);
this.view = view;
txtEnunciado=view.findViewById(R.id.txtNombreActividad);
tietHoras=view.findViewById(R.id.editTextHoras);
btnSiguient=view.findViewById(R.id.btnSiguiente);
btnAnterior=view.findViewById(R.id.btnAnterio);
}
public void binData(String item) {
if(valores.get(posicion)>0.0){
tietHoras.setText(String.valueOf(valores.get(posicion)));
}
else{
tietHoras.setText("");
}
txtEnunciado.setText(item);
tietHoras.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if(s.length()>0){
horas=Double.parseDouble(s.toString());
}
else{
horas=0.0;
}
if(horas>0.0){
valores.remove(posicion);
valores.add(posicion,horas);
instance.iniciarChips();
}
else{
valores.remove(posicion);
valores.add(posicion,0.0);
instance.iniciarChips();
}
}
});
btnSiguient.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean siguiente=instance.siguiente(item);
if(siguiente){
btnSiguient.setEnabled(true);
btnSiguient.setTextColor(context.getColor(R.color.purple_200));
}
else{
btnSiguient.setEnabled(false);
btnSiguient.setTextColor(context.getColor(R.color.tab));
}
}
});
btnAnterior.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean siguiente=instance.anterior(item);
if(siguiente){
btnAnterior.setEnabled(true);
btnAnterior.setTextColor(context.getColor(R.color.purple_200));
}
else{
btnAnterior.setEnabled(false);
btnAnterior.setTextColor(context.getColor(R.color.tab));
}
}
});
}
}
}
| UTF-8 | Java | 5,771 | java | ListAdapterActividades.java | Java | [] | null | [] | package com.example.operacionesmteriasprimas.Adapters;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.UnderlineSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.operacionesmteriasprimas.R;
import com.example.operacionesmteriasprimas.ui.reporte.ListaActividadOperadores;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ListAdapterActividades extends RecyclerView.Adapter<ListAdapterActividades.ViewHolder> {
private List<String> mdata;
private Context context;
List <Double> valores;
int posicion;
private ListaActividadOperadores instance;
Double horas;
LayoutInflater mInflater;
public ListAdapterActividades(List<String> mdata, Context context,List<Double> valores, int posicion, ListaActividadOperadores instance){
this.mInflater=LayoutInflater.from(context);
this.context=context;
this.mdata =mdata;
this.posicion=posicion;
this.instance = instance;
this.valores = valores;
}
public ListAdapterActividades(){
}
@NonNull
@Override
public ListAdapterActividades
.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= mInflater.inflate(R.layout.adaptador_reportes_diarios,null);
return new ListAdapterActividades.ViewHolder(view);
}
@Override
public void onViewRecycled(@NonNull ViewHolder holder) {
super.onViewRecycled(holder);
}
@Override
public void onBindViewHolder(@NonNull ListAdapterActividades.ViewHolder holder, int position) {
holder.binData(mdata.get(position));
}
@Override
public int getItemCount() {
return mdata.size();
}
public List<Double> getValores(){
return valores;
}
public void setValores(List<Double> valores){
this.valores=valores;
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView txtEnunciado;
TextInputEditText tietHoras;
Button btnSiguient;
Button btnAnterior;
View view;
public ViewHolder(View view) {
super(view);
this.view = view;
txtEnunciado=view.findViewById(R.id.txtNombreActividad);
tietHoras=view.findViewById(R.id.editTextHoras);
btnSiguient=view.findViewById(R.id.btnSiguiente);
btnAnterior=view.findViewById(R.id.btnAnterio);
}
public void binData(String item) {
if(valores.get(posicion)>0.0){
tietHoras.setText(String.valueOf(valores.get(posicion)));
}
else{
tietHoras.setText("");
}
txtEnunciado.setText(item);
tietHoras.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if(s.length()>0){
horas=Double.parseDouble(s.toString());
}
else{
horas=0.0;
}
if(horas>0.0){
valores.remove(posicion);
valores.add(posicion,horas);
instance.iniciarChips();
}
else{
valores.remove(posicion);
valores.add(posicion,0.0);
instance.iniciarChips();
}
}
});
btnSiguient.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean siguiente=instance.siguiente(item);
if(siguiente){
btnSiguient.setEnabled(true);
btnSiguient.setTextColor(context.getColor(R.color.purple_200));
}
else{
btnSiguient.setEnabled(false);
btnSiguient.setTextColor(context.getColor(R.color.tab));
}
}
});
btnAnterior.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean siguiente=instance.anterior(item);
if(siguiente){
btnAnterior.setEnabled(true);
btnAnterior.setTextColor(context.getColor(R.color.purple_200));
}
else{
btnAnterior.setEnabled(false);
btnAnterior.setTextColor(context.getColor(R.color.tab));
}
}
});
}
}
}
| 5,771 | 0.591579 | 0.588979 | 191 | 29.209425 | 25.845657 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.502618 | false | false | 13 |
8a191cb1f4a1a0b4a2f0d9f048b2371d7d94ace2 | 38,723,425,167,235 | a89ed1c001abccff5ee587b907dbb12e2ef3cd50 | /TransactionmanagementAndJdbcTemplatePractise/src/com/dao/StudentMapper.java | 7dc5a9c2fc79020edde3306edb18c0ed5ca4131d | [] | no_license | Param05/workspace-all | https://github.com/Param05/workspace-all | 2c8c333737a0348c0d3e5b97e3f3dab29b88c294 | 8af2560b28cf1f91374241c3f55873a91d219144 | refs/heads/master | 2020-02-16T02:25:47.761000 | 2018-10-16T17:53:37 | 2018-10-16T17:53:37 | 124,544,955 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.model.Student;
public class StudentMapper implements RowMapper<Student> {
@Override
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student student = new Student();
student.setStudentEmailId(rs.getString("studentEmailId"));
student.setStudentFirstName(student.getStudentFirstName());
student.setStudentLastName(student.getStudentLastName());
return student;
}
}
| UTF-8 | Java | 536 | java | StudentMapper.java | Java | [] | null | [] | package com.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.model.Student;
public class StudentMapper implements RowMapper<Student> {
@Override
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student student = new Student();
student.setStudentEmailId(rs.getString("studentEmailId"));
student.setStudentFirstName(student.getStudentFirstName());
student.setStudentLastName(student.getStudentLastName());
return student;
}
}
| 536 | 0.79291 | 0.79291 | 21 | 24.523809 | 24.488323 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.142857 | false | false | 13 |
288b8c75633a0967df9602f7a4182f2b6b936d70 | 39,479,339,404,431 | 34a77684dc5224512b5e6401837c1297b2e4f0b6 | /SPEREC_ECLIPSE/src/app/NewPopRef.java | 0c74d894ac457ff71918d59241018dd84fd98cc4 | [] | no_license | francesigo/sperec | https://github.com/francesigo/sperec | a41d01f582d7ece36152711f79dc785c36ef4d40 | 4ad87e22068dc6072f0e2dda77dc8aed708d8e5c | refs/heads/master | 2020-08-21T16:26:11.667000 | 2019-10-19T12:21:38 | 2019-10-19T12:21:38 | 216,198,587 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package app;
import java.awt.BorderLayout;
import java.awt.Container;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import guiutils.ChooseConfigurationFile;
import guiutils.ChooseFile;
import guiutils.InputSperecSpecs;
import guiutils.SaveFile;
import myMath.MyMatrix;
import sperec_common.ConfigurationFile;
import sperec_common.FeaSpecs;
import sperec_common.LabeledArrayList;
import sperec_common.POPREF_MODEL;
import sperec_common.SPEREC_Specs;
import sperec_common.SessionsTable_MyMatrix;
import sperec_common.Specs;
import sperec_common.LabeledArrayListOfSpeakers;
import sperec_common.AllSessionsArrays;
import sperec_common.StRecord;
import sperec_common.VadSpecs;
import sperec_jvm.POPREF_Builder;
public class NewPopRef {
/*
* A JtextArea where to print some messages. At the moment is not used
*/
JTextArea output = null;
/*
* The base path where to put files. At the moment is empty
*/
String MAIN_OUTPUT_FOLDER_PATH = ""; //Environment.getMainOutputFolderPath();
static final String newline = "\n";
/*
* GUI object to input the sperec specifications
*/
InputSperecSpecs inputSperecSpecs = null;
/*
* The current sperec specifications
*/
SPEREC_Specs specs = null;
/*
* The current configuration file object
*/
ConfigurationFile cfg = null;
/*
* The current path of the configuration file for the features
*/
String feaCfgFilePath = "";
Container createContentPane() {
//Create the content-pane-to-be.
JPanel contentPane = new JPanel(new BorderLayout());
JScrollPane scrollPane;
contentPane.setOpaque(true);
//Create a scrolled text area.
output = new JTextArea(15, 100);
output.setEditable(false);
scrollPane = new JScrollPane(output);
//Add the text area to the content pane.
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
private void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("NEW REFERENCE POPULATION MODELS"); //("SPEREC - POPREF Model Builder");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
//SperecLab demo = new SperecLab();
//frame.setJMenuBar(demo.createMenuBar());
frame.setContentPane(createContentPane());
//Display the window.
frame.setSize(450, 260);
frame.setVisible(true);
}
/**
* Stand-alone main
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
NewPopRef me = new NewPopRef();
me.createAndShowGUI();
try {
me.work();
}
catch (Exception e)
{
String msg = "ERROR" + newline + e.getMessage();
me.outputToUser(newline + msg + newline);
throw e;
}
}
/**
* Get the sperc specs. The user can provide also a cross validation specs.
* @throws IOException
*/
public void getSperecSpecs() throws IOException {
inputSperecSpecs = new InputSperecSpecs();
cfg = ChooseConfigurationFile.get("", inputSperecSpecs.humanReadableName);
if ((cfg==null) || (cfg.cfgFilePath.equals("")) )
{
specs = inputSperecSpecs.getFromGUI(null);
if (specs==null)
return;
}
else
{
//cfg = inputSperecSpecs.getConfigurationFile();
if (cfg.hasSection(inputSperecSpecs.cfgSectionName))
{
specs = Specs.fromJsonString(cfg.getItem(inputSperecSpecs.cfgSectionName, inputSperecSpecs.cfgItemName), SPEREC_Specs.class);
inputSperecSpecs = new InputSperecSpecs(specs);
feaCfgFilePath = cfg.getItem("FEA", "feaCfgFile");
}
else
{
InputCrossValidationSpecs inputCrossValidationSpecs = new InputCrossValidationSpecs();
if (cfg.hasSection(inputCrossValidationSpecs.cfgSectionName))
{
CrossValidationSpecs cvSpecs = Specs.fromJsonString(cfg.getItem(inputCrossValidationSpecs.cfgSectionName, inputCrossValidationSpecs.cfgItemName), CrossValidationSpecs.class);
inputSperecSpecs = new InputSperecSpecs(cvSpecs.specs);
feaCfgFilePath = cvSpecs.cleanFeaCfgFile;
}
}
}
specs = inputSperecSpecs.getSpecs();
// For the user
if (specs!=null)
outputToUser("Sperec specs:" + newline + specs.toPrettyJsonString() + newline);
}
/**
* Get the feature specification
* @param feaCfgFilePath
* @return
* @throws IOException
*/
FeaSpecs getFeaSpecs(String feaCfgFilePath) throws IOException {
//feaDir = new File(feaCfgFilePath).getParent();
// Import the configuration of the new selected fea and set the datasource name
ConfigurationFile feaCfg = ConfigurationFile.load(feaCfgFilePath);
//String vadJson = feaCfg.getItem("VAD", "VadSpecs"); UNUSED
//VadSpecs vadSpecs = VadSpecs.fromJsonString(vadJson, VadSpecs.class);
String feaJson = feaCfg.getItem("FEA", "FeaSpecs");
FeaSpecs feaSpecs = FeaSpecs.fromJsonString(feaJson, FeaSpecs.class);
//dataSource = feaSpecs.dataSource;
//String feaFileList = feaCfg.getItem("FEA", "feaFileList"); // Relative to the directory where is feaCfgFilePath
//feaFileList = feaDir + File.separator + feaFileList;
if (feaSpecs!=null)
{
cfg.addItem("FEA", "FeaSpecs", feaJson);
outputToUser(newline + "Feature specs: " + newline + feaSpecs.toPrettyJsonString() + newline);
String vadJson = feaCfg.getItem("VAD", "VadSpecs");
VadSpecs vadSpecs = VadSpecs.fromJsonString(vadJson);
cfg.addItem("VAD", "VadSpecs", vadJson);
outputToUser(newline + "Voice Activity Detection specs: " + newline + vadSpecs.toPrettyJsonString() + newline);
}
return feaSpecs;
}
/**
* Save the current configuration
* @param popRefOutFolder
* @param popRefOutFileName
* @param baseOutName
* @param feaSpecs
* @throws IOException
*/
String saveCfg(String popRefOutFolder, String popRefOutFileName, String baseOutName, FeaSpecs feaSpecs) throws IOException {
ConfigurationFile newCfg = new ConfigurationFile();
newCfg.addSection(inputSperecSpecs.cfgSectionName);
newCfg.addItem(inputSperecSpecs.cfgSectionName, inputSperecSpecs.cfgItemName, specs.toJsonString());
newCfg.addItem(inputSperecSpecs.cfgSectionName, "popRefFileName", popRefOutFileName);
newCfg.addItem(inputSperecSpecs.cfgSectionName, "dataSource", feaSpecs.dataSource);
newCfg.addSection("FEA");
newCfg.addItem("FEA", "FeaSpecs", cfg.getItem("FEA", "FeaSpecs"));
newCfg.addItem("FEA", "feaCfgFile", feaCfgFilePath);
newCfg.addSection("VAD");
newCfg.addItem("VAD", "VadSpecs", cfg.getItem("VAD", "VadSpecs"));
// Save the reference population configuration file
return newCfg.saveAs(popRefOutFolder, baseOutName + ".cfg");
}
/**
*
* @throws Exception
*/
public void work() throws Exception {
String popRefOutFolder = MAIN_OUTPUT_FOLDER_PATH; // Default, to be changed at run-time
String popRefOutFileName = "";
// 1. Get the specs specifications and other settings
getSperecSpecs();
if (specs==null)
return;
// 2. Get the feature specifications
feaCfgFilePath = ChooseFile.get(feaCfgFilePath, "Select the Feature Configuration File", "(.cfg)", "cfg");
if ( (feaCfgFilePath==null) || (feaCfgFilePath.equals("")))
return;
FeaSpecs feaSpecs = getFeaSpecs(feaCfgFilePath);
// ------------------------------ Output
// 3. Set output locations
String popRefFullPath = SaveFile.as(cfg.cfgFilePath, "Save reference popoulation as", "pop");
if ((popRefFullPath==null) || popRefFullPath.equals(""))
return;
File tempF = new File(popRefFullPath);
popRefOutFolder = tempF.getParent().toString();
popRefOutFileName = tempF.getName();
String baseOutName = popRefOutFileName.substring(0, popRefOutFileName.lastIndexOf("."));
// 4. Save the current configuration
String newCfgFullPath = saveCfg(popRefOutFolder, popRefOutFileName, baseOutName, feaSpecs);
// 5. ---------------------------------------- Do the job
// Get the feature dataset
FeaDataSet cleanFeaDataset = FeaDataSet.fromConfigFile(feaCfgFilePath);
// Get as array list of recordsets
ArrayList<LabeledArrayList<StRecord>> enrollmentSessions = cleanFeaDataset.getArrayListOfRecordSets(); // sotto forma di array
// Now make the chunks for enrollment
int enrollSessionDurationFrames = (int)Math.round(specs.enrollSessionDurationSec/ feaSpecs.fFrameIncrementSec);
SessionsTable_MyMatrix STM = new SessionsTable_MyMatrix();
LabeledArrayListOfSpeakers<MyMatrix> speakersChunks = STM.makeChunks(enrollmentSessions, enrollSessionDurationFrames);
outputToUser("FOUND " + speakersChunks.size() + " speaker available for reference population computation");
AllSessionsArrays<MyMatrix> a = STM.toSessionsArrays(speakersChunks);
POPREF_MODEL pop = new POPREF_Builder().build(specs, feaSpecs, a, false); // Can throw Exception
// Save
pop.writeToFile(new File(popRefFullPath));
// To user
outputToUser(newline + "Output file of engine models: " + popRefFullPath + newline + newline + "DONE" + newline);
outputToUser(newline + "Output file of configuration: " + newCfgFullPath + newline + newline + "DONE" + newline);
}
/**
* Display a message for the user
* @param msg
*/
void outputToUser(String msg) {
if (output!=null)
{
output.append(msg);
output.setCaretPosition(output.getDocument().getLength());
}
System.out.println(msg);
}
}
| UTF-8 | Java | 9,654 | java | NewPopRef.java | Java | [] | null | [] | package app;
import java.awt.BorderLayout;
import java.awt.Container;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import guiutils.ChooseConfigurationFile;
import guiutils.ChooseFile;
import guiutils.InputSperecSpecs;
import guiutils.SaveFile;
import myMath.MyMatrix;
import sperec_common.ConfigurationFile;
import sperec_common.FeaSpecs;
import sperec_common.LabeledArrayList;
import sperec_common.POPREF_MODEL;
import sperec_common.SPEREC_Specs;
import sperec_common.SessionsTable_MyMatrix;
import sperec_common.Specs;
import sperec_common.LabeledArrayListOfSpeakers;
import sperec_common.AllSessionsArrays;
import sperec_common.StRecord;
import sperec_common.VadSpecs;
import sperec_jvm.POPREF_Builder;
public class NewPopRef {
/*
* A JtextArea where to print some messages. At the moment is not used
*/
JTextArea output = null;
/*
* The base path where to put files. At the moment is empty
*/
String MAIN_OUTPUT_FOLDER_PATH = ""; //Environment.getMainOutputFolderPath();
static final String newline = "\n";
/*
* GUI object to input the sperec specifications
*/
InputSperecSpecs inputSperecSpecs = null;
/*
* The current sperec specifications
*/
SPEREC_Specs specs = null;
/*
* The current configuration file object
*/
ConfigurationFile cfg = null;
/*
* The current path of the configuration file for the features
*/
String feaCfgFilePath = "";
Container createContentPane() {
//Create the content-pane-to-be.
JPanel contentPane = new JPanel(new BorderLayout());
JScrollPane scrollPane;
contentPane.setOpaque(true);
//Create a scrolled text area.
output = new JTextArea(15, 100);
output.setEditable(false);
scrollPane = new JScrollPane(output);
//Add the text area to the content pane.
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
private void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("NEW REFERENCE POPULATION MODELS"); //("SPEREC - POPREF Model Builder");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
//SperecLab demo = new SperecLab();
//frame.setJMenuBar(demo.createMenuBar());
frame.setContentPane(createContentPane());
//Display the window.
frame.setSize(450, 260);
frame.setVisible(true);
}
/**
* Stand-alone main
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
NewPopRef me = new NewPopRef();
me.createAndShowGUI();
try {
me.work();
}
catch (Exception e)
{
String msg = "ERROR" + newline + e.getMessage();
me.outputToUser(newline + msg + newline);
throw e;
}
}
/**
* Get the sperc specs. The user can provide also a cross validation specs.
* @throws IOException
*/
public void getSperecSpecs() throws IOException {
inputSperecSpecs = new InputSperecSpecs();
cfg = ChooseConfigurationFile.get("", inputSperecSpecs.humanReadableName);
if ((cfg==null) || (cfg.cfgFilePath.equals("")) )
{
specs = inputSperecSpecs.getFromGUI(null);
if (specs==null)
return;
}
else
{
//cfg = inputSperecSpecs.getConfigurationFile();
if (cfg.hasSection(inputSperecSpecs.cfgSectionName))
{
specs = Specs.fromJsonString(cfg.getItem(inputSperecSpecs.cfgSectionName, inputSperecSpecs.cfgItemName), SPEREC_Specs.class);
inputSperecSpecs = new InputSperecSpecs(specs);
feaCfgFilePath = cfg.getItem("FEA", "feaCfgFile");
}
else
{
InputCrossValidationSpecs inputCrossValidationSpecs = new InputCrossValidationSpecs();
if (cfg.hasSection(inputCrossValidationSpecs.cfgSectionName))
{
CrossValidationSpecs cvSpecs = Specs.fromJsonString(cfg.getItem(inputCrossValidationSpecs.cfgSectionName, inputCrossValidationSpecs.cfgItemName), CrossValidationSpecs.class);
inputSperecSpecs = new InputSperecSpecs(cvSpecs.specs);
feaCfgFilePath = cvSpecs.cleanFeaCfgFile;
}
}
}
specs = inputSperecSpecs.getSpecs();
// For the user
if (specs!=null)
outputToUser("Sperec specs:" + newline + specs.toPrettyJsonString() + newline);
}
/**
* Get the feature specification
* @param feaCfgFilePath
* @return
* @throws IOException
*/
FeaSpecs getFeaSpecs(String feaCfgFilePath) throws IOException {
//feaDir = new File(feaCfgFilePath).getParent();
// Import the configuration of the new selected fea and set the datasource name
ConfigurationFile feaCfg = ConfigurationFile.load(feaCfgFilePath);
//String vadJson = feaCfg.getItem("VAD", "VadSpecs"); UNUSED
//VadSpecs vadSpecs = VadSpecs.fromJsonString(vadJson, VadSpecs.class);
String feaJson = feaCfg.getItem("FEA", "FeaSpecs");
FeaSpecs feaSpecs = FeaSpecs.fromJsonString(feaJson, FeaSpecs.class);
//dataSource = feaSpecs.dataSource;
//String feaFileList = feaCfg.getItem("FEA", "feaFileList"); // Relative to the directory where is feaCfgFilePath
//feaFileList = feaDir + File.separator + feaFileList;
if (feaSpecs!=null)
{
cfg.addItem("FEA", "FeaSpecs", feaJson);
outputToUser(newline + "Feature specs: " + newline + feaSpecs.toPrettyJsonString() + newline);
String vadJson = feaCfg.getItem("VAD", "VadSpecs");
VadSpecs vadSpecs = VadSpecs.fromJsonString(vadJson);
cfg.addItem("VAD", "VadSpecs", vadJson);
outputToUser(newline + "Voice Activity Detection specs: " + newline + vadSpecs.toPrettyJsonString() + newline);
}
return feaSpecs;
}
/**
* Save the current configuration
* @param popRefOutFolder
* @param popRefOutFileName
* @param baseOutName
* @param feaSpecs
* @throws IOException
*/
String saveCfg(String popRefOutFolder, String popRefOutFileName, String baseOutName, FeaSpecs feaSpecs) throws IOException {
ConfigurationFile newCfg = new ConfigurationFile();
newCfg.addSection(inputSperecSpecs.cfgSectionName);
newCfg.addItem(inputSperecSpecs.cfgSectionName, inputSperecSpecs.cfgItemName, specs.toJsonString());
newCfg.addItem(inputSperecSpecs.cfgSectionName, "popRefFileName", popRefOutFileName);
newCfg.addItem(inputSperecSpecs.cfgSectionName, "dataSource", feaSpecs.dataSource);
newCfg.addSection("FEA");
newCfg.addItem("FEA", "FeaSpecs", cfg.getItem("FEA", "FeaSpecs"));
newCfg.addItem("FEA", "feaCfgFile", feaCfgFilePath);
newCfg.addSection("VAD");
newCfg.addItem("VAD", "VadSpecs", cfg.getItem("VAD", "VadSpecs"));
// Save the reference population configuration file
return newCfg.saveAs(popRefOutFolder, baseOutName + ".cfg");
}
/**
*
* @throws Exception
*/
public void work() throws Exception {
String popRefOutFolder = MAIN_OUTPUT_FOLDER_PATH; // Default, to be changed at run-time
String popRefOutFileName = "";
// 1. Get the specs specifications and other settings
getSperecSpecs();
if (specs==null)
return;
// 2. Get the feature specifications
feaCfgFilePath = ChooseFile.get(feaCfgFilePath, "Select the Feature Configuration File", "(.cfg)", "cfg");
if ( (feaCfgFilePath==null) || (feaCfgFilePath.equals("")))
return;
FeaSpecs feaSpecs = getFeaSpecs(feaCfgFilePath);
// ------------------------------ Output
// 3. Set output locations
String popRefFullPath = SaveFile.as(cfg.cfgFilePath, "Save reference popoulation as", "pop");
if ((popRefFullPath==null) || popRefFullPath.equals(""))
return;
File tempF = new File(popRefFullPath);
popRefOutFolder = tempF.getParent().toString();
popRefOutFileName = tempF.getName();
String baseOutName = popRefOutFileName.substring(0, popRefOutFileName.lastIndexOf("."));
// 4. Save the current configuration
String newCfgFullPath = saveCfg(popRefOutFolder, popRefOutFileName, baseOutName, feaSpecs);
// 5. ---------------------------------------- Do the job
// Get the feature dataset
FeaDataSet cleanFeaDataset = FeaDataSet.fromConfigFile(feaCfgFilePath);
// Get as array list of recordsets
ArrayList<LabeledArrayList<StRecord>> enrollmentSessions = cleanFeaDataset.getArrayListOfRecordSets(); // sotto forma di array
// Now make the chunks for enrollment
int enrollSessionDurationFrames = (int)Math.round(specs.enrollSessionDurationSec/ feaSpecs.fFrameIncrementSec);
SessionsTable_MyMatrix STM = new SessionsTable_MyMatrix();
LabeledArrayListOfSpeakers<MyMatrix> speakersChunks = STM.makeChunks(enrollmentSessions, enrollSessionDurationFrames);
outputToUser("FOUND " + speakersChunks.size() + " speaker available for reference population computation");
AllSessionsArrays<MyMatrix> a = STM.toSessionsArrays(speakersChunks);
POPREF_MODEL pop = new POPREF_Builder().build(specs, feaSpecs, a, false); // Can throw Exception
// Save
pop.writeToFile(new File(popRefFullPath));
// To user
outputToUser(newline + "Output file of engine models: " + popRefFullPath + newline + newline + "DONE" + newline);
outputToUser(newline + "Output file of configuration: " + newCfgFullPath + newline + newline + "DONE" + newline);
}
/**
* Display a message for the user
* @param msg
*/
void outputToUser(String msg) {
if (output!=null)
{
output.append(msg);
output.setCaretPosition(output.getDocument().getLength());
}
System.out.println(msg);
}
}
| 9,654 | 0.703335 | 0.701575 | 300 | 30.18 | 31.594213 | 179 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.086667 | false | false | 13 |
2f840d97772e01d9284439eee3cede6f724f2157 | 36,919,538,914,429 | d97233eeb7300accb1b55cce8158c6cd4ac7aec2 | /src/main/java/com/timeline/entity/classes/ClassDetail.java | f8f130a12dc385f31d8c53fed73d00d90c7fc06e | [] | no_license | hyojinsim90/timeline | https://github.com/hyojinsim90/timeline | a10f1f380abba428d173d73c3e428913efaa1808 | 81eab12fcc820d581ae735b901257e1bc04bc3e1 | refs/heads/master | 2023-06-26T19:03:56.146000 | 2021-07-28T16:22:30 | 2021-07-28T16:22:30 | 357,631,661 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.timeline.entity.classes;
import com.timeline.entity.BaseTimeEntity;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
/**
* @author : Hyojin Sim
* @version : 1.0.0
* @date : 2021-07-09 오후 11:03
* @brief : class detail
**/
@Getter
@NoArgsConstructor
@Table(name = "class_detail")
@Entity
@IdClass(ClassDetailPk.class)
public class ClassDetail extends BaseTimeEntity {
@Id
@Column(name = "master_id")
private Long masterId; // 클래스 master_id
@Id
@Column(name = "id")
private Long id; // 클래스 detail_id
@Column(name = "group_name")
private String groupName; // 그룹명
@Column(name = "quantity")
private int quantity; // 수량
@Column(name = "price")
private int price; // 금액
@Builder
public ClassDetail(Long masterId, Long id, String groupName, int quantity, int price) {
this.masterId = masterId;
this.id = id;
this.groupName = groupName;
this.quantity = quantity;
this.price = price;
}
public void update(String groupName, int quantity, int price) {
this.groupName = groupName;
this.quantity = quantity;
this.price = price;
}
}
| UTF-8 | Java | 1,267 | java | ClassDetail.java | Java | [
{
"context": "r;\n\nimport javax.persistence.*;\n\n\n/**\n * @author : Hyojin Sim\n * @version : 1.0.0\n * @date : 2021-07-09 오후 11:0",
"end": 217,
"score": 0.9995688796043396,
"start": 207,
"tag": "NAME",
"value": "Hyojin Sim"
}
] | null | [] | package com.timeline.entity.classes;
import com.timeline.entity.BaseTimeEntity;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
/**
* @author : <NAME>
* @version : 1.0.0
* @date : 2021-07-09 오후 11:03
* @brief : class detail
**/
@Getter
@NoArgsConstructor
@Table(name = "class_detail")
@Entity
@IdClass(ClassDetailPk.class)
public class ClassDetail extends BaseTimeEntity {
@Id
@Column(name = "master_id")
private Long masterId; // 클래스 master_id
@Id
@Column(name = "id")
private Long id; // 클래스 detail_id
@Column(name = "group_name")
private String groupName; // 그룹명
@Column(name = "quantity")
private int quantity; // 수량
@Column(name = "price")
private int price; // 금액
@Builder
public ClassDetail(Long masterId, Long id, String groupName, int quantity, int price) {
this.masterId = masterId;
this.id = id;
this.groupName = groupName;
this.quantity = quantity;
this.price = price;
}
public void update(String groupName, int quantity, int price) {
this.groupName = groupName;
this.quantity = quantity;
this.price = price;
}
}
| 1,263 | 0.646726 | 0.6346 | 57 | 20.701754 | 18.41716 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.438596 | false | false | 13 |
0a92696641ec94a8431e77d899eb22cdb359a7b9 | 37,898,791,450,629 | 54ddb74f4253c099268a6da56ecab6bfee36b31d | /Assignment 5.java | 02f56075c75a4d62ae70f70736bcf4216be04fed | [] | no_license | 30013622/assignment-2 | https://github.com/30013622/assignment-2 | bc43a8b506c6de1715e550b43d354c163fa987b9 | 1b8f1d9495107ce17b1a4aefbf01a0d65a713c4f | refs/heads/master | 2020-08-29T19:35:31.068000 | 2020-02-12T20:51:09 | 2020-02-12T20:51:09 | 218,149,265 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
import java.lang.Math;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println( "How long do you want the array?");
int x = scan.nextInt();
if(x>0){
for(int i = 0; i < x; i++){
System.out.println( "Enter a number");
double y = scan.nextDouble();
}
} else {
System.out.println("Not a valid length!");
}
}
} | UTF-8 | Java | 532 | java | Assignment 5.java | Java | [] | null | [] | import java.util.Scanner;
import java.lang.Math;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println( "How long do you want the array?");
int x = scan.nextInt();
if(x>0){
for(int i = 0; i < x; i++){
System.out.println( "Enter a number");
double y = scan.nextDouble();
}
} else {
System.out.println("Not a valid length!");
}
}
} | 532 | 0.490602 | 0.486842 | 23 | 22.173914 | 18.841795 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false | 13 |
1f0b75742716de6ca41d7ee7a05e40fbd512ad56 | 26,697,516,713,325 | c2dce7adaeb681c5f1e34cffaba4d55104342c79 | /src/main/java/com/dreamgyf/gmqyttf/client/task/message/send/MqttPublishSendTask.java | 55f052480cec90ba32afe48b86deb698d9d3ae93 | [
"Apache-2.0"
] | permissive | dreamgyf/gmqyttf-client | https://github.com/dreamgyf/gmqyttf-client | 582bef133bb749b01721fc85958a5ceff5c4b9d7 | c832de22100267c4e96cb4d746d604acb93f4d96 | refs/heads/master | 2021-08-07T10:39:11.174000 | 2020-12-30T06:16:27 | 2020-12-30T06:16:27 | 290,427,240 | 102 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dreamgyf.gmqyttf.client.task.message.send;
import com.dreamgyf.gmqyttf.client.socket.MqttWritableSocket;
import com.dreamgyf.gmqyttf.client.task.MqttTask;
import com.dreamgyf.gmqyttf.common.enums.MqttVersion;
import com.dreamgyf.gmqyttf.common.packet.MqttPublishPacket;
import com.dreamgyf.gmqyttf.common.throwable.exception.net.MqttSocketException;
import java.util.concurrent.LinkedBlockingQueue;
public class MqttPublishSendTask extends MqttTask {
private final LinkedBlockingQueue<MqttPublishPacket> mPublishQueue;
public MqttPublishSendTask(MqttVersion version, MqttWritableSocket socket,
LinkedBlockingQueue<MqttPublishPacket> publishQueue) {
super(version, socket);
mPublishQueue = publishQueue;
}
@Override
public void onLoop() throws InterruptedException {
try {
MqttPublishPacket packet = mPublishQueue.take();
writeSocket(packet.getPacket());
onMqttPacketSend();
} catch (MqttSocketException e) {
e.printStackTrace();
onMqttExceptionThrow(e);
}
}
}
| UTF-8 | Java | 1,133 | java | MqttPublishSendTask.java | Java | [] | null | [] | package com.dreamgyf.gmqyttf.client.task.message.send;
import com.dreamgyf.gmqyttf.client.socket.MqttWritableSocket;
import com.dreamgyf.gmqyttf.client.task.MqttTask;
import com.dreamgyf.gmqyttf.common.enums.MqttVersion;
import com.dreamgyf.gmqyttf.common.packet.MqttPublishPacket;
import com.dreamgyf.gmqyttf.common.throwable.exception.net.MqttSocketException;
import java.util.concurrent.LinkedBlockingQueue;
public class MqttPublishSendTask extends MqttTask {
private final LinkedBlockingQueue<MqttPublishPacket> mPublishQueue;
public MqttPublishSendTask(MqttVersion version, MqttWritableSocket socket,
LinkedBlockingQueue<MqttPublishPacket> publishQueue) {
super(version, socket);
mPublishQueue = publishQueue;
}
@Override
public void onLoop() throws InterruptedException {
try {
MqttPublishPacket packet = mPublishQueue.take();
writeSocket(packet.getPacket());
onMqttPacketSend();
} catch (MqttSocketException e) {
e.printStackTrace();
onMqttExceptionThrow(e);
}
}
}
| 1,133 | 0.719329 | 0.719329 | 32 | 34.40625 | 26.969728 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5625 | false | false | 13 |
ab8012e480c02a425baf98c8412d86b38340b654 | 28,922,309,804,350 | 6b2f81ff4015eecc6b258ceeed6d739c523c4a0f | /io/shui-io/shui-netty/src/main/java/com.shui.netty/first/DatagramChannelNio.java | 1586a7fa8d9b3a070b7c4a07c6e0506c49771b95 | [] | no_license | jiaofu/javatest | https://github.com/jiaofu/javatest | 117463ccec5e255befddda533b90e5ca84ce1e28 | 183574a1f17a0414812292753248e38378953229 | refs/heads/master | 2021-01-15T13:28:49.779000 | 2020-02-27T07:52:49 | 2020-02-27T07:52:49 | 99,673,646 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.shui.netty.first;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
public class DatagramChannelNio {
public static void main(String[] args) {
}
public static void receive(){
DatagramChannel channel=null;
try{
channel=DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(8888));
ByteBuffer buf=ByteBuffer.allocate(1024);
buf.clear();
channel.receive(buf);
buf.flip();
while (buf.hasRemaining()){
System.out.print((char)buf.get());
}
System.out.println();
}catch (Exception ex){
ex.printStackTrace();
}finally{
try{
if(channel!=null){
channel.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
public static void send(){
DatagramChannel channel = null;
try{
channel = DatagramChannel.open();
String info = "I'm the Sender!";
ByteBuffer buf=ByteBuffer.allocate(1024);
buf.clear();
buf.put(info.getBytes());
buf.flip();
int bytesSent = channel.send(buf, new InetSocketAddress("10.10.195.115",8888));
System.out.println(bytesSent);
}catch (Exception ex){
ex.printStackTrace();
}finally {
try{
if(channel!=null){
channel.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
| UTF-8 | Java | 1,763 | java | DatagramChannelNio.java | Java | [
{
"context": "esSent = channel.send(buf, new InetSocketAddress(\"10.10.195.115\",8888));\n System.out.println(bytesSent",
"end": 1415,
"score": 0.952479898929596,
"start": 1402,
"tag": "IP_ADDRESS",
"value": "10.10.195.115"
}
] | null | [] | package com.shui.netty.first;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
public class DatagramChannelNio {
public static void main(String[] args) {
}
public static void receive(){
DatagramChannel channel=null;
try{
channel=DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(8888));
ByteBuffer buf=ByteBuffer.allocate(1024);
buf.clear();
channel.receive(buf);
buf.flip();
while (buf.hasRemaining()){
System.out.print((char)buf.get());
}
System.out.println();
}catch (Exception ex){
ex.printStackTrace();
}finally{
try{
if(channel!=null){
channel.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
public static void send(){
DatagramChannel channel = null;
try{
channel = DatagramChannel.open();
String info = "I'm the Sender!";
ByteBuffer buf=ByteBuffer.allocate(1024);
buf.clear();
buf.put(info.getBytes());
buf.flip();
int bytesSent = channel.send(buf, new InetSocketAddress("10.10.195.115",8888));
System.out.println(bytesSent);
}catch (Exception ex){
ex.printStackTrace();
}finally {
try{
if(channel!=null){
channel.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
| 1,763 | 0.505956 | 0.491208 | 62 | 27.435484 | 17.182718 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 13 |
d178d0f2e63811e90ac1f5f8d8a67a21e077f0fc | 27,771,258,552,678 | 187414dcb264fb49d82507a099fd5fdca6e55e38 | /common/network-shuffle/src/test/java/org/apache/spark/network/sasl/SaslIntegrationSuite.java | ec749cb571b123d589f21e74dabc912d30da3de1 | [
"BSD-3-Clause",
"CC0-1.0",
"CDDL-1.1",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"EPL-2.0",
"CDDL-1.0",
"MIT",
"LGPL-2.0-or-later",
"Python-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-free-unknown",... | permissive | apache/spark | https://github.com/apache/spark | 8aeba2d80465a262acc95781ede105a5b5886f6d | 60d8fc49bec5dae1b8cf39a0670cb640b430f520 | refs/heads/master | 2023-09-04T04:33:36.058000 | 2023-09-04T03:48:52 | 2023-09-04T03:48:52 | 17,165,658 | 39,983 | 32,449 | Apache-2.0 | false | 2023-09-14T19:46:24 | 2014-02-25T08:00:08 | 2023-09-14T18:30:40 | 2023-09-14T19:46:23 | 431,166 | 36,711 | 27,625 | 261 | Scala | false | false | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.network.sasl;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.apache.spark.network.TestUtils;
import org.apache.spark.network.TransportContext;
import org.apache.spark.network.client.RpcResponseCallback;
import org.apache.spark.network.client.TransportClient;
import org.apache.spark.network.client.TransportClientFactory;
import org.apache.spark.network.server.OneForOneStreamManager;
import org.apache.spark.network.server.RpcHandler;
import org.apache.spark.network.server.StreamManager;
import org.apache.spark.network.server.TransportServer;
import org.apache.spark.network.server.TransportServerBootstrap;
import org.apache.spark.network.util.JavaUtils;
import org.apache.spark.network.util.MapConfigProvider;
import org.apache.spark.network.util.TransportConf;
public class SaslIntegrationSuite {
// Use a long timeout to account for slow / overloaded build machines. In the normal case,
// tests should finish way before the timeout expires.
private static final long TIMEOUT_MS = 10_000;
static TransportServer server;
static TransportConf conf;
static TransportContext context;
static SecretKeyHolder secretKeyHolder;
TransportClientFactory clientFactory;
@BeforeClass
public static void beforeAll() throws IOException {
conf = new TransportConf("shuffle", MapConfigProvider.EMPTY);
context = new TransportContext(conf, new TestRpcHandler());
secretKeyHolder = mock(SecretKeyHolder.class);
when(secretKeyHolder.getSaslUser(eq("app-1"))).thenReturn("app-1");
when(secretKeyHolder.getSecretKey(eq("app-1"))).thenReturn("app-1");
when(secretKeyHolder.getSaslUser(eq("app-2"))).thenReturn("app-2");
when(secretKeyHolder.getSecretKey(eq("app-2"))).thenReturn("app-2");
when(secretKeyHolder.getSaslUser(anyString())).thenReturn("other-app");
when(secretKeyHolder.getSecretKey(anyString())).thenReturn("correct-password");
TransportServerBootstrap bootstrap = new SaslServerBootstrap(conf, secretKeyHolder);
server = context.createServer(Arrays.asList(bootstrap));
}
@AfterClass
public static void afterAll() {
server.close();
context.close();
}
@After
public void afterEach() {
if (clientFactory != null) {
clientFactory.close();
clientFactory = null;
}
}
@Test
public void testGoodClient() throws IOException, InterruptedException {
clientFactory = context.createClientFactory(
Arrays.asList(new SaslClientBootstrap(conf, "app-1", secretKeyHolder)));
TransportClient client = clientFactory.createClient(TestUtils.getLocalHost(), server.getPort());
String msg = "Hello, World!";
ByteBuffer resp = client.sendRpcSync(JavaUtils.stringToBytes(msg), TIMEOUT_MS);
assertEquals(msg, JavaUtils.bytesToString(resp));
}
@Test
public void testBadClient() {
SecretKeyHolder badKeyHolder = mock(SecretKeyHolder.class);
when(badKeyHolder.getSaslUser(anyString())).thenReturn("other-app");
when(badKeyHolder.getSecretKey(anyString())).thenReturn("wrong-password");
clientFactory = context.createClientFactory(
Arrays.asList(new SaslClientBootstrap(conf, "unknown-app", badKeyHolder)));
// Bootstrap should fail on startup.
Exception e = assertThrows(Exception.class,
() -> clientFactory.createClient(TestUtils.getLocalHost(), server.getPort()));
assertTrue(e.getMessage(), e.getMessage().contains("Mismatched response"));
}
@Test
public void testNoSaslClient() throws IOException, InterruptedException {
clientFactory = context.createClientFactory(new ArrayList<>());
TransportClient client = clientFactory.createClient(TestUtils.getLocalHost(), server.getPort());
Exception e1 = assertThrows(Exception.class,
() -> client.sendRpcSync(ByteBuffer.allocate(13), TIMEOUT_MS));
assertTrue(e1.getMessage(), e1.getMessage().contains("Expected SaslMessage"));
// Guessing the right tag byte doesn't magically get you in...
Exception e2 = assertThrows(Exception.class,
() -> client.sendRpcSync(ByteBuffer.wrap(new byte[] { (byte) 0xEA }), TIMEOUT_MS));
assertTrue(e2.getMessage(), e2.getMessage().contains("java.lang.IndexOutOfBoundsException"));
}
@Test
public void testNoSaslServer() {
RpcHandler handler = new TestRpcHandler();
try (TransportContext context = new TransportContext(conf, handler)) {
clientFactory = context.createClientFactory(
Arrays.asList(new SaslClientBootstrap(conf, "app-1", secretKeyHolder)));
try (TransportServer server = context.createServer()) {
Exception e = assertThrows(Exception.class,
() -> clientFactory.createClient(TestUtils.getLocalHost(), server.getPort()));
assertTrue(e.getMessage(), e.getMessage().contains("Digest-challenge format violation"));
}
}
}
/** RPC handler which simply responds with the message it received. */
public static class TestRpcHandler extends RpcHandler {
@Override
public void receive(TransportClient client, ByteBuffer message, RpcResponseCallback callback) {
callback.onSuccess(message);
}
@Override
public StreamManager getStreamManager() {
return new OneForOneStreamManager();
}
}
}
| UTF-8 | Java | 6,284 | java | SaslIntegrationSuite.java | Java | [
{
"context": "dKeyHolder.getSecretKey(anyString())).thenReturn(\"wrong-password\");\n clientFactory = context.createClientFactor",
"end": 4100,
"score": 0.9907864928245544,
"start": 4086,
"tag": "PASSWORD",
"value": "wrong-password"
}
] | null | [] | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.network.sasl;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.apache.spark.network.TestUtils;
import org.apache.spark.network.TransportContext;
import org.apache.spark.network.client.RpcResponseCallback;
import org.apache.spark.network.client.TransportClient;
import org.apache.spark.network.client.TransportClientFactory;
import org.apache.spark.network.server.OneForOneStreamManager;
import org.apache.spark.network.server.RpcHandler;
import org.apache.spark.network.server.StreamManager;
import org.apache.spark.network.server.TransportServer;
import org.apache.spark.network.server.TransportServerBootstrap;
import org.apache.spark.network.util.JavaUtils;
import org.apache.spark.network.util.MapConfigProvider;
import org.apache.spark.network.util.TransportConf;
public class SaslIntegrationSuite {
// Use a long timeout to account for slow / overloaded build machines. In the normal case,
// tests should finish way before the timeout expires.
private static final long TIMEOUT_MS = 10_000;
static TransportServer server;
static TransportConf conf;
static TransportContext context;
static SecretKeyHolder secretKeyHolder;
TransportClientFactory clientFactory;
@BeforeClass
public static void beforeAll() throws IOException {
conf = new TransportConf("shuffle", MapConfigProvider.EMPTY);
context = new TransportContext(conf, new TestRpcHandler());
secretKeyHolder = mock(SecretKeyHolder.class);
when(secretKeyHolder.getSaslUser(eq("app-1"))).thenReturn("app-1");
when(secretKeyHolder.getSecretKey(eq("app-1"))).thenReturn("app-1");
when(secretKeyHolder.getSaslUser(eq("app-2"))).thenReturn("app-2");
when(secretKeyHolder.getSecretKey(eq("app-2"))).thenReturn("app-2");
when(secretKeyHolder.getSaslUser(anyString())).thenReturn("other-app");
when(secretKeyHolder.getSecretKey(anyString())).thenReturn("correct-password");
TransportServerBootstrap bootstrap = new SaslServerBootstrap(conf, secretKeyHolder);
server = context.createServer(Arrays.asList(bootstrap));
}
@AfterClass
public static void afterAll() {
server.close();
context.close();
}
@After
public void afterEach() {
if (clientFactory != null) {
clientFactory.close();
clientFactory = null;
}
}
@Test
public void testGoodClient() throws IOException, InterruptedException {
clientFactory = context.createClientFactory(
Arrays.asList(new SaslClientBootstrap(conf, "app-1", secretKeyHolder)));
TransportClient client = clientFactory.createClient(TestUtils.getLocalHost(), server.getPort());
String msg = "Hello, World!";
ByteBuffer resp = client.sendRpcSync(JavaUtils.stringToBytes(msg), TIMEOUT_MS);
assertEquals(msg, JavaUtils.bytesToString(resp));
}
@Test
public void testBadClient() {
SecretKeyHolder badKeyHolder = mock(SecretKeyHolder.class);
when(badKeyHolder.getSaslUser(anyString())).thenReturn("other-app");
when(badKeyHolder.getSecretKey(anyString())).thenReturn("<PASSWORD>");
clientFactory = context.createClientFactory(
Arrays.asList(new SaslClientBootstrap(conf, "unknown-app", badKeyHolder)));
// Bootstrap should fail on startup.
Exception e = assertThrows(Exception.class,
() -> clientFactory.createClient(TestUtils.getLocalHost(), server.getPort()));
assertTrue(e.getMessage(), e.getMessage().contains("Mismatched response"));
}
@Test
public void testNoSaslClient() throws IOException, InterruptedException {
clientFactory = context.createClientFactory(new ArrayList<>());
TransportClient client = clientFactory.createClient(TestUtils.getLocalHost(), server.getPort());
Exception e1 = assertThrows(Exception.class,
() -> client.sendRpcSync(ByteBuffer.allocate(13), TIMEOUT_MS));
assertTrue(e1.getMessage(), e1.getMessage().contains("Expected SaslMessage"));
// Guessing the right tag byte doesn't magically get you in...
Exception e2 = assertThrows(Exception.class,
() -> client.sendRpcSync(ByteBuffer.wrap(new byte[] { (byte) 0xEA }), TIMEOUT_MS));
assertTrue(e2.getMessage(), e2.getMessage().contains("java.lang.IndexOutOfBoundsException"));
}
@Test
public void testNoSaslServer() {
RpcHandler handler = new TestRpcHandler();
try (TransportContext context = new TransportContext(conf, handler)) {
clientFactory = context.createClientFactory(
Arrays.asList(new SaslClientBootstrap(conf, "app-1", secretKeyHolder)));
try (TransportServer server = context.createServer()) {
Exception e = assertThrows(Exception.class,
() -> clientFactory.createClient(TestUtils.getLocalHost(), server.getPort()));
assertTrue(e.getMessage(), e.getMessage().contains("Digest-challenge format violation"));
}
}
}
/** RPC handler which simply responds with the message it received. */
public static class TestRpcHandler extends RpcHandler {
@Override
public void receive(TransportClient client, ByteBuffer message, RpcResponseCallback callback) {
callback.onSuccess(message);
}
@Override
public StreamManager getStreamManager() {
return new OneForOneStreamManager();
}
}
}
| 6,280 | 0.745703 | 0.741248 | 158 | 38.772152 | 30.558079 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.664557 | false | false | 13 |
2dbdefc8760bfddf2b314dd2c59719454c771edd | 26,491,358,301,949 | 00e2055b0d5d88e33d87e19fed43395d47ff208c | /IslandGlobal/build/generated-sources/ap-source-output/entity/TransactionProduct_.java | fcaf2c82ee3628686f0c4875aaff09bef4c7b04d | [] | no_license | pernjie/IslandFurniture | https://github.com/pernjie/IslandFurniture | 5fbb4ea03c82baca5bca5a3d3b9a039423ede4ef | b85d2db3dde26efa2343f5c98e2da24c8a69a359 | refs/heads/master | 2021-01-15T22:34:21.363000 | 2014-11-13T04:29:00 | 2014-11-13T04:29:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package entity;
import entity.Product;
import entity.TransactionRecord;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="EclipseLink-2.5.1.v20130918-rNA", date="2014-11-10T19:15:58")
@StaticMetamodel(TransactionProduct.class)
public class TransactionProduct_ {
public static volatile SingularAttribute<TransactionProduct, Long> id;
public static volatile SingularAttribute<TransactionProduct, Double> price;
public static volatile SingularAttribute<TransactionProduct, TransactionRecord> transact;
public static volatile SingularAttribute<TransactionProduct, Integer> quantity;
public static volatile SingularAttribute<TransactionProduct, Product> prod;
} | UTF-8 | Java | 790 | java | TransactionProduct_.java | Java | [] | null | [] | package entity;
import entity.Product;
import entity.TransactionRecord;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="EclipseLink-2.5.1.v20130918-rNA", date="2014-11-10T19:15:58")
@StaticMetamodel(TransactionProduct.class)
public class TransactionProduct_ {
public static volatile SingularAttribute<TransactionProduct, Long> id;
public static volatile SingularAttribute<TransactionProduct, Double> price;
public static volatile SingularAttribute<TransactionProduct, TransactionRecord> transact;
public static volatile SingularAttribute<TransactionProduct, Integer> quantity;
public static volatile SingularAttribute<TransactionProduct, Product> prod;
} | 790 | 0.827848 | 0.796203 | 19 | 40.63158 | 32.166035 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.894737 | false | false | 13 |
95bb5ae22e30a9fb462f1493c40215eea2ccef04 | 17,119,739,706,329 | f08af2166baa9240aa1f33a604c9f00de42de906 | /151-ReverseWordsInAString.java | fbb1d2cf047130c49375eb7f94790a4fd12bb1ca | [] | no_license | sirius206/LeetCode | https://github.com/sirius206/LeetCode | 69d23a2b2585951593591d7fea7f5849b2f14056 | 331072373a7ae7909bdcd80ccd98407dee7ca847 | refs/heads/master | 2021-10-26T03:42:58.319000 | 2021-10-13T20:22:12 | 2021-10-13T20:22:12 | 211,740,083 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //Method 1 by myself #not so good
//Runtime: O(n), Space: O(n)
class Solution {
public String reverseWords(String s) {
String rString = "";
int len = s.length();
String word = "";
boolean spaceFlag = false;
boolean firstWord = true;
for (int i = len-1; i >= 0; i--) {
if (s.charAt(i) != ' ') {
spaceFlag = true;
word = word + s.charAt(i);
if (i != 0) {
continue;
}
}
if (spaceFlag != false || i == 0) {
if (!firstWord && !word.equals("")) {
rString = rString + " ";
}
else {
firstWord = false;
}
for (int j = word.length() - 1; j >= 0; j--) {
rString += word.charAt(j);
}
word = "";
spaceFlag = false;
}
}
return rString;
}
}
//Method 1.5 by myself, use StringBuilder instead of String
class Solution {
public String reverseWords(String s) {
StringBuilder rString = new StringBuilder();
int len = s.length();
StringBuilder word = new StringBuilder();
boolean newWordFlag = false;
for (int i = len-1; i >= 0; i--) {
if (s.charAt(i) != ' ') {
newWordFlag = true;
word.append(s.charAt(i));
if (i != 0) {
continue;
}
}
if (newWordFlag != false || i == 0) {
if (rString.length() != 0 && !word.toString().equals("")) {
rString.append(" ");
}
rString.append(word.reverse());
word.setLength(0);
newWordFlag = false;
}
}
return rString.toString();
}
}
//Method 2 from book
//O(n) runtime, O(n) space:
//We can do better in one-pass. While iterating the string in reverse order, we keep track of
//a word’s begin and end position. When we are at the beginning of a word, we append it.
class Solution {
public String reverseWords(String s) {
StringBuilder reversed = new StringBuilder();
int j = s.length();
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == ' ') {
j = i;
} else if (i == 0 || s.charAt(i - 1) == ' ') {
if (reversed.length() != 0) {
reversed.append(' ');
}
reversed.append(s.substring(i, j));
}
}
return reversed.toString();
}
}
//Method 3 from LC all in one, myself
//而如果我们使用Java的String的split函数来做的话就非常简单了,没有那么多的幺蛾子,简单明了,我们首先将原字符串调用trim()来去除冗余空格,然后调用
//split()来分隔,分隔符设为"\\s+",这其实是一个正则表达式,\\s表示空格字符,+表示可以有一个或多个空格字符,那么我们就可以把单词分隔开装入一个字
//符串数组中,然后我们从末尾开始,一个个把单词取出来加入结果res中,并且单词之间加上空格字符,注意我们把第一个单词留着不取,然后返回的时候再加上即可
class Solution {
public String reverseWords(String s) {
StringBuilder rString = new StringBuilder();
String[] words = s.trim().split("\\s+");
for (int i = words.length - 1; i > 0; i--) {
rString.append(words[i]).append(" ");
}
return rString.append(words[0]).toString();
}
}
//Method 4 from LC all in one
//利用到了Java的内置函数,这也是Java的强大之处,注意这里的分隔符没有用正则表达式,而是直接放了个空格符进去,后面还是有+号,跟上面的写法得到的效果是
//一样的,然后我们对字符串数组进行翻转,然后调用join()函数来把字符串数组拼接成一个字符串,中间夹上空格符即可
public class Solution {
public String reverseWords(String s) {
String[] words = s.trim().split(" +");
Collections.reverse(Arrays.asList(words));
return String.join(" ", words);
}
}
| UTF-8 | Java | 4,366 | java | 151-ReverseWordsInAString.java | Java | [] | null | [] | //Method 1 by myself #not so good
//Runtime: O(n), Space: O(n)
class Solution {
public String reverseWords(String s) {
String rString = "";
int len = s.length();
String word = "";
boolean spaceFlag = false;
boolean firstWord = true;
for (int i = len-1; i >= 0; i--) {
if (s.charAt(i) != ' ') {
spaceFlag = true;
word = word + s.charAt(i);
if (i != 0) {
continue;
}
}
if (spaceFlag != false || i == 0) {
if (!firstWord && !word.equals("")) {
rString = rString + " ";
}
else {
firstWord = false;
}
for (int j = word.length() - 1; j >= 0; j--) {
rString += word.charAt(j);
}
word = "";
spaceFlag = false;
}
}
return rString;
}
}
//Method 1.5 by myself, use StringBuilder instead of String
class Solution {
public String reverseWords(String s) {
StringBuilder rString = new StringBuilder();
int len = s.length();
StringBuilder word = new StringBuilder();
boolean newWordFlag = false;
for (int i = len-1; i >= 0; i--) {
if (s.charAt(i) != ' ') {
newWordFlag = true;
word.append(s.charAt(i));
if (i != 0) {
continue;
}
}
if (newWordFlag != false || i == 0) {
if (rString.length() != 0 && !word.toString().equals("")) {
rString.append(" ");
}
rString.append(word.reverse());
word.setLength(0);
newWordFlag = false;
}
}
return rString.toString();
}
}
//Method 2 from book
//O(n) runtime, O(n) space:
//We can do better in one-pass. While iterating the string in reverse order, we keep track of
//a word’s begin and end position. When we are at the beginning of a word, we append it.
class Solution {
public String reverseWords(String s) {
StringBuilder reversed = new StringBuilder();
int j = s.length();
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == ' ') {
j = i;
} else if (i == 0 || s.charAt(i - 1) == ' ') {
if (reversed.length() != 0) {
reversed.append(' ');
}
reversed.append(s.substring(i, j));
}
}
return reversed.toString();
}
}
//Method 3 from LC all in one, myself
//而如果我们使用Java的String的split函数来做的话就非常简单了,没有那么多的幺蛾子,简单明了,我们首先将原字符串调用trim()来去除冗余空格,然后调用
//split()来分隔,分隔符设为"\\s+",这其实是一个正则表达式,\\s表示空格字符,+表示可以有一个或多个空格字符,那么我们就可以把单词分隔开装入一个字
//符串数组中,然后我们从末尾开始,一个个把单词取出来加入结果res中,并且单词之间加上空格字符,注意我们把第一个单词留着不取,然后返回的时候再加上即可
class Solution {
public String reverseWords(String s) {
StringBuilder rString = new StringBuilder();
String[] words = s.trim().split("\\s+");
for (int i = words.length - 1; i > 0; i--) {
rString.append(words[i]).append(" ");
}
return rString.append(words[0]).toString();
}
}
//Method 4 from LC all in one
//利用到了Java的内置函数,这也是Java的强大之处,注意这里的分隔符没有用正则表达式,而是直接放了个空格符进去,后面还是有+号,跟上面的写法得到的效果是
//一样的,然后我们对字符串数组进行翻转,然后调用join()函数来把字符串数组拼接成一个字符串,中间夹上空格符即可
public class Solution {
public String reverseWords(String s) {
String[] words = s.trim().split(" +");
Collections.reverse(Arrays.asList(words));
return String.join(" ", words);
}
}
| 4,366 | 0.493586 | 0.486638 | 113 | 32.106194 | 21.02437 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.557522 | false | false | 13 |
2348a7195e46a44047b0a67bfa4f5763fb8ffd64 | 22,076,131,921,701 | cdb4d62c782c2467f00fca671f00006c4b6c0e90 | /src/main/java/cn/zhishush/finance/hotloan/common/util/FileUtils.java | f535499633e7fddfb1b918ac180f372c39242b97 | [] | no_license | qiankunhu/hotloan-admin | https://github.com/qiankunhu/hotloan-admin | 2a818f0c5db0fa85cddb6f4a7acfffb641d2c270 | 6d6f7cc6a96ddad9612d6007b8359d9093d4fab5 | refs/heads/master | 2020-06-15T18:00:04.801000 | 2019-07-05T07:18:07 | 2019-07-05T07:18:07 | 195,358,304 | 0 | 0 | null | false | 2020-10-13T14:23:22 | 2019-07-05T07:14:24 | 2019-07-05T07:19:24 | 2020-10-13T14:23:21 | 8,108 | 0 | 0 | 2 | JavaScript | false | false | package cn.zhishush.finance.hotloan.common.util;
import java.io.*;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.multipart.MultipartFile;
/**
* <p>文件上传</p>
*
* @author lili
* @version 1.0: FileUtils.java, v0.1 2019-03-25 13:49 PM lili Exp $
*/
public interface FileUtils {
Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);
static void upload(MultipartFile file, String filePath) {
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件的后缀名,比如图片的jpeg,png
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 文件上传后的路径
fileName = UUID.randomUUID() + suffixName;
File dest = new File(filePath + fileName);
try {
file.transferTo(dest);
} catch (IllegalStateException | IOException e) {
LOGGER.error("文件上传异常:{}", ExceptionUtils.getStackTrace(e));
}
}
static void downLoadExcelTemplate(String fileName, File file, HttpServletResponse response) {
ResourceLoader loader = new DefaultResourceLoader();
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
byte[] buff = new byte[1024];
try (OutputStream os = response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
} catch (final Exception e) {
LOGGER.error("文件下载,异常:{}", ExceptionUtils.getStackTrace(e));
}
}
}
| UTF-8 | Java | 2,165 | java | FileUtils.java | Java | [
{
"context": "t.MultipartFile;\n\n/**\n * <p>文件上传</p>\n *\n * @author lili\n * @version 1.0: FileUtils.java, v0.1 2019-03-25 ",
"end": 458,
"score": 0.9991579651832581,
"start": 454,
"tag": "USERNAME",
"value": "lili"
}
] | null | [] | package cn.zhishush.finance.hotloan.common.util;
import java.io.*;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.multipart.MultipartFile;
/**
* <p>文件上传</p>
*
* @author lili
* @version 1.0: FileUtils.java, v0.1 2019-03-25 13:49 PM lili Exp $
*/
public interface FileUtils {
Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);
static void upload(MultipartFile file, String filePath) {
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件的后缀名,比如图片的jpeg,png
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 文件上传后的路径
fileName = UUID.randomUUID() + suffixName;
File dest = new File(filePath + fileName);
try {
file.transferTo(dest);
} catch (IllegalStateException | IOException e) {
LOGGER.error("文件上传异常:{}", ExceptionUtils.getStackTrace(e));
}
}
static void downLoadExcelTemplate(String fileName, File file, HttpServletResponse response) {
ResourceLoader loader = new DefaultResourceLoader();
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
byte[] buff = new byte[1024];
try (OutputStream os = response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
} catch (final Exception e) {
LOGGER.error("文件下载,异常:{}", ExceptionUtils.getStackTrace(e));
}
}
}
| 2,165 | 0.651756 | 0.639731 | 60 | 33.650002 | 27.236511 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7 | false | false | 13 |
9ff2854abf35884ea9e744198979acb41f6c1729 | 19,980,187,892,268 | dcdb35d421bd31d57923cc5b67338bd79fefca82 | /cmclient/com.elasticpath.cmclient.core/src/main/java/com/elasticpath/cmclient/core/controller/impl/AbstractBaseControllerImpl.java | fcedb7ccf7df23edf56d1a7b450256e9f88ae861 | [] | no_license | ucamit/ep-demo | https://github.com/ucamit/ep-demo | 7a257f7d15f1e784fde4415d55ca66d7ecae7395 | 4b527fa4b3c006efcf245a4f3819a62ab7d4741b | refs/heads/master | 2015-07-11T17:10:06 | 2015-05-21T10:20:31 | 2015-05-21T10:20:31 | 36,004,935 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package com.elasticpath.cmclient.core.controller.impl;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.ListUtils;
import com.elasticpath.cmclient.core.controller.BaseController;
import com.elasticpath.cmclient.core.event.SearchResultEvent;
import com.elasticpath.cmclient.core.event.UIEvent;
import com.elasticpath.cmclient.core.eventlistener.UIEventListener;
/**
* AbstractBaseControllerImpl
* Abstract UI Controller interface.
* @param <T> type.
*/
@SuppressWarnings("unchecked")
public abstract class AbstractBaseControllerImpl<T>
implements BaseController<SearchResultEvent<T>, UIEventListener<SearchResultEvent<T>>>, UIEventListener<UIEvent<?>> {
private final List<UIEventListener<SearchResultEvent < T >>> listeners =
ListUtils.synchronizedList(new ArrayList<UIEventListener<SearchResultEvent < T >>>());
/**
* {@inheritDoc}
*/
public void addListener(final UIEventListener<SearchResultEvent < T >> eventListener) {
synchronized (this.listeners) {
this.listeners.add(eventListener);
}
}
/**
* {@inheritDoc}
*/
public void removeAllListeners() {
synchronized (this.listeners) {
this.listeners.clear();
}
}
/**
* {@inheritDoc}
*/
public void removeListener(final UIEventListener<SearchResultEvent < T >> eventListener) {
synchronized (this.listeners) {
this.listeners.remove(eventListener);
}
}
/**
* Get the list of event listeners.
* @return list of event listeners.
*/
protected List<UIEventListener<SearchResultEvent < T >>> getListeners() {
return listeners;
}
/**
* Fire event.
* @param eventObject event object.
*/
public void fireEvent(final SearchResultEvent < T > eventObject) {
synchronized (this.listeners) {
int size = listeners.size();
for (int x = 0; x < size; x++) {
this.listeners.get(x).onEvent(eventObject);
}
}
}
}
| UTF-8 | Java | 1,894 | java | AbstractBaseControllerImpl.java | Java | [] | null | [] | /**
*
*/
package com.elasticpath.cmclient.core.controller.impl;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.ListUtils;
import com.elasticpath.cmclient.core.controller.BaseController;
import com.elasticpath.cmclient.core.event.SearchResultEvent;
import com.elasticpath.cmclient.core.event.UIEvent;
import com.elasticpath.cmclient.core.eventlistener.UIEventListener;
/**
* AbstractBaseControllerImpl
* Abstract UI Controller interface.
* @param <T> type.
*/
@SuppressWarnings("unchecked")
public abstract class AbstractBaseControllerImpl<T>
implements BaseController<SearchResultEvent<T>, UIEventListener<SearchResultEvent<T>>>, UIEventListener<UIEvent<?>> {
private final List<UIEventListener<SearchResultEvent < T >>> listeners =
ListUtils.synchronizedList(new ArrayList<UIEventListener<SearchResultEvent < T >>>());
/**
* {@inheritDoc}
*/
public void addListener(final UIEventListener<SearchResultEvent < T >> eventListener) {
synchronized (this.listeners) {
this.listeners.add(eventListener);
}
}
/**
* {@inheritDoc}
*/
public void removeAllListeners() {
synchronized (this.listeners) {
this.listeners.clear();
}
}
/**
* {@inheritDoc}
*/
public void removeListener(final UIEventListener<SearchResultEvent < T >> eventListener) {
synchronized (this.listeners) {
this.listeners.remove(eventListener);
}
}
/**
* Get the list of event listeners.
* @return list of event listeners.
*/
protected List<UIEventListener<SearchResultEvent < T >>> getListeners() {
return listeners;
}
/**
* Fire event.
* @param eventObject event object.
*/
public void fireEvent(final SearchResultEvent < T > eventObject) {
synchronized (this.listeners) {
int size = listeners.size();
for (int x = 0; x < size; x++) {
this.listeners.get(x).onEvent(eventObject);
}
}
}
}
| 1,894 | 0.724393 | 0.723865 | 77 | 23.597403 | 27.162933 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.155844 | false | false | 13 |
a909be4f1c63e86d515d911a1d2bb273a199abe5 | 31,379,031,097,092 | 984d6d2d8887c4c5675cf657155531b625bc38b8 | /src/Patterns/IPrototype.java | db6500d99cf62d71dc707e968d70e048ad5c59b9 | [] | no_license | gersonEspinoza722/CharacterCreationComponent | https://github.com/gersonEspinoza722/CharacterCreationComponent | 958d2797d588ecdedc7236e9c5b4f9fb5c27a553 | 51a1fa7310dedc4abe0ceacc1cd971da336cf287 | refs/heads/master | 2020-07-28T07:16:50.068000 | 2019-10-31T00:34:22 | 2019-10-31T00:34:22 | 209,143,584 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Patterns;
public interface IPrototype <T extends IPrototype> extends Cloneable{
IPrototype clone();
IPrototype deepClone();
}
| UTF-8 | Java | 143 | java | IPrototype.java | Java | [] | null | [] | package Patterns;
public interface IPrototype <T extends IPrototype> extends Cloneable{
IPrototype clone();
IPrototype deepClone();
}
| 143 | 0.755245 | 0.755245 | 6 | 22.833334 | 23.024746 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 13 |
2b45fd7de92c517a7c7af82cd1a9f35039215d2c | 15,401,752,748,541 | a587892e43743e9581fd5c0ff2376221f83bd4fb | /src/test/java/com/magicsoftbay/qbuildersandroid/testsupport/QBuilderTestBase.java | 83730d15eaaeccef4f6f820ba1ed9b13373144a1 | [
"MIT"
] | permissive | magicsoftbay/q-builders-android | https://github.com/magicsoftbay/q-builders-android | e8e8d9df91948df81cf5455ffdc1c96e7ed176e1 | 94cc54ade9fe17a2e459907d619252e2a3d28ba3 | refs/heads/master | 2020-03-19T23:24:14.628000 | 2018-11-10T04:20:19 | 2018-11-10T04:20:19 | 137,005,012 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* The MIT License (MIT)
*
* Copyright (c) 2018 MAGIC SOFTWARE BAY SRL
* Copyright (c) 2016 Paul Rutledge <paul.v.rutledge@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.magicsoftbay.qbuildersandroid.testsupport;
import com.magicsoftbay.qbuildersandroid.conditions.Condition;
import com.magicsoftbay.qbuildersandroid.util.date.DateAndFormat;
import com.magicsoftbay.qbuildersandroid.visitors.ContextualNodeVisitor;
import org.apache.commons.lang3.time.FastDateFormat;
import org.junit.Test;
import java.util.Calendar;
import java.util.TimeZone;
import static com.magicsoftbay.qbuildersandroid.testsupport.DomainModel.MyEnum.VALUE1;
import static com.magicsoftbay.qbuildersandroid.testsupport.DomainModel.MyEnum.VALUE2;
import static com.magicsoftbay.qbuildersandroid.testsupport.DomainModel.MyEnum.VALUE3;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.myBoolean;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.myDateTime;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.myDouble;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.myEnum;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.myFloat;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.myInteger;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.myLong;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.myShort;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.myString;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.mySubList;
/**
* @author Paul Rutledge <paul.v.rutledge@gmail.com>
* @author Clivens Petit <clivens.petit@magicsoftbay.com>
*/
public abstract class QBuilderTestBase<T extends ContextualNodeVisitor<S, U>, S, U> {
private final static Calendar EPOCH = Calendar.getInstance();
private final static Calendar EPOCH_ONE_YEAR_AFTER = Calendar.getInstance();
private final static FastDateFormat FAST_DATE_FORMAT =
FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss'Z'", TimeZone.getTimeZone("UTC"));
static {
EPOCH.set(1970, 0, 1, 0, 0, 0);
EPOCH.setTimeZone(TimeZone.getTimeZone("UTC"));
EPOCH_ONE_YEAR_AFTER.set(1971, 0, 1, 0, 0, 0);
EPOCH_ONE_YEAR_AFTER.setTimeZone(TimeZone.getTimeZone("UTC"));
}
protected abstract T getVisitor();
protected abstract void compare(String expected, S converted);
protected interface Simple {
interface String {
Condition<QueryModel> EQ = myString().eq("abcdefg");
Condition<QueryModel> NE = myString().ne("abcdefg");
Condition<QueryModel> LT = myString().lexicallyBefore("abcdefg");
Condition<QueryModel> GT = myString().lexicallyAfter("abcdefg");
Condition<QueryModel> GTE = myString().lexicallyNotBefore("abcdefg");
Condition<QueryModel> LTE = myString().lexicallyNotAfter("abcdefg");
Condition<QueryModel> EX = myString().exists();
Condition<QueryModel> DNE = myString().doesNotExist();
Condition<QueryModel> IN = myString().in("a", "b", "c");
Condition<QueryModel> NIN = myString().nin("d", "e", "f");
Condition<QueryModel> RE = myString().pattern("(abc|def)");
}
interface Enum {
Condition<QueryModel> EQ = myEnum().eq(VALUE1);
Condition<QueryModel> NE = myEnum().ne(VALUE1);
Condition<QueryModel> EX = myEnum().exists();
Condition<QueryModel> DNE = myEnum().doesNotExist();
Condition<QueryModel> IN = myEnum().in(VALUE1, VALUE2, VALUE3);
Condition<QueryModel> NIN = myEnum().nin(VALUE1, VALUE2, VALUE3);
}
interface Boolean {
Condition<QueryModel> TRUE = myBoolean().isTrue();
Condition<QueryModel> FALSE = myBoolean().isFalse();
Condition<QueryModel> EX = myBoolean().exists();
Condition<QueryModel> DNE = myBoolean().doesNotExist();
}
interface Short {
Condition<QueryModel> EQ = myShort().eq((short) 100);
Condition<QueryModel> NE = myShort().ne((short) 100);
Condition<QueryModel> GT = myShort().gt((short) 100);
Condition<QueryModel> LT = myShort().lt((short) 100);
Condition<QueryModel> GTE = myShort().gte((short) 100);
Condition<QueryModel> LTE = myShort().lte((short) 100);
Condition<QueryModel> EX = myShort().exists();
Condition<QueryModel> DNE = myShort().doesNotExist();
Condition<QueryModel> IN = myShort().in((short) 98, (short) 99, (short) 100);
Condition<QueryModel> NIN = myShort().nin((short) 101, (short) 102, (short) 103);
}
interface Integer {
Condition<QueryModel> EQ = myInteger().eq(100);
Condition<QueryModel> NE = myInteger().ne(100);
Condition<QueryModel> GT = myInteger().gt(100);
Condition<QueryModel> LT = myInteger().lt(100);
Condition<QueryModel> GTE = myInteger().gte(100);
Condition<QueryModel> LTE = myInteger().lte(100);
Condition<QueryModel> EX = myInteger().exists();
Condition<QueryModel> DNE = myInteger().doesNotExist();
Condition<QueryModel> IN = myInteger().in(98, 99, 100);
Condition<QueryModel> NIN = myInteger().nin(101, 102, 103);
}
interface Long {
Condition<QueryModel> EQ = myLong().eq(100L);
Condition<QueryModel> NE = myLong().ne(100L);
Condition<QueryModel> GT = myLong().gt(100L);
Condition<QueryModel> LT = myLong().lt(100L);
Condition<QueryModel> GTE = myLong().gte(100L);
Condition<QueryModel> LTE = myLong().lte(100L);
Condition<QueryModel> EX = myLong().exists();
Condition<QueryModel> DNE = myLong().doesNotExist();
Condition<QueryModel> IN = myLong().in(98L, 99L, 100L);
Condition<QueryModel> NIN = myLong().nin(101L, 102L, 103L);
}
interface Float {
Condition<QueryModel> EQ = myFloat().eq(100f);
Condition<QueryModel> NE = myFloat().ne(100f);
Condition<QueryModel> GT = myFloat().gt(100f);
Condition<QueryModel> LT = myFloat().lt(100f);
Condition<QueryModel> GTE = myFloat().gte(100f);
Condition<QueryModel> LTE = myFloat().lte(100f);
Condition<QueryModel> EX = myFloat().exists();
Condition<QueryModel> DNE = myFloat().doesNotExist();
Condition<QueryModel> IN = myFloat().in(98f, 99f, 100f);
Condition<QueryModel> NIN = myFloat().nin(101f, 102f, 103f);
}
interface Double {
Condition<QueryModel> EQ = myDouble().eq(100.0);
Condition<QueryModel> NE = myDouble().ne(100.0);
Condition<QueryModel> GT = myDouble().gt(100.0);
Condition<QueryModel> LT = myDouble().lt(100.0);
Condition<QueryModel> GTE = myDouble().gte(100.0);
Condition<QueryModel> LTE = myDouble().lte(100.0);
Condition<QueryModel> EX = myDouble().exists();
Condition<QueryModel> DNE = myDouble().doesNotExist();
Condition<QueryModel> IN = myDouble().in(98.0, 99.0, 100.0);
Condition<QueryModel> NIN = myDouble().nin(101.0, 102.0, 103.0);
}
interface DateEx {
DateAndFormat epoch = new DateAndFormat(EPOCH.getTime(), FAST_DATE_FORMAT);
DateAndFormat yearAfterEpoch = new DateAndFormat(EPOCH_ONE_YEAR_AFTER.getTime(), FAST_DATE_FORMAT);
Condition<QueryModel> EQ = myDateTime().eq(epoch);
Condition<QueryModel> NE = myDateTime().ne(epoch);
Condition<QueryModel> GT = myDateTime().after(epoch, true);
Condition<QueryModel> GTE = myDateTime().after(epoch, false);
Condition<QueryModel> LT = myDateTime().before(yearAfterEpoch, true);
Condition<QueryModel> LTE = myDateTime().before(yearAfterEpoch, false);
Condition<QueryModel> BETWEEN = myDateTime().between(epoch, false, yearAfterEpoch, false);
Condition<QueryModel> EX = myDateTime().exists();
Condition<QueryModel> DNE = myDateTime().doesNotExist();
}
}
protected interface Logical {
Condition<QueryModel> INLINE_ANDING = myString().eq("Thing").and().myLong().doesNotExist();
Condition<QueryModel> INLINE_ORING = myString().eq("Thing").or().myLong().doesNotExist();
Condition<QueryModel> LIST_ANDING = QueryModel.QueryModelPredef
.and(myString().eq("Thing"), myLong().doesNotExist());
Condition<QueryModel> LIST_ORING = QueryModel.QueryModelPredef
.or(myString().eq("Thing"), myLong().doesNotExist());
Condition<QueryModel> LIST_ORING_OF_INLINE_ANDING = QueryModel.QueryModelPredef
.or(myString().eq("Thing").and().myLong().doesNotExist(),
myString().ne("Cats").and().myLong().gt(30L));
Condition<QueryModel> LIST_ANDING_OF_INLINE_ORING = QueryModel.QueryModelPredef
.and(myString().eq("Thing").or().myLong().doesNotExist(),
myString().ne("Cats").or().myLong().gt(30L));
Condition<QueryModel> LIST_ANDING_OR_LIST_ORING = QueryModel.QueryModelPredef
.and(myString().eq("Thing").or().myLong().doesNotExist(),
myString().ne("Cats").or().myLong().gt(30L)).or()
.or(myString().eq("Thing").and().myLong().doesNotExist(), myString().ne("Cats").and().myLong().gt(30L));
Condition<QueryModel> LIST_ORING_ANDLIST_ANDING = QueryModel.QueryModelPredef
.or(myString().eq("Thing").and().myLong().doesNotExist(),
myString().ne("Cats").and().myLong().gt(30L)).and()
.and(myString().eq("Thing").or().myLong().doesNotExist(), myString().ne("Cats").or().myLong().gt(30L));
}
protected interface Chained {
Condition<QueryModel> CHAINED_ANDS = myString().eq("thing").and().myInteger().gt(0)
.and().myInteger().lt(5).and().myLong().in(0L, 1L, 2L).and().myDouble().lte(2.9)
.and().myBoolean().isFalse().and().myDateTime().doesNotExist();
Condition<QueryModel> CHAINED_ORS = myString().eq("thing").or().myInteger().gt(0).or()
.myInteger().lt(5).or().myLong().in(0L, 1L, 2L).or().myDouble().lte(2.9).or()
.myBoolean().isFalse().or().myDateTime().doesNotExist();
Condition<QueryModel> CHAINED_ANDS_AND_ORS = myString().eq("thing").and().myInteger()
.gt(0).or().myInteger().lt(5).or().myLong().in(0L, 1L, 2L).and().myDouble()
.lte(2.9).and().myBoolean().isFalse().or().myDateTime().doesNotExist();
Condition<QueryModel> CHAINED_ORS_AND_ANDS = myString().eq("thing").or().myInteger()
.gt(0).and().myInteger().lt(5).and().myLong().in(0L, 1L, 2L).or().myDouble()
.lte(2.9).or().myBoolean().isFalse().and().myDateTime().doesNotExist();
}
protected interface Composed {
Condition<QueryModel> SUB_QUERY = mySubList().any(Logical.INLINE_ANDING).and().myBoolean().isTrue();
}
protected interface VariedInputs {
Condition<QueryModel> NULL_EQUALITY = myString().eq(null);
Condition<QueryModel> NULL_INEQUALITY = myString().ne(null);
}
protected String Enum_EQ;
protected String Enum_NE;
protected String Enum_EX;
protected String Enum_DNE;
protected String Enum_IN;
protected String Enum_NIN;
@Test
public void simple_Enum() {
compare(Enum_EQ, Simple.Enum.EQ);
compare(Enum_NE, Simple.Enum.NE);
compare(Enum_EX, Simple.Enum.EX);
compare(Enum_DNE, Simple.Enum.DNE);
compare(Enum_IN, Simple.Enum.IN);
compare(Enum_NIN, Simple.Enum.NIN);
}
protected String String_EQ;
protected String String_NE;
protected String String_LT;
protected String String_GT;
protected String String_LTE;
protected String String_GTE;
protected String String_EX;
protected String String_DNE;
protected String String_IN;
protected String String_NIN;
protected String String_RE;
@Test
public void simple_String() {
compare(String_EQ, Simple.String.EQ);
compare(String_NE, Simple.String.NE);
compare(String_LT, Simple.String.LT);
compare(String_GT, Simple.String.GT);
compare(String_LTE, Simple.String.LTE);
compare(String_GTE, Simple.String.GTE);
compare(String_EX, Simple.String.EX);
compare(String_DNE, Simple.String.DNE);
compare(String_IN, Simple.String.IN);
compare(String_NIN, Simple.String.NIN);
compare(String_RE, Simple.String.RE);
}
protected String Boolean_TRUE;
protected String Boolean_FALSE;
protected String Boolean_EX;
protected String Boolean_DNE;
@Test
public void simple_Boolean() {
compare(Boolean_TRUE, Simple.Boolean.TRUE);
compare(Boolean_FALSE, Simple.Boolean.FALSE);
compare(Boolean_EX, Simple.Boolean.EX);
compare(Boolean_DNE, Simple.Boolean.DNE);
}
protected String Short_EQ;
protected String Short_NE;
protected String Short_LT;
protected String Short_GT;
protected String Short_LTE;
protected String Short_GTE;
protected String Short_EX;
protected String Short_DNE;
protected String Short_IN;
protected String Short_NIN;
@Test
public void simple_Short() {
compare(Short_EQ, Simple.Short.EQ);
compare(Short_NE, Simple.Short.NE);
compare(Short_LT, Simple.Short.LT);
compare(Short_LTE, Simple.Short.LTE);
compare(Short_GT, Simple.Short.GT);
compare(Short_GTE, Simple.Short.GTE);
compare(Short_EX, Simple.Short.EX);
compare(Short_DNE, Simple.Short.DNE);
compare(Short_IN, Simple.Short.IN);
compare(Short_NIN, Simple.Short.NIN);
}
protected String Integer_EQ;
protected String Integer_NE;
protected String Integer_LT;
protected String Integer_GT;
protected String Integer_LTE;
protected String Integer_GTE;
protected String Integer_EX;
protected String Integer_DNE;
protected String Integer_IN;
protected String Integer_NIN;
@Test
public void simple_Integer() {
compare(Integer_EQ, Simple.Integer.EQ);
compare(Integer_NE, Simple.Integer.NE);
compare(Integer_LT, Simple.Integer.LT);
compare(Integer_LTE, Simple.Integer.LTE);
compare(Integer_GT, Simple.Integer.GT);
compare(Integer_GTE, Simple.Integer.GTE);
compare(Integer_EX, Simple.Integer.EX);
compare(Integer_DNE, Simple.Integer.DNE);
compare(Integer_IN, Simple.Integer.IN);
compare(Integer_NIN, Simple.Integer.NIN);
}
protected String Long_EQ;
protected String Long_NE;
protected String Long_LT;
protected String Long_GT;
protected String Long_LTE;
protected String Long_GTE;
protected String Long_EX;
protected String Long_DNE;
protected String Long_IN;
protected String Long_NIN;
@Test
public void simple_Long() {
compare(Long_EQ, Simple.Long.EQ);
compare(Long_NE, Simple.Long.NE);
compare(Long_LT, Simple.Long.LT);
compare(Long_LTE, Simple.Long.LTE);
compare(Long_GT, Simple.Long.GT);
compare(Long_GTE, Simple.Long.GTE);
compare(Long_EX, Simple.Long.EX);
compare(Long_DNE, Simple.Long.DNE);
compare(Long_IN, Simple.Long.IN);
compare(Long_NIN, Simple.Long.NIN);
}
protected String Float_EQ;
protected String Float_NE;
protected String Float_LT;
protected String Float_GT;
protected String Float_LTE;
protected String Float_GTE;
protected String Float_EX;
protected String Float_DNE;
protected String Float_IN;
protected String Float_NIN;
@Test
public void simple_Float() {
compare(Float_EQ, Simple.Float.EQ);
compare(Float_NE, Simple.Float.NE);
compare(Float_LT, Simple.Float.LT);
compare(Float_LTE, Simple.Float.LTE);
compare(Float_GT, Simple.Float.GT);
compare(Float_GTE, Simple.Float.GTE);
compare(Float_EX, Simple.Float.EX);
compare(Float_DNE, Simple.Float.DNE);
compare(Float_IN, Simple.Float.IN);
compare(Float_NIN, Simple.Float.NIN);
}
protected String Double_EQ;
protected String Double_NE;
protected String Double_LT;
protected String Double_GT;
protected String Double_LTE;
protected String Double_GTE;
protected String Double_EX;
protected String Double_DNE;
protected String Double_IN;
protected String Double_NIN;
@Test
public void simple_Double() {
compare(Double_EQ, Simple.Double.EQ);
compare(Double_NE, Simple.Double.NE);
compare(Double_LT, Simple.Double.LT);
compare(Double_LTE, Simple.Double.LTE);
compare(Double_GT, Simple.Double.GT);
compare(Double_GTE, Simple.Double.GTE);
compare(Double_EX, Simple.Double.EX);
compare(Double_DNE, Simple.Double.DNE);
compare(Double_IN, Simple.Double.IN);
compare(Double_NIN, Simple.Double.NIN);
}
protected String DateTime_EQ;
protected String DateTime_NE;
protected String DateTime_LT;
protected String DateTime_GT;
protected String DateTime_LTE;
protected String DateTime_GTE;
protected String DateTime_EX;
protected String DateTime_DNE;
protected String DateTime_BETWEEN;
@Test
public void simple_DateTime() {
compare(DateTime_EQ, Simple.DateEx.EQ);
compare(DateTime_NE, Simple.DateEx.NE);
compare(DateTime_LT, Simple.DateEx.LT);
compare(DateTime_LTE, Simple.DateEx.LTE);
compare(DateTime_GT, Simple.DateEx.GT);
compare(DateTime_GTE, Simple.DateEx.GTE);
compare(DateTime_EX, Simple.DateEx.EX);
compare(DateTime_DNE, Simple.DateEx.DNE);
compare(DateTime_BETWEEN, Simple.DateEx.BETWEEN);
}
protected String INLINE_ANDING;
@Test
public void inline_Anding() {
compare(INLINE_ANDING, Logical.INLINE_ANDING);
}
protected String INLINE_ORING;
@Test
public void inline_Oring() {
compare(INLINE_ORING, Logical.INLINE_ORING);
}
protected String LIST_ANDING;
@Test
public void list_Anding() {
compare(LIST_ANDING, Logical.LIST_ANDING);
}
protected String LIST_ORING;
@Test
public void list_Oring() {
compare(LIST_ORING, Logical.LIST_ORING);
}
protected String LIST_ORING_OF_INLINE_ANDING;
@Test
public void listOringOfInlineAnding() {
compare(LIST_ORING_OF_INLINE_ANDING, Logical.LIST_ORING_OF_INLINE_ANDING);
}
protected String LIST_ANDING_OF_INLINE_ORING;
@Test
public void listAndingOfInlineOring() {
compare(LIST_ANDING_OF_INLINE_ORING, Logical.LIST_ANDING_OF_INLINE_ORING);
}
protected String LIST_ANDING_OR_LIST_ORING;
@Test
public void listAndingOrListOring() {
compare(LIST_ANDING_OR_LIST_ORING, Logical.LIST_ANDING_OR_LIST_ORING);
}
protected String LIST_ORING_AND_LIST_ANDING;
@Test
public void listOringAndListAnding() {
compare(LIST_ORING_AND_LIST_ANDING, Logical.LIST_ORING_ANDLIST_ANDING);
}
protected String CHAINED_ANDS;
@Test
public void chainedAnds() {
compare(CHAINED_ANDS, Chained.CHAINED_ANDS);
}
protected String CHAINED_ORS;
@Test
public void chainedOrs() {
compare(CHAINED_ORS, Chained.CHAINED_ORS);
}
protected String CHAINED_ANDS_AND_ORS;
@Test
public void chainedAndsAndOrs() {
compare(CHAINED_ANDS_AND_ORS, Chained.CHAINED_ANDS_AND_ORS);
}
protected String CHAINED_ORS_AND_ANDS;
@Test
public void chainedOrsAndAnds() {
compare(CHAINED_ORS_AND_ANDS, Chained.CHAINED_ORS_AND_ANDS);
}
protected String SUB_QUERY;
@Test
public void subquery() {
compare(SUB_QUERY, Composed.SUB_QUERY);
}
protected String NULL_EQUALITY;
protected String NULL_INEQUALITY;
@Test
public void variedInputs() {
compare(NULL_EQUALITY, VariedInputs.NULL_EQUALITY);
compare(NULL_INEQUALITY, VariedInputs.NULL_INEQUALITY);
}
protected U getContext() {
return null;
}
protected void compare(String expected, Condition<QueryModel> condition) {
T visitor = getVisitor();
compare(expected, condition.query(visitor, getContext()));
}
}
| UTF-8 | Java | 22,076 | java | QBuilderTestBase.java | Java | [
{
"context": " 2018 MAGIC SOFTWARE BAY SRL\n * Copyright (c) 2016 Paul Rutledge <paul.v.rutledge@gmail.com>\n *\n * Permission is h",
"end": 111,
"score": 0.9998723268508911,
"start": 98,
"tag": "NAME",
"value": "Paul Rutledge"
},
{
"context": "WARE BAY SRL\n * Copyright (c) 2016 Pau... | null | [] | /*
* The MIT License (MIT)
*
* Copyright (c) 2018 MAGIC SOFTWARE BAY SRL
* Copyright (c) 2016 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.magicsoftbay.qbuildersandroid.testsupport;
import com.magicsoftbay.qbuildersandroid.conditions.Condition;
import com.magicsoftbay.qbuildersandroid.util.date.DateAndFormat;
import com.magicsoftbay.qbuildersandroid.visitors.ContextualNodeVisitor;
import org.apache.commons.lang3.time.FastDateFormat;
import org.junit.Test;
import java.util.Calendar;
import java.util.TimeZone;
import static com.magicsoftbay.qbuildersandroid.testsupport.DomainModel.MyEnum.VALUE1;
import static com.magicsoftbay.qbuildersandroid.testsupport.DomainModel.MyEnum.VALUE2;
import static com.magicsoftbay.qbuildersandroid.testsupport.DomainModel.MyEnum.VALUE3;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.myBoolean;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.myDateTime;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.myDouble;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.myEnum;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.myFloat;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.myInteger;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.myLong;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.myShort;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.myString;
import static com.magicsoftbay.qbuildersandroid.testsupport.QueryModel.QueryModelPredef.mySubList;
/**
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
*/
public abstract class QBuilderTestBase<T extends ContextualNodeVisitor<S, U>, S, U> {
private final static Calendar EPOCH = Calendar.getInstance();
private final static Calendar EPOCH_ONE_YEAR_AFTER = Calendar.getInstance();
private final static FastDateFormat FAST_DATE_FORMAT =
FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss'Z'", TimeZone.getTimeZone("UTC"));
static {
EPOCH.set(1970, 0, 1, 0, 0, 0);
EPOCH.setTimeZone(TimeZone.getTimeZone("UTC"));
EPOCH_ONE_YEAR_AFTER.set(1971, 0, 1, 0, 0, 0);
EPOCH_ONE_YEAR_AFTER.setTimeZone(TimeZone.getTimeZone("UTC"));
}
protected abstract T getVisitor();
protected abstract void compare(String expected, S converted);
protected interface Simple {
interface String {
Condition<QueryModel> EQ = myString().eq("abcdefg");
Condition<QueryModel> NE = myString().ne("abcdefg");
Condition<QueryModel> LT = myString().lexicallyBefore("abcdefg");
Condition<QueryModel> GT = myString().lexicallyAfter("abcdefg");
Condition<QueryModel> GTE = myString().lexicallyNotBefore("abcdefg");
Condition<QueryModel> LTE = myString().lexicallyNotAfter("abcdefg");
Condition<QueryModel> EX = myString().exists();
Condition<QueryModel> DNE = myString().doesNotExist();
Condition<QueryModel> IN = myString().in("a", "b", "c");
Condition<QueryModel> NIN = myString().nin("d", "e", "f");
Condition<QueryModel> RE = myString().pattern("(abc|def)");
}
interface Enum {
Condition<QueryModel> EQ = myEnum().eq(VALUE1);
Condition<QueryModel> NE = myEnum().ne(VALUE1);
Condition<QueryModel> EX = myEnum().exists();
Condition<QueryModel> DNE = myEnum().doesNotExist();
Condition<QueryModel> IN = myEnum().in(VALUE1, VALUE2, VALUE3);
Condition<QueryModel> NIN = myEnum().nin(VALUE1, VALUE2, VALUE3);
}
interface Boolean {
Condition<QueryModel> TRUE = myBoolean().isTrue();
Condition<QueryModel> FALSE = myBoolean().isFalse();
Condition<QueryModel> EX = myBoolean().exists();
Condition<QueryModel> DNE = myBoolean().doesNotExist();
}
interface Short {
Condition<QueryModel> EQ = myShort().eq((short) 100);
Condition<QueryModel> NE = myShort().ne((short) 100);
Condition<QueryModel> GT = myShort().gt((short) 100);
Condition<QueryModel> LT = myShort().lt((short) 100);
Condition<QueryModel> GTE = myShort().gte((short) 100);
Condition<QueryModel> LTE = myShort().lte((short) 100);
Condition<QueryModel> EX = myShort().exists();
Condition<QueryModel> DNE = myShort().doesNotExist();
Condition<QueryModel> IN = myShort().in((short) 98, (short) 99, (short) 100);
Condition<QueryModel> NIN = myShort().nin((short) 101, (short) 102, (short) 103);
}
interface Integer {
Condition<QueryModel> EQ = myInteger().eq(100);
Condition<QueryModel> NE = myInteger().ne(100);
Condition<QueryModel> GT = myInteger().gt(100);
Condition<QueryModel> LT = myInteger().lt(100);
Condition<QueryModel> GTE = myInteger().gte(100);
Condition<QueryModel> LTE = myInteger().lte(100);
Condition<QueryModel> EX = myInteger().exists();
Condition<QueryModel> DNE = myInteger().doesNotExist();
Condition<QueryModel> IN = myInteger().in(98, 99, 100);
Condition<QueryModel> NIN = myInteger().nin(101, 102, 103);
}
interface Long {
Condition<QueryModel> EQ = myLong().eq(100L);
Condition<QueryModel> NE = myLong().ne(100L);
Condition<QueryModel> GT = myLong().gt(100L);
Condition<QueryModel> LT = myLong().lt(100L);
Condition<QueryModel> GTE = myLong().gte(100L);
Condition<QueryModel> LTE = myLong().lte(100L);
Condition<QueryModel> EX = myLong().exists();
Condition<QueryModel> DNE = myLong().doesNotExist();
Condition<QueryModel> IN = myLong().in(98L, 99L, 100L);
Condition<QueryModel> NIN = myLong().nin(101L, 102L, 103L);
}
interface Float {
Condition<QueryModel> EQ = myFloat().eq(100f);
Condition<QueryModel> NE = myFloat().ne(100f);
Condition<QueryModel> GT = myFloat().gt(100f);
Condition<QueryModel> LT = myFloat().lt(100f);
Condition<QueryModel> GTE = myFloat().gte(100f);
Condition<QueryModel> LTE = myFloat().lte(100f);
Condition<QueryModel> EX = myFloat().exists();
Condition<QueryModel> DNE = myFloat().doesNotExist();
Condition<QueryModel> IN = myFloat().in(98f, 99f, 100f);
Condition<QueryModel> NIN = myFloat().nin(101f, 102f, 103f);
}
interface Double {
Condition<QueryModel> EQ = myDouble().eq(100.0);
Condition<QueryModel> NE = myDouble().ne(100.0);
Condition<QueryModel> GT = myDouble().gt(100.0);
Condition<QueryModel> LT = myDouble().lt(100.0);
Condition<QueryModel> GTE = myDouble().gte(100.0);
Condition<QueryModel> LTE = myDouble().lte(100.0);
Condition<QueryModel> EX = myDouble().exists();
Condition<QueryModel> DNE = myDouble().doesNotExist();
Condition<QueryModel> IN = myDouble().in(98.0, 99.0, 100.0);
Condition<QueryModel> NIN = myDouble().nin(101.0, 102.0, 103.0);
}
interface DateEx {
DateAndFormat epoch = new DateAndFormat(EPOCH.getTime(), FAST_DATE_FORMAT);
DateAndFormat yearAfterEpoch = new DateAndFormat(EPOCH_ONE_YEAR_AFTER.getTime(), FAST_DATE_FORMAT);
Condition<QueryModel> EQ = myDateTime().eq(epoch);
Condition<QueryModel> NE = myDateTime().ne(epoch);
Condition<QueryModel> GT = myDateTime().after(epoch, true);
Condition<QueryModel> GTE = myDateTime().after(epoch, false);
Condition<QueryModel> LT = myDateTime().before(yearAfterEpoch, true);
Condition<QueryModel> LTE = myDateTime().before(yearAfterEpoch, false);
Condition<QueryModel> BETWEEN = myDateTime().between(epoch, false, yearAfterEpoch, false);
Condition<QueryModel> EX = myDateTime().exists();
Condition<QueryModel> DNE = myDateTime().doesNotExist();
}
}
protected interface Logical {
Condition<QueryModel> INLINE_ANDING = myString().eq("Thing").and().myLong().doesNotExist();
Condition<QueryModel> INLINE_ORING = myString().eq("Thing").or().myLong().doesNotExist();
Condition<QueryModel> LIST_ANDING = QueryModel.QueryModelPredef
.and(myString().eq("Thing"), myLong().doesNotExist());
Condition<QueryModel> LIST_ORING = QueryModel.QueryModelPredef
.or(myString().eq("Thing"), myLong().doesNotExist());
Condition<QueryModel> LIST_ORING_OF_INLINE_ANDING = QueryModel.QueryModelPredef
.or(myString().eq("Thing").and().myLong().doesNotExist(),
myString().ne("Cats").and().myLong().gt(30L));
Condition<QueryModel> LIST_ANDING_OF_INLINE_ORING = QueryModel.QueryModelPredef
.and(myString().eq("Thing").or().myLong().doesNotExist(),
myString().ne("Cats").or().myLong().gt(30L));
Condition<QueryModel> LIST_ANDING_OR_LIST_ORING = QueryModel.QueryModelPredef
.and(myString().eq("Thing").or().myLong().doesNotExist(),
myString().ne("Cats").or().myLong().gt(30L)).or()
.or(myString().eq("Thing").and().myLong().doesNotExist(), myString().ne("Cats").and().myLong().gt(30L));
Condition<QueryModel> LIST_ORING_ANDLIST_ANDING = QueryModel.QueryModelPredef
.or(myString().eq("Thing").and().myLong().doesNotExist(),
myString().ne("Cats").and().myLong().gt(30L)).and()
.and(myString().eq("Thing").or().myLong().doesNotExist(), myString().ne("Cats").or().myLong().gt(30L));
}
protected interface Chained {
Condition<QueryModel> CHAINED_ANDS = myString().eq("thing").and().myInteger().gt(0)
.and().myInteger().lt(5).and().myLong().in(0L, 1L, 2L).and().myDouble().lte(2.9)
.and().myBoolean().isFalse().and().myDateTime().doesNotExist();
Condition<QueryModel> CHAINED_ORS = myString().eq("thing").or().myInteger().gt(0).or()
.myInteger().lt(5).or().myLong().in(0L, 1L, 2L).or().myDouble().lte(2.9).or()
.myBoolean().isFalse().or().myDateTime().doesNotExist();
Condition<QueryModel> CHAINED_ANDS_AND_ORS = myString().eq("thing").and().myInteger()
.gt(0).or().myInteger().lt(5).or().myLong().in(0L, 1L, 2L).and().myDouble()
.lte(2.9).and().myBoolean().isFalse().or().myDateTime().doesNotExist();
Condition<QueryModel> CHAINED_ORS_AND_ANDS = myString().eq("thing").or().myInteger()
.gt(0).and().myInteger().lt(5).and().myLong().in(0L, 1L, 2L).or().myDouble()
.lte(2.9).or().myBoolean().isFalse().and().myDateTime().doesNotExist();
}
protected interface Composed {
Condition<QueryModel> SUB_QUERY = mySubList().any(Logical.INLINE_ANDING).and().myBoolean().isTrue();
}
protected interface VariedInputs {
Condition<QueryModel> NULL_EQUALITY = myString().eq(null);
Condition<QueryModel> NULL_INEQUALITY = myString().ne(null);
}
protected String Enum_EQ;
protected String Enum_NE;
protected String Enum_EX;
protected String Enum_DNE;
protected String Enum_IN;
protected String Enum_NIN;
@Test
public void simple_Enum() {
compare(Enum_EQ, Simple.Enum.EQ);
compare(Enum_NE, Simple.Enum.NE);
compare(Enum_EX, Simple.Enum.EX);
compare(Enum_DNE, Simple.Enum.DNE);
compare(Enum_IN, Simple.Enum.IN);
compare(Enum_NIN, Simple.Enum.NIN);
}
protected String String_EQ;
protected String String_NE;
protected String String_LT;
protected String String_GT;
protected String String_LTE;
protected String String_GTE;
protected String String_EX;
protected String String_DNE;
protected String String_IN;
protected String String_NIN;
protected String String_RE;
@Test
public void simple_String() {
compare(String_EQ, Simple.String.EQ);
compare(String_NE, Simple.String.NE);
compare(String_LT, Simple.String.LT);
compare(String_GT, Simple.String.GT);
compare(String_LTE, Simple.String.LTE);
compare(String_GTE, Simple.String.GTE);
compare(String_EX, Simple.String.EX);
compare(String_DNE, Simple.String.DNE);
compare(String_IN, Simple.String.IN);
compare(String_NIN, Simple.String.NIN);
compare(String_RE, Simple.String.RE);
}
protected String Boolean_TRUE;
protected String Boolean_FALSE;
protected String Boolean_EX;
protected String Boolean_DNE;
@Test
public void simple_Boolean() {
compare(Boolean_TRUE, Simple.Boolean.TRUE);
compare(Boolean_FALSE, Simple.Boolean.FALSE);
compare(Boolean_EX, Simple.Boolean.EX);
compare(Boolean_DNE, Simple.Boolean.DNE);
}
protected String Short_EQ;
protected String Short_NE;
protected String Short_LT;
protected String Short_GT;
protected String Short_LTE;
protected String Short_GTE;
protected String Short_EX;
protected String Short_DNE;
protected String Short_IN;
protected String Short_NIN;
@Test
public void simple_Short() {
compare(Short_EQ, Simple.Short.EQ);
compare(Short_NE, Simple.Short.NE);
compare(Short_LT, Simple.Short.LT);
compare(Short_LTE, Simple.Short.LTE);
compare(Short_GT, Simple.Short.GT);
compare(Short_GTE, Simple.Short.GTE);
compare(Short_EX, Simple.Short.EX);
compare(Short_DNE, Simple.Short.DNE);
compare(Short_IN, Simple.Short.IN);
compare(Short_NIN, Simple.Short.NIN);
}
protected String Integer_EQ;
protected String Integer_NE;
protected String Integer_LT;
protected String Integer_GT;
protected String Integer_LTE;
protected String Integer_GTE;
protected String Integer_EX;
protected String Integer_DNE;
protected String Integer_IN;
protected String Integer_NIN;
@Test
public void simple_Integer() {
compare(Integer_EQ, Simple.Integer.EQ);
compare(Integer_NE, Simple.Integer.NE);
compare(Integer_LT, Simple.Integer.LT);
compare(Integer_LTE, Simple.Integer.LTE);
compare(Integer_GT, Simple.Integer.GT);
compare(Integer_GTE, Simple.Integer.GTE);
compare(Integer_EX, Simple.Integer.EX);
compare(Integer_DNE, Simple.Integer.DNE);
compare(Integer_IN, Simple.Integer.IN);
compare(Integer_NIN, Simple.Integer.NIN);
}
protected String Long_EQ;
protected String Long_NE;
protected String Long_LT;
protected String Long_GT;
protected String Long_LTE;
protected String Long_GTE;
protected String Long_EX;
protected String Long_DNE;
protected String Long_IN;
protected String Long_NIN;
@Test
public void simple_Long() {
compare(Long_EQ, Simple.Long.EQ);
compare(Long_NE, Simple.Long.NE);
compare(Long_LT, Simple.Long.LT);
compare(Long_LTE, Simple.Long.LTE);
compare(Long_GT, Simple.Long.GT);
compare(Long_GTE, Simple.Long.GTE);
compare(Long_EX, Simple.Long.EX);
compare(Long_DNE, Simple.Long.DNE);
compare(Long_IN, Simple.Long.IN);
compare(Long_NIN, Simple.Long.NIN);
}
protected String Float_EQ;
protected String Float_NE;
protected String Float_LT;
protected String Float_GT;
protected String Float_LTE;
protected String Float_GTE;
protected String Float_EX;
protected String Float_DNE;
protected String Float_IN;
protected String Float_NIN;
@Test
public void simple_Float() {
compare(Float_EQ, Simple.Float.EQ);
compare(Float_NE, Simple.Float.NE);
compare(Float_LT, Simple.Float.LT);
compare(Float_LTE, Simple.Float.LTE);
compare(Float_GT, Simple.Float.GT);
compare(Float_GTE, Simple.Float.GTE);
compare(Float_EX, Simple.Float.EX);
compare(Float_DNE, Simple.Float.DNE);
compare(Float_IN, Simple.Float.IN);
compare(Float_NIN, Simple.Float.NIN);
}
protected String Double_EQ;
protected String Double_NE;
protected String Double_LT;
protected String Double_GT;
protected String Double_LTE;
protected String Double_GTE;
protected String Double_EX;
protected String Double_DNE;
protected String Double_IN;
protected String Double_NIN;
@Test
public void simple_Double() {
compare(Double_EQ, Simple.Double.EQ);
compare(Double_NE, Simple.Double.NE);
compare(Double_LT, Simple.Double.LT);
compare(Double_LTE, Simple.Double.LTE);
compare(Double_GT, Simple.Double.GT);
compare(Double_GTE, Simple.Double.GTE);
compare(Double_EX, Simple.Double.EX);
compare(Double_DNE, Simple.Double.DNE);
compare(Double_IN, Simple.Double.IN);
compare(Double_NIN, Simple.Double.NIN);
}
protected String DateTime_EQ;
protected String DateTime_NE;
protected String DateTime_LT;
protected String DateTime_GT;
protected String DateTime_LTE;
protected String DateTime_GTE;
protected String DateTime_EX;
protected String DateTime_DNE;
protected String DateTime_BETWEEN;
@Test
public void simple_DateTime() {
compare(DateTime_EQ, Simple.DateEx.EQ);
compare(DateTime_NE, Simple.DateEx.NE);
compare(DateTime_LT, Simple.DateEx.LT);
compare(DateTime_LTE, Simple.DateEx.LTE);
compare(DateTime_GT, Simple.DateEx.GT);
compare(DateTime_GTE, Simple.DateEx.GTE);
compare(DateTime_EX, Simple.DateEx.EX);
compare(DateTime_DNE, Simple.DateEx.DNE);
compare(DateTime_BETWEEN, Simple.DateEx.BETWEEN);
}
protected String INLINE_ANDING;
@Test
public void inline_Anding() {
compare(INLINE_ANDING, Logical.INLINE_ANDING);
}
protected String INLINE_ORING;
@Test
public void inline_Oring() {
compare(INLINE_ORING, Logical.INLINE_ORING);
}
protected String LIST_ANDING;
@Test
public void list_Anding() {
compare(LIST_ANDING, Logical.LIST_ANDING);
}
protected String LIST_ORING;
@Test
public void list_Oring() {
compare(LIST_ORING, Logical.LIST_ORING);
}
protected String LIST_ORING_OF_INLINE_ANDING;
@Test
public void listOringOfInlineAnding() {
compare(LIST_ORING_OF_INLINE_ANDING, Logical.LIST_ORING_OF_INLINE_ANDING);
}
protected String LIST_ANDING_OF_INLINE_ORING;
@Test
public void listAndingOfInlineOring() {
compare(LIST_ANDING_OF_INLINE_ORING, Logical.LIST_ANDING_OF_INLINE_ORING);
}
protected String LIST_ANDING_OR_LIST_ORING;
@Test
public void listAndingOrListOring() {
compare(LIST_ANDING_OR_LIST_ORING, Logical.LIST_ANDING_OR_LIST_ORING);
}
protected String LIST_ORING_AND_LIST_ANDING;
@Test
public void listOringAndListAnding() {
compare(LIST_ORING_AND_LIST_ANDING, Logical.LIST_ORING_ANDLIST_ANDING);
}
protected String CHAINED_ANDS;
@Test
public void chainedAnds() {
compare(CHAINED_ANDS, Chained.CHAINED_ANDS);
}
protected String CHAINED_ORS;
@Test
public void chainedOrs() {
compare(CHAINED_ORS, Chained.CHAINED_ORS);
}
protected String CHAINED_ANDS_AND_ORS;
@Test
public void chainedAndsAndOrs() {
compare(CHAINED_ANDS_AND_ORS, Chained.CHAINED_ANDS_AND_ORS);
}
protected String CHAINED_ORS_AND_ANDS;
@Test
public void chainedOrsAndAnds() {
compare(CHAINED_ORS_AND_ANDS, Chained.CHAINED_ORS_AND_ANDS);
}
protected String SUB_QUERY;
@Test
public void subquery() {
compare(SUB_QUERY, Composed.SUB_QUERY);
}
protected String NULL_EQUALITY;
protected String NULL_INEQUALITY;
@Test
public void variedInputs() {
compare(NULL_EQUALITY, VariedInputs.NULL_EQUALITY);
compare(NULL_INEQUALITY, VariedInputs.NULL_INEQUALITY);
}
protected U getContext() {
return null;
}
protected void compare(String expected, Condition<QueryModel> condition) {
T visitor = getVisitor();
compare(expected, condition.query(visitor, getContext()));
}
}
| 21,996 | 0.652745 | 0.640968 | 550 | 39.138184 | 28.87199 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.925455 | false | false | 13 |
f59cd20e8b7e847b46ec63fc79ec27e8f6e950eb | 22,582,938,109,098 | 058606da5007241e1b043ede9324e1bff0f08198 | /src/main/java/Models/Player/Player.java | 85c9475e759bf9c52390e52992449c13cc01b4b3 | [
"MIT"
] | permissive | Rejman/TicTacToe | https://github.com/Rejman/TicTacToe | 8d25f8cd15ffd28da2e3c59e722b0a375f46afb1 | dcab13d8a650fc9b8062804f9390bcc593b7bccc | refs/heads/master | 2021-06-19T22:58:06.955000 | 2021-03-06T14:29:58 | 2021-03-06T14:29:58 | 190,354,439 | 0 | 0 | MIT | false | 2021-02-06T17:00:16 | 2019-06-05T08:17:01 | 2021-01-22T16:25:53 | 2021-02-06T17:00:16 | 59,845 | 0 | 0 | 0 | Java | false | false | package Models.Player;
import Models.Game.Game;
import Models.Game.Sign;
import java.util.HashSet;
import java.util.Set;
public abstract class Player {
//name of player
private String name;
//reference to game object
protected Game game;
//sign represents the player
protected Sign value;
/**
*
* @param name
* @param value
*/
public Player(String name, Sign value, Game game){
this.game = game;
this.name = name;
this.value = value;
}
public void setGame(Game game){
this.game = game;
}
/**
* @return name of the player
*/
public String getName(){
return this.name;
}
/**
* @return sign that represents the player
*/
public Sign getValue(){
return value;
}
public void setValue(Sign sign){
this.value = sign;
}
public String toString(){
return name;
}
}
| UTF-8 | Java | 955 | java | Player.java | Java | [] | null | [] | package Models.Player;
import Models.Game.Game;
import Models.Game.Sign;
import java.util.HashSet;
import java.util.Set;
public abstract class Player {
//name of player
private String name;
//reference to game object
protected Game game;
//sign represents the player
protected Sign value;
/**
*
* @param name
* @param value
*/
public Player(String name, Sign value, Game game){
this.game = game;
this.name = name;
this.value = value;
}
public void setGame(Game game){
this.game = game;
}
/**
* @return name of the player
*/
public String getName(){
return this.name;
}
/**
* @return sign that represents the player
*/
public Sign getValue(){
return value;
}
public void setValue(Sign sign){
this.value = sign;
}
public String toString(){
return name;
}
}
| 955 | 0.573822 | 0.573822 | 56 | 16.053572 | 13.482024 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.321429 | false | false | 13 |
19d20c024609ed78808c1fe68ce5a0068fb0cf9b | 22,582,938,105,045 | 4a444cf5dbfdb35e38870b223c513b1fdfd6e752 | /app/src/main/java/com/cheng/rxhandle/Order.java | 3555e00eb24daaf80f5d86775cd65ddc257488d6 | [] | no_license | DIY-green/RxHandleException | https://github.com/DIY-green/RxHandleException | 96aad1fc965e81623156543e8f71279a21c7696a | b884262836868b745c5d8be4ab29ad620dbeee05 | refs/heads/master | 2020-07-14T07:47:37.242000 | 2019-08-30T09:30:36 | 2019-08-30T09:30:36 | 205,277,613 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cheng.rxhandle;
/**
* @author liwangcheng
* @date 2019-08-30 06:44.
*/
public class Order {
public int orderVersion;
public String orderId;
public Order() {
}
public Order(int orderVersion, String orderId) {
this.orderVersion = orderVersion;
this.orderId = orderId;
}
}
| UTF-8 | Java | 328 | java | Order.java | Java | [
{
"context": "package com.cheng.rxhandle;\n\n/**\n * @author liwangcheng\n * @date 2019-08-30 06:44.\n */\npublic class Order",
"end": 55,
"score": 0.9965076446533203,
"start": 44,
"tag": "USERNAME",
"value": "liwangcheng"
}
] | null | [] | package com.cheng.rxhandle;
/**
* @author liwangcheng
* @date 2019-08-30 06:44.
*/
public class Order {
public int orderVersion;
public String orderId;
public Order() {
}
public Order(int orderVersion, String orderId) {
this.orderVersion = orderVersion;
this.orderId = orderId;
}
}
| 328 | 0.634146 | 0.597561 | 18 | 17.222221 | 15.320848 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 13 |
84c9a15f87117ae865c69ec487d9c64bd4c29ae8 | 18,236,431,141,235 | 9c47b9ad1cebc9a82f525cbafcff6cf19887728c | /src/main/java/org/bian/controller/SystemAdministrationApiController.java | f08cb6bade280c93b8227aff9b5db98e05f8f774 | [
"Apache-2.0"
] | permissive | bianapis/sd-system-administration-v3 | https://github.com/bianapis/sd-system-administration-v3 | 45a56f7151ebf4faf5897e079fc47c03bc3aeec2 | 03207e64f66c3f9878cc842254b0aa0327efc93f | refs/heads/master | 2022-12-25T12:10:22.731000 | 2020-10-05T13:15:55 | 2020-10-05T13:15:55 | 299,562,030 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* @author Virtusa
*/
package org.bian.controller;
import java.util.List;
import org.bian.annotation.BianRestController;
import org.bian.annotation.BQ;
import org.bian.dto.BianRequest;
import org.bian.dto.BianResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.bian.dto.*;
import org.bian.service.*;
import org.bian.annotation.functionalpattern.Administer;
@BianRestController
public class SystemAdministrationApiController {
@Autowired
SystemAdministrationApiService service;
@Administer.Activate
public BianResponse<SDSystemAdministrationActivateOutputModel> activate(@RequestBody BianRequest<SDSystemAdministrationActivateInputModel> bianRequest) {
return BianResponse.forSuccess(service.activate(bianRequest.getData()));
}
@BQ("assurance")
@Administer.Capture
public BianResponse<BQAssuranceCaptureOutputModel> captureAssurance(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQAssuranceCaptureInputModel> bianRequest) {
return BianResponse.forSuccess(service.captureAssurance(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@BQ("capacityplanningandresilience")
@Administer.Capture
public BianResponse<BQCapacityPlanningandResilienceCaptureOutputModel> captureCapacityplanningandresilience(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQCapacityPlanningandResilienceCaptureInputModel> bianRequest) {
return BianResponse.forSuccess(service.captureCapacityplanningandresilience(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@BQ("configuration")
@Administer.Capture
public BianResponse<BQConfigurationCaptureOutputModel> captureConfiguration(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQConfigurationCaptureInputModel> bianRequest) {
return BianResponse.forSuccess(service.captureConfiguration(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@BQ("inventory")
@Administer.Capture
public BianResponse<BQInventoryCaptureOutputModel> captureInventory(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQInventoryCaptureInputModel> bianRequest) {
return BianResponse.forSuccess(service.captureInventory(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@Administer.Capture
public BianResponse<CRITSystemAdministrativePlanCaptureOutputModel> capture(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @RequestBody BianRequest<CRITSystemAdministrativePlanCaptureInputModel> bianRequest) {
return BianResponse.forSuccess(service.capture(sdReferenceId, crReferenceId, bianRequest.getData()));
}
@Administer.Configure
public BianResponse<SDSystemAdministrationConfigureOutputModel> configure(@PathVariable("sd-reference-id") String sdReferenceId, @RequestBody BianRequest<SDSystemAdministrationConfigureInputModel> bianRequest) {
return BianResponse.forSuccess(service.configure(sdReferenceId, bianRequest.getData()));
}
@Administer.Control
public BianResponse<CRITSystemAdministrativePlanControlOutputModel> control(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @RequestBody BianRequest<CRITSystemAdministrativePlanControlInputModel> bianRequest) {
return BianResponse.forSuccess(service.control(sdReferenceId, crReferenceId, bianRequest.getData()));
}
@Administer.Exchange
public BianResponse<CRITSystemAdministrativePlanExchangeOutputModel> exchange(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @RequestBody BianRequest<CRITSystemAdministrativePlanExchangeInputModel> bianRequest) {
return BianResponse.forSuccess(service.exchange(sdReferenceId, crReferenceId, bianRequest.getData()));
}
@Administer.Feedback
public BianResponse<SDSystemAdministrationFeedbackOutputModel> feedback(@PathVariable("sd-reference-id") String sdReferenceId, @RequestBody BianRequest<SDSystemAdministrationFeedbackInputModel> bianRequest) {
return BianResponse.forSuccess(service.feedback(sdReferenceId, bianRequest.getData()));
}
@Administer.Grant
public BianResponse<CRITSystemAdministrativePlanGrantOutputModel> grant(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @RequestBody BianRequest<CRITSystemAdministrativePlanGrantInputModel> bianRequest) {
return BianResponse.forSuccess(service.grant(sdReferenceId, crReferenceId, bianRequest.getData()));
}
@Administer.Initiate
public BianResponse<CRITSystemAdministrativePlanInitiateOutputModel> initiate(@PathVariable("sd-reference-id") String sdReferenceId, @RequestBody BianRequest<CRITSystemAdministrativePlanInitiateInputModel> bianRequest) {
return BianResponse.forSuccess(service.initiate(sdReferenceId, bianRequest.getData()));
}
@BQ("assurance")
@Administer.Request
public BianResponse<BQAssuranceRequestOutputModel> requestAssurance(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQAssuranceRequestInputModel> bianRequest) {
return BianResponse.forSuccess(service.requestAssurance(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@BQ("capacityplanningandresilience")
@Administer.Request
public BianResponse<BQCapacityPlanningandResilienceRequestOutputModel> requestCapacityplanningandresilience(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQCapacityPlanningandResilienceRequestInputModel> bianRequest) {
return BianResponse.forSuccess(service.requestCapacityplanningandresilience(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@BQ("configuration")
@Administer.Request
public BianResponse<BQConfigurationRequestOutputModel> requestConfiguration(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQConfigurationRequestInputModel> bianRequest) {
return BianResponse.forSuccess(service.requestConfiguration(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@BQ("inventory")
@Administer.Request
public BianResponse<BQInventoryRequestOutputModel> requestInventory(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQInventoryRequestInputModel> bianRequest) {
return BianResponse.forSuccess(service.requestInventory(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@Administer.Request
public BianResponse<CRITSystemAdministrativePlanRequestOutputModel> request(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @RequestBody BianRequest<CRITSystemAdministrativePlanRequestInputModel> bianRequest) {
return BianResponse.forSuccess(service.request(sdReferenceId, crReferenceId, bianRequest.getData()));
}
@BQ("assurance")
@Administer.Retrieve
public BianResponse<BQAssuranceRetrieveOutputModel> retrieveAssurance(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId) {
return BianResponse.forSuccess(service.retrieveAssurance(sdReferenceId, crReferenceId, bqReferenceId));
}
@BQ("capacityplanningandresilience")
@Administer.Retrieve
public BianResponse<BQCapacityPlanningandResilienceRetrieveOutputModel> retrieveCapacityplanningandresilience(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId) {
return BianResponse.forSuccess(service.retrieveCapacityplanningandresilience(sdReferenceId, crReferenceId, bqReferenceId));
}
@BQ("configuration")
@Administer.Retrieve
public BianResponse<BQConfigurationRetrieveOutputModel> retrieveConfiguration(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId) {
return BianResponse.forSuccess(service.retrieveConfiguration(sdReferenceId, crReferenceId, bqReferenceId));
}
@BQ("inventory")
@Administer.Retrieve
public BianResponse<BQInventoryRetrieveOutputModel> retrieveInventory(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId) {
return BianResponse.forSuccess(service.retrieveInventory(sdReferenceId, crReferenceId, bqReferenceId));
}
@Administer.RetrieveSD
public BianResponse<SDSystemAdministrationRetrieveOutputModel> retrieveSD(@PathVariable("sd-reference-id") String sdReferenceId) {
return BianResponse.forSuccess(service.retrieveSD(sdReferenceId));
}
@Administer.Retrieve
public BianResponse<CRITSystemAdministrativePlanRetrieveOutputModel> retrieve(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId) {
return BianResponse.forSuccess(service.retrieve(sdReferenceId, crReferenceId));
}
@Administer.RetrieveBQIds
public BianResponse<List<String>> retrieveBQIds(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("behavior-qualifier") String behaviorQualifier) {
return BianResponse.forSuccess(service.retrieveBQIds(sdReferenceId, crReferenceId, behaviorQualifier));
}
@Administer.RetrieveBQs
public BianResponse<List<String>> retrieveBQs() {
return BianResponse.forSuccess(service.retrieveBQs());
}
@Administer.RetrieveRefIds
public BianResponse<List<String>> retrieveRefIds(@PathVariable("sd-reference-id") String sdReferenceId) {
return BianResponse.forSuccess(service.retrieveRefIds(sdReferenceId));
}
@Administer.Update
public BianResponse<CRITSystemAdministrativePlanUpdateOutputModel> update(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @RequestBody BianRequest<CRITSystemAdministrativePlanUpdateInputModel> bianRequest) {
return BianResponse.forSuccess(service.update(sdReferenceId, crReferenceId, bianRequest.getData()));
}
@BQ("assurance")
@Administer.Update
public BianResponse<BQAssuranceUpdateOutputModel> updateAssurance(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQAssuranceUpdateInputModel> bianRequest) {
return BianResponse.forSuccess(service.updateAssurance(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@BQ("capacityplanningandresilience")
@Administer.Update
public BianResponse<BQCapacityPlanningandResilienceUpdateOutputModel> updateCapacityplanningandresilience(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQCapacityPlanningandResilienceUpdateInputModel> bianRequest) {
return BianResponse.forSuccess(service.updateCapacityplanningandresilience(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@BQ("configuration")
@Administer.Update
public BianResponse<BQConfigurationUpdateOutputModel> updateConfiguration(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQConfigurationUpdateInputModel> bianRequest) {
return BianResponse.forSuccess(service.updateConfiguration(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@BQ("inventory")
@Administer.Update
public BianResponse<BQInventoryUpdateOutputModel> updateInventory(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQInventoryUpdateInputModel> bianRequest) {
return BianResponse.forSuccess(service.updateInventory(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
}
| UTF-8 | Java | 13,259 | java | SystemAdministrationApiController.java | Java | [
{
"context": "/**\n * @author Virtusa\n */\npackage org.bian.controller;\n\nimport java.uti",
"end": 22,
"score": 0.99980229139328,
"start": 15,
"tag": "NAME",
"value": "Virtusa"
}
] | null | [] | /**
* @author Virtusa
*/
package org.bian.controller;
import java.util.List;
import org.bian.annotation.BianRestController;
import org.bian.annotation.BQ;
import org.bian.dto.BianRequest;
import org.bian.dto.BianResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.bian.dto.*;
import org.bian.service.*;
import org.bian.annotation.functionalpattern.Administer;
@BianRestController
public class SystemAdministrationApiController {
@Autowired
SystemAdministrationApiService service;
@Administer.Activate
public BianResponse<SDSystemAdministrationActivateOutputModel> activate(@RequestBody BianRequest<SDSystemAdministrationActivateInputModel> bianRequest) {
return BianResponse.forSuccess(service.activate(bianRequest.getData()));
}
@BQ("assurance")
@Administer.Capture
public BianResponse<BQAssuranceCaptureOutputModel> captureAssurance(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQAssuranceCaptureInputModel> bianRequest) {
return BianResponse.forSuccess(service.captureAssurance(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@BQ("capacityplanningandresilience")
@Administer.Capture
public BianResponse<BQCapacityPlanningandResilienceCaptureOutputModel> captureCapacityplanningandresilience(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQCapacityPlanningandResilienceCaptureInputModel> bianRequest) {
return BianResponse.forSuccess(service.captureCapacityplanningandresilience(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@BQ("configuration")
@Administer.Capture
public BianResponse<BQConfigurationCaptureOutputModel> captureConfiguration(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQConfigurationCaptureInputModel> bianRequest) {
return BianResponse.forSuccess(service.captureConfiguration(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@BQ("inventory")
@Administer.Capture
public BianResponse<BQInventoryCaptureOutputModel> captureInventory(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQInventoryCaptureInputModel> bianRequest) {
return BianResponse.forSuccess(service.captureInventory(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@Administer.Capture
public BianResponse<CRITSystemAdministrativePlanCaptureOutputModel> capture(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @RequestBody BianRequest<CRITSystemAdministrativePlanCaptureInputModel> bianRequest) {
return BianResponse.forSuccess(service.capture(sdReferenceId, crReferenceId, bianRequest.getData()));
}
@Administer.Configure
public BianResponse<SDSystemAdministrationConfigureOutputModel> configure(@PathVariable("sd-reference-id") String sdReferenceId, @RequestBody BianRequest<SDSystemAdministrationConfigureInputModel> bianRequest) {
return BianResponse.forSuccess(service.configure(sdReferenceId, bianRequest.getData()));
}
@Administer.Control
public BianResponse<CRITSystemAdministrativePlanControlOutputModel> control(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @RequestBody BianRequest<CRITSystemAdministrativePlanControlInputModel> bianRequest) {
return BianResponse.forSuccess(service.control(sdReferenceId, crReferenceId, bianRequest.getData()));
}
@Administer.Exchange
public BianResponse<CRITSystemAdministrativePlanExchangeOutputModel> exchange(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @RequestBody BianRequest<CRITSystemAdministrativePlanExchangeInputModel> bianRequest) {
return BianResponse.forSuccess(service.exchange(sdReferenceId, crReferenceId, bianRequest.getData()));
}
@Administer.Feedback
public BianResponse<SDSystemAdministrationFeedbackOutputModel> feedback(@PathVariable("sd-reference-id") String sdReferenceId, @RequestBody BianRequest<SDSystemAdministrationFeedbackInputModel> bianRequest) {
return BianResponse.forSuccess(service.feedback(sdReferenceId, bianRequest.getData()));
}
@Administer.Grant
public BianResponse<CRITSystemAdministrativePlanGrantOutputModel> grant(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @RequestBody BianRequest<CRITSystemAdministrativePlanGrantInputModel> bianRequest) {
return BianResponse.forSuccess(service.grant(sdReferenceId, crReferenceId, bianRequest.getData()));
}
@Administer.Initiate
public BianResponse<CRITSystemAdministrativePlanInitiateOutputModel> initiate(@PathVariable("sd-reference-id") String sdReferenceId, @RequestBody BianRequest<CRITSystemAdministrativePlanInitiateInputModel> bianRequest) {
return BianResponse.forSuccess(service.initiate(sdReferenceId, bianRequest.getData()));
}
@BQ("assurance")
@Administer.Request
public BianResponse<BQAssuranceRequestOutputModel> requestAssurance(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQAssuranceRequestInputModel> bianRequest) {
return BianResponse.forSuccess(service.requestAssurance(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@BQ("capacityplanningandresilience")
@Administer.Request
public BianResponse<BQCapacityPlanningandResilienceRequestOutputModel> requestCapacityplanningandresilience(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQCapacityPlanningandResilienceRequestInputModel> bianRequest) {
return BianResponse.forSuccess(service.requestCapacityplanningandresilience(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@BQ("configuration")
@Administer.Request
public BianResponse<BQConfigurationRequestOutputModel> requestConfiguration(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQConfigurationRequestInputModel> bianRequest) {
return BianResponse.forSuccess(service.requestConfiguration(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@BQ("inventory")
@Administer.Request
public BianResponse<BQInventoryRequestOutputModel> requestInventory(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQInventoryRequestInputModel> bianRequest) {
return BianResponse.forSuccess(service.requestInventory(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@Administer.Request
public BianResponse<CRITSystemAdministrativePlanRequestOutputModel> request(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @RequestBody BianRequest<CRITSystemAdministrativePlanRequestInputModel> bianRequest) {
return BianResponse.forSuccess(service.request(sdReferenceId, crReferenceId, bianRequest.getData()));
}
@BQ("assurance")
@Administer.Retrieve
public BianResponse<BQAssuranceRetrieveOutputModel> retrieveAssurance(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId) {
return BianResponse.forSuccess(service.retrieveAssurance(sdReferenceId, crReferenceId, bqReferenceId));
}
@BQ("capacityplanningandresilience")
@Administer.Retrieve
public BianResponse<BQCapacityPlanningandResilienceRetrieveOutputModel> retrieveCapacityplanningandresilience(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId) {
return BianResponse.forSuccess(service.retrieveCapacityplanningandresilience(sdReferenceId, crReferenceId, bqReferenceId));
}
@BQ("configuration")
@Administer.Retrieve
public BianResponse<BQConfigurationRetrieveOutputModel> retrieveConfiguration(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId) {
return BianResponse.forSuccess(service.retrieveConfiguration(sdReferenceId, crReferenceId, bqReferenceId));
}
@BQ("inventory")
@Administer.Retrieve
public BianResponse<BQInventoryRetrieveOutputModel> retrieveInventory(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId) {
return BianResponse.forSuccess(service.retrieveInventory(sdReferenceId, crReferenceId, bqReferenceId));
}
@Administer.RetrieveSD
public BianResponse<SDSystemAdministrationRetrieveOutputModel> retrieveSD(@PathVariable("sd-reference-id") String sdReferenceId) {
return BianResponse.forSuccess(service.retrieveSD(sdReferenceId));
}
@Administer.Retrieve
public BianResponse<CRITSystemAdministrativePlanRetrieveOutputModel> retrieve(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId) {
return BianResponse.forSuccess(service.retrieve(sdReferenceId, crReferenceId));
}
@Administer.RetrieveBQIds
public BianResponse<List<String>> retrieveBQIds(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("behavior-qualifier") String behaviorQualifier) {
return BianResponse.forSuccess(service.retrieveBQIds(sdReferenceId, crReferenceId, behaviorQualifier));
}
@Administer.RetrieveBQs
public BianResponse<List<String>> retrieveBQs() {
return BianResponse.forSuccess(service.retrieveBQs());
}
@Administer.RetrieveRefIds
public BianResponse<List<String>> retrieveRefIds(@PathVariable("sd-reference-id") String sdReferenceId) {
return BianResponse.forSuccess(service.retrieveRefIds(sdReferenceId));
}
@Administer.Update
public BianResponse<CRITSystemAdministrativePlanUpdateOutputModel> update(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @RequestBody BianRequest<CRITSystemAdministrativePlanUpdateInputModel> bianRequest) {
return BianResponse.forSuccess(service.update(sdReferenceId, crReferenceId, bianRequest.getData()));
}
@BQ("assurance")
@Administer.Update
public BianResponse<BQAssuranceUpdateOutputModel> updateAssurance(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQAssuranceUpdateInputModel> bianRequest) {
return BianResponse.forSuccess(service.updateAssurance(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@BQ("capacityplanningandresilience")
@Administer.Update
public BianResponse<BQCapacityPlanningandResilienceUpdateOutputModel> updateCapacityplanningandresilience(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQCapacityPlanningandResilienceUpdateInputModel> bianRequest) {
return BianResponse.forSuccess(service.updateCapacityplanningandresilience(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@BQ("configuration")
@Administer.Update
public BianResponse<BQConfigurationUpdateOutputModel> updateConfiguration(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQConfigurationUpdateInputModel> bianRequest) {
return BianResponse.forSuccess(service.updateConfiguration(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
@BQ("inventory")
@Administer.Update
public BianResponse<BQInventoryUpdateOutputModel> updateInventory(@PathVariable("sd-reference-id") String sdReferenceId, @PathVariable("cr-reference-id") String crReferenceId, @PathVariable("bq-reference-id") String bqReferenceId, @RequestBody BianRequest<BQInventoryUpdateInputModel> bianRequest) {
return BianResponse.forSuccess(service.updateInventory(sdReferenceId, crReferenceId, bqReferenceId, bianRequest.getData()));
}
}
| 13,259 | 0.832944 | 0.832944 | 195 | 66.994873 | 95.159164 | 363 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.91282 | false | false | 13 |
2db3d42e550dfddd0a3a3c00f84dce5f44463cb8 | 27,127,013,484,988 | 41259a190ff1fee8b0b8f28b9979aa1f11fdfe2f | /Android/src/uy/bunker/deliverylibre/AsyncLogin.java | 56a897e226e428bf9dbdb6700a57f36c8e07ce28 | [] | no_license | humodev/deliveryLibre | https://github.com/humodev/deliveryLibre | 65d1c23ca3bc96637d29221b0f17afc1d425d47e | 414dd01e38d5c9da64241a4230c649432344921e | refs/heads/master | 2017-12-04T07:58:19.179000 | 2015-04-12T12:30:42 | 2015-04-12T12:30:42 | 33,782,963 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uy.bunker.deliverylibre;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
//Debo hacer una tarea asincronica para consumir el servicio rest correctamente
public class AsyncLogin extends AsyncTask<String, String, JSONObject>{
//Defino variables a utilizar por el constructor
private Activity activity;
private String url;
private boolean checkCode;
private Context context;
private boolean logueado;
//Defino variables a utilizar por getJSONFromUrl
private InputStream is = null;
private JSONObject jObj = null;
private String json = "";
//Shared preferences
// Instancia de SharedPreferences
private SharedPreferences prefs;
//Defino variables a utilizar para hacer el addUser
String user_id;
String access_token;
//Defino variables objetos y urls
WebView wblogin;
String code = "https://deliverylibre.herokuapp.com/code";
/**
*
* @param ac
*
* Constructor AsyncLogin(Activity, String, boolean, Context, boolean)
*/
public AsyncLogin(Activity ac, String url, boolean codehere, Context context1, boolean logueado) {
activity = ac;
this.url = url;
this.checkCode = codehere;
this.context = context1;
this.logueado = logueado;
}
/**
*
* @param ac
*
* Constructor por defecto.
*/
public AsyncLogin() {
}
/**
*
* @param url
* @return JSONObject
*
* Obtiene y parsea el json.
*/
@SuppressWarnings("deprecation")
private JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
is.close();
json = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
// return JSON String
return jObj;
}
/**
*
* @param url
* @return JSONObject
*
* Obtiene y parsea el json.
*/
@SuppressWarnings("deprecation")
private JSONObject postJSONToUrl(String url, String clientId, String token, String deviceId) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
//Set params
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("clientId", clientId));
nameValuePairs.add(new BasicNameValuePair("token", token));
nameValuePairs.add(new BasicNameValuePair("deviceId", deviceId));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
is.close();
json = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
// return JSON String
return jObj;
}
@Override
protected JSONObject doInBackground(String... arg0) {
AsyncLogin AsLogin = new AsyncLogin();
if(logueado){
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String postUrl = "https://deliverylibre.herokuapp.com/addUser";//context.getString(R.string.add_user);
prefs = Prefs.get(context);
this.user_id = prefs.getString("user_id", "");
this.access_token = prefs.getString("access_token", "");
// Getting JSON from URL
JSONObject json = AsLogin.postJSONToUrl(postUrl, this.user_id, this.access_token, "pruebadiego");
return json;
}
else{
// Getting JSON from URL
JSONObject json = AsLogin.getJSONFromUrl(url);
return json;
}
}
@Override
protected void onPostExecute(JSONObject json) {
super.onPostExecute(json);
// Do stuff
if(!logueado){
if (checkCode) {
SharedPreferences prefs = Prefs.get(context);
SharedPreferences.Editor editor = prefs.edit();
try {
user_id = json.getString("user_id");
access_token = json.getString("access_token");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
editor.putString("user_id", user_id);
editor.putString("access_token", access_token);
editor.commit();
//hacer el post de add user
String urlLogueado = "https://deliverylibre.herokuapp.com/addUser";
AsyncLogin asyncTask = new AsyncLogin(
new Login(), urlLogueado, true, context, true);
asyncTask.execute();
} else {
String url2;
try {
url2 = json.getString("url");
wblogin = (WebView) activity.findViewById(R.id.wblogin);
WebSettings webSettings = wblogin.getSettings();
webSettings.setJavaScriptEnabled(true); // enable javascript
webSettings.setDomStorageEnabled(true);
wblogin.getSettings().setJavaScriptCanOpenWindowsAutomatically(
true);
wblogin.setWebChromeClient(new WebChromeClient());
wblogin.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
}
@Override
public void onPageFinished(WebView view, String url) {
String current = "";
current = getUrl();
if (current != null) {
if (current.contains(code)) {
checkCode = true;
AsyncLogin asyncTask = new AsyncLogin(
new Login(), current, true, context, false);
asyncTask.execute();
}
}
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
}
});
if (!url2.equals("")) {
wblogin.loadUrl(url2);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else{
activity.finish();
Intent intent = new Intent(context,
Recientes.class);
context.startActivity(intent);
try {
this.finalize();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String getUrl() {
return wblogin.getUrl();
}
public boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
}
| UTF-8 | Java | 8,851 | java | AsyncLogin.java | Java | [
{
"context": "NToUrl(postUrl, this.user_id, this.access_token, \"pruebadiego\");\n\t\t\treturn json;\n\t\t}\n\t\telse{\n\t\t\t// Getting JSON",
"end": 5902,
"score": 0.9543517827987671,
"start": 5891,
"tag": "PASSWORD",
"value": "pruebadiego"
}
] | null | [] | package uy.bunker.deliverylibre;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
//Debo hacer una tarea asincronica para consumir el servicio rest correctamente
public class AsyncLogin extends AsyncTask<String, String, JSONObject>{
//Defino variables a utilizar por el constructor
private Activity activity;
private String url;
private boolean checkCode;
private Context context;
private boolean logueado;
//Defino variables a utilizar por getJSONFromUrl
private InputStream is = null;
private JSONObject jObj = null;
private String json = "";
//Shared preferences
// Instancia de SharedPreferences
private SharedPreferences prefs;
//Defino variables a utilizar para hacer el addUser
String user_id;
String access_token;
//Defino variables objetos y urls
WebView wblogin;
String code = "https://deliverylibre.herokuapp.com/code";
/**
*
* @param ac
*
* Constructor AsyncLogin(Activity, String, boolean, Context, boolean)
*/
public AsyncLogin(Activity ac, String url, boolean codehere, Context context1, boolean logueado) {
activity = ac;
this.url = url;
this.checkCode = codehere;
this.context = context1;
this.logueado = logueado;
}
/**
*
* @param ac
*
* Constructor por defecto.
*/
public AsyncLogin() {
}
/**
*
* @param url
* @return JSONObject
*
* Obtiene y parsea el json.
*/
@SuppressWarnings("deprecation")
private JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
is.close();
json = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
// return JSON String
return jObj;
}
/**
*
* @param url
* @return JSONObject
*
* Obtiene y parsea el json.
*/
@SuppressWarnings("deprecation")
private JSONObject postJSONToUrl(String url, String clientId, String token, String deviceId) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
//Set params
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("clientId", clientId));
nameValuePairs.add(new BasicNameValuePair("token", token));
nameValuePairs.add(new BasicNameValuePair("deviceId", deviceId));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
is.close();
json = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
// return JSON String
return jObj;
}
@Override
protected JSONObject doInBackground(String... arg0) {
AsyncLogin AsLogin = new AsyncLogin();
if(logueado){
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String postUrl = "https://deliverylibre.herokuapp.com/addUser";//context.getString(R.string.add_user);
prefs = Prefs.get(context);
this.user_id = prefs.getString("user_id", "");
this.access_token = prefs.getString("access_token", "");
// Getting JSON from URL
JSONObject json = AsLogin.postJSONToUrl(postUrl, this.user_id, this.access_token, "<PASSWORD>");
return json;
}
else{
// Getting JSON from URL
JSONObject json = AsLogin.getJSONFromUrl(url);
return json;
}
}
@Override
protected void onPostExecute(JSONObject json) {
super.onPostExecute(json);
// Do stuff
if(!logueado){
if (checkCode) {
SharedPreferences prefs = Prefs.get(context);
SharedPreferences.Editor editor = prefs.edit();
try {
user_id = json.getString("user_id");
access_token = json.getString("access_token");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
editor.putString("user_id", user_id);
editor.putString("access_token", access_token);
editor.commit();
//hacer el post de add user
String urlLogueado = "https://deliverylibre.herokuapp.com/addUser";
AsyncLogin asyncTask = new AsyncLogin(
new Login(), urlLogueado, true, context, true);
asyncTask.execute();
} else {
String url2;
try {
url2 = json.getString("url");
wblogin = (WebView) activity.findViewById(R.id.wblogin);
WebSettings webSettings = wblogin.getSettings();
webSettings.setJavaScriptEnabled(true); // enable javascript
webSettings.setDomStorageEnabled(true);
wblogin.getSettings().setJavaScriptCanOpenWindowsAutomatically(
true);
wblogin.setWebChromeClient(new WebChromeClient());
wblogin.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
}
@Override
public void onPageFinished(WebView view, String url) {
String current = "";
current = getUrl();
if (current != null) {
if (current.contains(code)) {
checkCode = true;
AsyncLogin asyncTask = new AsyncLogin(
new Login(), current, true, context, false);
asyncTask.execute();
}
}
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
}
});
if (!url2.equals("")) {
wblogin.loadUrl(url2);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else{
activity.finish();
Intent intent = new Intent(context,
Recientes.class);
context.startActivity(intent);
try {
this.finalize();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String getUrl() {
return wblogin.getUrl();
}
public boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
}
| 8,850 | 0.684103 | 0.682748 | 350 | 24.288572 | 22.438478 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.711429 | false | false | 13 |
4e77026516bea2d25b6e5e6b2b989bd24caab07e | 31,894,427,198,221 | e08fb3fde83c5ead57954f7cb03209ba4e450855 | /hazelcast-jet-core/src/test/java/com/hazelcast/jet/pipeline/WindowAggregateTest.java | 90b84ccc9a04edfe0b1035ecdf9459400a232df8 | [
"Apache-2.0"
] | permissive | googlielmo/hazelcast-jet | https://github.com/googlielmo/hazelcast-jet | 54a81b67fae0120bd208217c7eea85ced068076e | 14f9a4fac9084fe5c8b495086f13ed03a91ea417 | refs/heads/master | 2020-03-14T12:23:25.483000 | 2019-02-25T09:09:39 | 2019-02-26T12:19:25 | 131,610,785 | 0 | 0 | null | true | 2018-04-30T15:09:36 | 2018-04-30T15:09:35 | 2018-04-30T15:09:29 | 2018-04-30T08:55:21 | 7,728 | 0 | 0 | 0 | null | false | null | /*
* Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.
*
* 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.hazelcast.jet.pipeline;
import com.hazelcast.jet.accumulator.LongAccumulator;
import com.hazelcast.jet.aggregate.AggregateOperation1;
import com.hazelcast.jet.aggregate.CoAggregateOperationBuilder;
import com.hazelcast.jet.datamodel.Tag;
import com.hazelcast.jet.datamodel.TimestampedItem;
import com.hazelcast.jet.datamodel.Tuple2;
import com.hazelcast.jet.datamodel.Tuple3;
import com.hazelcast.jet.function.DistributedBiFunction;
import org.junit.Test;
import java.util.List;
import java.util.function.BiFunction;
import java.util.stream.IntStream;
import static com.hazelcast.jet.aggregate.AggregateOperations.aggregateOperation2;
import static com.hazelcast.jet.aggregate.AggregateOperations.aggregateOperation3;
import static com.hazelcast.jet.aggregate.AggregateOperations.coAggregateOperationBuilder;
import static com.hazelcast.jet.aggregate.AggregateOperations.counting;
import static com.hazelcast.jet.aggregate.AggregateOperations.summingLong;
import static com.hazelcast.jet.datamodel.Tuple2.tuple2;
import static com.hazelcast.jet.datamodel.Tuple3.tuple3;
import static com.hazelcast.jet.pipeline.WindowDefinition.session;
import static com.hazelcast.jet.pipeline.WindowDefinition.sliding;
import static com.hazelcast.jet.pipeline.WindowDefinition.tumbling;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertEquals;
public class WindowAggregateTest extends PipelineStreamTestSupport {
private static final DistributedBiFunction<Long, Tuple2<Long, Long>, String> FORMAT_FN_2 =
(timestamp, sums) -> String.format("(%04d: %04d, %04d)", timestamp, sums.f0(), sums.f1());
private static final DistributedBiFunction<Long, Tuple3<Long, Long, Long>, String> FORMAT_FN_3 =
(timestamp, sums) -> String.format("(%04d: %04d, %04d, %04d)",
timestamp, sums.f0(), sums.f1(), sums.f2());
private static final AggregateOperation1<Integer, LongAccumulator, Long> SUMMING = summingLong(i -> i);
@Test
public void when_setWindowDefinition_then_windowDefinitionReturnsIt() {
// Given
SlidingWindowDefinition tumbling = tumbling(2);
// When
StageWithWindow<Integer> stage = streamStageFromList(emptyList()).window(tumbling);
// Then
assertEquals(tumbling, stage.windowDefinition());
}
@Test
public void distinct() {
// Given
int winSize = itemCount / 2;
// timestamps: [0, 0, 1, 1, 2, 2, ...]
List<Integer> timestamps = IntStream.range(0, itemCount)
.flatMap(i -> IntStream.of(i, i))
.boxed()
.collect(toList());
StageWithWindow<Integer> windowed = streamStageFromList(timestamps)
.window(tumbling(winSize));
// When
StreamStage<TimestampedItem<Integer>> distinct = windowed.distinct();
// Then
distinct.drainTo(sink);
execute();
assertEquals(
streamToString(
IntStream.range(0, itemCount)
.mapToObj(i -> String.format("(%04d, %04d)", roundUp(i + 1, winSize), i))
.distinct(),
identity()),
streamToString(
this.<Integer>sinkStreamOfTsItem(),
tsItem -> String.format("(%04d, %04d)", tsItem.timestamp(), tsItem.item()))
);
}
@Test
public void tumblingWindow() {
// Given
int winSize = 4;
BiFunction<Long, Long, String> formatFn =
(timestamp, item) -> String.format("(%04d, %04d)", timestamp, item);
List<Integer> input = sequence(itemCount);
StreamStage<Integer> stage = streamStageFromList(input);
// When
SlidingWindowDefinition wDef = tumbling(winSize);
StageWithWindow<Integer> windowed = stage.window(wDef);
// Then
windowed.aggregate(summingLong(i -> i))
.drainTo(sink);
execute();
assertEquals(
new SlidingWindowSimulator(wDef)
.acceptStream(input.stream())
.stringResults(e -> formatFn.apply(e.getKey(), e.getValue())),
streamToString(this.<Long>sinkStreamOfTsItem(),
tsItem -> formatFn.apply(tsItem.timestamp(), tsItem.item()))
);
}
@Test
public void tumblingWindow_withEarlyResults() {
// Given
int winSize = 4;
BiFunction<Long, Long, String> formatFn =
(timestamp, item) -> String.format("(%04d, %04d)", timestamp, item);
List<Integer> input = sequence(itemCount);
StreamStage<Integer> stage = streamStageFromList(input, EARLY_RESULTS_PERIOD);
// When
SlidingWindowDefinition wDef = tumbling(winSize).setEarlyResultsPeriod(EARLY_RESULTS_PERIOD);
StageWithWindow<Integer> windowed = stage.window(wDef);
// Then
windowed.aggregate(summingLong(i -> i))
.drainTo(sink);
jet().newJob(p);
String expectedString = new SlidingWindowSimulator(wDef)
.acceptStream(input.stream())
.stringResults(e -> formatFn.apply(e.getKey(), e.getValue()));
assertTrueEventually(() -> assertEquals(
expectedString,
streamToString(this.<Long>sinkStreamOfTsItem(),
tsItem -> formatFn.apply(tsItem.timestamp(), tsItem.item()),
TimestampedItem::timestamp
)),
ASSERT_TIMEOUT_SECONDS);
}
@Test
public void slidingWindow() {
// Given
int winSize = 4;
int slideBy = 2;
List<Integer> input = sequence(itemCount);
BiFunction<Long, Long, String> formatFn =
(timestamp, item) -> String.format("(%04d, %04d)", timestamp, item);
// If emitting early results, keep the watermark behind all input
StreamStage<Integer> stage = streamStageFromList(input);
// When
SlidingWindowDefinition wDef = sliding(winSize, slideBy);
StreamStage<TimestampedItem<Long>> aggregated = stage.window(wDef)
.aggregate(summingLong(i -> i));
// Then
aggregated.drainTo(sink);
execute();
assertEquals(
new SlidingWindowSimulator(wDef)
.acceptStream(input.stream())
.stringResults(e -> formatFn.apply(e.getKey(), e.getValue())),
streamToString(this.<Long>sinkStreamOfTsItem(),
tsItem -> formatFn.apply(tsItem.timestamp(), tsItem.item()))
);
}
@Test
public void slidingWindow_withEarlyResults() {
// Given
int winSize = 4;
int slideBy = 2;
List<Integer> input = sequence(itemCount);
BiFunction<Long, Long, String> formatFn =
(timestamp, item) -> String.format("(%04d, %04d)", timestamp, item);
// If emitting early results, keep the watermark behind all input
StreamStage<Integer> stage = streamStageFromList(input, EARLY_RESULTS_PERIOD);
// When
SlidingWindowDefinition wDef = sliding(winSize, slideBy).setEarlyResultsPeriod(EARLY_RESULTS_PERIOD);
StreamStage<TimestampedItem<Long>> aggregated = stage.window(wDef)
.aggregate(summingLong(i -> i));
// Then
aggregated.drainTo(sink);
jet().newJob(p);
String expectedString = new SlidingWindowSimulator(wDef)
.acceptStream(input.stream())
.stringResults(e -> formatFn.apply(e.getKey(), e.getValue()));
assertTrueEventually(() -> assertEquals(
expectedString,
streamToString(this.<Long>sinkStreamOfTsItem(),
tsItem -> formatFn.apply(tsItem.timestamp(), tsItem.item()),
TimestampedItem::timestamp
)),
ASSERT_TIMEOUT_SECONDS);
}
@Test
public void sessionWindow() {
// Given
int sessionLength = 4;
int sessionTimeout = 2;
// Sample input: [0, 1, 2, 3, 6, 7, 8, 9, 12, 13, 14, 15, ...]
List<Integer> input = sequence(itemCount).stream()
.map(ts -> ts + (ts / sessionLength) * sessionTimeout)
.collect(toList());
BiFunction<Long, Long, String> formatFn = (timestamp, sum) -> String.format("(%04d, %04d)", timestamp, sum);
// When
SessionWindowDefinition wDef = session(sessionTimeout);
StageWithWindow<Integer> windowed = streamStageFromList(input).window(wDef);
// Then
windowed.aggregate(summingLong(i -> i),
(start, end, sum) -> new TimestampedItem<>(start, sum))
.drainTo(sink);
execute();
assertEquals(
new SessionWindowSimulator(wDef, sessionLength + sessionTimeout)
.acceptStream(input.stream())
.stringResults(e -> formatFn.apply(e.getKey(), e.getValue())),
streamToString(
this.<Long>sinkStreamOfTsItem(),
tsItem -> formatFn.apply(tsItem.timestamp(), tsItem.item()))
);
}
@Test
public void sessionWindow_withEarlyResults() {
// Given
int sessionLength = 4;
int sessionTimeout = 2;
// Sample input: [0, 1, 2, 3, 6, 7, 8, 9, 12, 13, 14, 15, ...]
List<Integer> input = sequence(itemCount).stream()
.map(ts -> ts + (ts / sessionLength) * sessionTimeout)
.collect(toList());
BiFunction<Long, Long, String> formatFn = (timestamp, sum) -> String.format("(%04d, %04d)", timestamp, sum);
// Keep the watermark behind all input
StreamStage<Integer> stage = streamStageFromList(input, EARLY_RESULTS_PERIOD);
// When
SessionWindowDefinition wDef = session(sessionTimeout).setEarlyResultsPeriod(EARLY_RESULTS_PERIOD);
StageWithWindow<Integer> windowed = stage.window(wDef);
// Then
windowed.aggregate(summingLong(i -> i),
// suppress incomplete windows to get predictable results
(start, end, sum) -> end - start != sessionLength + sessionTimeout - 1
? null
: new TimestampedItem<>(start, sum))
.drainTo(sink);
jet().newJob(p);
String expectedString = new SessionWindowSimulator(wDef, sessionLength + sessionTimeout)
.acceptStream(input.stream())
.stringResults(e -> formatFn.apply(e.getKey(), e.getValue()));
assertTrueEventually(() -> assertEquals(
expectedString,
streamToString(
this.<Long>sinkStreamOfTsItem(),
tsItem -> formatFn.apply(tsItem.timestamp(), tsItem.item()),
TimestampedItem::timestamp
)),
ASSERT_TIMEOUT_SECONDS);
}
@Test
public void when_tumblingWinWithEarlyResults_then_emitRepeatedly() {
assertEarlyResultsEmittedRepeatedly(tumbling(10));
}
@Test
public void when_sessionWinWithEarlyResults_then_emitRepeatedly() {
assertEarlyResultsEmittedRepeatedly(session(9));
}
private void assertEarlyResultsEmittedRepeatedly(WindowDefinition wDef) {
// Given
long earlyResultPeriod = 50;
StreamStage<Integer> srcStage = streamStageFromList(singletonList(1), earlyResultPeriod);
// When
StageWithWindow<Integer> stage = srcStage.window(wDef.setEarlyResultsPeriod(earlyResultPeriod));
// Then
stage.aggregate(counting()).drainTo(Sinks.list(sinkList));
jet().newJob(p);
assertTrueEventually(() -> assertGreaterOrEquals("sinkList.size()", sinkList.size(), 10));
TimestampedItem expected = new TimestampedItem<>(10L, 1L);
sinkList.forEach(it -> assertEquals(expected, it));
}
@Test
public void when_slidingWindow_outputFnReturnsNull_then_filteredOut() {
// Given
StreamStage<Integer> stage = streamStageFromList(sequence(itemCount));
// When
StreamStage<Object> aggregated = stage.window(sliding(2, 1))
.aggregate(counting(), (x, y, z) -> null);
// Then
aggregated.drainTo(sink);
jet().newJob(p);
assertTrueFiveSeconds(() -> assertEquals(0, sinkList.size()));
}
@Test
public void when_sessionWindow_outputFnReturnsNull_then_filteredOut() {
// Given
StreamStage<Integer> stage = streamStageFromList(sequence(itemCount));
// When
StreamStage<Object> aggregated = stage.window(session(1))
.aggregate(counting(), (x, y, z) -> null);
// Then
aggregated.drainTo(sink);
jet().newJob(p);
assertTrueFiveSeconds(() -> assertEquals(0, sinkList.size()));
}
private class CoAggregateFixture {
final SlidingWindowDefinition wDef = tumbling(4);
final List<Integer> input = sequence(itemCount);
final StageWithWindow<Integer> stage0 = newStage().window(wDef);
final String expectedString2 = new SlidingWindowSimulator(wDef)
.acceptStream(input.stream())
.stringResults(e -> FORMAT_FN_2.apply(e.getKey(), tuple2(e.getValue(), e.getValue())));
final String expectedString3 = new SlidingWindowSimulator(wDef)
.acceptStream(input.stream())
.stringResults(e -> FORMAT_FN_3.apply(e.getKey(), tuple3(e.getValue(), e.getValue(), e.getValue())));
StreamStage<Integer> newStage() {
return streamStageFromList(input);
}
}
@Test
public void aggregate2_withSeparateAggrOps() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
StreamStage<TimestampedItem<Tuple2<Long, Long>>> aggregated =
fx.stage0.aggregate2(SUMMING, fx.newStage(), SUMMING);
//Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString2,
streamToString(
this.<Tuple2<Long, Long>>sinkStreamOfTsItem(),
tsItem -> FORMAT_FN_2.apply(tsItem.timestamp(), tsItem.item())
));
}
@Test
public void aggregate2_withAggrOp2() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
StreamStage<TimestampedItem<Tuple2<Long, Long>>> aggregated =
fx.stage0.aggregate2(fx.newStage(), aggregateOperation2(SUMMING, SUMMING));
//Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString2,
streamToString(
this.<Tuple2<Long, Long>>sinkStreamOfTsItem(),
tsItem -> FORMAT_FN_2.apply(tsItem.timestamp(), tsItem.item())
));
}
@Test
public void aggregate2_withSeparateAggrOps_withOutputFn() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
StreamStage<String> aggregated = fx.stage0.aggregate2(SUMMING, fx.newStage(), SUMMING,
(start, end, sum0, sum1) -> FORMAT_FN_2.apply(end, tuple2(sum0, sum1)));
// Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString2,
streamToString(sinkList.stream().map(String.class::cast), identity()));
}
@Test
public void aggregate2_withAggrOp2_withOutputFn() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
StreamStage<String> aggregated = fx.stage0.aggregate2(
fx.newStage(),
aggregateOperation2(SUMMING, SUMMING),
(start, end, sums) -> FORMAT_FN_2.apply(end, sums));
// Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString2,
streamToString(sinkList.stream().map(String.class::cast), identity()));
}
@Test
public void aggregate3_withSeparateAggrOps() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
StreamStage<TimestampedItem<Tuple3<Long, Long, Long>>> aggregated =
fx.stage0.aggregate3(SUMMING, fx.newStage(), SUMMING, fx.newStage(), SUMMING);
// Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString3,
streamToString(this.<Tuple3<Long, Long, Long>>sinkStreamOfTsItem(),
tsItem -> FORMAT_FN_3.apply(tsItem.timestamp(), tsItem.item())
));
}
@Test
public void aggregate3_withAggrOp3() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
StreamStage<TimestampedItem<Tuple3<Long, Long, Long>>> aggregated =
fx.stage0.aggregate3(fx.newStage(), fx.newStage(),
aggregateOperation3(SUMMING, SUMMING, SUMMING));
//Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString3,
streamToString(this.<Tuple3<Long, Long, Long>>sinkStreamOfTsItem(),
tsItem -> FORMAT_FN_3.apply(tsItem.timestamp(), tsItem.item())
));
}
@Test
public void aggregate3_withSeparateAggrOps_withOutputFn() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
StreamStage<String> aggregated = fx.stage0.aggregate3(SUMMING,
fx.newStage(), SUMMING,
fx.newStage(), SUMMING,
(start, end, sum0, sum1, sum2) -> FORMAT_FN_3.apply(end, tuple3(sum0, sum1, sum2)));
// Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString3,
streamToString(sinkList.stream().map(String.class::cast), identity()));
}
@Test
public void aggregate3_withAggrOp3_withOutputFn() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
StreamStage<String> aggregated = fx.stage0.aggregate3(
fx.newStage(), fx.newStage(),
aggregateOperation3(SUMMING, SUMMING, SUMMING),
(start, end, sums) -> FORMAT_FN_3.apply(end, sums));
// Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString3,
streamToString(sinkList.stream().map(String.class::cast), identity()));
}
@Test
public void aggregateBuilder_withSeparateAggrOps() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
WindowAggregateBuilder<Long> b = fx.stage0.aggregateBuilder(SUMMING);
Tag<Long> tag0 = b.tag0();
Tag<Long> tag1 = b.add(fx.newStage(), SUMMING);
StreamStage<String> aggregated = b.build((start, end, sums) ->
FORMAT_FN_2.apply(end, tuple2(sums.get(tag0), sums.get(tag1))));
// Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString2,
streamToString(sinkList.stream().map(String.class::cast), identity()));
}
@Test
public void aggregateBuilder_withComplexAggrOp() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
WindowAggregateBuilder1<Integer> b = fx.stage0.aggregateBuilder();
Tag<Integer> tag0_in = b.tag0();
Tag<Integer> tag1_in = b.add(fx.newStage());
CoAggregateOperationBuilder b2 = coAggregateOperationBuilder();
Tag<Long> tag0 = b2.add(tag0_in, SUMMING);
Tag<Long> tag1 = b2.add(tag1_in, SUMMING);
StreamStage<String> aggregated = b.build(b2.build(),
(start, end, sums) -> FORMAT_FN_2.apply(end, tuple2(sums.get(tag0), sums.get(tag1))));
// Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString2,
streamToString(sinkList.stream().map(String.class::cast), identity())
);
}
}
| UTF-8 | Java | 21,529 | java | WindowAggregateTest.java | Java | [
{
"context": "/*\n * Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.\n *\n * Licensed",
"end": 32,
"score": 0.893385112285614,
"start": 31,
"tag": "NAME",
"value": "H"
}
] | null | [] | /*
* Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.
*
* 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.hazelcast.jet.pipeline;
import com.hazelcast.jet.accumulator.LongAccumulator;
import com.hazelcast.jet.aggregate.AggregateOperation1;
import com.hazelcast.jet.aggregate.CoAggregateOperationBuilder;
import com.hazelcast.jet.datamodel.Tag;
import com.hazelcast.jet.datamodel.TimestampedItem;
import com.hazelcast.jet.datamodel.Tuple2;
import com.hazelcast.jet.datamodel.Tuple3;
import com.hazelcast.jet.function.DistributedBiFunction;
import org.junit.Test;
import java.util.List;
import java.util.function.BiFunction;
import java.util.stream.IntStream;
import static com.hazelcast.jet.aggregate.AggregateOperations.aggregateOperation2;
import static com.hazelcast.jet.aggregate.AggregateOperations.aggregateOperation3;
import static com.hazelcast.jet.aggregate.AggregateOperations.coAggregateOperationBuilder;
import static com.hazelcast.jet.aggregate.AggregateOperations.counting;
import static com.hazelcast.jet.aggregate.AggregateOperations.summingLong;
import static com.hazelcast.jet.datamodel.Tuple2.tuple2;
import static com.hazelcast.jet.datamodel.Tuple3.tuple3;
import static com.hazelcast.jet.pipeline.WindowDefinition.session;
import static com.hazelcast.jet.pipeline.WindowDefinition.sliding;
import static com.hazelcast.jet.pipeline.WindowDefinition.tumbling;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertEquals;
public class WindowAggregateTest extends PipelineStreamTestSupport {
private static final DistributedBiFunction<Long, Tuple2<Long, Long>, String> FORMAT_FN_2 =
(timestamp, sums) -> String.format("(%04d: %04d, %04d)", timestamp, sums.f0(), sums.f1());
private static final DistributedBiFunction<Long, Tuple3<Long, Long, Long>, String> FORMAT_FN_3 =
(timestamp, sums) -> String.format("(%04d: %04d, %04d, %04d)",
timestamp, sums.f0(), sums.f1(), sums.f2());
private static final AggregateOperation1<Integer, LongAccumulator, Long> SUMMING = summingLong(i -> i);
@Test
public void when_setWindowDefinition_then_windowDefinitionReturnsIt() {
// Given
SlidingWindowDefinition tumbling = tumbling(2);
// When
StageWithWindow<Integer> stage = streamStageFromList(emptyList()).window(tumbling);
// Then
assertEquals(tumbling, stage.windowDefinition());
}
@Test
public void distinct() {
// Given
int winSize = itemCount / 2;
// timestamps: [0, 0, 1, 1, 2, 2, ...]
List<Integer> timestamps = IntStream.range(0, itemCount)
.flatMap(i -> IntStream.of(i, i))
.boxed()
.collect(toList());
StageWithWindow<Integer> windowed = streamStageFromList(timestamps)
.window(tumbling(winSize));
// When
StreamStage<TimestampedItem<Integer>> distinct = windowed.distinct();
// Then
distinct.drainTo(sink);
execute();
assertEquals(
streamToString(
IntStream.range(0, itemCount)
.mapToObj(i -> String.format("(%04d, %04d)", roundUp(i + 1, winSize), i))
.distinct(),
identity()),
streamToString(
this.<Integer>sinkStreamOfTsItem(),
tsItem -> String.format("(%04d, %04d)", tsItem.timestamp(), tsItem.item()))
);
}
@Test
public void tumblingWindow() {
// Given
int winSize = 4;
BiFunction<Long, Long, String> formatFn =
(timestamp, item) -> String.format("(%04d, %04d)", timestamp, item);
List<Integer> input = sequence(itemCount);
StreamStage<Integer> stage = streamStageFromList(input);
// When
SlidingWindowDefinition wDef = tumbling(winSize);
StageWithWindow<Integer> windowed = stage.window(wDef);
// Then
windowed.aggregate(summingLong(i -> i))
.drainTo(sink);
execute();
assertEquals(
new SlidingWindowSimulator(wDef)
.acceptStream(input.stream())
.stringResults(e -> formatFn.apply(e.getKey(), e.getValue())),
streamToString(this.<Long>sinkStreamOfTsItem(),
tsItem -> formatFn.apply(tsItem.timestamp(), tsItem.item()))
);
}
@Test
public void tumblingWindow_withEarlyResults() {
// Given
int winSize = 4;
BiFunction<Long, Long, String> formatFn =
(timestamp, item) -> String.format("(%04d, %04d)", timestamp, item);
List<Integer> input = sequence(itemCount);
StreamStage<Integer> stage = streamStageFromList(input, EARLY_RESULTS_PERIOD);
// When
SlidingWindowDefinition wDef = tumbling(winSize).setEarlyResultsPeriod(EARLY_RESULTS_PERIOD);
StageWithWindow<Integer> windowed = stage.window(wDef);
// Then
windowed.aggregate(summingLong(i -> i))
.drainTo(sink);
jet().newJob(p);
String expectedString = new SlidingWindowSimulator(wDef)
.acceptStream(input.stream())
.stringResults(e -> formatFn.apply(e.getKey(), e.getValue()));
assertTrueEventually(() -> assertEquals(
expectedString,
streamToString(this.<Long>sinkStreamOfTsItem(),
tsItem -> formatFn.apply(tsItem.timestamp(), tsItem.item()),
TimestampedItem::timestamp
)),
ASSERT_TIMEOUT_SECONDS);
}
@Test
public void slidingWindow() {
// Given
int winSize = 4;
int slideBy = 2;
List<Integer> input = sequence(itemCount);
BiFunction<Long, Long, String> formatFn =
(timestamp, item) -> String.format("(%04d, %04d)", timestamp, item);
// If emitting early results, keep the watermark behind all input
StreamStage<Integer> stage = streamStageFromList(input);
// When
SlidingWindowDefinition wDef = sliding(winSize, slideBy);
StreamStage<TimestampedItem<Long>> aggregated = stage.window(wDef)
.aggregate(summingLong(i -> i));
// Then
aggregated.drainTo(sink);
execute();
assertEquals(
new SlidingWindowSimulator(wDef)
.acceptStream(input.stream())
.stringResults(e -> formatFn.apply(e.getKey(), e.getValue())),
streamToString(this.<Long>sinkStreamOfTsItem(),
tsItem -> formatFn.apply(tsItem.timestamp(), tsItem.item()))
);
}
@Test
public void slidingWindow_withEarlyResults() {
// Given
int winSize = 4;
int slideBy = 2;
List<Integer> input = sequence(itemCount);
BiFunction<Long, Long, String> formatFn =
(timestamp, item) -> String.format("(%04d, %04d)", timestamp, item);
// If emitting early results, keep the watermark behind all input
StreamStage<Integer> stage = streamStageFromList(input, EARLY_RESULTS_PERIOD);
// When
SlidingWindowDefinition wDef = sliding(winSize, slideBy).setEarlyResultsPeriod(EARLY_RESULTS_PERIOD);
StreamStage<TimestampedItem<Long>> aggregated = stage.window(wDef)
.aggregate(summingLong(i -> i));
// Then
aggregated.drainTo(sink);
jet().newJob(p);
String expectedString = new SlidingWindowSimulator(wDef)
.acceptStream(input.stream())
.stringResults(e -> formatFn.apply(e.getKey(), e.getValue()));
assertTrueEventually(() -> assertEquals(
expectedString,
streamToString(this.<Long>sinkStreamOfTsItem(),
tsItem -> formatFn.apply(tsItem.timestamp(), tsItem.item()),
TimestampedItem::timestamp
)),
ASSERT_TIMEOUT_SECONDS);
}
@Test
public void sessionWindow() {
// Given
int sessionLength = 4;
int sessionTimeout = 2;
// Sample input: [0, 1, 2, 3, 6, 7, 8, 9, 12, 13, 14, 15, ...]
List<Integer> input = sequence(itemCount).stream()
.map(ts -> ts + (ts / sessionLength) * sessionTimeout)
.collect(toList());
BiFunction<Long, Long, String> formatFn = (timestamp, sum) -> String.format("(%04d, %04d)", timestamp, sum);
// When
SessionWindowDefinition wDef = session(sessionTimeout);
StageWithWindow<Integer> windowed = streamStageFromList(input).window(wDef);
// Then
windowed.aggregate(summingLong(i -> i),
(start, end, sum) -> new TimestampedItem<>(start, sum))
.drainTo(sink);
execute();
assertEquals(
new SessionWindowSimulator(wDef, sessionLength + sessionTimeout)
.acceptStream(input.stream())
.stringResults(e -> formatFn.apply(e.getKey(), e.getValue())),
streamToString(
this.<Long>sinkStreamOfTsItem(),
tsItem -> formatFn.apply(tsItem.timestamp(), tsItem.item()))
);
}
@Test
public void sessionWindow_withEarlyResults() {
// Given
int sessionLength = 4;
int sessionTimeout = 2;
// Sample input: [0, 1, 2, 3, 6, 7, 8, 9, 12, 13, 14, 15, ...]
List<Integer> input = sequence(itemCount).stream()
.map(ts -> ts + (ts / sessionLength) * sessionTimeout)
.collect(toList());
BiFunction<Long, Long, String> formatFn = (timestamp, sum) -> String.format("(%04d, %04d)", timestamp, sum);
// Keep the watermark behind all input
StreamStage<Integer> stage = streamStageFromList(input, EARLY_RESULTS_PERIOD);
// When
SessionWindowDefinition wDef = session(sessionTimeout).setEarlyResultsPeriod(EARLY_RESULTS_PERIOD);
StageWithWindow<Integer> windowed = stage.window(wDef);
// Then
windowed.aggregate(summingLong(i -> i),
// suppress incomplete windows to get predictable results
(start, end, sum) -> end - start != sessionLength + sessionTimeout - 1
? null
: new TimestampedItem<>(start, sum))
.drainTo(sink);
jet().newJob(p);
String expectedString = new SessionWindowSimulator(wDef, sessionLength + sessionTimeout)
.acceptStream(input.stream())
.stringResults(e -> formatFn.apply(e.getKey(), e.getValue()));
assertTrueEventually(() -> assertEquals(
expectedString,
streamToString(
this.<Long>sinkStreamOfTsItem(),
tsItem -> formatFn.apply(tsItem.timestamp(), tsItem.item()),
TimestampedItem::timestamp
)),
ASSERT_TIMEOUT_SECONDS);
}
@Test
public void when_tumblingWinWithEarlyResults_then_emitRepeatedly() {
assertEarlyResultsEmittedRepeatedly(tumbling(10));
}
@Test
public void when_sessionWinWithEarlyResults_then_emitRepeatedly() {
assertEarlyResultsEmittedRepeatedly(session(9));
}
private void assertEarlyResultsEmittedRepeatedly(WindowDefinition wDef) {
// Given
long earlyResultPeriod = 50;
StreamStage<Integer> srcStage = streamStageFromList(singletonList(1), earlyResultPeriod);
// When
StageWithWindow<Integer> stage = srcStage.window(wDef.setEarlyResultsPeriod(earlyResultPeriod));
// Then
stage.aggregate(counting()).drainTo(Sinks.list(sinkList));
jet().newJob(p);
assertTrueEventually(() -> assertGreaterOrEquals("sinkList.size()", sinkList.size(), 10));
TimestampedItem expected = new TimestampedItem<>(10L, 1L);
sinkList.forEach(it -> assertEquals(expected, it));
}
@Test
public void when_slidingWindow_outputFnReturnsNull_then_filteredOut() {
// Given
StreamStage<Integer> stage = streamStageFromList(sequence(itemCount));
// When
StreamStage<Object> aggregated = stage.window(sliding(2, 1))
.aggregate(counting(), (x, y, z) -> null);
// Then
aggregated.drainTo(sink);
jet().newJob(p);
assertTrueFiveSeconds(() -> assertEquals(0, sinkList.size()));
}
@Test
public void when_sessionWindow_outputFnReturnsNull_then_filteredOut() {
// Given
StreamStage<Integer> stage = streamStageFromList(sequence(itemCount));
// When
StreamStage<Object> aggregated = stage.window(session(1))
.aggregate(counting(), (x, y, z) -> null);
// Then
aggregated.drainTo(sink);
jet().newJob(p);
assertTrueFiveSeconds(() -> assertEquals(0, sinkList.size()));
}
private class CoAggregateFixture {
final SlidingWindowDefinition wDef = tumbling(4);
final List<Integer> input = sequence(itemCount);
final StageWithWindow<Integer> stage0 = newStage().window(wDef);
final String expectedString2 = new SlidingWindowSimulator(wDef)
.acceptStream(input.stream())
.stringResults(e -> FORMAT_FN_2.apply(e.getKey(), tuple2(e.getValue(), e.getValue())));
final String expectedString3 = new SlidingWindowSimulator(wDef)
.acceptStream(input.stream())
.stringResults(e -> FORMAT_FN_3.apply(e.getKey(), tuple3(e.getValue(), e.getValue(), e.getValue())));
StreamStage<Integer> newStage() {
return streamStageFromList(input);
}
}
@Test
public void aggregate2_withSeparateAggrOps() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
StreamStage<TimestampedItem<Tuple2<Long, Long>>> aggregated =
fx.stage0.aggregate2(SUMMING, fx.newStage(), SUMMING);
//Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString2,
streamToString(
this.<Tuple2<Long, Long>>sinkStreamOfTsItem(),
tsItem -> FORMAT_FN_2.apply(tsItem.timestamp(), tsItem.item())
));
}
@Test
public void aggregate2_withAggrOp2() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
StreamStage<TimestampedItem<Tuple2<Long, Long>>> aggregated =
fx.stage0.aggregate2(fx.newStage(), aggregateOperation2(SUMMING, SUMMING));
//Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString2,
streamToString(
this.<Tuple2<Long, Long>>sinkStreamOfTsItem(),
tsItem -> FORMAT_FN_2.apply(tsItem.timestamp(), tsItem.item())
));
}
@Test
public void aggregate2_withSeparateAggrOps_withOutputFn() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
StreamStage<String> aggregated = fx.stage0.aggregate2(SUMMING, fx.newStage(), SUMMING,
(start, end, sum0, sum1) -> FORMAT_FN_2.apply(end, tuple2(sum0, sum1)));
// Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString2,
streamToString(sinkList.stream().map(String.class::cast), identity()));
}
@Test
public void aggregate2_withAggrOp2_withOutputFn() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
StreamStage<String> aggregated = fx.stage0.aggregate2(
fx.newStage(),
aggregateOperation2(SUMMING, SUMMING),
(start, end, sums) -> FORMAT_FN_2.apply(end, sums));
// Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString2,
streamToString(sinkList.stream().map(String.class::cast), identity()));
}
@Test
public void aggregate3_withSeparateAggrOps() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
StreamStage<TimestampedItem<Tuple3<Long, Long, Long>>> aggregated =
fx.stage0.aggregate3(SUMMING, fx.newStage(), SUMMING, fx.newStage(), SUMMING);
// Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString3,
streamToString(this.<Tuple3<Long, Long, Long>>sinkStreamOfTsItem(),
tsItem -> FORMAT_FN_3.apply(tsItem.timestamp(), tsItem.item())
));
}
@Test
public void aggregate3_withAggrOp3() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
StreamStage<TimestampedItem<Tuple3<Long, Long, Long>>> aggregated =
fx.stage0.aggregate3(fx.newStage(), fx.newStage(),
aggregateOperation3(SUMMING, SUMMING, SUMMING));
//Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString3,
streamToString(this.<Tuple3<Long, Long, Long>>sinkStreamOfTsItem(),
tsItem -> FORMAT_FN_3.apply(tsItem.timestamp(), tsItem.item())
));
}
@Test
public void aggregate3_withSeparateAggrOps_withOutputFn() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
StreamStage<String> aggregated = fx.stage0.aggregate3(SUMMING,
fx.newStage(), SUMMING,
fx.newStage(), SUMMING,
(start, end, sum0, sum1, sum2) -> FORMAT_FN_3.apply(end, tuple3(sum0, sum1, sum2)));
// Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString3,
streamToString(sinkList.stream().map(String.class::cast), identity()));
}
@Test
public void aggregate3_withAggrOp3_withOutputFn() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
StreamStage<String> aggregated = fx.stage0.aggregate3(
fx.newStage(), fx.newStage(),
aggregateOperation3(SUMMING, SUMMING, SUMMING),
(start, end, sums) -> FORMAT_FN_3.apply(end, sums));
// Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString3,
streamToString(sinkList.stream().map(String.class::cast), identity()));
}
@Test
public void aggregateBuilder_withSeparateAggrOps() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
WindowAggregateBuilder<Long> b = fx.stage0.aggregateBuilder(SUMMING);
Tag<Long> tag0 = b.tag0();
Tag<Long> tag1 = b.add(fx.newStage(), SUMMING);
StreamStage<String> aggregated = b.build((start, end, sums) ->
FORMAT_FN_2.apply(end, tuple2(sums.get(tag0), sums.get(tag1))));
// Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString2,
streamToString(sinkList.stream().map(String.class::cast), identity()));
}
@Test
public void aggregateBuilder_withComplexAggrOp() {
// Given
CoAggregateFixture fx = new CoAggregateFixture();
// When
WindowAggregateBuilder1<Integer> b = fx.stage0.aggregateBuilder();
Tag<Integer> tag0_in = b.tag0();
Tag<Integer> tag1_in = b.add(fx.newStage());
CoAggregateOperationBuilder b2 = coAggregateOperationBuilder();
Tag<Long> tag0 = b2.add(tag0_in, SUMMING);
Tag<Long> tag1 = b2.add(tag1_in, SUMMING);
StreamStage<String> aggregated = b.build(b2.build(),
(start, end, sums) -> FORMAT_FN_2.apply(end, tuple2(sums.get(tag0), sums.get(tag1))));
// Then
aggregated.drainTo(sink);
execute();
assertEquals(fx.expectedString2,
streamToString(sinkList.stream().map(String.class::cast), identity())
);
}
}
| 21,529 | 0.593107 | 0.581495 | 552 | 38.001812 | 30.826389 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.822464 | false | false | 13 |
25efadf1ee9861b56976444e40a0b5a04bc184b3 | 29,635,274,408,948 | 2f33d22d4514ba8119d8702f9a58bffc9c3ce3ea | /java/bookStore/src/com/lastation/exercise/bookSrore/user/vo/UserValueObject.java | b4d65e171409a57fb438aad8f0d6f534cf375873 | [] | no_license | shuiqukeyou/CodeExercise | https://github.com/shuiqukeyou/CodeExercise | fedf8f8cac3ec5bcae13e9aaebb7d9a46eca649d | 6e2d836afd5e9a47f6b9854075679e0c16c7356f | refs/heads/master | 2021-01-21T17:33:17.418000 | 2020-04-16T17:12:02 | 2020-04-16T17:12:02 | 81,847,107 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lastation.exercise.bookSrore.user.vo;
import java.io.Serializable;
import com.lastation.exercise.bookSrore.common.UserEnum;
/**
*
* @author <a href="mailto:shuiqukeyou@gmail.com">ShuiQu</a>
* @version 2017年3月11日 下午1:01:39
* @fileName UserValueObject.java
*/
public class UserValueObject implements Serializable{
private static final long serialVersionUID = 1L;
private int uuid;
private String userName;
private String passWd;
private UserEnum type;
public UserValueObject(){
}
public UserValueObject(String username, String passWd, UserEnum type) {
this.userName = username;
this.passWd = passWd;
this.type = type;
}
public UserValueObject(int uuid, String username, String passWd, UserEnum type) {
this.uuid = uuid;
this.userName = username;
this.passWd = passWd;
this.type = type;
}
public int getUuid() {
return uuid;
}
public void setUuid(int uuid) {
this.uuid = uuid;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWd() {
return passWd;
}
public void setPassWd(String passWd) {
this.passWd = passWd;
}
public UserEnum getType() {
return type;
}
public void setType(UserEnum type) {
this.type = type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + uuid;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserValueObject other = (UserValueObject) obj;
if (uuid != other.uuid)
return false;
return true;
}
@Override
public String toString() {
return "id: " + uuid + " 用户名: " + userName + " 用户类型: " + type.getName();
}
public void update(UserValueObject user) {
this.userName = user.userName;
this.passWd = user.passWd;
this.type = user.type;
}
}
| UTF-8 | Java | 2,096 | java | UserValueObject.java | Java | [
{
"context": "UserEnum;\r\n\r\n/**\r\n * \r\n * @author <a href=\"mailto:shuiqukeyou@gmail.com\">ShuiQu</a>\r\n * @version 2017年3月11日 下午1:01:39\r\n *",
"end": 203,
"score": 0.9999274015426636,
"start": 182,
"tag": "EMAIL",
"value": "shuiqukeyou@gmail.com"
},
{
"context": " * @author ... | null | [] | package com.lastation.exercise.bookSrore.user.vo;
import java.io.Serializable;
import com.lastation.exercise.bookSrore.common.UserEnum;
/**
*
* @author <a href="mailto:<EMAIL>">ShuiQu</a>
* @version 2017年3月11日 下午1:01:39
* @fileName UserValueObject.java
*/
public class UserValueObject implements Serializable{
private static final long serialVersionUID = 1L;
private int uuid;
private String userName;
private String passWd;
private UserEnum type;
public UserValueObject(){
}
public UserValueObject(String username, String passWd, UserEnum type) {
this.userName = username;
this.passWd = passWd;
this.type = type;
}
public UserValueObject(int uuid, String username, String passWd, UserEnum type) {
this.uuid = uuid;
this.userName = username;
this.passWd = passWd;
this.type = type;
}
public int getUuid() {
return uuid;
}
public void setUuid(int uuid) {
this.uuid = uuid;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWd() {
return passWd;
}
public void setPassWd(String passWd) {
this.passWd = passWd;
}
public UserEnum getType() {
return type;
}
public void setType(UserEnum type) {
this.type = type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + uuid;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserValueObject other = (UserValueObject) obj;
if (uuid != other.uuid)
return false;
return true;
}
@Override
public String toString() {
return "id: " + uuid + " 用户名: " + userName + " 用户类型: " + type.getName();
}
public void update(UserValueObject user) {
this.userName = user.userName;
this.passWd = <PASSWORD>;
this.type = user.type;
}
}
| 2,081 | 0.653958 | 0.646236 | 99 | 18.929293 | 18.21158 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.59596 | false | false | 13 |
7dfbf7dab88dfd3143bf94b5204793c79bdb6d3c | 25,735,444,087,301 | 0dfdff0f5c746ca35f5395fed10af2912cbfec61 | /day1/EditLead.java | 3dc823dfc91dd9edb42db372c1d699a902a05390 | [] | no_license | gayathiriloganathan/SeleniumAssignments | https://github.com/gayathiriloganathan/SeleniumAssignments | dfa27502580e3777f056eb3ddf89f00ed92f14fd | 65a08e3689ab71e5c930e665458d96219b35e45d | refs/heads/main | 2023-04-12T19:59:21.682000 | 2021-05-01T08:10:33 | 2021-05-01T08:10:33 | 361,046,098 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Week2.day1;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class EditLead {
public static void main(String[] args) throws Exception {
String name = "Edit Lead";
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
driver.get("http://leaftaps.com/opentaps");
driver.manage().window().maximize();
driver.findElement(By.id("username")).sendKeys("DemoSalesManager");
driver.findElement(By.id("password")).sendKeys("crmsfa");
driver.findElement(By.className("decorativeSubmit")).click();
driver.findElement(By.linkText("CRM/SFA")).click();
driver.findElement(By.linkText("Leads")).click();
driver.findElement(By.xpath("//a[text()='Find Leads']")).click();
driver.findElement(By.xpath("(//input[@name='firstName'])[3]")).sendKeys("firstname");
driver.findElement(By.xpath("//button[text()='Find Leads']")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("//div[@class='x-grid3-cell-inner x-grid3-col-partyId']/a")).click();
String title = driver.getTitle();
if (title.contains("View Lead")) {
System.out.println("Title verification done");
} else {
System.out.println("Title verification is not done");
}
// Edit Lead
driver.findElement(By.xpath("//a[text()='Edit']")).click();
driver.findElement(By.xpath("//input[@id='updateLeadForm_companyName']")).clear();
driver.findElement(By.xpath("//input[@id='updateLeadForm_companyName']")).sendKeys(name);
driver.findElement(By.xpath("//input[@name='submitButton']")).click();
String updatedName = driver.findElement(By.xpath("//span[@id='viewLead_companyName_sp']")).getText();
System.out.println(updatedName);
if(updatedName.contains(name)) {
System.out.println("updated");
} else {
System.out.println("Not updated");
}
driver.close();
}
}
| UTF-8 | Java | 1,938 | java | EditLead.java | Java | [
{
"context": "a.selenium.chrome.ChromeDriver;\n\nimport io.github.bonigarcia.wdm.WebDriverManager;\n\npublic class EditLead {\n\n\t",
"end": 128,
"score": 0.9983645677566528,
"start": 118,
"tag": "USERNAME",
"value": "bonigarcia"
},
{
"context": "tring[] args) throws Exception {\n\t\... | null | [] | package Week2.day1;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class EditLead {
public static void main(String[] args) throws Exception {
String name = "<NAME>";
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
driver.get("http://leaftaps.com/opentaps");
driver.manage().window().maximize();
driver.findElement(By.id("username")).sendKeys("DemoSalesManager");
driver.findElement(By.id("password")).sendKeys("<PASSWORD>");
driver.findElement(By.className("decorativeSubmit")).click();
driver.findElement(By.linkText("CRM/SFA")).click();
driver.findElement(By.linkText("Leads")).click();
driver.findElement(By.xpath("//a[text()='Find Leads']")).click();
driver.findElement(By.xpath("(//input[@name='firstName'])[3]")).sendKeys("firstname");
driver.findElement(By.xpath("//button[text()='Find Leads']")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("//div[@class='x-grid3-cell-inner x-grid3-col-partyId']/a")).click();
String title = driver.getTitle();
if (title.contains("View Lead")) {
System.out.println("Title verification done");
} else {
System.out.println("Title verification is not done");
}
// Edit Lead
driver.findElement(By.xpath("//a[text()='Edit']")).click();
driver.findElement(By.xpath("//input[@id='updateLeadForm_companyName']")).clear();
driver.findElement(By.xpath("//input[@id='updateLeadForm_companyName']")).sendKeys(name);
driver.findElement(By.xpath("//input[@name='submitButton']")).click();
String updatedName = driver.findElement(By.xpath("//span[@id='viewLead_companyName_sp']")).getText();
System.out.println(updatedName);
if(updatedName.contains(name)) {
System.out.println("updated");
} else {
System.out.println("Not updated");
}
driver.close();
}
}
| 1,939 | 0.687823 | 0.683179 | 59 | 31.813559 | 29.719864 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.152542 | false | false | 13 |
3370ecd27dabd14a1449fd3f5a5e35e56bb29460 | 6,339,371,786,159 | 668cfe76acb791286e5274947fdf7270294b6f04 | /BinarySearch.java | 06fcb6d8f4ebcfb5461a051bdc07e3f19dc59c16 | [] | no_license | TheKnight/Java_examples | https://github.com/TheKnight/Java_examples | 54f8024339906c7fdd973479bfb91344f3d9e9d6 | d939b156f1708886fbf1a2deccec72b5a5f8d594 | refs/heads/master | 2016-05-26T19:43:34.226000 | 2013-02-21T21:35:02 | 2013-02-21T21:35:02 | 1,579,038 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Comparator;
/**
* Created by TheKnight
* Date: 21.02.13
* Time: 23:42
*
* @author TheKnight
* @version 0.1
*/
public class BinarySearch {
/**
* Simple binary search implementation
*
* @param array Array for search;
* @param key Key for search;
* @return Position key in array or -1 if key not found.
*/
public static int binarySearch(int[] array, int key) {
if (key > array[array.length - 1] || key < array[0])
return -1;
int from = 0;
int to = array.length - 1;
while (to >= from) {
int mid = from + (to - from) / 2;
int midVal = array[mid];
if (midVal == key) {
return mid;
}
if (midVal < key) {
from = mid + 1;
}
if (midVal > key) {
to = mid - 1;
}
}
return -1;
}
/**
* Binary search for object implements Comparable interface
*
* @param array Array for search;
* @param key Key for search;
* @return Position key in array or -1 if key not found.
*/
public static <T extends Comparable<T>> int binarySearch(T[] array, T key) {
if (key == null || array == null)
return -1;
if (key.compareTo(array[array.length - 1]) > 0 || key.compareTo(array[0]) < 0)
return -1;
int from = 0;
int to = array.length - 1;
while (to >= from) {
int mid = from + (to - from) / 2;
T midVal = array[mid];
int compare = midVal.compareTo(key);
if (compare == 0) {
return mid;
}
if (compare < 0) {
from = mid + 1;
}
if (compare > 0) {
to = mid - 1;
}
}
return -1;
}
/**
* Binary search with comparator for arbitrary object
*
* @param a Array for search;
* @param key Key for search;
* @param c Comparator for objects in array;
* @return Position key in array or -1 if key not found.
*/
public static <T extends Object> int binarySearch(T[] a, T key, Comparator<? super T> c) {
if (key == null || a == null || c == null)
return -1;
if (c.compare(key, a[a.length - 1]) > 0 || c.compare(key, a[0]) < 0)
return -1;
int from = 0;
int to = a.length - 1;
while (to >= from) {
int mid = from + (to - from) / 2;
T midVal = a[mid];
int compare = c.compare(midVal, key);
if (compare == 0) {
return mid;
}
if (compare < 0) {
from = mid + 1;
}
if (compare > 0) {
to = mid - 1;
}
}
return -1;
}
}
| UTF-8 | Java | 2,919 | java | BinarySearch.java | Java | [
{
"context": "import java.util.Comparator;\n\n/**\n * Created by TheKnight\n * Date: 21.02.13\n * Time: 23:42\n *\n * @author Th",
"end": 57,
"score": 0.9990291595458984,
"start": 48,
"tag": "USERNAME",
"value": "TheKnight"
},
{
"context": "ght\n * Date: 21.02.13\n * Time: 23:42\n *\... | null | [] | import java.util.Comparator;
/**
* Created by TheKnight
* Date: 21.02.13
* Time: 23:42
*
* @author TheKnight
* @version 0.1
*/
public class BinarySearch {
/**
* Simple binary search implementation
*
* @param array Array for search;
* @param key Key for search;
* @return Position key in array or -1 if key not found.
*/
public static int binarySearch(int[] array, int key) {
if (key > array[array.length - 1] || key < array[0])
return -1;
int from = 0;
int to = array.length - 1;
while (to >= from) {
int mid = from + (to - from) / 2;
int midVal = array[mid];
if (midVal == key) {
return mid;
}
if (midVal < key) {
from = mid + 1;
}
if (midVal > key) {
to = mid - 1;
}
}
return -1;
}
/**
* Binary search for object implements Comparable interface
*
* @param array Array for search;
* @param key Key for search;
* @return Position key in array or -1 if key not found.
*/
public static <T extends Comparable<T>> int binarySearch(T[] array, T key) {
if (key == null || array == null)
return -1;
if (key.compareTo(array[array.length - 1]) > 0 || key.compareTo(array[0]) < 0)
return -1;
int from = 0;
int to = array.length - 1;
while (to >= from) {
int mid = from + (to - from) / 2;
T midVal = array[mid];
int compare = midVal.compareTo(key);
if (compare == 0) {
return mid;
}
if (compare < 0) {
from = mid + 1;
}
if (compare > 0) {
to = mid - 1;
}
}
return -1;
}
/**
* Binary search with comparator for arbitrary object
*
* @param a Array for search;
* @param key Key for search;
* @param c Comparator for objects in array;
* @return Position key in array or -1 if key not found.
*/
public static <T extends Object> int binarySearch(T[] a, T key, Comparator<? super T> c) {
if (key == null || a == null || c == null)
return -1;
if (c.compare(key, a[a.length - 1]) > 0 || c.compare(key, a[0]) < 0)
return -1;
int from = 0;
int to = a.length - 1;
while (to >= from) {
int mid = from + (to - from) / 2;
T midVal = a[mid];
int compare = c.compare(midVal, key);
if (compare == 0) {
return mid;
}
if (compare < 0) {
from = mid + 1;
}
if (compare > 0) {
to = mid - 1;
}
}
return -1;
}
}
| 2,919 | 0.446043 | 0.427544 | 120 | 23.325001 | 20.399822 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.483333 | false | false | 13 |
d293333942de4a1629ece8b73383cc62a4cc030b | 36,438,502,576,545 | 89c8aa5f96dcb5f03f66b161446e2bf2afd632ee | /src/main/java/com/huotn/bootjsp/bootjsp/service/RoleService.java | c71305f7568a84349c7e0d4a212ab592d84d0d2c | [] | no_license | ChengyangLei/bootjsp | https://github.com/ChengyangLei/bootjsp | f19d197d65c46d86ef32f55c9b76e5a031922273 | 21d9d312ee3a7378b941afe5bf2d9d58bbbdad1d | refs/heads/master | 2022-11-06T07:06:25.860000 | 2022-02-10T06:33:49 | 2022-02-10T06:33:49 | 183,987,257 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.huotn.bootjsp.bootjsp.service;
import com.huotn.bootjsp.bootjsp.mapper.RoleMapper;
import com.huotn.bootjsp.bootjsp.pojo.Role;
import com.huotn.bootjsp.bootjsp.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @Description: RoleService
*
* @Auther: leichengyang
* @Date: 2019/4/29 0029
* @Version 1.0
*/
@Service
public class RoleService {
@Autowired
private RoleMapper roleMapper;
public List<Role> findAll() {
return roleMapper.findAll();
}
public int add(Role role) {
return roleMapper.add(role);
}
public int delRole(Role role) {
return roleMapper.delRole(role);
}
public Role getRoleById(String id) {
return roleMapper.getRoleById(id);
}
public int updateRole(Role role) {
return roleMapper.updateRole(role);
}
}
| UTF-8 | Java | 934 | java | RoleService.java | Java | [
{
"context": ";\n\n/**\n * @Description: RoleService\n *\n * @Auther: leichengyang\n * @Date: 2019/4/29 0029\n * @Version 1.0\n */\n@Ser",
"end": 379,
"score": 0.9994350671768188,
"start": 367,
"tag": "USERNAME",
"value": "leichengyang"
}
] | null | [] | package com.huotn.bootjsp.bootjsp.service;
import com.huotn.bootjsp.bootjsp.mapper.RoleMapper;
import com.huotn.bootjsp.bootjsp.pojo.Role;
import com.huotn.bootjsp.bootjsp.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @Description: RoleService
*
* @Auther: leichengyang
* @Date: 2019/4/29 0029
* @Version 1.0
*/
@Service
public class RoleService {
@Autowired
private RoleMapper roleMapper;
public List<Role> findAll() {
return roleMapper.findAll();
}
public int add(Role role) {
return roleMapper.add(role);
}
public int delRole(Role role) {
return roleMapper.delRole(role);
}
public Role getRoleById(String id) {
return roleMapper.getRoleById(id);
}
public int updateRole(Role role) {
return roleMapper.updateRole(role);
}
}
| 934 | 0.69379 | 0.679871 | 44 | 20.227272 | 18.48201 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.295455 | false | false | 13 |
560f47bbb4f2e7b52fd954b5328f90941f19c121 | 34,557,306,914,932 | 709e16d7b9ce6c1a2f3d3918f02f690e4a842eef | /src/com/company/Main.java | c5e639f75fa51915646e8fb476adfd665cb9aa6f | [] | no_license | bensonresseler/VoetbalUitslagen | https://github.com/bensonresseler/VoetbalUitslagen | f5f2b561c7e116af4fc4faced62bad0ae9d2f456 | aac04b0213a500c613d019dac693cc4ea7b9c325 | refs/heads/master | 2020-03-28T00:18:55.806000 | 2018-09-04T19:53:49 | 2018-09-04T19:53:49 | 147,395,727 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Ploeg> ploegen = maakPloegen();
ArrayList<Uitslag> kalender = maakKalender(ploegen);
for(Uitslag uitslag: kalender){
System.out.printf("Wedstrijd %s - %s%n", uitslag.getThuisploeg(), uitslag.getUitploeg());
System.out.printf("Geef doelpunten %s: ", uitslag.getThuisploeg());
int doelpuntenThuis = Integer.parseInt(scanner.nextLine());
System.out.printf("Geef doelpunten %s: ", uitslag.getUitploeg());
int doelpuntenUit = Integer.parseInt(scanner.nextLine());
uitslag.setDoelpuntenThuisploeg(doelpuntenThuis);
uitslag.setDoelpuntenUitploeg(doelpuntenUit);
}
toonKalender(kalender);
for(Uitslag uitslag: kalender){
for(Ploeg ploeg: ploegen){
ploeg.verwerkUitslag(uitslag);
}
}
//Collections.sort(ploegen);
toonPloegen(ploegen);
}
public static void toonPloegen(ArrayList<Ploeg> ploegen){
System.out.printf(" %-20s %9s %8s %4s %4s %4s %4s %4s %4s%n","Ploeg", "gespeeld", "punten", "W", "V", "G", "+", "-", "+/-");
for(int i=0; i< ploegen.size();i++){
System.out.printf("%2d %s%n", i+1, ploegen.get(i).getLijn());
}
}
private static ArrayList<Ploeg> maakPloegen(){
ArrayList<Ploeg> ploegen = new ArrayList<>();
ploegen.add(new Ploeg("RSC Anderlecht"));
ploegen.add(new Ploeg("K. RC. Genk"));
ploegen.add(new Ploeg("Club Brugge KV"));
ploegen.add(new Ploeg("R. Standard de Liège"));
return ploegen;
}
private static ArrayList<Uitslag> maakKalender(ArrayList<Ploeg> ploegen){
ArrayList<Uitslag> kalender = new ArrayList<>();
LocalDate speeldag = LocalDate.of(2018, 8, 17);
kalender.add(new Uitslag(speeldag, ploegen.get(0).getNaam(), ploegen.get(1).getNaam()));
kalender.add(new Uitslag(speeldag, ploegen.get(2).getNaam(), ploegen.get(3).getNaam()));
speeldag = speeldag.plusDays(7);
kalender.add(new Uitslag(speeldag, ploegen.get(0).getNaam(),ploegen.get(2).getNaam()));
kalender.add(new Uitslag(speeldag, ploegen.get(1).getNaam(),ploegen.get(3).getNaam()));
speeldag = speeldag.plusDays(7);
kalender.add(new Uitslag(speeldag, ploegen.get(0).getNaam(),ploegen.get(3).getNaam()));
kalender.add(new Uitslag(speeldag, ploegen.get(1).getNaam(),ploegen.get(2).getNaam()));
speeldag = speeldag.plusDays(7);
kalender.add(new Uitslag(speeldag, ploegen.get(1).getNaam(), ploegen.get(0).getNaam()));
kalender.add(new Uitslag(speeldag, ploegen.get(3).getNaam(), ploegen.get(2).getNaam()));
speeldag = speeldag.plusDays(7);
kalender.add(new Uitslag(speeldag, ploegen.get(2).getNaam(),ploegen.get(0).getNaam()));
kalender.add(new Uitslag(speeldag, ploegen.get(3).getNaam(),ploegen.get(1).getNaam()));
speeldag = speeldag.plusDays(7);
kalender.add(new Uitslag(speeldag, ploegen.get(3).getNaam(),ploegen.get(0).getNaam()));
kalender.add(new Uitslag(speeldag, ploegen.get(2).getNaam(),ploegen.get(1).getNaam()));
return kalender;
}
private static void toonKalender(ArrayList<Uitslag> kalender){
LocalDate datum = LocalDate.of(2000, 1, 1);
for(Uitslag uitslag : kalender){
if (!uitslag.getDatum().equals(datum))
{
datum = uitslag.getDatum();
System.out.println(datum);
}
System.out.println(uitslag.getLijn());
}
}
}
class Ploeg {
private String naam;
private String lijn;
public Ploeg(String naam) {
this.naam = naam;
}
public String getNaam() {
return naam;
}
public void verwerkUitslag(Uitslag uitslag) {
}
public String getLijn() {
return null;
}
}
class Uitslag {
private LocalDate speeldag;
private String thuisploeg;
private String uitploeg;
private int doelpuntenThuisploeg;
private int doelpuntenUitploeg;
public Uitslag(LocalDate speeldag, String thuisploeg, String uitploeg) {
this.speeldag = speeldag;
this.thuisploeg = thuisploeg;
this.uitploeg = uitploeg;
}
public LocalDate getSpeeldag() {
return speeldag;
}
public void setSpeeldag(LocalDate speeldag) {
this.speeldag = speeldag;
}
public String getThuisploeg() {
return thuisploeg;
}
public void setThuisploeg(String thuisploeg) {
this.thuisploeg = thuisploeg;
}
public String getUitploeg() {
return uitploeg;
}
public void setUitploeg(String uitploeg) {
this.uitploeg = uitploeg;
}
public void setDoelpuntenThuisploeg(int doelpuntenThuisploeg) {
this.doelpuntenThuisploeg = doelpuntenThuisploeg;
}
public void setDoelpuntenUitploeg(int doelpuntenUitploeg) {
this.doelpuntenUitploeg = doelpuntenUitploeg;
}
public String getLijn() {
return null;
}
public LocalDate getDatum() {
return null;
}
} | UTF-8 | Java | 5,407 | java | Main.java | Java | [
{
"context": " ArrayList<>();\n ploegen.add(new Ploeg(\"RSC Anderlecht\"));\n ploegen.add(new Ploeg(\"K. RC. Genk\"))",
"end": 1698,
"score": 0.8058705925941467,
"start": 1688,
"tag": "NAME",
"value": "Anderlecht"
},
{
"context": "RSC Anderlecht\"));\n ploegen.ad... | null | [] | package com.company;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Ploeg> ploegen = maakPloegen();
ArrayList<Uitslag> kalender = maakKalender(ploegen);
for(Uitslag uitslag: kalender){
System.out.printf("Wedstrijd %s - %s%n", uitslag.getThuisploeg(), uitslag.getUitploeg());
System.out.printf("Geef doelpunten %s: ", uitslag.getThuisploeg());
int doelpuntenThuis = Integer.parseInt(scanner.nextLine());
System.out.printf("Geef doelpunten %s: ", uitslag.getUitploeg());
int doelpuntenUit = Integer.parseInt(scanner.nextLine());
uitslag.setDoelpuntenThuisploeg(doelpuntenThuis);
uitslag.setDoelpuntenUitploeg(doelpuntenUit);
}
toonKalender(kalender);
for(Uitslag uitslag: kalender){
for(Ploeg ploeg: ploegen){
ploeg.verwerkUitslag(uitslag);
}
}
//Collections.sort(ploegen);
toonPloegen(ploegen);
}
public static void toonPloegen(ArrayList<Ploeg> ploegen){
System.out.printf(" %-20s %9s %8s %4s %4s %4s %4s %4s %4s%n","Ploeg", "gespeeld", "punten", "W", "V", "G", "+", "-", "+/-");
for(int i=0; i< ploegen.size();i++){
System.out.printf("%2d %s%n", i+1, ploegen.get(i).getLijn());
}
}
private static ArrayList<Ploeg> maakPloegen(){
ArrayList<Ploeg> ploegen = new ArrayList<>();
ploegen.add(new Ploeg("RSC Anderlecht"));
ploegen.add(new Ploeg("<NAME>"));
ploegen.add(new Ploeg("Club Brugge KV"));
ploegen.add(new Ploeg("R. Standard de Liège"));
return ploegen;
}
private static ArrayList<Uitslag> maakKalender(ArrayList<Ploeg> ploegen){
ArrayList<Uitslag> kalender = new ArrayList<>();
LocalDate speeldag = LocalDate.of(2018, 8, 17);
kalender.add(new Uitslag(speeldag, ploegen.get(0).getNaam(), ploegen.get(1).getNaam()));
kalender.add(new Uitslag(speeldag, ploegen.get(2).getNaam(), ploegen.get(3).getNaam()));
speeldag = speeldag.plusDays(7);
kalender.add(new Uitslag(speeldag, ploegen.get(0).getNaam(),ploegen.get(2).getNaam()));
kalender.add(new Uitslag(speeldag, ploegen.get(1).getNaam(),ploegen.get(3).getNaam()));
speeldag = speeldag.plusDays(7);
kalender.add(new Uitslag(speeldag, ploegen.get(0).getNaam(),ploegen.get(3).getNaam()));
kalender.add(new Uitslag(speeldag, ploegen.get(1).getNaam(),ploegen.get(2).getNaam()));
speeldag = speeldag.plusDays(7);
kalender.add(new Uitslag(speeldag, ploegen.get(1).getNaam(), ploegen.get(0).getNaam()));
kalender.add(new Uitslag(speeldag, ploegen.get(3).getNaam(), ploegen.get(2).getNaam()));
speeldag = speeldag.plusDays(7);
kalender.add(new Uitslag(speeldag, ploegen.get(2).getNaam(),ploegen.get(0).getNaam()));
kalender.add(new Uitslag(speeldag, ploegen.get(3).getNaam(),ploegen.get(1).getNaam()));
speeldag = speeldag.plusDays(7);
kalender.add(new Uitslag(speeldag, ploegen.get(3).getNaam(),ploegen.get(0).getNaam()));
kalender.add(new Uitslag(speeldag, ploegen.get(2).getNaam(),ploegen.get(1).getNaam()));
return kalender;
}
private static void toonKalender(ArrayList<Uitslag> kalender){
LocalDate datum = LocalDate.of(2000, 1, 1);
for(Uitslag uitslag : kalender){
if (!uitslag.getDatum().equals(datum))
{
datum = uitslag.getDatum();
System.out.println(datum);
}
System.out.println(uitslag.getLijn());
}
}
}
class Ploeg {
private String naam;
private String lijn;
public Ploeg(String naam) {
this.naam = naam;
}
public String getNaam() {
return naam;
}
public void verwerkUitslag(Uitslag uitslag) {
}
public String getLijn() {
return null;
}
}
class Uitslag {
private LocalDate speeldag;
private String thuisploeg;
private String uitploeg;
private int doelpuntenThuisploeg;
private int doelpuntenUitploeg;
public Uitslag(LocalDate speeldag, String thuisploeg, String uitploeg) {
this.speeldag = speeldag;
this.thuisploeg = thuisploeg;
this.uitploeg = uitploeg;
}
public LocalDate getSpeeldag() {
return speeldag;
}
public void setSpeeldag(LocalDate speeldag) {
this.speeldag = speeldag;
}
public String getThuisploeg() {
return thuisploeg;
}
public void setThuisploeg(String thuisploeg) {
this.thuisploeg = thuisploeg;
}
public String getUitploeg() {
return uitploeg;
}
public void setUitploeg(String uitploeg) {
this.uitploeg = uitploeg;
}
public void setDoelpuntenThuisploeg(int doelpuntenThuisploeg) {
this.doelpuntenThuisploeg = doelpuntenThuisploeg;
}
public void setDoelpuntenUitploeg(int doelpuntenUitploeg) {
this.doelpuntenUitploeg = doelpuntenUitploeg;
}
public String getLijn() {
return null;
}
public LocalDate getDatum() {
return null;
}
} | 5,402 | 0.627451 | 0.617277 | 160 | 32.793751 | 29.625179 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7625 | false | false | 13 |
ab483403c6e01d4f429a8cb9126e4ebf0c609bfb | 34,557,306,916,513 | a37366bb899b43eaa289d27626c3fefe9d2d534e | /online-bookstore-server/microservice-bookstore-book/src/main/java/com/onlinebookstore/BookServerApplication.java | 09f06e077ec00f502db26f3d9a0e72ca9fbe8626 | [
"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;
import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.client.RestTemplate;
/**
* @author rkc
* @date 2020/9/14 15:19
* @version 1.0
*/
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
@EnableTransactionManagement
public class BookServerApplication {
public static void main(String[] args) {
SpringApplication.run(BookServerApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectTimeout(5000);
httpRequestFactory.setReadTimeout(5000);
return new RestTemplate(httpRequestFactory);
}
@Bean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
}
}
| UTF-8 | Java | 1,474 | java | BookServerApplication.java | Java | [
{
"context": "framework.web.client.RestTemplate;\n\n/**\n * @author rkc\n * @date 2020/9/14 15:19\n * @version 1.0\n */\n@Ena",
"end": 709,
"score": 0.9996328353881836,
"start": 706,
"tag": "USERNAME",
"value": "rkc"
}
] | null | [] | package com.onlinebookstore;
import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.client.RestTemplate;
/**
* @author rkc
* @date 2020/9/14 15:19
* @version 1.0
*/
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
@EnableTransactionManagement
public class BookServerApplication {
public static void main(String[] args) {
SpringApplication.run(BookServerApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectTimeout(5000);
httpRequestFactory.setReadTimeout(5000);
return new RestTemplate(httpRequestFactory);
}
@Bean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
}
}
| 1,474 | 0.804613 | 0.790366 | 42 | 34.095238 | 28.426857 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 13 |
bbda0ad00369aacb9e7f7b71fe65c31c41248616 | 35,631,048,726,318 | ec6271f31635245028ad7459abcacc553c5b5c97 | /SpringBootSwagger/src/main/java/com/example/web/MemberController.java | 668d8b6ce6900a71bd0c16a45a35d31df686296f | [] | no_license | Heo-Won-Chul/SpringBootSample | https://github.com/Heo-Won-Chul/SpringBootSample | 085b42c7ebd51df2a053073a9f653de80c5dfeae | 4bf6ccde4408743876a1e6da7813c136c1b29c81 | refs/heads/main | 2021-01-11T11:22:19.844000 | 2021-01-11T04:59:50 | 2021-01-11T04:59:50 | 72,743,098 | 11 | 10 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.web;
import com.example.domain.Member;
import com.example.domain.MemberRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Api(value = "Member for API")
@RestController
@RequestMapping("/member")
public class MemberController {
@Autowired
private MemberRepository repository;
@ApiOperation(
value = "getId",
notes = "아이디 조회",
httpMethod = "GET",
// produces = "application/json",
consumes = "application/json",
protocols = "http",
responseHeaders = {
// Headers ...
})
@ApiResponses({
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "No param")
// Other Http Status Code ...
})
@GetMapping("/{id}")
public Member getId(@PathVariable("id") String id) {
return repository.findById(id).orElse(null);
}
@PostMapping
public Member createMember(@RequestBody Member member) {
return repository.save(member);
}
@PutMapping
public Member updateMember(@RequestBody Member member) {
return repository.save(member);
}
@DeleteMapping("/{id}")
public String deleteById(@PathVariable("id") String id) {
try {
repository.deleteById(id);
return "success";
} catch (Exception e) {
return "fail";
}
}
}
| UTF-8 | Java | 1,465 | java | MemberController.java | Java | [] | null | [] | package com.example.web;
import com.example.domain.Member;
import com.example.domain.MemberRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Api(value = "Member for API")
@RestController
@RequestMapping("/member")
public class MemberController {
@Autowired
private MemberRepository repository;
@ApiOperation(
value = "getId",
notes = "아이디 조회",
httpMethod = "GET",
// produces = "application/json",
consumes = "application/json",
protocols = "http",
responseHeaders = {
// Headers ...
})
@ApiResponses({
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "No param")
// Other Http Status Code ...
})
@GetMapping("/{id}")
public Member getId(@PathVariable("id") String id) {
return repository.findById(id).orElse(null);
}
@PostMapping
public Member createMember(@RequestBody Member member) {
return repository.save(member);
}
@PutMapping
public Member updateMember(@RequestBody Member member) {
return repository.save(member);
}
@DeleteMapping("/{id}")
public String deleteById(@PathVariable("id") String id) {
try {
repository.deleteById(id);
return "success";
} catch (Exception e) {
return "fail";
}
}
}
| 1,465 | 0.714089 | 0.709966 | 59 | 23.661016 | 17.891964 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.711864 | false | false | 13 |
901aee5a470e15b56ba422cf6aa2a2b46a30d7a9 | 28,449,863,420,993 | b181f4edf1b951e52c74e0b198b2965bb45691fd | /src/main/java/com/zxc74171/thaumicpotatoes/entities/EntityAmmoBaked.java | e1e598e203546cbc17b8c69bd5a51423e121a787 | [
"WTFPL"
] | permissive | limuness/ThaumicPotatoes2 | https://github.com/limuness/ThaumicPotatoes2 | 52da835c210f041677e3fac68647b87288029059 | 523714447a91194a9294fefb7316c7d851211cce | refs/heads/master | 2021-01-02T08:54:02.550000 | 2017-08-01T14:25:05 | 2017-08-01T14:25:05 | 99,091,460 | 0 | 0 | null | true | 2017-08-02T08:23:09 | 2017-08-02T08:23:09 | 2017-07-08T14:36:57 | 2017-08-01T14:25:05 | 9,966 | 0 | 0 | 0 | null | null | null | package com.zxc74171.thaumicpotatoes.entities;
import com.zxc74171.thaumicpotatoes.potatolauncher.Ammos;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.Item;
import net.minecraft.world.World;
public class EntityAmmoBaked extends EntityAmmo{
public static Item renderSnowball;
public EntityAmmoBaked(World worldIn) {
super(worldIn);
this.bolt = Ammos.BAKED;
}
public EntityAmmoBaked(World worldIn, double x, double y, double z)
{
super(worldIn, x, y, z);
this.bolt = Ammos.BAKED;
}
public EntityAmmoBaked(World worldIn, EntityLivingBase shooter, Ammos bolt){
super(worldIn, shooter, bolt);
this.bolt = Ammos.BAKED;
}
}
| UTF-8 | Java | 680 | java | EntityAmmoBaked.java | Java | [
{
"context": "package com.zxc74171.thaumicpotatoes.entities;\n\n\nimport com.zxc74171.t",
"end": 20,
"score": 0.9638349413871765,
"start": 13,
"tag": "USERNAME",
"value": "xc74171"
},
{
"context": ".zxc74171.thaumicpotatoes.entities;\n\n\nimport com.zxc74171.thaumicpotatoes.potatolau... | null | [] | package com.zxc74171.thaumicpotatoes.entities;
import com.zxc74171.thaumicpotatoes.potatolauncher.Ammos;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.Item;
import net.minecraft.world.World;
public class EntityAmmoBaked extends EntityAmmo{
public static Item renderSnowball;
public EntityAmmoBaked(World worldIn) {
super(worldIn);
this.bolt = Ammos.BAKED;
}
public EntityAmmoBaked(World worldIn, double x, double y, double z)
{
super(worldIn, x, y, z);
this.bolt = Ammos.BAKED;
}
public EntityAmmoBaked(World worldIn, EntityLivingBase shooter, Ammos bolt){
super(worldIn, shooter, bolt);
this.bolt = Ammos.BAKED;
}
}
| 680 | 0.757353 | 0.742647 | 29 | 22.448277 | 22.648111 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.482759 | false | false | 13 |
5a6f15fefde59b488132ab07d97e760a7302d0fe | 34,720,515,672,168 | e4763d6f76c59e31a73121db83c3ba222606f6af | /base-front/src/main/java/com/infosky/common/query/jdbc/ImprovedNamingStrategy.java | e189e4882c789fbd0dc2a7f9d16f6df1472aca2d | [] | no_license | zql3315/test1 | https://github.com/zql3315/test1 | 5828e10e0cdd2c1a0666f7dbfa70bd88a0fec000 | 2b12c0a1ba03dca0cb5e8270f4401854a97a343c | refs/heads/master | 2021-01-21T17:59:59.254000 | 2017-09-30T09:42:26 | 2017-09-30T09:42:26 | 92,006,280 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.infosky.common.query.jdbc;
/**
* <一句话功能简述>
* <功能详细描述>
*
* @author zan
* @version [版本号, 2015年2月10日]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class ImprovedNamingStrategy {
public String columnToProperty(String column) {
String[] array = column.split("_");
StringBuffer buff = new StringBuffer();
buff.append(array[0].toLowerCase());
for (int i = 1; i < array.length; i++) {
buff.append(array[i].substring(0, 1) + array[i].substring(1).toLowerCase());
}
return buff.toString();
}
}
| UTF-8 | Java | 666 | java | ImprovedNamingStrategy.java | Java | [
{
"context": "\r\n/**\r\n * <一句话功能简述>\r\n * <功能详细描述>\r\n * \r\n * @author zan\r\n * @version [版本号, 2015年2月10日]\r\n * @see [相关类/",
"end": 92,
"score": 0.7812718749046326,
"start": 91,
"tag": "NAME",
"value": "z"
},
{
"context": "/**\r\n * <一句话功能简述>\r\n * <功能详细描述>\r\n * \r\n * @auth... | null | [] | package com.infosky.common.query.jdbc;
/**
* <一句话功能简述>
* <功能详细描述>
*
* @author zan
* @version [版本号, 2015年2月10日]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class ImprovedNamingStrategy {
public String columnToProperty(String column) {
String[] array = column.split("_");
StringBuffer buff = new StringBuffer();
buff.append(array[0].toLowerCase());
for (int i = 1; i < array.length; i++) {
buff.append(array[i].substring(0, 1) + array[i].substring(1).toLowerCase());
}
return buff.toString();
}
}
| 666 | 0.559406 | 0.539604 | 25 | 22.24 | 22.149096 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 13 |
3016a6a12a2b14d095baa6e7c791c62f8611ea1d | 35,175,782,205,032 | f71f0861513b6379dc10bcb81191847a54789b51 | /src/shape/Text.java | d70d70053119e092cc9152c65846e63c0612f362 | [] | no_license | sonnguyenhong/BK-PAINT | https://github.com/sonnguyenhong/BK-PAINT | 6df519fe1605a8088f112ad71c30d48f146c9da2 | 985a7be3d5c2aa3d4e1c98f706bed2f6f1d538be | refs/heads/master | 2023-04-21T04:29:33.097000 | 2021-05-31T14:11:31 | 2021-05-31T14:11:31 | 366,895,611 | 0 | 1 | null | false | 2021-05-29T08:04:42 | 2021-05-13T01:07:15 | 2021-05-29T01:39:27 | 2021-05-29T08:04:42 | 6,762 | 0 | 0 | 1 | Java | false | false | /*
* 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 shape;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import property.TextPanel;
/**
*
* @author KA
*/
public class Text extends Shape implements DrawType{
private boolean isOpaque;
private TextPanel textPanel = new TextPanel();
private Color fillColor = Color.WHITE;
BasicStroke STROKE_1 = new BasicStroke(1f);
BasicStroke STROKE_2 = new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 1.0f, new float[]{2f, 0f, 2f}, 2f);
private Color color;
private Color textColor;
private static final int EDGE_SQUARE = 4;
private String string = "";
private JTextPane area;
private Point start;
private Point end;
private boolean isCreated = false;
private Font font;
public Text() {
this.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_ROUND, 1.0f, new float[]{2f, 0f, 2f}, 2f));
this.setTextColor(Color.BLACK);
this.setColor(Color.BLUE);
}
public void setFillColor(Color fillColor){
this.fillColor = fillColor;
}
public Color getFillColor(){
return this.fillColor;
}
public void setTextColor(Color textColor) {
this.textColor = textColor;
}
public Color getTextColor() {
return this.textColor;
}
public void setColor(Color color) {
this.color = color;
}
public Color getColor() {
return this.color;
}
public void setString(String string) {
this.string = string;
}
public void setArea(JPanel panel) {
area = new JTextPane();
int[] a = {Math.min(start.x, end.x), Math.min(start.y, end.y), Math.max(start.x, end.x), Math.max(start.y, end.y)};
area.setBounds(a[0] + 1, a[1] + 1, a[2] - a[0] - 1, a[3] - a[1] - 1);
panel.add(area);
}
public void removeArea(JPanel panel) {
panel.remove(area);
}
public void setIsCreated(boolean isCreated) {
this.isCreated = isCreated;
}
public boolean getIsCreated() {
return this.isCreated;
}
public void setString() {
this.string = area.getText();
}
public String getString() {
return string;
}
public boolean equals(String s) {
return string.equals(s) == true;
}
public void setStart(Point start) {
this.start = start;
}
public void setEnd(Point end) {
this.end = end;
}
public JTextPane getArea() {
return area;
}
@Override
public Point getStart() {
return start;
}
public Point getEnd() {
return end;
}
public void setFontArea() {
area.setFont(this.font);
}
public Font getFontArea() {
return this.font;
}
public void setIsOpaque(boolean isOpaque) {
this.isOpaque = isOpaque;
}
public boolean getIsOpaque() {
return this.isOpaque;
}
public void setFont(Font font) {
this.font = font;
}
public Font getFont() {
return this.font;
}
public boolean checkOverlap() {
return start.x == end.x || start.y == end.y;
}
public void draw(Graphics2D g2, Graphics g2d) {
int[] a = {Math.min(start.x, end.x), Math.min(start.y, end.y), Math.max(start.x, end.x), Math.max(start.y, end.y)};
if (isCreated == false) {
BasicStroke stroke = new BasicStroke(strokeThickness,endStrokeCap,lineStrokeJoin,dashPhase,
dashArray,miterLimit);
g2.setStroke(stroke);
if (start != null && end != null) {
g2.setColor(color);
//draw rect...
g2.setStroke(STROKE_1);
g2.drawRect(a[0] - EDGE_SQUARE / 2, a[1] - EDGE_SQUARE / 2, EDGE_SQUARE, EDGE_SQUARE);
g2.drawRect(a[2] - EDGE_SQUARE / 2, a[1] - EDGE_SQUARE / 2, EDGE_SQUARE, EDGE_SQUARE);
g2.drawRect(a[2] - EDGE_SQUARE / 2, a[3] - EDGE_SQUARE / 2, EDGE_SQUARE, EDGE_SQUARE);
g2.drawRect(a[0] - EDGE_SQUARE / 2, a[3] - EDGE_SQUARE / 2, EDGE_SQUARE, EDGE_SQUARE);
g2.drawRect((a[0] + a[2]) / 2 - EDGE_SQUARE / 2, a[1] - EDGE_SQUARE / 2, EDGE_SQUARE, EDGE_SQUARE);
g2.drawRect(a[2] - EDGE_SQUARE / 2, (a[1] + a[3]) / 2 - EDGE_SQUARE / 2, EDGE_SQUARE, EDGE_SQUARE);
g2.drawRect((a[0] + a[2]) / 2 - EDGE_SQUARE / 2, a[3] - EDGE_SQUARE / 2, EDGE_SQUARE, EDGE_SQUARE);
g2.drawRect(a[0] - EDGE_SQUARE / 2, (a[1] + a[3]) / 2 - EDGE_SQUARE / 2, EDGE_SQUARE, EDGE_SQUARE);
g2.setStroke(STROKE_2);
g2.drawLine(a[0] + EDGE_SQUARE / 2, a[1], (a[0] + a[2]) / 2 - EDGE_SQUARE / 2, a[1]);
g2.drawLine((a[0] + a[2]) / 2 + EDGE_SQUARE / 2, a[1], a[2] - EDGE_SQUARE / 2, a[1]);
g2.drawLine(a[2], a[1] + EDGE_SQUARE / 2, a[2], (a[1] + a[3]) / 2 - EDGE_SQUARE / 2);
g2.drawLine(a[2], (a[1] + a[3]) / 2 + EDGE_SQUARE / 2, a[2], a[3] - EDGE_SQUARE / 2);
g2.drawLine(a[2] - EDGE_SQUARE / 2, a[3], (a[0] + a[2]) / 2 + EDGE_SQUARE / 2, a[3]);
g2.drawLine((a[0] + a[2]) / 2 - EDGE_SQUARE / 2, a[3], a[0] + EDGE_SQUARE / 2, a[3]);
g2.drawLine(a[0], a[3] - EDGE_SQUARE / 2, a[0], (a[1] + a[3]) / 2 + EDGE_SQUARE / 2);
g2.drawLine(a[0], (a[1] + a[3]) / 2 - EDGE_SQUARE / 2, a[0], a[1] + EDGE_SQUARE / 2);
}
}
if (string.equals("") == false) {
if (isOpaque) {
g2d.setFont(font);
g2d.setColor(fillColor);
g2d.fillRect(a[0], a[1], a[2] - a[0], a[3] - a[1]);
g2d.setColor(textColor);
for (String line : string.split("\n")) {
g2d.drawString(line, start.x, start.y += g2d.getFontMetrics().getHeight());
}
} else {
g2d.setFont(font);
g2d.setColor(textColor);
for (String line : string.split("\n")) {
g2d.drawString(line, a[0], a[1] += g2d.getFontMetrics().getHeight());
}
}
}
}
@Override
public void draw(Graphics2D g2d) {
}
}
| UTF-8 | Java | 6,593 | java | Text.java | Java | [
{
"context": "Pane;\nimport property.TextPanel;\n/**\n *\n * @author KA\n */\npublic class Text extends Shape implements Dra",
"end": 456,
"score": 0.8194801211357117,
"start": 454,
"tag": "USERNAME",
"value": "KA"
}
] | 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 shape;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import property.TextPanel;
/**
*
* @author KA
*/
public class Text extends Shape implements DrawType{
private boolean isOpaque;
private TextPanel textPanel = new TextPanel();
private Color fillColor = Color.WHITE;
BasicStroke STROKE_1 = new BasicStroke(1f);
BasicStroke STROKE_2 = new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 1.0f, new float[]{2f, 0f, 2f}, 2f);
private Color color;
private Color textColor;
private static final int EDGE_SQUARE = 4;
private String string = "";
private JTextPane area;
private Point start;
private Point end;
private boolean isCreated = false;
private Font font;
public Text() {
this.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_ROUND, 1.0f, new float[]{2f, 0f, 2f}, 2f));
this.setTextColor(Color.BLACK);
this.setColor(Color.BLUE);
}
public void setFillColor(Color fillColor){
this.fillColor = fillColor;
}
public Color getFillColor(){
return this.fillColor;
}
public void setTextColor(Color textColor) {
this.textColor = textColor;
}
public Color getTextColor() {
return this.textColor;
}
public void setColor(Color color) {
this.color = color;
}
public Color getColor() {
return this.color;
}
public void setString(String string) {
this.string = string;
}
public void setArea(JPanel panel) {
area = new JTextPane();
int[] a = {Math.min(start.x, end.x), Math.min(start.y, end.y), Math.max(start.x, end.x), Math.max(start.y, end.y)};
area.setBounds(a[0] + 1, a[1] + 1, a[2] - a[0] - 1, a[3] - a[1] - 1);
panel.add(area);
}
public void removeArea(JPanel panel) {
panel.remove(area);
}
public void setIsCreated(boolean isCreated) {
this.isCreated = isCreated;
}
public boolean getIsCreated() {
return this.isCreated;
}
public void setString() {
this.string = area.getText();
}
public String getString() {
return string;
}
public boolean equals(String s) {
return string.equals(s) == true;
}
public void setStart(Point start) {
this.start = start;
}
public void setEnd(Point end) {
this.end = end;
}
public JTextPane getArea() {
return area;
}
@Override
public Point getStart() {
return start;
}
public Point getEnd() {
return end;
}
public void setFontArea() {
area.setFont(this.font);
}
public Font getFontArea() {
return this.font;
}
public void setIsOpaque(boolean isOpaque) {
this.isOpaque = isOpaque;
}
public boolean getIsOpaque() {
return this.isOpaque;
}
public void setFont(Font font) {
this.font = font;
}
public Font getFont() {
return this.font;
}
public boolean checkOverlap() {
return start.x == end.x || start.y == end.y;
}
public void draw(Graphics2D g2, Graphics g2d) {
int[] a = {Math.min(start.x, end.x), Math.min(start.y, end.y), Math.max(start.x, end.x), Math.max(start.y, end.y)};
if (isCreated == false) {
BasicStroke stroke = new BasicStroke(strokeThickness,endStrokeCap,lineStrokeJoin,dashPhase,
dashArray,miterLimit);
g2.setStroke(stroke);
if (start != null && end != null) {
g2.setColor(color);
//draw rect...
g2.setStroke(STROKE_1);
g2.drawRect(a[0] - EDGE_SQUARE / 2, a[1] - EDGE_SQUARE / 2, EDGE_SQUARE, EDGE_SQUARE);
g2.drawRect(a[2] - EDGE_SQUARE / 2, a[1] - EDGE_SQUARE / 2, EDGE_SQUARE, EDGE_SQUARE);
g2.drawRect(a[2] - EDGE_SQUARE / 2, a[3] - EDGE_SQUARE / 2, EDGE_SQUARE, EDGE_SQUARE);
g2.drawRect(a[0] - EDGE_SQUARE / 2, a[3] - EDGE_SQUARE / 2, EDGE_SQUARE, EDGE_SQUARE);
g2.drawRect((a[0] + a[2]) / 2 - EDGE_SQUARE / 2, a[1] - EDGE_SQUARE / 2, EDGE_SQUARE, EDGE_SQUARE);
g2.drawRect(a[2] - EDGE_SQUARE / 2, (a[1] + a[3]) / 2 - EDGE_SQUARE / 2, EDGE_SQUARE, EDGE_SQUARE);
g2.drawRect((a[0] + a[2]) / 2 - EDGE_SQUARE / 2, a[3] - EDGE_SQUARE / 2, EDGE_SQUARE, EDGE_SQUARE);
g2.drawRect(a[0] - EDGE_SQUARE / 2, (a[1] + a[3]) / 2 - EDGE_SQUARE / 2, EDGE_SQUARE, EDGE_SQUARE);
g2.setStroke(STROKE_2);
g2.drawLine(a[0] + EDGE_SQUARE / 2, a[1], (a[0] + a[2]) / 2 - EDGE_SQUARE / 2, a[1]);
g2.drawLine((a[0] + a[2]) / 2 + EDGE_SQUARE / 2, a[1], a[2] - EDGE_SQUARE / 2, a[1]);
g2.drawLine(a[2], a[1] + EDGE_SQUARE / 2, a[2], (a[1] + a[3]) / 2 - EDGE_SQUARE / 2);
g2.drawLine(a[2], (a[1] + a[3]) / 2 + EDGE_SQUARE / 2, a[2], a[3] - EDGE_SQUARE / 2);
g2.drawLine(a[2] - EDGE_SQUARE / 2, a[3], (a[0] + a[2]) / 2 + EDGE_SQUARE / 2, a[3]);
g2.drawLine((a[0] + a[2]) / 2 - EDGE_SQUARE / 2, a[3], a[0] + EDGE_SQUARE / 2, a[3]);
g2.drawLine(a[0], a[3] - EDGE_SQUARE / 2, a[0], (a[1] + a[3]) / 2 + EDGE_SQUARE / 2);
g2.drawLine(a[0], (a[1] + a[3]) / 2 - EDGE_SQUARE / 2, a[0], a[1] + EDGE_SQUARE / 2);
}
}
if (string.equals("") == false) {
if (isOpaque) {
g2d.setFont(font);
g2d.setColor(fillColor);
g2d.fillRect(a[0], a[1], a[2] - a[0], a[3] - a[1]);
g2d.setColor(textColor);
for (String line : string.split("\n")) {
g2d.drawString(line, start.x, start.y += g2d.getFontMetrics().getHeight());
}
} else {
g2d.setFont(font);
g2d.setColor(textColor);
for (String line : string.split("\n")) {
g2d.drawString(line, a[0], a[1] += g2d.getFontMetrics().getHeight());
}
}
}
}
@Override
public void draw(Graphics2D g2d) {
}
}
| 6,593 | 0.546792 | 0.519794 | 210 | 30.385714 | 31.374979 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.871429 | false | false | 13 |
15df1abbf93c0286f8ef1bf5395da80d095c7bd6 | 39,178,691,684,120 | f0bbd977b9f17b67040ba9d49a06b783d52f9a12 | /KokoFarm_project/src/kokofarm/Inquiry/action/InsertInquiryReplyAction.java | aeb2ad5e01f5ba5bc79ae94ccdbdc7cff2ccf21b | [] | no_license | youngran90/KokoFarm_Project | https://github.com/youngran90/KokoFarm_Project | db381e1b6d300c4fca9fbfb5cdfdf003b49e7dae | 7ba1fb24b9f7cc69855a74faf497022332a96c51 | refs/heads/master | 2021-01-20T00:48:27.916000 | 2017-05-10T01:06:52 | 2017-05-10T01:06:52 | 89,193,999 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kokofarm.Inquiry.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kokofarm.Inquiry.domain.InquiryDTO;
import kokofarm.Inquiry.service.InquiryService;
public class InsertInquiryReplyAction implements Action {
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("question*********ReplyAction");
InquiryService service = InquiryService.getInstance();
InquiryDTO Inquiry = new InquiryDTO();
Inquiry.setInquiry_no(request.getParameter("inquiry_no"));
Inquiry.setInquiry_reply(request.getParameter("inquiry_reply"));
System.out.println("inquiry_no :" +request.getParameter("inquiry_no"));
System.out.println("inquiry_reply:" +request.getParameter("inquiry_reply"));
service.insertInquiryReplySerivce(Inquiry);
ActionForward forward = new ActionForward();
forward.setPath("ListInquiryAction.Inquiry");
forward.setRedirect(false);
return forward;
}
}
| UTF-8 | Java | 1,069 | java | InsertInquiryReplyAction.java | Java | [] | null | [] | package kokofarm.Inquiry.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kokofarm.Inquiry.domain.InquiryDTO;
import kokofarm.Inquiry.service.InquiryService;
public class InsertInquiryReplyAction implements Action {
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("question*********ReplyAction");
InquiryService service = InquiryService.getInstance();
InquiryDTO Inquiry = new InquiryDTO();
Inquiry.setInquiry_no(request.getParameter("inquiry_no"));
Inquiry.setInquiry_reply(request.getParameter("inquiry_reply"));
System.out.println("inquiry_no :" +request.getParameter("inquiry_no"));
System.out.println("inquiry_reply:" +request.getParameter("inquiry_reply"));
service.insertInquiryReplySerivce(Inquiry);
ActionForward forward = new ActionForward();
forward.setPath("ListInquiryAction.Inquiry");
forward.setRedirect(false);
return forward;
}
}
| 1,069 | 0.759588 | 0.759588 | 32 | 31.40625 | 28.816076 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.625 | false | false | 13 |
5a5210d93ccf02032109f01cfbef737734d0ee13 | 37,194,416,790,384 | 9dab96f623bbc8fa143f05b6910100a8d4e1d568 | /paradigms-hw/java-solutions/main/expression/Const.java | 73bfb52aeb6f1293e0d927813faa292a298df53a | [] | no_license | fellowweeb/itmo | https://github.com/fellowweeb/itmo | d96af0434960e3cf566136be9ad769065ccda455 | 1713303351a233f2d5ce7ee5e1e2517da186b698 | refs/heads/main | 2023-04-07T20:42:47.019000 | 2021-04-11T21:16:18 | 2021-04-11T21:16:18 | 356,978,487 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package expression;
import expression.number.Number;
public class Const<T extends Number<T>> implements CommonExpression<T> {
private final T value;
public Const(T value) {
this.value = value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@Override
public T evaluate(T x, T y, T z) {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Const<?> aConst = (Const<?>) o;
return value == aConst.value;
}
@Override
public int hashCode() {
return value.toString().hashCode();
}
@Override
public int priority() {
return -1;
}
@Override
public boolean isOrdered() {
return false;
}
}
| UTF-8 | Java | 869 | java | Const.java | Java | [] | null | [] | package expression;
import expression.number.Number;
public class Const<T extends Number<T>> implements CommonExpression<T> {
private final T value;
public Const(T value) {
this.value = value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@Override
public T evaluate(T x, T y, T z) {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Const<?> aConst = (Const<?>) o;
return value == aConst.value;
}
@Override
public int hashCode() {
return value.toString().hashCode();
}
@Override
public int priority() {
return -1;
}
@Override
public boolean isOrdered() {
return false;
}
}
| 869 | 0.56847 | 0.567319 | 44 | 18.75 | 17.525469 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.386364 | false | false | 13 |
c653c516103aab31bb355526c2135ff1dd2e2eac | 21,466,246,588,854 | c4b973aff7b4d26cac70342251d404524e917e60 | /model/src/main/java/it.ozimov.seldon/model/transformer/LongIntDataEntryToLongLongDataEntry.java | a14fe5c98c0b0ca81dd23efcca518290d7e1e08b | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | ozimov/seldon | https://github.com/ozimov/seldon | 55509a8f1403bcba60fc1846a6b8c136150d57f7 | aa290f51749085876bb4f6643f1be988eb790ced | refs/heads/master | 2023-08-26T17:33:14.807000 | 2016-01-11T21:56:37 | 2016-01-17T22:27:17 | 48,643,381 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.ozimov.seldon.model.transformer;
import static java.util.Objects.requireNonNull;
import java.util.function.Function;
import javax.annotation.Nonnull;
import it.ozimov.seldon.model.primitive.LongIntDataEntry;
import it.ozimov.seldon.model.primitive.LongLongDataEntry;
public class LongIntDataEntryToLongLongDataEntry implements Function<LongIntDataEntry, LongLongDataEntry> {
@Override
public LongLongDataEntry apply(@Nonnull final LongIntDataEntry dataEntry) {
requireNonNull(dataEntry);
return new LongLongDataEntry(dataEntry.x(), dataEntry.y());
}
}
| UTF-8 | Java | 599 | java | LongIntDataEntryToLongLongDataEntry.java | Java | [] | null | [] | package it.ozimov.seldon.model.transformer;
import static java.util.Objects.requireNonNull;
import java.util.function.Function;
import javax.annotation.Nonnull;
import it.ozimov.seldon.model.primitive.LongIntDataEntry;
import it.ozimov.seldon.model.primitive.LongLongDataEntry;
public class LongIntDataEntryToLongLongDataEntry implements Function<LongIntDataEntry, LongLongDataEntry> {
@Override
public LongLongDataEntry apply(@Nonnull final LongIntDataEntry dataEntry) {
requireNonNull(dataEntry);
return new LongLongDataEntry(dataEntry.x(), dataEntry.y());
}
}
| 599 | 0.794658 | 0.794658 | 21 | 27.523809 | 31.275457 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.47619 | false | false | 13 |
185213dc5332f63e6eab1081f41b8350117e01ba | 21,466,246,585,713 | 4d4d6b5a52643e602f65918c5d30450e9bd8ff84 | /src/recommendation/GeoRecommendation.java | a5aa111563220ece86d0d96907037e470435fa9c | [] | no_license | iamjustnobody/Event_Manager | https://github.com/iamjustnobody/Event_Manager | 38f4a393ba3249d5c0543d1414df36d9bcf203ad | 186f9edbe19e73324d8e0fadb508949405351282 | refs/heads/master | 2023-06-13T09:10:26.846000 | 2021-07-08T10:48:13 | 2021-07-08T10:48:13 | 364,864,958 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package recommendation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import db.DBConnection;
import db.DBConnectionFactory;
import entity.Item;
public class GeoRecommendation {
public List<Item> recommendations(String userId,double lat,double lon){
List<Item> recommendedItems=new ArrayList<>();
//get all fav itemids
DBConnection connection=DBConnectionFactory.getConnection();
Set<String> favouritedItemIds=connection.getFavouriteItemIds(userId);
//get all categories and sort by count
Map<String,Integer> allCategories=new HashMap<>();
for(String itemId:favouritedItemIds) {
Set<String> categories=connection.getCategories(itemId);
for(String category:categories) {
allCategories.put(category, allCategories.getOrDefault(category, 0) + 1);
}
}
List<Entry<String, Integer>> categoryList = new ArrayList<>(allCategories.entrySet());
Collections.sort(categoryList, (Entry<String, Integer> e1, Entry<String, Integer> e2) -> {
return Integer.compare(e2.getValue(), e1.getValue());
});
// Step 3, search based on category, filter out favorite items //
//search based on Map<String,Integer> allCategories
Set<String> visitedItemIds = new HashSet<>();
for (Entry<String, Integer> category : categoryList) {
List<Item> items = connection.searchItems(lat, lon, category.getKey());
for(Item item:items) {
if(!visitedItemIds.contains(item.getItemId())&&!favouritedItemIds.contains(item.getItemId())) {
//if(!visitedItemIds.contains(item.getItemId())) {
recommendedItems.add(item);
visitedItemIds.add(item.getItemId());
}
}
}
connection.close();
return recommendedItems;
}
}
| UTF-8 | Java | 1,900 | java | GeoRecommendation.java | Java | [] | null | [] | package recommendation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import db.DBConnection;
import db.DBConnectionFactory;
import entity.Item;
public class GeoRecommendation {
public List<Item> recommendations(String userId,double lat,double lon){
List<Item> recommendedItems=new ArrayList<>();
//get all fav itemids
DBConnection connection=DBConnectionFactory.getConnection();
Set<String> favouritedItemIds=connection.getFavouriteItemIds(userId);
//get all categories and sort by count
Map<String,Integer> allCategories=new HashMap<>();
for(String itemId:favouritedItemIds) {
Set<String> categories=connection.getCategories(itemId);
for(String category:categories) {
allCategories.put(category, allCategories.getOrDefault(category, 0) + 1);
}
}
List<Entry<String, Integer>> categoryList = new ArrayList<>(allCategories.entrySet());
Collections.sort(categoryList, (Entry<String, Integer> e1, Entry<String, Integer> e2) -> {
return Integer.compare(e2.getValue(), e1.getValue());
});
// Step 3, search based on category, filter out favorite items //
//search based on Map<String,Integer> allCategories
Set<String> visitedItemIds = new HashSet<>();
for (Entry<String, Integer> category : categoryList) {
List<Item> items = connection.searchItems(lat, lon, category.getKey());
for(Item item:items) {
if(!visitedItemIds.contains(item.getItemId())&&!favouritedItemIds.contains(item.getItemId())) {
//if(!visitedItemIds.contains(item.getItemId())) {
recommendedItems.add(item);
visitedItemIds.add(item.getItemId());
}
}
}
connection.close();
return recommendedItems;
}
}
| 1,900 | 0.708947 | 0.705263 | 58 | 30.758621 | 27.059519 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.344828 | false | false | 13 |
6e794655595c0dfd14aa0589dc56efebb6b6df3d | 34,729,105,577,143 | a2227a3de1091a476c3ba651b09907e8fbeb0417 | /AntarcticRescueDesktop/src/com/sadcoon/tumble/gameobjects/PlatformConstruct.java | 19d914fc66101e738c88a98c2a70648c89d5d51d | [] | no_license | hmuar/tumble | https://github.com/hmuar/tumble | 90aefd1c81aa362337a295089797b547bbca96ad | 38c60ceb0ffc71eabf08851f3031eb27fcc7114d | refs/heads/master | 2017-08-04T05:10:29.166000 | 2015-12-09T06:01:16 | 2015-12-09T06:01:16 | 47,673,800 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sadcoon.tumble.gameobjects;
import java.util.List;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.sadcoon.tumble.GC.InteractiveType;
import com.sadcoon.tumble.GameWorld;
import com.sadcoon.tumble.SpriteAnim;
import com.sadcoon.tumble.Utils;
import com.sadcoon.tumble.resources.AnimRes;
import com.sadcoon.tumble.resources.ArtUIRes;
public class PlatformConstruct extends PlatformIce {
private Texture placeGraphic;
private float placeGraphicX, placeGraphicY;
private float graphicOffsetX, graphicOffsetY;
private float curAlpha;
private float alphaSpeed = 2.0f;
private Color curColor;
public PlatformConstruct(GameWorld _world, float xLoc, float yLoc){
super();
placeGraphic = ArtUIRes.placeObjectGraphic;
UpdateInstance(_world, xLoc, yLoc);
}
public void UpdateInstance(GameWorld _world, float xLoc, float yLoc){
super.UpdateInstance(_world, xLoc, yLoc);
placeGraphicX = converter.meterToPix(loc.x);
placeGraphicY = converter.meterToPix(loc.y);
graphicOffsetX = -placeGraphic.getWidth()/2.0f;
graphicOffsetY = -placeGraphic.getHeight()/2.0f;
curAlpha = 1.0f;
}
@Override
protected void setupRigidBodyScaling(){
bodyScaleX = 1.0f;
}
@Override
public void render(SpriteBatch spriteBatch) {
curAlpha = Math.max(0.0f, curAlpha-alphaSpeed*Gdx.graphics.getDeltaTime());
if(curAlpha > 0.02f){
curColor = spriteBatch.getColor();
spriteBatch.setColor(1.0f, 1.0f, 1.0f, curAlpha);
spriteBatch.draw(placeGraphic, placeGraphicX + graphicOffsetX,
placeGraphicY + graphicOffsetY);
spriteBatch.setColor(curColor);
}
if(isActive){
stateTime += Gdx.graphics.getDeltaTime();
sprite = (Sprite) anim.getKeyFrame(stateTime, false);
handleRecoilState();
updateSpritePos();
sprite.draw(spriteBatch);
}
}
@Override
protected void setupAnimations(){
sprite = new Sprite();
List<Sprite> keyFrames = AnimRes.platformConstruct;
texHalfWidth = keyFrames.get(0).getWidth()/2.0f;
texHalfHeight = keyFrames.get(0).getHeight()/2.0f;
int[] animFrameIndices = {0, 1, 2, 3, 3, 2, 1, 0};
anim = new SpriteAnim(TIME_PER_FRAME, Utils.getAnimFrames(keyFrames, animFrameIndices));
}
@Override
public InteractiveType getType() {
return InteractiveType.PLATFORM_CONSTRUCT;
}
}
| UTF-8 | Java | 2,503 | java | PlatformConstruct.java | Java | [] | null | [] | package com.sadcoon.tumble.gameobjects;
import java.util.List;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.sadcoon.tumble.GC.InteractiveType;
import com.sadcoon.tumble.GameWorld;
import com.sadcoon.tumble.SpriteAnim;
import com.sadcoon.tumble.Utils;
import com.sadcoon.tumble.resources.AnimRes;
import com.sadcoon.tumble.resources.ArtUIRes;
public class PlatformConstruct extends PlatformIce {
private Texture placeGraphic;
private float placeGraphicX, placeGraphicY;
private float graphicOffsetX, graphicOffsetY;
private float curAlpha;
private float alphaSpeed = 2.0f;
private Color curColor;
public PlatformConstruct(GameWorld _world, float xLoc, float yLoc){
super();
placeGraphic = ArtUIRes.placeObjectGraphic;
UpdateInstance(_world, xLoc, yLoc);
}
public void UpdateInstance(GameWorld _world, float xLoc, float yLoc){
super.UpdateInstance(_world, xLoc, yLoc);
placeGraphicX = converter.meterToPix(loc.x);
placeGraphicY = converter.meterToPix(loc.y);
graphicOffsetX = -placeGraphic.getWidth()/2.0f;
graphicOffsetY = -placeGraphic.getHeight()/2.0f;
curAlpha = 1.0f;
}
@Override
protected void setupRigidBodyScaling(){
bodyScaleX = 1.0f;
}
@Override
public void render(SpriteBatch spriteBatch) {
curAlpha = Math.max(0.0f, curAlpha-alphaSpeed*Gdx.graphics.getDeltaTime());
if(curAlpha > 0.02f){
curColor = spriteBatch.getColor();
spriteBatch.setColor(1.0f, 1.0f, 1.0f, curAlpha);
spriteBatch.draw(placeGraphic, placeGraphicX + graphicOffsetX,
placeGraphicY + graphicOffsetY);
spriteBatch.setColor(curColor);
}
if(isActive){
stateTime += Gdx.graphics.getDeltaTime();
sprite = (Sprite) anim.getKeyFrame(stateTime, false);
handleRecoilState();
updateSpritePos();
sprite.draw(spriteBatch);
}
}
@Override
protected void setupAnimations(){
sprite = new Sprite();
List<Sprite> keyFrames = AnimRes.platformConstruct;
texHalfWidth = keyFrames.get(0).getWidth()/2.0f;
texHalfHeight = keyFrames.get(0).getHeight()/2.0f;
int[] animFrameIndices = {0, 1, 2, 3, 3, 2, 1, 0};
anim = new SpriteAnim(TIME_PER_FRAME, Utils.getAnimFrames(keyFrames, animFrameIndices));
}
@Override
public InteractiveType getType() {
return InteractiveType.PLATFORM_CONSTRUCT;
}
}
| 2,503 | 0.73352 | 0.718738 | 80 | 30.2875 | 21.722219 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.9625 | false | false | 13 |
4ca4dcfb2bb91538962a409ec53c43909a774e1d | 34,729,105,576,578 | 465cd5d0926e758dafa61fe4efedc18458f2f3cd | /src/main/java/com/sc/spring/mapper/UserinfoMapper.java | 6fb5b4be174e9746102ff65370b48efd2b019622 | [] | no_license | zxyleiyunfeng/mybatis_01 | https://github.com/zxyleiyunfeng/mybatis_01 | 52bec168b922d300fce77477a29873fef9549097 | a51b9f423d46b308df6ccddefa696b9da1224b6e | refs/heads/master | 2023-01-13T00:13:34.061000 | 2020-11-21T10:44:12 | 2020-11-21T10:44:12 | 314,773,919 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sc.spring.mapper;
import com.sc.spring.entity.Userinfo;
import java.util.List;
/**
* 类名:UserinfoMapper
* 描述:一段话描述类的信息
* 作者:雷云风
* 日期:2020/10/9 10:53
* 版本:V1.0
*/
public interface UserinfoMapper {
public void addUserinfo(Userinfo userinfo);
public void updateUserinfo(Userinfo userinfo);
public void deleteUserinfo(Integer userId);
public List<Userinfo> selectUserinfo();
public List<Userinfo> selectUserinfo1();
}
| UTF-8 | Java | 514 | java | UserinfoMapper.java | Java | [
{
"context": ";\n\n/**\n * 类名:UserinfoMapper\n * 描述:一段话描述类的信息\n * 作者:雷云风\n * 日期:2020/10/9 10:53\n * 版本:V1.0\n */\npublic inter",
"end": 144,
"score": 0.9143633842468262,
"start": 141,
"tag": "NAME",
"value": "雷云风"
}
] | null | [] | package com.sc.spring.mapper;
import com.sc.spring.entity.Userinfo;
import java.util.List;
/**
* 类名:UserinfoMapper
* 描述:一段话描述类的信息
* 作者:雷云风
* 日期:2020/10/9 10:53
* 版本:V1.0
*/
public interface UserinfoMapper {
public void addUserinfo(Userinfo userinfo);
public void updateUserinfo(Userinfo userinfo);
public void deleteUserinfo(Integer userId);
public List<Userinfo> selectUserinfo();
public List<Userinfo> selectUserinfo1();
}
| 514 | 0.719565 | 0.68913 | 26 | 16.692308 | 18.089031 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false | 13 |
97fa5f9f79bf6be74ac84deeb891aeeeec9e3d40 | 34,445,637,738,214 | e27ce1427ddbe73bc91cdde56bd75096ddd46f7d | /TweetAnalyze/src/main/java/Task3.java | 28fcd66dbda8f6b569ffd168e9403b0f56532d25 | [] | no_license | EzgiNurUcay/mapreduce-hadoop | https://github.com/EzgiNurUcay/mapreduce-hadoop | dc4f3ab21bd60cad159ebcb80a87e4fc847759c9 | 021eb69618e6b540d1f8eae04d91a99e2a21f18d | refs/heads/master | 2023-02-20T17:54:49.595000 | 2021-01-09T18:28:48 | 2021-01-09T18:28:48 | 262,932,834 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import java.io.IOException;
import java.util.List;
public class Task3 {
//In Task-3, the total count of word in the corpus is calculated using Task-2 output.
public static class Mapper extends org.apache.hadoop.mapreduce.Mapper<LongWritable, Text, Text, IntWritable> {
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String[] inputs = value.toString().split("\t");
//input[0] = preprocessed word, input[1] = document name, input[2] = word frequency in doc, input[3] = N
WordFrequencyMap.addWordFrequency(inputs[0], inputs[1], inputs[2], inputs[3]);
context.write(new Text(inputs[0]), new IntWritable(Integer.parseInt(inputs[2])));
}
}
public static class Reducer extends org.apache.hadoop.mapreduce.Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterable<IntWritable> values,
Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
List<WordCount> list = WordFrequencyMap.getWordFrequency(key.toString());
for (WordCount word : list) {
context.write(new Text(key + "\t" + word.getDocName() + "\t" + word.getFrequency() + "\t" + word.getN()), new IntWritable(sum));
}
}
}
}
| UTF-8 | Java | 1,602 | java | Task3.java | Java | [] | null | [] | import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import java.io.IOException;
import java.util.List;
public class Task3 {
//In Task-3, the total count of word in the corpus is calculated using Task-2 output.
public static class Mapper extends org.apache.hadoop.mapreduce.Mapper<LongWritable, Text, Text, IntWritable> {
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String[] inputs = value.toString().split("\t");
//input[0] = preprocessed word, input[1] = document name, input[2] = word frequency in doc, input[3] = N
WordFrequencyMap.addWordFrequency(inputs[0], inputs[1], inputs[2], inputs[3]);
context.write(new Text(inputs[0]), new IntWritable(Integer.parseInt(inputs[2])));
}
}
public static class Reducer extends org.apache.hadoop.mapreduce.Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterable<IntWritable> values,
Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
List<WordCount> list = WordFrequencyMap.getWordFrequency(key.toString());
for (WordCount word : list) {
context.write(new Text(key + "\t" + word.getDocName() + "\t" + word.getFrequency() + "\t" + word.getN()), new IntWritable(sum));
}
}
}
}
| 1,602 | 0.631086 | 0.622347 | 37 | 42.297298 | 40.744999 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.891892 | false | false | 13 |
d0569b7c19b0f82f8edf1d02509372261201c337 | 15,522,011,851,265 | 5a925ed19ab24a22b33c035dc1aad8bf77f619db | /ppholic_server_demo/src/main/java/com/zh/ppholic_server_demo/dao/SubtotalDaoImpl.java | 0c9998063a92251e47f2c282678bba0e071f45da | [] | no_license | jl3000x/Public_Demo_Repository | https://github.com/jl3000x/Public_Demo_Repository | 5c0512bbc914a4d96d5c3ab5fbcc003267ab8411 | 152ece88ddcadb4d556e113c04b10d7192a5b13e | refs/heads/master | 2023-06-01T22:44:16.226000 | 2021-06-12T09:03:58 | 2021-06-12T09:03:58 | 367,248,869 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zh.ppholic_server_demo.dao;
import java.util.List;
import javax.persistence.EntityManager;
import com.zh.ppholic_server_demo.entity.Subtotal;
import com.zh.ppholic_server_demo.util.SortUtils;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class SubtotalDaoImpl implements SubtotalDao {
// define field for entitymanager
private EntityManager entityManager;
// set up constructor injection
@Autowired
public SubtotalDaoImpl(EntityManager theEntityManager) {
entityManager = theEntityManager;
}
@Override
public Subtotal getSubtotal(int theSubtotalId) {
// get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class);
// retrieve/read from database using product name
Query<Subtotal> theQuery = currentSession.createQuery("FROM Subtotal WHERE id=:theSubtotalId", Subtotal.class);
theQuery.setParameter("theSubtotalId", theSubtotalId);
Subtotal theSubtotal = null;
// confirm the result is unique, or throw exception
try {
theSubtotal = theQuery.getSingleResult();
currentSession.saveOrUpdate(theSubtotal);
} catch (Exception e) {
theSubtotal = null;
}
return theSubtotal;
}
@Override
public List<Subtotal> getSortedSubtotals(int theSortField, String theSearchName) {
// get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class);
// determine sort field
String theFieldName = null;
switch (theSortField) {
case SortUtils.PRODUCT_NAME:
theFieldName = "S.product.name";
break;
case SortUtils.PRICE:
theFieldName = "S.product.price";
break;
case SortUtils.INFO:
theFieldName = "S.product.information";
break;
case SortUtils.LAST_UPDATE:
theFieldName = "S.product.last_update desc";
break;
case SortUtils.SUB_CATEGORY:
theFieldName = "S.product.subCategory.name";
break;
default:
// if nothing matches the default to sort by lastName
theFieldName = "S.product.last_update desc";
}
Query<Subtotal> theQuery = null;
if (theSearchName != null && theSearchName.trim().length() > 0) {
// create a query and sorted by option
String searchConfig = "WHERE lower(S.product.name) LIKE: keyword OR lower(S.product.info) LIKE :keyword " +
"OR lower(S.product.subCategory.name) LIKE :keyword ";
String queryString = "FROM Subtotal S " + searchConfig + "ORDER BY " + theFieldName;
theQuery = currentSession.createQuery(queryString, Subtotal.class);
theQuery.setParameter("keyword", "%" + theSearchName.toLowerCase() + "%");
}
else {
// collect all data and sorted by last name
String queryString = "FROM Subtotal S ORDER BY " + theFieldName;
theQuery = currentSession.createQuery(queryString, Subtotal.class);
}
// execute query and get list
List<Subtotal> subtotals = theQuery.getResultList();
// return the result
return subtotals;
}
@Override
public void saveSubtotal(Subtotal theSubtotal) {
// get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class);
currentSession.saveOrUpdate(theSubtotal);
}
@Override
public void deleteSubtotal(int theSubtotalId) {
// get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class);
// save / update the product
Query<Subtotal> theQuery = currentSession.createQuery("DELETE FROM Subtotal WHERE id=:theSubtotalId");
theQuery.setParameter("theSubtotalId", theSubtotalId);
theQuery.executeUpdate();
}
}
| UTF-8 | Java | 4,317 | java | SubtotalDaoImpl.java | Java | [] | null | [] | package com.zh.ppholic_server_demo.dao;
import java.util.List;
import javax.persistence.EntityManager;
import com.zh.ppholic_server_demo.entity.Subtotal;
import com.zh.ppholic_server_demo.util.SortUtils;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class SubtotalDaoImpl implements SubtotalDao {
// define field for entitymanager
private EntityManager entityManager;
// set up constructor injection
@Autowired
public SubtotalDaoImpl(EntityManager theEntityManager) {
entityManager = theEntityManager;
}
@Override
public Subtotal getSubtotal(int theSubtotalId) {
// get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class);
// retrieve/read from database using product name
Query<Subtotal> theQuery = currentSession.createQuery("FROM Subtotal WHERE id=:theSubtotalId", Subtotal.class);
theQuery.setParameter("theSubtotalId", theSubtotalId);
Subtotal theSubtotal = null;
// confirm the result is unique, or throw exception
try {
theSubtotal = theQuery.getSingleResult();
currentSession.saveOrUpdate(theSubtotal);
} catch (Exception e) {
theSubtotal = null;
}
return theSubtotal;
}
@Override
public List<Subtotal> getSortedSubtotals(int theSortField, String theSearchName) {
// get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class);
// determine sort field
String theFieldName = null;
switch (theSortField) {
case SortUtils.PRODUCT_NAME:
theFieldName = "S.product.name";
break;
case SortUtils.PRICE:
theFieldName = "S.product.price";
break;
case SortUtils.INFO:
theFieldName = "S.product.information";
break;
case SortUtils.LAST_UPDATE:
theFieldName = "S.product.last_update desc";
break;
case SortUtils.SUB_CATEGORY:
theFieldName = "S.product.subCategory.name";
break;
default:
// if nothing matches the default to sort by lastName
theFieldName = "S.product.last_update desc";
}
Query<Subtotal> theQuery = null;
if (theSearchName != null && theSearchName.trim().length() > 0) {
// create a query and sorted by option
String searchConfig = "WHERE lower(S.product.name) LIKE: keyword OR lower(S.product.info) LIKE :keyword " +
"OR lower(S.product.subCategory.name) LIKE :keyword ";
String queryString = "FROM Subtotal S " + searchConfig + "ORDER BY " + theFieldName;
theQuery = currentSession.createQuery(queryString, Subtotal.class);
theQuery.setParameter("keyword", "%" + theSearchName.toLowerCase() + "%");
}
else {
// collect all data and sorted by last name
String queryString = "FROM Subtotal S ORDER BY " + theFieldName;
theQuery = currentSession.createQuery(queryString, Subtotal.class);
}
// execute query and get list
List<Subtotal> subtotals = theQuery.getResultList();
// return the result
return subtotals;
}
@Override
public void saveSubtotal(Subtotal theSubtotal) {
// get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class);
currentSession.saveOrUpdate(theSubtotal);
}
@Override
public void deleteSubtotal(int theSubtotalId) {
// get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class);
// save / update the product
Query<Subtotal> theQuery = currentSession.createQuery("DELETE FROM Subtotal WHERE id=:theSubtotalId");
theQuery.setParameter("theSubtotalId", theSubtotalId);
theQuery.executeUpdate();
}
}
| 4,317 | 0.628446 | 0.628214 | 125 | 33.535999 | 28.314672 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.44 | false | false | 13 |
053f71308d5a0e8bb1cf963f1b8104d62cb5c651 | 15,831,249,497,842 | 1c13ba7e7d32c97ba039936f98edf99e56f1c7fe | /src/lt_300_399/LC_390.java | 6ce7584885ab0d103e15d89ad49f048ef210de4b | [] | no_license | Acker2015/Leetcode-Pro | https://github.com/Acker2015/Leetcode-Pro | 83b36a2315982173164c9e51f4292c1fc02f1a8b | 3b067f2e83cc10fcce239b0f1d283711c29ae585 | refs/heads/master | 2020-04-01T09:10:13.894000 | 2019-11-10T07:53:21 | 2019-11-10T07:53:21 | 153,062,895 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lt_300_399;
/**
* [390] Elimination Game
*
* There is a list of sorted integers from 1 to n.
* Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.
* Repeat the previous step again, but this time from right to left, remove the right most number and every other number from the remaining numbers.
We keep repeating the steps again, alternating left to right and right to left, until a single number remains.
Find the last number that remains starting with a list of length n.
Input:
n = 9,
1 2 3 4 5 6 7 8 9
2 4 6 8
2 6
6
Output:
6
*/
public class LC_390 {
/**
* the idea is to record head value in each turn, when the total number left is 1. the left value would be the answer.
*
* 记住每次eliminate的起始值和相邻两个数的距离
* 1. 相邻两个数的距离distance默认为1,后边每一次eliminate的时候距离翻倍
* 2. 如何改变起始位置start?
* 2.1 如果是正向消除,那么起始位置start肯定会被eliminate,更新start=start+distance
* 2.2 如果是逆向消除,那么起始位置是否被eliminate取决于本轮参与game的元素个数
* 2.2.1 如果元素个数为偶数,那么起始位置不变,因为不会被eliminate
* 2.2.2 如果元素个数为奇数,那么起始位置改变为第二个数,start=start+distance
*/
public int lastRemaining(int n) {
boolean headToTail = true;
int start = 1, distance = 1;
while (n > 1) {
if (headToTail) {
start += distance;
} else {
if (n % 2 == 1) {
start += distance;
}
}
n /= 2;
distance *= 2;
headToTail = !headToTail;
}
return start;
}
}
| UTF-8 | Java | 1,913 | java | LC_390.java | Java | [] | null | [] | package lt_300_399;
/**
* [390] Elimination Game
*
* There is a list of sorted integers from 1 to n.
* Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.
* Repeat the previous step again, but this time from right to left, remove the right most number and every other number from the remaining numbers.
We keep repeating the steps again, alternating left to right and right to left, until a single number remains.
Find the last number that remains starting with a list of length n.
Input:
n = 9,
1 2 3 4 5 6 7 8 9
2 4 6 8
2 6
6
Output:
6
*/
public class LC_390 {
/**
* the idea is to record head value in each turn, when the total number left is 1. the left value would be the answer.
*
* 记住每次eliminate的起始值和相邻两个数的距离
* 1. 相邻两个数的距离distance默认为1,后边每一次eliminate的时候距离翻倍
* 2. 如何改变起始位置start?
* 2.1 如果是正向消除,那么起始位置start肯定会被eliminate,更新start=start+distance
* 2.2 如果是逆向消除,那么起始位置是否被eliminate取决于本轮参与game的元素个数
* 2.2.1 如果元素个数为偶数,那么起始位置不变,因为不会被eliminate
* 2.2.2 如果元素个数为奇数,那么起始位置改变为第二个数,start=start+distance
*/
public int lastRemaining(int n) {
boolean headToTail = true;
int start = 1, distance = 1;
while (n > 1) {
if (headToTail) {
start += distance;
} else {
if (n % 2 == 1) {
start += distance;
}
}
n /= 2;
distance *= 2;
headToTail = !headToTail;
}
return start;
}
}
| 1,913 | 0.606061 | 0.573902 | 53 | 29.509434 | 33.844608 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.320755 | false | false | 13 |
94fb5396bc434c8e231bf99f1242abd6322408bf | 4,063,039,106,827 | 0b1cb374f7a7f972d377f8491311902e95e21dff | /web/src/main/java/by/itacademy/controller/DataBaseController.java | c6cc7bdc3174cab2786fde5fd546e7bdc85da9ad | [] | no_license | theone55/HomeWork | https://github.com/theone55/HomeWork | 207f178173e37fd79a14062d05978a56daaef871 | 5fe93a8357f76027a6c8092007e9afe28c96119b | refs/heads/master | 2018-09-30T16:02:29.757000 | 2018-06-27T09:21:03 | 2018-06-27T09:21:03 | 131,428,721 | 0 | 0 | null | false | 2018-06-10T14:16:54 | 2018-04-28T17:07:16 | 2018-06-07T18:42:56 | 2018-06-10T14:16:45 | 7,835 | 0 | 0 | 1 | Java | false | null | package by.itacademy.controller;
import by.itacademy.entity.Role;
import by.itacademy.entity.User;
import by.itacademy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class DataBaseController extends ControllerBase {
@ModelAttribute("roles")
public Role[] cuisines() {
return Role.values();
}
private static UserService userService;
@Autowired
public DataBaseController(UserService userService) {
this.userService = userService;
}
@GetMapping("/database")
public String dbage(Model model) {
model.addAttribute("user", new User());
model.addAttribute("errorMsg", new String());
return "database";
}
@PostMapping("/databaseUserFind")
public String findMethod(Model model, User user) {
user = userService.getByEmail(user.getEmail());
if (user == null) {
model.addAttribute("errorMsg", new String("Nothing found..."));
return "database";
}
model.addAttribute("user_from_base", user);
return "database";
}
@PostMapping("/databaseUser")
public String updateMethod(Model model, User user) {
User userFromBase = userService.getUserById(user.getId()).orElse(null);
if (userService.getByEmail(user.getEmail()) != null && !userFromBase.getEmail().equals(user.getEmail())) {
model.addAttribute("errorMsg", new String("This email occupied..."));
return "database";
}
userFromBase.setEmail(user.getEmail());
userFromBase.setRole(user.getRole());
userFromBase.setName(user.getName());
userFromBase.setVersion(user.getVersion());
userService.saveUser(userFromBase);
return "database";
}
}
| UTF-8 | Java | 2,069 | java | DataBaseController.java | Java | [] | null | [] | package by.itacademy.controller;
import by.itacademy.entity.Role;
import by.itacademy.entity.User;
import by.itacademy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class DataBaseController extends ControllerBase {
@ModelAttribute("roles")
public Role[] cuisines() {
return Role.values();
}
private static UserService userService;
@Autowired
public DataBaseController(UserService userService) {
this.userService = userService;
}
@GetMapping("/database")
public String dbage(Model model) {
model.addAttribute("user", new User());
model.addAttribute("errorMsg", new String());
return "database";
}
@PostMapping("/databaseUserFind")
public String findMethod(Model model, User user) {
user = userService.getByEmail(user.getEmail());
if (user == null) {
model.addAttribute("errorMsg", new String("Nothing found..."));
return "database";
}
model.addAttribute("user_from_base", user);
return "database";
}
@PostMapping("/databaseUser")
public String updateMethod(Model model, User user) {
User userFromBase = userService.getUserById(user.getId()).orElse(null);
if (userService.getByEmail(user.getEmail()) != null && !userFromBase.getEmail().equals(user.getEmail())) {
model.addAttribute("errorMsg", new String("This email occupied..."));
return "database";
}
userFromBase.setEmail(user.getEmail());
userFromBase.setRole(user.getRole());
userFromBase.setName(user.getName());
userFromBase.setVersion(user.getVersion());
userService.saveUser(userFromBase);
return "database";
}
}
| 2,069 | 0.682939 | 0.682939 | 60 | 33.483334 | 24.656637 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.616667 | false | false | 13 |
0ef96cbebdc69972312a39676377635bc6b7ff73 | 30,511,447,727,570 | 48876e2964af54d4beea829978506c839822492f | /app/src/main/java/com/example/superluckylotus/MainActivity.java | c18ac7ccf91e2b334c16842b522f981ac94c7de6 | [] | no_license | Super-Lucky-Lotus/UI2 | https://github.com/Super-Lucky-Lotus/UI2 | b74713b8ba13453bec75f45242b9effe32113721 | 8f1e3d31ab92723ba57ec6998fe436432379442b | refs/heads/master | 2022-11-21T09:15:32.130000 | 2020-07-25T11:55:49 | 2020-07-25T11:55:49 | 281,475,339 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.superluckylotus;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.baidu.location.LocationClient;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClientOption;
import com.example.superluckylotus.Earth.EarthFragment;
import com.example.superluckylotus.Me.MeFragment;
import com.example.superluckylotus.Near.NearFragment;
import com.example.superluckylotus.Notice.NoticeFragment;
import com.example.superluckylotus.ShootSdk.ShootActivity;
import static com.veuisdk.SdkEntry.editMedia;
/**
* @version: 1.0
* @author: 宋佳容
* @className: MainFragment
* @packageName:com.example.superluckylotus
* @description: 主界面
* @data: 2020.07.11 21:12
**/
public class MainActivity extends AppCompatActivity {
public static String city;
private RadioGroup mTabRadioGroup;
private MeFragment meFragment;
private EarthFragment earthFragment;
private NearFragment nearFragment;
private NoticeFragment noticeFragment;
private final String TAG = "MainActivity";
// private ShootDialog sd;
private Button near_Btn;
private Button notice_Btn;
private Button me_Btn;
private Button shoot_Btn;
private Button earth_Btn;
//声明LocationClient类,定位服务客户对象
public LocationClient mLocationClient = null;
//声明重写的监听类
private MyLocationListener mLocationListener = new MyLocationListener();
//是否首次定位
private boolean isFirstLoc = true;
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //没有标题栏
setContentView(R.layout.activity_main);
shoot_Btn = (Button)findViewById(R.id.btn_addshoot);
//setListeners();
// sd=new ShootDialog(MainActivity.this);
// sd=new ShootDialog(MainActivity.this,new ShootDialog.LeaveMyDialogListener(){
//
// @Override
// public void onClick(View view) {
// switch (view.getId()) {
//
// case R.id.add_shoot: // 正方形,长方形可切换录制视频,编辑录制后的视频,如果有导出时,导出视频的路径
// SdkEntry.registerOSDBuilder(CameraWatermarkBuilder.class);
// CameraWatermarkBuilder.setText("好运莲莲");// 可自定义水印显示文本
// initCameraConfig(SQUARE_SCREEN_CAN_CHANGE);
// SdkEntry.record(view.getContext(), CAMERA_REQUEST_CODE);
// break;
//
// }
// }
//
// });
shoot_Btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// sd.popupWindowDialog(view);
Intent intent = null;
intent = new Intent(MainActivity.this, ShootActivity.class);
startActivity(intent);
// mContext.startActivity(intent);
}
});
//实例化EarthFragment
earthFragment = new EarthFragment();
//把EarthFragment添加到Avtivity中
getFragmentManager().beginTransaction().add(R.id.fragment_container,earthFragment).commitAllowingStateLoss();
earth_Btn = (Button)findViewById(R.id.earth_tab);
earth_Btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
if(earthFragment == null)
{
earthFragment = new EarthFragment();
}
getFragmentManager().beginTransaction().replace(R.id.fragment_container,earthFragment).commitAllowingStateLoss();
}
});
near_Btn = (Button)findViewById(R.id.near_tab);
near_Btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
if(nearFragment == null)
{
nearFragment = new NearFragment();
}
getFragmentManager().beginTransaction().replace(R.id.fragment_container,nearFragment).commitAllowingStateLoss();
}
});
notice_Btn = (Button)findViewById(R.id.notice_tab);
notice_Btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
if(noticeFragment == null)
{
noticeFragment = new NoticeFragment();
}
getFragmentManager().beginTransaction().replace(R.id.fragment_container,noticeFragment).commitAllowingStateLoss();
}
});
me_Btn = (Button)findViewById(R.id.me_tab);
me_Btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
if(meFragment == null)
{
meFragment = new MeFragment();
}
getFragmentManager().beginTransaction().replace(R.id.fragment_container,meFragment).commitAllowingStateLoss();
}
});
// mLocationClient.start();
initLocation();
mLocationClient.start();
}
private void initLocation(){
mLocationClient = new LocationClient((getApplicationContext()));
mLocationListener = new MyLocationListener();
//注册监听器
mLocationClient.registerLocationListener(mLocationListener);
//设置定位参数
LocationClientOption option = new LocationClientOption();
//设置坐标类型
option.setCoorType("bd09ll");
//设置是否需要地址信息,默认为无地址
option.setIsNeedAddress(true);
//设置是否打开gps进行定位
option.setOpenGps(true);
//设置扫描间隔为0
option.setScanSpan(0);
//传入设置好的信息
mLocationClient.setLocOption(option);
}
//重写百度地图监听类
public class MyLocationListener extends BDAbstractLocationListener {
@Override
public void onReceiveLocation(BDLocation location){
Toast.makeText(getApplicationContext(),"定位成功",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),String.valueOf(location.getCity()),Toast.LENGTH_SHORT).show();
city=String.valueOf(location.getCity());
}
}
} | UTF-8 | Java | 6,973 | java | MainActivity.java | Java | [
{
"context": "ntry.editMedia;\n\n/**\n * @version: 1.0\n * @author: 宋佳容\n * @className: MainFragment\n * @packageName:com.e",
"end": 941,
"score": 0.9998720288276672,
"start": 938,
"tag": "NAME",
"value": "宋佳容"
}
] | null | [] | package com.example.superluckylotus;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.baidu.location.LocationClient;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClientOption;
import com.example.superluckylotus.Earth.EarthFragment;
import com.example.superluckylotus.Me.MeFragment;
import com.example.superluckylotus.Near.NearFragment;
import com.example.superluckylotus.Notice.NoticeFragment;
import com.example.superluckylotus.ShootSdk.ShootActivity;
import static com.veuisdk.SdkEntry.editMedia;
/**
* @version: 1.0
* @author: 宋佳容
* @className: MainFragment
* @packageName:com.example.superluckylotus
* @description: 主界面
* @data: 2020.07.11 21:12
**/
public class MainActivity extends AppCompatActivity {
public static String city;
private RadioGroup mTabRadioGroup;
private MeFragment meFragment;
private EarthFragment earthFragment;
private NearFragment nearFragment;
private NoticeFragment noticeFragment;
private final String TAG = "MainActivity";
// private ShootDialog sd;
private Button near_Btn;
private Button notice_Btn;
private Button me_Btn;
private Button shoot_Btn;
private Button earth_Btn;
//声明LocationClient类,定位服务客户对象
public LocationClient mLocationClient = null;
//声明重写的监听类
private MyLocationListener mLocationListener = new MyLocationListener();
//是否首次定位
private boolean isFirstLoc = true;
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //没有标题栏
setContentView(R.layout.activity_main);
shoot_Btn = (Button)findViewById(R.id.btn_addshoot);
//setListeners();
// sd=new ShootDialog(MainActivity.this);
// sd=new ShootDialog(MainActivity.this,new ShootDialog.LeaveMyDialogListener(){
//
// @Override
// public void onClick(View view) {
// switch (view.getId()) {
//
// case R.id.add_shoot: // 正方形,长方形可切换录制视频,编辑录制后的视频,如果有导出时,导出视频的路径
// SdkEntry.registerOSDBuilder(CameraWatermarkBuilder.class);
// CameraWatermarkBuilder.setText("好运莲莲");// 可自定义水印显示文本
// initCameraConfig(SQUARE_SCREEN_CAN_CHANGE);
// SdkEntry.record(view.getContext(), CAMERA_REQUEST_CODE);
// break;
//
// }
// }
//
// });
shoot_Btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// sd.popupWindowDialog(view);
Intent intent = null;
intent = new Intent(MainActivity.this, ShootActivity.class);
startActivity(intent);
// mContext.startActivity(intent);
}
});
//实例化EarthFragment
earthFragment = new EarthFragment();
//把EarthFragment添加到Avtivity中
getFragmentManager().beginTransaction().add(R.id.fragment_container,earthFragment).commitAllowingStateLoss();
earth_Btn = (Button)findViewById(R.id.earth_tab);
earth_Btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
if(earthFragment == null)
{
earthFragment = new EarthFragment();
}
getFragmentManager().beginTransaction().replace(R.id.fragment_container,earthFragment).commitAllowingStateLoss();
}
});
near_Btn = (Button)findViewById(R.id.near_tab);
near_Btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
if(nearFragment == null)
{
nearFragment = new NearFragment();
}
getFragmentManager().beginTransaction().replace(R.id.fragment_container,nearFragment).commitAllowingStateLoss();
}
});
notice_Btn = (Button)findViewById(R.id.notice_tab);
notice_Btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
if(noticeFragment == null)
{
noticeFragment = new NoticeFragment();
}
getFragmentManager().beginTransaction().replace(R.id.fragment_container,noticeFragment).commitAllowingStateLoss();
}
});
me_Btn = (Button)findViewById(R.id.me_tab);
me_Btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
if(meFragment == null)
{
meFragment = new MeFragment();
}
getFragmentManager().beginTransaction().replace(R.id.fragment_container,meFragment).commitAllowingStateLoss();
}
});
// mLocationClient.start();
initLocation();
mLocationClient.start();
}
private void initLocation(){
mLocationClient = new LocationClient((getApplicationContext()));
mLocationListener = new MyLocationListener();
//注册监听器
mLocationClient.registerLocationListener(mLocationListener);
//设置定位参数
LocationClientOption option = new LocationClientOption();
//设置坐标类型
option.setCoorType("bd09ll");
//设置是否需要地址信息,默认为无地址
option.setIsNeedAddress(true);
//设置是否打开gps进行定位
option.setOpenGps(true);
//设置扫描间隔为0
option.setScanSpan(0);
//传入设置好的信息
mLocationClient.setLocOption(option);
}
//重写百度地图监听类
public class MyLocationListener extends BDAbstractLocationListener {
@Override
public void onReceiveLocation(BDLocation location){
Toast.makeText(getApplicationContext(),"定位成功",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),String.valueOf(location.getCity()),Toast.LENGTH_SHORT).show();
city=String.valueOf(location.getCity());
}
}
} | 6,973 | 0.63376 | 0.631047 | 206 | 31.213593 | 27.892878 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.490291 | false | false | 13 |
8c96fa5e45b842e88c79244a8711daea50b224c2 | 4,269,197,531,972 | ca6616c0a9487b68941b181af8e60c76158f532b | /usci/modules/cli/src/main/java/kz/bsbnb/usci/cli/app/ref/reps/OffshoreRepository.java | 258fb152e6f28444bd36aa69ff18b45fbb6d41c9 | [] | no_license | smukashev/essp | https://github.com/smukashev/essp | a830fe9c9985d8149bf708bb6c82027cfbf6d6f2 | 78a278b1d4b9717d72ec7cdb2fc79ac348380387 | refs/heads/master | 2020-03-15T15:21:37.258000 | 2017-11-02T08:01:02 | 2017-11-02T08:01:02 | 132,210,321 | 0 | 1 | null | false | 2018-06-07T05:52:19 | 2018-05-05T03:13:35 | 2018-05-10T06:17:28 | 2018-06-05T06:40:12 | 80,960 | 0 | 1 | 2 | CSS | false | null |
package kz.bsbnb.usci.cli.app.ref.reps;
import kz.bsbnb.usci.cli.app.ref.BaseRepository;
import kz.bsbnb.usci.cli.app.ref.craw.CountryCrawler;
import kz.bsbnb.usci.cli.app.ref.refs.Country;
import kz.bsbnb.usci.cli.app.ref.refs.Offshore;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
public class OffshoreRepository extends BaseRepository {
/*private static HashMap repository;
private static HashSet columns;
private static String QUERY = "SELECT * FROM ref.OFFSHORE t" + " where t.open_date = to_date('repDate', 'dd.MM.yyyy')\n"+
" and (t.close_date > to_date('repDate', 'dd.MM.yyyy') or t.close_date is null)";
private static String COLUMNS_QUERY = "SELECT * FROM all_tab_cols WHERE owner = 'REF' AND TABLE_NAME='OFFSHORE'";*/
public OffshoreRepository() {
QUERY_ALL = "SELECT * FROM ref.offshore";
QUERY_OPEN = "SELECT * FROM ref.offshore where open_date = to_date('repDate', 'dd.MM.yyyy') " +
" and (close_date > to_date('repDate','dd.MM.yyyy') or close_date is null)";
QUERY_CLOSE = "SELECT * FROM ref.offshore where close_date = to_date('repDate', 'dd.MM.yyyy') and is_last = 1";
COLUMNS_QUERY = "SELECT * FROM all_tab_cols WHERE owner = 'REF' AND TABLE_NAME='OFFSHORE'";
countryCrawler = new CountryCrawler();
countryCrawler.constructAll();
}
CountryCrawler countryCrawler;
@Override
public HashMap construct(String query){
try {
HashSet hs = getColumns();
CountryRepository countryRepository = (CountryRepository) countryCrawler.getRepositoryInstance();
ResultSet rows = getStatement().executeQuery(query.replaceAll("repDate",repDate));
HashMap hm = new HashMap();
while(rows.next()){
HashMap tmp = new HashMap();
//System.out.println(rows.getString("NAME_RU"));
for(Object s: hs){
//System.out.println(s);
tmp.put((String)s,rows.getString((String)s));
}
Country country = countryRepository.getById((String)tmp.get("COUNTRY_ID"));
tmp.put("country",country);
Offshore dt = new Offshore(tmp);
hm.put(dt.get(dt.getKeyName()),dt);
}
return hm;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public Offshore[] getByProperty(String key,String value){
Offshore [] ret = new Offshore[0];
List<Offshore> list = new ArrayList<Offshore>();
for(Object v: getRepository().values()){
if(((Offshore) v).get(key) != null)
if(((Offshore) v).get(key).equals(value)) list.add((Offshore)v);
}
return list.toArray(ret);
}
public Offshore getById(String id){
return (Offshore) getRepository().get(id);
}
public void rc(){
repository = null;
}
}
| UTF-8 | Java | 3,102 | java | OffshoreRepository.java | Java | [] | null | [] |
package kz.bsbnb.usci.cli.app.ref.reps;
import kz.bsbnb.usci.cli.app.ref.BaseRepository;
import kz.bsbnb.usci.cli.app.ref.craw.CountryCrawler;
import kz.bsbnb.usci.cli.app.ref.refs.Country;
import kz.bsbnb.usci.cli.app.ref.refs.Offshore;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
public class OffshoreRepository extends BaseRepository {
/*private static HashMap repository;
private static HashSet columns;
private static String QUERY = "SELECT * FROM ref.OFFSHORE t" + " where t.open_date = to_date('repDate', 'dd.MM.yyyy')\n"+
" and (t.close_date > to_date('repDate', 'dd.MM.yyyy') or t.close_date is null)";
private static String COLUMNS_QUERY = "SELECT * FROM all_tab_cols WHERE owner = 'REF' AND TABLE_NAME='OFFSHORE'";*/
public OffshoreRepository() {
QUERY_ALL = "SELECT * FROM ref.offshore";
QUERY_OPEN = "SELECT * FROM ref.offshore where open_date = to_date('repDate', 'dd.MM.yyyy') " +
" and (close_date > to_date('repDate','dd.MM.yyyy') or close_date is null)";
QUERY_CLOSE = "SELECT * FROM ref.offshore where close_date = to_date('repDate', 'dd.MM.yyyy') and is_last = 1";
COLUMNS_QUERY = "SELECT * FROM all_tab_cols WHERE owner = 'REF' AND TABLE_NAME='OFFSHORE'";
countryCrawler = new CountryCrawler();
countryCrawler.constructAll();
}
CountryCrawler countryCrawler;
@Override
public HashMap construct(String query){
try {
HashSet hs = getColumns();
CountryRepository countryRepository = (CountryRepository) countryCrawler.getRepositoryInstance();
ResultSet rows = getStatement().executeQuery(query.replaceAll("repDate",repDate));
HashMap hm = new HashMap();
while(rows.next()){
HashMap tmp = new HashMap();
//System.out.println(rows.getString("NAME_RU"));
for(Object s: hs){
//System.out.println(s);
tmp.put((String)s,rows.getString((String)s));
}
Country country = countryRepository.getById((String)tmp.get("COUNTRY_ID"));
tmp.put("country",country);
Offshore dt = new Offshore(tmp);
hm.put(dt.get(dt.getKeyName()),dt);
}
return hm;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public Offshore[] getByProperty(String key,String value){
Offshore [] ret = new Offshore[0];
List<Offshore> list = new ArrayList<Offshore>();
for(Object v: getRepository().values()){
if(((Offshore) v).get(key) != null)
if(((Offshore) v).get(key).equals(value)) list.add((Offshore)v);
}
return list.toArray(ret);
}
public Offshore getById(String id){
return (Offshore) getRepository().get(id);
}
public void rc(){
repository = null;
}
}
| 3,102 | 0.60864 | 0.607995 | 81 | 37.271606 | 32.052044 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.654321 | false | false | 13 |
6b7c651f17923443be09225ec1c0069983854031 | 28,887,950,087,253 | d68c4f9deb05ebac3a18ec344b96d0a3827a8f83 | /hash-code/2019/practise/pizza/src/Pizza.java | 81d4a8d2d2262018b00da52f81beb907399f7f34 | [] | no_license | LaurenceRawlings/google-challenges | https://github.com/LaurenceRawlings/google-challenges | 342c89de60c561906f774d307c146e0b9bc9c0a7 | 3abc0a37aafcfd60c8dc99b69497f0368dcbb4f3 | refs/heads/master | 2023-05-01T06:46:09.061000 | 2021-05-11T16:55:14 | 2021-05-11T16:55:14 | 236,064,882 | 1 | 0 | null | false | 2021-02-04T18:40:43 | 2020-01-24T19:01:50 | 2021-02-01T15:27:16 | 2021-02-04T18:40:42 | 11,570 | 0 | 0 | 0 | Python | false | false | public class Pizza {
private int row;
private int column;
private int min;
private int max;
Pizza(int row, int column, int min, int max){
this.row = row;
this.column = column;
this.min = min;
this.max = max;
}
}
| UTF-8 | Java | 273 | java | Pizza.java | Java | [] | null | [] | public class Pizza {
private int row;
private int column;
private int min;
private int max;
Pizza(int row, int column, int min, int max){
this.row = row;
this.column = column;
this.min = min;
this.max = max;
}
}
| 273 | 0.545788 | 0.545788 | 16 | 16 | 13.435029 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6875 | false | false | 13 |
a418a5638f1c410257afc511d621043a356640a0 | 28,887,950,088,273 | c49e3def3d523ba6c41b436f47e7bb8563a2a479 | /2.SourceCode/api/gzr-internal-api/src/main/java/jp/co/gzr_internal/api/web/rest/errors/ErrorConstants.java | 7f123df29294b5b61372067f61d3692f822117ea | [] | no_license | NMQuang/GMO-Internal | https://github.com/NMQuang/GMO-Internal | 3f9230542d72ef876117eec1b450e71fb1924e45 | 8df57fb9513c74632281d836e4363aaa61214a77 | refs/heads/master | 2022-12-12T22:20:27.922000 | 2020-01-20T08:51:08 | 2020-01-20T08:51:15 | 235,054,499 | 0 | 0 | null | false | 2022-12-11T21:19:15 | 2020-01-20T08:37:07 | 2020-01-20T08:52:23 | 2022-12-11T21:19:14 | 3,893 | 0 | 0 | 38 | JavaScript | false | false | /*
* Seed's Lounge マッチングサイト
* COPYRIGHT(C) GMO-Z.com RUNSYSTEM
*
* Author: VuDA
* Creation Date : Apr 11, 2019
*/
package jp.co.gzr_internal.api.web.rest.errors;
import java.net.URI;
/**
* The Class ErrorConstants.
*/
public final class ErrorConstants {
/** The Constant ERR_CONCURRENCY_FAILURE. */
public static final String ERR_CONCURRENCY_FAILURE = "error.concurrencyFailure";
/** The Constant ERR_VALIDATION. */
public static final String ERR_VALIDATION = "error.validation";
/** The Constant PROBLEM_BASE_URL. */
public static final String PROBLEM_BASE_URL = "https://www.jhipster.tech/problem";
/** The Constant DEFAULT_TYPE. */
public static final URI DEFAULT_TYPE = URI.create(PROBLEM_BASE_URL + "/problem-with-message");
/** The Constant CONSTRAINT_VIOLATION_TYPE. */
public static final URI CONSTRAINT_VIOLATION_TYPE = URI.create(PROBLEM_BASE_URL + "/constraint-violation");
/** The Constant PARAMETERIZED_TYPE. */
public static final URI PARAMETERIZED_TYPE = URI.create(PROBLEM_BASE_URL + "/parameterized");
/** The Constant ENTITY_NOT_FOUND_TYPE. */
public static final URI ENTITY_NOT_FOUND_TYPE = URI.create(PROBLEM_BASE_URL + "/entity-not-found");
/** The Constant INVALID_PASSWORD_TYPE. */
public static final URI INVALID_PASSWORD_TYPE = URI.create(PROBLEM_BASE_URL + "/invalid-password");
/** The Constant EMAIL_ALREADY_USED_TYPE. */
public static final URI EMAIL_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/email-already-used");
/** The Constant LOGIN_ALREADY_USED_TYPE. */
public static final URI LOGIN_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/login-already-used");
/** The Constant EMAIL_NOT_FOUND_TYPE. */
public static final URI EMAIL_NOT_FOUND_TYPE = URI.create(PROBLEM_BASE_URL + "/email-not-found");
private ErrorConstants() {
}
}
| UTF-8 | Java | 1,952 | java | ErrorConstants.java | Java | [
{
"context": " * COPYRIGHT(C) GMO-Z.com RUNSYSTEM\n *\t\n * Author: VuDA\t\n * Creation Date : Apr 11, 2019\t\n */\npackage jp.",
"end": 85,
"score": 0.928584098815918,
"start": 81,
"tag": "USERNAME",
"value": "VuDA"
}
] | null | [] | /*
* Seed's Lounge マッチングサイト
* COPYRIGHT(C) GMO-Z.com RUNSYSTEM
*
* Author: VuDA
* Creation Date : Apr 11, 2019
*/
package jp.co.gzr_internal.api.web.rest.errors;
import java.net.URI;
/**
* The Class ErrorConstants.
*/
public final class ErrorConstants {
/** The Constant ERR_CONCURRENCY_FAILURE. */
public static final String ERR_CONCURRENCY_FAILURE = "error.concurrencyFailure";
/** The Constant ERR_VALIDATION. */
public static final String ERR_VALIDATION = "error.validation";
/** The Constant PROBLEM_BASE_URL. */
public static final String PROBLEM_BASE_URL = "https://www.jhipster.tech/problem";
/** The Constant DEFAULT_TYPE. */
public static final URI DEFAULT_TYPE = URI.create(PROBLEM_BASE_URL + "/problem-with-message");
/** The Constant CONSTRAINT_VIOLATION_TYPE. */
public static final URI CONSTRAINT_VIOLATION_TYPE = URI.create(PROBLEM_BASE_URL + "/constraint-violation");
/** The Constant PARAMETERIZED_TYPE. */
public static final URI PARAMETERIZED_TYPE = URI.create(PROBLEM_BASE_URL + "/parameterized");
/** The Constant ENTITY_NOT_FOUND_TYPE. */
public static final URI ENTITY_NOT_FOUND_TYPE = URI.create(PROBLEM_BASE_URL + "/entity-not-found");
/** The Constant INVALID_PASSWORD_TYPE. */
public static final URI INVALID_PASSWORD_TYPE = URI.create(PROBLEM_BASE_URL + "/invalid-password");
/** The Constant EMAIL_ALREADY_USED_TYPE. */
public static final URI EMAIL_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/email-already-used");
/** The Constant LOGIN_ALREADY_USED_TYPE. */
public static final URI LOGIN_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/login-already-used");
/** The Constant EMAIL_NOT_FOUND_TYPE. */
public static final URI EMAIL_NOT_FOUND_TYPE = URI.create(PROBLEM_BASE_URL + "/email-not-found");
private ErrorConstants() {
}
}
| 1,952 | 0.677686 | 0.674587 | 52 | 36.23077 | 35.975746 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.346154 | false | false | 13 |
117b81e114d521d55fdf546bde6131cc342e852f | 9,783,935,547,580 | 5a4164e4fd4e557e818e84749e4fe2553a5357b9 | /systemBiometric/src/main/java/co/edu/usbcali/logica/IUsuarioHuellaLogica.java | 17a0e0ecbb0107df0969fb6e751acdcc8e0ca681 | [] | no_license | takuratomi/SystemBiometric | https://github.com/takuratomi/SystemBiometric | f072738daff45d122b008b1376c9f3c7101dab60 | d4246bb8b3e22a538930b19d894dd3a06c9ff62c | refs/heads/master | 2020-03-22T05:52:33.783000 | 2018-07-03T14:38:48 | 2018-07-03T14:38:48 | 139,596,090 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package co.edu.usbcali.logica;
import java.util.List;
import co.edu.usbcali.modelo.UsuarioHuella;
public interface IUsuarioHuellaLogica {
public void crearUsuarioHuella(UsuarioHuella entity) throws Exception;
public void modificarUsuarioHuella(UsuarioHuella entity) throws Exception;
public void borrarUsuarioHuella(UsuarioHuella entity) throws Exception;
public UsuarioHuella consultarPorIdUsuarioHuella(Long id) throws Exception;
public List<UsuarioHuella> consultarTodosUsuarioHuella() throws Exception;
}
| UTF-8 | Java | 537 | java | IUsuarioHuellaLogica.java | Java | [] | null | [] | package co.edu.usbcali.logica;
import java.util.List;
import co.edu.usbcali.modelo.UsuarioHuella;
public interface IUsuarioHuellaLogica {
public void crearUsuarioHuella(UsuarioHuella entity) throws Exception;
public void modificarUsuarioHuella(UsuarioHuella entity) throws Exception;
public void borrarUsuarioHuella(UsuarioHuella entity) throws Exception;
public UsuarioHuella consultarPorIdUsuarioHuella(Long id) throws Exception;
public List<UsuarioHuella> consultarTodosUsuarioHuella() throws Exception;
}
| 537 | 0.815642 | 0.815642 | 16 | 31.5625 | 31.689842 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.875 | false | false | 13 |
f8280e9b5fb65fa790403b162324fa38baa295f6 | 11,235,634,451,003 | ed8f9252934c5014dcb721ad2f28fe3f81e6d00c | /Break_Game/src/interfaces/HitNotifier.java | f169b6091206bbcae4b4840e93978e207d565602 | [] | no_license | danielkag2000/Break_Game | https://github.com/danielkag2000/Break_Game | 42cd154f03653e2ee708b438a684ef437a3bec93 | 4480b71bf1d9d7e10a1874ed025746094e1504bb | refs/heads/master | 2020-05-03T05:00:38.786000 | 2019-03-29T16:14:26 | 2019-03-29T16:14:26 | 178,437,871 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package interfaces;
/**
* Notifier of hitting a block from the action to be performed
* when a block is hit.
*
* @author Daniel Kaganovich
* @version 1.0
* @since 2018-05-13
*/
public interface HitNotifier {
/**
* Add hl as a listener to hit events.
*
* @param hl the HitListener
*/
void addHitListener(HitListener hl);
/**
* Remove hl from the list of listeners to hit events.
*
* @param hl the HitListener
*/
void removeHitListener(HitListener hl);
}
| UTF-8 | Java | 520 | java | HitNotifier.java | Java | [
{
"context": "be performed\n * when a block is hit.\n *\n * @author Daniel Kaganovich\n * @version 1.0\n * @since 2018-05-13\n */\npublic i",
"end": 144,
"score": 0.999875545501709,
"start": 127,
"tag": "NAME",
"value": "Daniel Kaganovich"
}
] | null | [] | package interfaces;
/**
* Notifier of hitting a block from the action to be performed
* when a block is hit.
*
* @author <NAME>
* @version 1.0
* @since 2018-05-13
*/
public interface HitNotifier {
/**
* Add hl as a listener to hit events.
*
* @param hl the HitListener
*/
void addHitListener(HitListener hl);
/**
* Remove hl from the list of listeners to hit events.
*
* @param hl the HitListener
*/
void removeHitListener(HitListener hl);
}
| 509 | 0.626923 | 0.607692 | 26 | 19 | 18.290392 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.115385 | false | false | 13 |
2a412541f5244a551eef6ce4b8e979a60cf72593 | 3,272,765,124,662 | 5c87f8ef638a78bed64e32a6a4a8f6c952f720f6 | /PDA/src/FileCutter.java | 4d1b97b1a753b31dac7b1eaf1823d5f17b0e758d | [] | no_license | gill-gemini/Synchronize-Directory-using-Chunk-File-Transfer | https://github.com/gill-gemini/Synchronize-Directory-using-Chunk-File-Transfer | e774ba2bc5e9626ed6be63cdb295de070ea4dc6c | e602ee903425385088294540eb927d18d6352333 | refs/heads/master | 2016-09-05T14:32:09.301000 | 2016-02-02T19:11:46 | 2016-02-02T19:11:46 | 26,106,691 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import org.apache.log4j.Logger;
import stack.Utils;
public class FileCutter {
private static Logger logger = Logger.getLogger(FileCutter.class);
static final int NumberOfChunksPerSession = 500;
static final int NumberOfBytesPerChunk = 1000;
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String filePath = args[0];
File file = new File(filePath);
long fileSize = file.length();
long numOfChunks = ((fileSize-1)/NumberOfBytesPerChunk) + 1;
long numOfSessions = ((numOfChunks-1) / NumberOfChunksPerSession) + 1;
int chunksInLastSession = (int) (numOfChunks % NumberOfChunksPerSession);
for (int i = 1; i <= numOfSessions; i++) {
long startingChunkId = (i - 1) * NumberOfChunksPerSession + 1;
long endingChunkId = i * NumberOfChunksPerSession;
if (i == numOfSessions) {
endingChunkId = startingChunkId + chunksInLastSession -1;
}
// retrieve the chunks from the peer Host and save it in local dir
// with some temporary file name
// create a name for this temporary file
String partFileName = filePath + ".cft_"+"part_"+i;
logger.debug("creating " +partFileName );
createChunk(file, startingChunkId, endingChunkId, partFileName);
}
mergeFile(file.getParent(), file.getName(), numOfSessions);
}
private static int createChunk(File file, long startingChunkId, long endingChunkId,
String partFileName) throws IOException {
File newFile = new File(partFileName);
newFile.createNewFile();
FileOutputStream fout = new FileOutputStream(newFile);
RandomAccessFile fileAccess = new RandomAccessFile(file, "r");
byte[] chunkBuffer = new byte[NumberOfBytesPerChunk];
long startingOffset = (startingChunkId - 1)
* NumberOfBytesPerChunk;
// move file pointer to the right position;
fileAccess.seek(startingOffset);
for (long chunkID = startingChunkId; chunkID < endingChunkId; chunkID++) {
fileAccess.readFully(chunkBuffer);
fout.write(chunkBuffer);
}
// deal with the last Chunk in this range, which maybe smaller than
// NumberOfBytesPerChunk
long numOfChunks = ((file.length() - 1) / NumberOfBytesPerChunk) + 1;
if (endingChunkId < numOfChunks) {
fileAccess.readFully(chunkBuffer);
fout.write(chunkBuffer);
} else {
long num2bRead = file.length() - fileAccess.getFilePointer() ;
byte[] lastChunk = new byte[(int) num2bRead];
logger.debug("last chunk size is: "+ lastChunk.length);
fileAccess.readFully(lastChunk);
fout.write(lastChunk);
}
fileAccess.close();
fout.close();
return 0;
}
public static void mergeFile(String localDir, String fileName, long numOfSessions) throws IOException {
// now collecting all the different "part files" and concatenate them together
File finalFile = new File(localDir, "final_"+fileName);
if (finalFile.exists()) {
if (false == finalFile.delete()) {
logger.error("cann't delete local file " + finalFile.getName());
}
}
for (int i = 1; i <= numOfSessions; i++) {
String partFileName = fileName + ".cft_"+"part_"+i;
File partFile = new File(localDir, partFileName);
Utils.concatFile(finalFile, partFile);
// partFile.delete();
}
}
}
| UTF-8 | Java | 3,468 | java | FileCutter.java | Java | [] | null | [] | import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import org.apache.log4j.Logger;
import stack.Utils;
public class FileCutter {
private static Logger logger = Logger.getLogger(FileCutter.class);
static final int NumberOfChunksPerSession = 500;
static final int NumberOfBytesPerChunk = 1000;
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String filePath = args[0];
File file = new File(filePath);
long fileSize = file.length();
long numOfChunks = ((fileSize-1)/NumberOfBytesPerChunk) + 1;
long numOfSessions = ((numOfChunks-1) / NumberOfChunksPerSession) + 1;
int chunksInLastSession = (int) (numOfChunks % NumberOfChunksPerSession);
for (int i = 1; i <= numOfSessions; i++) {
long startingChunkId = (i - 1) * NumberOfChunksPerSession + 1;
long endingChunkId = i * NumberOfChunksPerSession;
if (i == numOfSessions) {
endingChunkId = startingChunkId + chunksInLastSession -1;
}
// retrieve the chunks from the peer Host and save it in local dir
// with some temporary file name
// create a name for this temporary file
String partFileName = filePath + ".cft_"+"part_"+i;
logger.debug("creating " +partFileName );
createChunk(file, startingChunkId, endingChunkId, partFileName);
}
mergeFile(file.getParent(), file.getName(), numOfSessions);
}
private static int createChunk(File file, long startingChunkId, long endingChunkId,
String partFileName) throws IOException {
File newFile = new File(partFileName);
newFile.createNewFile();
FileOutputStream fout = new FileOutputStream(newFile);
RandomAccessFile fileAccess = new RandomAccessFile(file, "r");
byte[] chunkBuffer = new byte[NumberOfBytesPerChunk];
long startingOffset = (startingChunkId - 1)
* NumberOfBytesPerChunk;
// move file pointer to the right position;
fileAccess.seek(startingOffset);
for (long chunkID = startingChunkId; chunkID < endingChunkId; chunkID++) {
fileAccess.readFully(chunkBuffer);
fout.write(chunkBuffer);
}
// deal with the last Chunk in this range, which maybe smaller than
// NumberOfBytesPerChunk
long numOfChunks = ((file.length() - 1) / NumberOfBytesPerChunk) + 1;
if (endingChunkId < numOfChunks) {
fileAccess.readFully(chunkBuffer);
fout.write(chunkBuffer);
} else {
long num2bRead = file.length() - fileAccess.getFilePointer() ;
byte[] lastChunk = new byte[(int) num2bRead];
logger.debug("last chunk size is: "+ lastChunk.length);
fileAccess.readFully(lastChunk);
fout.write(lastChunk);
}
fileAccess.close();
fout.close();
return 0;
}
public static void mergeFile(String localDir, String fileName, long numOfSessions) throws IOException {
// now collecting all the different "part files" and concatenate them together
File finalFile = new File(localDir, "final_"+fileName);
if (finalFile.exists()) {
if (false == finalFile.delete()) {
logger.error("cann't delete local file " + finalFile.getName());
}
}
for (int i = 1; i <= numOfSessions; i++) {
String partFileName = fileName + ".cft_"+"part_"+i;
File partFile = new File(localDir, partFileName);
Utils.concatFile(finalFile, partFile);
// partFile.delete();
}
}
}
| 3,468 | 0.683968 | 0.677047 | 116 | 27.896551 | 26.161758 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.258621 | false | false | 13 |
8a385191d47cdc410578f3f045d4253153e34c76 | 30,425,548,375,295 | 3860d0272a248a05e74e9b3703243dc5cafc2803 | /application/src/test/java/io/protone/application/web/api/traffic/TraPlaylistResourceImplTest.java | 7954e26f8f66bfd1fc1db4960d3465e0f386941b | [] | no_license | lukaszozimek/radio-system | https://github.com/lukaszozimek/radio-system | 1ef0456fa41411ce0d91d12cf0ff32318c63c242 | a29504723505a8fe21d47e0b592fc14853c6e6e4 | refs/heads/master | 2023-01-11T00:28:25.576000 | 2019-07-28T13:04:30 | 2019-07-28T13:04:30 | 199,288,287 | 0 | 2 | null | false | 2022-12-27T14:50:13 | 2019-07-28T13:05:39 | 2019-11-11T10:15:56 | 2022-12-27T14:50:10 | 76,738 | 0 | 2 | 6 | Java | false | false | package io.protone.application.web.api.traffic;
import com.google.common.collect.Lists;
import io.protone.application.ProtoneApp;
import io.protone.application.util.TestUtil;
import io.protone.application.web.api.cor.CorNetworkResourceIntTest;
import io.protone.application.web.api.traffic.impl.TraPlaylistResourceImpl;
import io.protone.application.web.rest.errors.ExceptionTranslator;
import io.protone.core.domain.CorChannel;
import io.protone.core.domain.CorNetwork;
import io.protone.core.service.CorChannelService;
import io.protone.core.service.CorNetworkService;
import io.protone.traffic.api.dto.TraPlaylistDTO;
import io.protone.traffic.domain.TraBlock;
import io.protone.traffic.domain.TraEmission;
import io.protone.traffic.domain.TraPlaylist;
import io.protone.traffic.mapper.TraPlaylistMapper;
import io.protone.traffic.repository.TraPlaylistRepository;
import io.protone.traffic.service.TraPlaylistService;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.notNullValue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Created by lukaszozimek on 15/05/2017.
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ProtoneApp.class)
public class TraPlaylistResourceImplTest {
private static final LocalDate DEFAULT_PLAYLIST_DATE = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_PLAYLIST_DATE = LocalDate.now(ZoneId.systemDefault());
@Autowired
private TraPlaylistRepository traPlaylistRepository;
@Autowired
private TraPlaylistService traPlaylistService;
@Autowired
private TraPlaylistMapper traPlaylistMapper;
@Autowired
private CorChannelService corChannelService;
@Autowired
private CorNetworkService corNetworkService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restTraPlaylistMockMvc;
private TraPlaylist traPlaylist;
private CorNetwork corNetwork;
private CorChannel corChannel;
/**
* Create an entity for this test.
* <p>
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static TraPlaylist createEntity(EntityManager em) {
TraPlaylist traPlaylist = new TraPlaylist()
.playlistDate(DEFAULT_PLAYLIST_DATE);
return traPlaylist;
}
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
TraPlaylistResourceImpl traPlaylistResource = new TraPlaylistResourceImpl();
ReflectionTestUtils.setField(traPlaylistResource, "traPlaylistService", traPlaylistService);
ReflectionTestUtils.setField(traPlaylistResource, "traPlaylistMapper", traPlaylistMapper);
ReflectionTestUtils.setField(traPlaylistResource, "corNetworkService", corNetworkService);
ReflectionTestUtils.setField(traPlaylistResource, "corChannelService", corChannelService);
this.restTraPlaylistMockMvc = MockMvcBuilders.standaloneSetup(traPlaylistResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter).build();
}
@Before
public void initTest() {
corNetwork = new CorNetwork().shortcut(CorNetworkResourceIntTest.TEST_NETWORK);
corNetwork.setId(1L);
corChannel = new CorChannel().shortcut("tes");
corChannel.setId(1L);
traPlaylist = createEntity(em).network(corNetwork).channel(corChannel);
}
@Test
@Transactional
public void createTraPlaylist() throws Exception {
int databaseSizeBeforeCreate = traPlaylistRepository.findAll().size();
// Create the TraPlaylist
TraPlaylistDTO traPlaylistDTO = traPlaylistMapper.DB2DTO(traPlaylist);
restTraPlaylistMockMvc.perform(post("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist", corNetwork.getShortcut(), corChannel.getShortcut())
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(traPlaylistDTO)))
.andExpect(status().isCreated());
// Validate the TraPlaylist in the database
List<TraPlaylist> traPlaylistList = traPlaylistRepository.findAll();
assertThat(traPlaylistList).hasSize(databaseSizeBeforeCreate + 1);
TraPlaylist testTraPlaylist = traPlaylistList.get(traPlaylistList.size() - 1);
assertThat(testTraPlaylist.getPlaylistDate()).isEqualTo(DEFAULT_PLAYLIST_DATE);
}
@Test
@Transactional
public void createBatchTraPlaylist() throws Exception {
int databaseSizeBeforeCreate = traPlaylistRepository.findAll().size();
TraPlaylist traPlaylist1 = createEntity(em).network(corNetwork).channel(corChannel);
traPlaylist1.playlistDate(LocalDate.now().plusMonths(1));
// Create the TraPlaylist
List<TraPlaylistDTO> traPlaylistDTOS = traPlaylistMapper.DBs2DTOs(Lists.newArrayList(traPlaylist, traPlaylist1));
restTraPlaylistMockMvc.perform(post("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist/batch", corNetwork.getShortcut(), corChannel.getShortcut())
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(traPlaylistDTOS)))
.andExpect(status().isCreated());
// Validate the TraPlaylist in the database
List<TraPlaylist> traPlaylistList = traPlaylistRepository.findAll();
assertThat(traPlaylistList).hasSize(databaseSizeBeforeCreate + 2);
}
@Test
@Transactional
public void createTraPlaylistWithExistingId() throws Exception {
int databaseSizeBeforeCreate = traPlaylistRepository.findAll().size();
// Create the TraPlaylist with an existing ID
TraPlaylist existingTraPlaylist = new TraPlaylist();
existingTraPlaylist.setId(1L);
TraPlaylistDTO existingTraPlaylistDTO = traPlaylistMapper.DB2DTO(existingTraPlaylist);
// An entity with an existing ID cannot be created, so this API call must fail
restTraPlaylistMockMvc.perform(post("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist", corNetwork.getShortcut(), corChannel.getShortcut())
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(existingTraPlaylistDTO)))
.andExpect(status().isBadRequest());
// Validate the Alice in the database
List<TraPlaylist> traPlaylistList = traPlaylistRepository.findAll();
assertThat(traPlaylistList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllTraPlaylists() throws Exception {
// Initialize the database
traPlaylistRepository.saveAndFlush(traPlaylist.network(corNetwork).channel(corChannel));
// Get all the traPlaylistList
restTraPlaylistMockMvc.perform(get("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist?sort=id,desc", corNetwork.getShortcut(), corChannel.getShortcut()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(traPlaylist.getId().intValue())))
.andExpect(jsonPath("$.[*].playlistDate").value(hasItem(DEFAULT_PLAYLIST_DATE.toString())));
}
@Test
@Transactional
public void getTraPlaylist() throws Exception {
// Initialize the database
traPlaylistRepository.saveAndFlush(traPlaylist.network(corNetwork).channel(corChannel));
// Get the traPlaylist
restTraPlaylistMockMvc.perform(get("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist/{date}", corNetwork.getShortcut(), corChannel.getShortcut(), DEFAULT_PLAYLIST_DATE))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(traPlaylist.getId().intValue()))
.andExpect(jsonPath("$.playlistDate").value(DEFAULT_PLAYLIST_DATE.toString()));
}
@Test
@Transactional
public void getNonExistingTraPlaylist() throws Exception {
// Get the traPlaylist
LocalDate localDate = LocalDate.now();
restTraPlaylistMockMvc.perform(get("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist/{date}", corNetwork.getShortcut(), corChannel.getShortcut(), localDate))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(notNullValue()))
.andExpect(jsonPath("$.playlistDate").value(localDate.toString()));
}
@Test
@Transactional
public void updateTraPlaylist() throws Exception {
// Initialize the database
traPlaylistRepository.saveAndFlush(traPlaylist.network(corNetwork).channel(corChannel));
int databaseSizeBeforeUpdate = traPlaylistRepository.findAll().size();
// Update the traPlaylist
TraPlaylist updatedTraPlaylist = traPlaylistRepository.findOne(traPlaylist.getId());
updatedTraPlaylist
.playlistDate(UPDATED_PLAYLIST_DATE);
TraPlaylistDTO traPlaylistDTO = traPlaylistMapper.DB2DTO(updatedTraPlaylist);
restTraPlaylistMockMvc.perform(put("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist", corNetwork.getShortcut(), corChannel.getShortcut())
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(traPlaylistDTO)))
.andExpect(status().isOk());
// Validate the TraPlaylist in the database
List<TraPlaylist> traPlaylistList = traPlaylistRepository.findAll();
assertThat(traPlaylistList).hasSize(databaseSizeBeforeUpdate);
TraPlaylist testTraPlaylist = traPlaylistList.get(traPlaylistList.size() - 1);
assertThat(testTraPlaylist.getPlaylistDate()).isEqualTo(UPDATED_PLAYLIST_DATE);
}
@Test
@Transactional
public void updateNonExistingTraPlaylist() throws Exception {
int databaseSizeBeforeUpdate = traPlaylistRepository.findAll().size();
// Create the TraPlaylist
TraPlaylistDTO traPlaylistDTO = traPlaylistMapper.DB2DTO(traPlaylist);
// If the entity doesn't have an ID, it will be created instead of just being updated
restTraPlaylistMockMvc.perform(put("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist", corNetwork.getShortcut(), corChannel.getShortcut())
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(traPlaylistDTO)))
.andExpect(status().isCreated());
// Validate the TraPlaylist in the database
List<TraPlaylist> traPlaylistList = traPlaylistRepository.findAll();
assertThat(traPlaylistList).hasSize(databaseSizeBeforeUpdate + 1);
}
@Test
@Transactional
public void deleteTraPlaylist() throws Exception {
// Initialize the database
traPlaylistRepository.saveAndFlush(traPlaylist.network(corNetwork).channel(corChannel));
int databaseSizeBeforeDelete = traPlaylistRepository.findAll().size();
// Get the traPlaylist
restTraPlaylistMockMvc.perform(delete("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist/{date}", corNetwork.getShortcut(), corChannel.getShortcut(), DEFAULT_PLAYLIST_DATE)
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<TraPlaylist> traPlaylistList = traPlaylistRepository.findAll();
assertThat(traPlaylistList).hasSize(databaseSizeBeforeDelete - 1);
}
@Ignore(value = "Should be fixed couse expception ind DI")
@Transactional
public void shouldDownloadTraPlaylist() throws Exception {
// Initialize the database
traPlaylistService.savePlaylist(traPlaylist.network(corNetwork).channel(corChannel).addPlaylists(new TraBlock().channel(corChannel).network(corNetwork).addEmissions(new TraEmission().timeStart(1L).timeStop(2L))));
String csvFileName = DEFAULT_PLAYLIST_DATE + ".csv";
// Get the traPlaylist
restTraPlaylistMockMvc.perform(get("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist/{date}/download", corNetwork.getShortcut(), corChannel.getShortcut(), DEFAULT_PLAYLIST_DATE)
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(content().contentType("text/csv"))
.andExpect(header().string("Content-Disposition", String.format("attachment; filename=\"%s\"",
csvFileName)));
// Validate the database is empty
}
@Test
@Transactional
public void checkDateIsRequired() throws Exception {
traPlaylist = createEntity(em).network(corNetwork).channel(corChannel);
int databaseSizeBeforeTest = traPlaylistRepository.findAll().size();
// set the field null
traPlaylist.setPlaylistDate(null);
// Create the TraOrder, which fails.
TraPlaylistDTO traOrderDTO = traPlaylistMapper.DB2DTO(traPlaylist);
restTraPlaylistMockMvc.perform(post("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist", corNetwork.getShortcut(), corChannel.getShortcut())
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(traOrderDTO)))
.andExpect(status().isBadRequest());
List<TraPlaylist> traOrderList = traPlaylistRepository.findAll();
assertThat(traOrderList).hasSize(databaseSizeBeforeTest);
}
@Test
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(TraPlaylist.class);
}
}
| UTF-8 | Java | 15,314 | java | TraPlaylistResourceImplTest.java | Java | [
{
"context": "result.MockMvcResultMatchers.*;\n\n/**\n * Created by lukaszozimek on 15/05/2017.\n */\n@RunWith(SpringRunner.class)\n@",
"end": 2168,
"score": 0.9995072484016418,
"start": 2156,
"tag": "USERNAME",
"value": "lukaszozimek"
}
] | null | [] | package io.protone.application.web.api.traffic;
import com.google.common.collect.Lists;
import io.protone.application.ProtoneApp;
import io.protone.application.util.TestUtil;
import io.protone.application.web.api.cor.CorNetworkResourceIntTest;
import io.protone.application.web.api.traffic.impl.TraPlaylistResourceImpl;
import io.protone.application.web.rest.errors.ExceptionTranslator;
import io.protone.core.domain.CorChannel;
import io.protone.core.domain.CorNetwork;
import io.protone.core.service.CorChannelService;
import io.protone.core.service.CorNetworkService;
import io.protone.traffic.api.dto.TraPlaylistDTO;
import io.protone.traffic.domain.TraBlock;
import io.protone.traffic.domain.TraEmission;
import io.protone.traffic.domain.TraPlaylist;
import io.protone.traffic.mapper.TraPlaylistMapper;
import io.protone.traffic.repository.TraPlaylistRepository;
import io.protone.traffic.service.TraPlaylistService;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.notNullValue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Created by lukaszozimek on 15/05/2017.
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ProtoneApp.class)
public class TraPlaylistResourceImplTest {
private static final LocalDate DEFAULT_PLAYLIST_DATE = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_PLAYLIST_DATE = LocalDate.now(ZoneId.systemDefault());
@Autowired
private TraPlaylistRepository traPlaylistRepository;
@Autowired
private TraPlaylistService traPlaylistService;
@Autowired
private TraPlaylistMapper traPlaylistMapper;
@Autowired
private CorChannelService corChannelService;
@Autowired
private CorNetworkService corNetworkService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restTraPlaylistMockMvc;
private TraPlaylist traPlaylist;
private CorNetwork corNetwork;
private CorChannel corChannel;
/**
* Create an entity for this test.
* <p>
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static TraPlaylist createEntity(EntityManager em) {
TraPlaylist traPlaylist = new TraPlaylist()
.playlistDate(DEFAULT_PLAYLIST_DATE);
return traPlaylist;
}
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
TraPlaylistResourceImpl traPlaylistResource = new TraPlaylistResourceImpl();
ReflectionTestUtils.setField(traPlaylistResource, "traPlaylistService", traPlaylistService);
ReflectionTestUtils.setField(traPlaylistResource, "traPlaylistMapper", traPlaylistMapper);
ReflectionTestUtils.setField(traPlaylistResource, "corNetworkService", corNetworkService);
ReflectionTestUtils.setField(traPlaylistResource, "corChannelService", corChannelService);
this.restTraPlaylistMockMvc = MockMvcBuilders.standaloneSetup(traPlaylistResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter).build();
}
@Before
public void initTest() {
corNetwork = new CorNetwork().shortcut(CorNetworkResourceIntTest.TEST_NETWORK);
corNetwork.setId(1L);
corChannel = new CorChannel().shortcut("tes");
corChannel.setId(1L);
traPlaylist = createEntity(em).network(corNetwork).channel(corChannel);
}
@Test
@Transactional
public void createTraPlaylist() throws Exception {
int databaseSizeBeforeCreate = traPlaylistRepository.findAll().size();
// Create the TraPlaylist
TraPlaylistDTO traPlaylistDTO = traPlaylistMapper.DB2DTO(traPlaylist);
restTraPlaylistMockMvc.perform(post("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist", corNetwork.getShortcut(), corChannel.getShortcut())
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(traPlaylistDTO)))
.andExpect(status().isCreated());
// Validate the TraPlaylist in the database
List<TraPlaylist> traPlaylistList = traPlaylistRepository.findAll();
assertThat(traPlaylistList).hasSize(databaseSizeBeforeCreate + 1);
TraPlaylist testTraPlaylist = traPlaylistList.get(traPlaylistList.size() - 1);
assertThat(testTraPlaylist.getPlaylistDate()).isEqualTo(DEFAULT_PLAYLIST_DATE);
}
@Test
@Transactional
public void createBatchTraPlaylist() throws Exception {
int databaseSizeBeforeCreate = traPlaylistRepository.findAll().size();
TraPlaylist traPlaylist1 = createEntity(em).network(corNetwork).channel(corChannel);
traPlaylist1.playlistDate(LocalDate.now().plusMonths(1));
// Create the TraPlaylist
List<TraPlaylistDTO> traPlaylistDTOS = traPlaylistMapper.DBs2DTOs(Lists.newArrayList(traPlaylist, traPlaylist1));
restTraPlaylistMockMvc.perform(post("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist/batch", corNetwork.getShortcut(), corChannel.getShortcut())
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(traPlaylistDTOS)))
.andExpect(status().isCreated());
// Validate the TraPlaylist in the database
List<TraPlaylist> traPlaylistList = traPlaylistRepository.findAll();
assertThat(traPlaylistList).hasSize(databaseSizeBeforeCreate + 2);
}
@Test
@Transactional
public void createTraPlaylistWithExistingId() throws Exception {
int databaseSizeBeforeCreate = traPlaylistRepository.findAll().size();
// Create the TraPlaylist with an existing ID
TraPlaylist existingTraPlaylist = new TraPlaylist();
existingTraPlaylist.setId(1L);
TraPlaylistDTO existingTraPlaylistDTO = traPlaylistMapper.DB2DTO(existingTraPlaylist);
// An entity with an existing ID cannot be created, so this API call must fail
restTraPlaylistMockMvc.perform(post("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist", corNetwork.getShortcut(), corChannel.getShortcut())
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(existingTraPlaylistDTO)))
.andExpect(status().isBadRequest());
// Validate the Alice in the database
List<TraPlaylist> traPlaylistList = traPlaylistRepository.findAll();
assertThat(traPlaylistList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllTraPlaylists() throws Exception {
// Initialize the database
traPlaylistRepository.saveAndFlush(traPlaylist.network(corNetwork).channel(corChannel));
// Get all the traPlaylistList
restTraPlaylistMockMvc.perform(get("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist?sort=id,desc", corNetwork.getShortcut(), corChannel.getShortcut()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(traPlaylist.getId().intValue())))
.andExpect(jsonPath("$.[*].playlistDate").value(hasItem(DEFAULT_PLAYLIST_DATE.toString())));
}
@Test
@Transactional
public void getTraPlaylist() throws Exception {
// Initialize the database
traPlaylistRepository.saveAndFlush(traPlaylist.network(corNetwork).channel(corChannel));
// Get the traPlaylist
restTraPlaylistMockMvc.perform(get("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist/{date}", corNetwork.getShortcut(), corChannel.getShortcut(), DEFAULT_PLAYLIST_DATE))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(traPlaylist.getId().intValue()))
.andExpect(jsonPath("$.playlistDate").value(DEFAULT_PLAYLIST_DATE.toString()));
}
@Test
@Transactional
public void getNonExistingTraPlaylist() throws Exception {
// Get the traPlaylist
LocalDate localDate = LocalDate.now();
restTraPlaylistMockMvc.perform(get("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist/{date}", corNetwork.getShortcut(), corChannel.getShortcut(), localDate))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(notNullValue()))
.andExpect(jsonPath("$.playlistDate").value(localDate.toString()));
}
@Test
@Transactional
public void updateTraPlaylist() throws Exception {
// Initialize the database
traPlaylistRepository.saveAndFlush(traPlaylist.network(corNetwork).channel(corChannel));
int databaseSizeBeforeUpdate = traPlaylistRepository.findAll().size();
// Update the traPlaylist
TraPlaylist updatedTraPlaylist = traPlaylistRepository.findOne(traPlaylist.getId());
updatedTraPlaylist
.playlistDate(UPDATED_PLAYLIST_DATE);
TraPlaylistDTO traPlaylistDTO = traPlaylistMapper.DB2DTO(updatedTraPlaylist);
restTraPlaylistMockMvc.perform(put("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist", corNetwork.getShortcut(), corChannel.getShortcut())
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(traPlaylistDTO)))
.andExpect(status().isOk());
// Validate the TraPlaylist in the database
List<TraPlaylist> traPlaylistList = traPlaylistRepository.findAll();
assertThat(traPlaylistList).hasSize(databaseSizeBeforeUpdate);
TraPlaylist testTraPlaylist = traPlaylistList.get(traPlaylistList.size() - 1);
assertThat(testTraPlaylist.getPlaylistDate()).isEqualTo(UPDATED_PLAYLIST_DATE);
}
@Test
@Transactional
public void updateNonExistingTraPlaylist() throws Exception {
int databaseSizeBeforeUpdate = traPlaylistRepository.findAll().size();
// Create the TraPlaylist
TraPlaylistDTO traPlaylistDTO = traPlaylistMapper.DB2DTO(traPlaylist);
// If the entity doesn't have an ID, it will be created instead of just being updated
restTraPlaylistMockMvc.perform(put("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist", corNetwork.getShortcut(), corChannel.getShortcut())
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(traPlaylistDTO)))
.andExpect(status().isCreated());
// Validate the TraPlaylist in the database
List<TraPlaylist> traPlaylistList = traPlaylistRepository.findAll();
assertThat(traPlaylistList).hasSize(databaseSizeBeforeUpdate + 1);
}
@Test
@Transactional
public void deleteTraPlaylist() throws Exception {
// Initialize the database
traPlaylistRepository.saveAndFlush(traPlaylist.network(corNetwork).channel(corChannel));
int databaseSizeBeforeDelete = traPlaylistRepository.findAll().size();
// Get the traPlaylist
restTraPlaylistMockMvc.perform(delete("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist/{date}", corNetwork.getShortcut(), corChannel.getShortcut(), DEFAULT_PLAYLIST_DATE)
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<TraPlaylist> traPlaylistList = traPlaylistRepository.findAll();
assertThat(traPlaylistList).hasSize(databaseSizeBeforeDelete - 1);
}
@Ignore(value = "Should be fixed couse expception ind DI")
@Transactional
public void shouldDownloadTraPlaylist() throws Exception {
// Initialize the database
traPlaylistService.savePlaylist(traPlaylist.network(corNetwork).channel(corChannel).addPlaylists(new TraBlock().channel(corChannel).network(corNetwork).addEmissions(new TraEmission().timeStart(1L).timeStop(2L))));
String csvFileName = DEFAULT_PLAYLIST_DATE + ".csv";
// Get the traPlaylist
restTraPlaylistMockMvc.perform(get("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist/{date}/download", corNetwork.getShortcut(), corChannel.getShortcut(), DEFAULT_PLAYLIST_DATE)
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(content().contentType("text/csv"))
.andExpect(header().string("Content-Disposition", String.format("attachment; filename=\"%s\"",
csvFileName)));
// Validate the database is empty
}
@Test
@Transactional
public void checkDateIsRequired() throws Exception {
traPlaylist = createEntity(em).network(corNetwork).channel(corChannel);
int databaseSizeBeforeTest = traPlaylistRepository.findAll().size();
// set the field null
traPlaylist.setPlaylistDate(null);
// Create the TraOrder, which fails.
TraPlaylistDTO traOrderDTO = traPlaylistMapper.DB2DTO(traPlaylist);
restTraPlaylistMockMvc.perform(post("/api/v1/network/{networkShortcut}/channel/{channelShortcut}/traffic/playlist", corNetwork.getShortcut(), corChannel.getShortcut())
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(traOrderDTO)))
.andExpect(status().isBadRequest());
List<TraPlaylist> traOrderList = traPlaylistRepository.findAll();
assertThat(traOrderList).hasSize(databaseSizeBeforeTest);
}
@Test
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(TraPlaylist.class);
}
}
| 15,314 | 0.735863 | 0.732336 | 337 | 44.442135 | 41.56776 | 221 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.513353 | false | false | 13 |
c0f85566fdcb050c135d5d098fb1ad743628e635 | 6,579,889,929,892 | 2a67877f0ddac9afd26213fb60b0e4e81ca4b8b1 | /Java/CacheDemo/src/main/java/cn/haixiao/cache/UserCache.java | 1c132aeaf29e903e299c7f1734363cbb6cdd7596 | [
"Apache-2.0"
] | permissive | dabaosod011/Practise | https://github.com/dabaosod011/Practise | 4d7ac5624449bdd123448619318e697b527357ac | aa1d3c9665156f8cbf17d074e6188f6818fc23ae | refs/heads/master | 2021-08-28T17:33:25.064000 | 2021-08-07T07:04:43 | 2021-08-07T07:04:43 | 49,036,908 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.haixiao.cache;
import cn.haixiao.bean.User;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class UserCache {
private Map<String, User> userMap;
//// singleton
private static UserCache ourInstance = new UserCache();
public static UserCache getInstance() {
return ourInstance;
}
private UserCache() {
userMap = new ConcurrentHashMap<String, User>();
}
//////
public void put(String key, User value) {
userMap.put(key, value);
}
public User get(Object key) {
return userMap.get(key);
}
}
| UTF-8 | Java | 573 | java | UserCache.java | Java | [] | null | [] | package cn.haixiao.cache;
import cn.haixiao.bean.User;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class UserCache {
private Map<String, User> userMap;
//// singleton
private static UserCache ourInstance = new UserCache();
public static UserCache getInstance() {
return ourInstance;
}
private UserCache() {
userMap = new ConcurrentHashMap<String, User>();
}
//////
public void put(String key, User value) {
userMap.put(key, value);
}
public User get(Object key) {
return userMap.get(key);
}
}
| 573 | 0.689354 | 0.689354 | 30 | 18.1 | 17.735746 | 57 | true | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false | 13 |
518139c75d7e84686aeef553d23ff010876a1605 | 30,915,174,630,101 | d07a4cdbe45062b6706d923c8afe4192e2bb7118 | /src/main/java/cz/cuni/mff/respefo/function/ew/MeasureEWResultPointCategory.java | 5af84fcf01eabeb4fbac1f8e843e30544949d76b | [] | no_license | harmanea/reSpefo2 | https://github.com/harmanea/reSpefo2 | 21664969b3169d1e8dacdf1b231c31d969c4aff6 | 8b6297a25953ce269cab4e745cd7b7de92fd57ef | refs/heads/master | 2023-07-20T02:36:33.729000 | 2023-07-09T08:40:31 | 2023-07-09T08:40:31 | 216,344,838 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cz.cuni.mff.respefo.function.ew;
public enum MeasureEWResultPointCategory {
Ic,
V,
R
}
| UTF-8 | Java | 108 | java | MeasureEWResultPointCategory.java | Java | [] | null | [] | package cz.cuni.mff.respefo.function.ew;
public enum MeasureEWResultPointCategory {
Ic,
V,
R
}
| 108 | 0.694444 | 0.694444 | 7 | 14.428572 | 16.977777 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 13 |
7db606df1a1c44fa574f03fdb1578b8f9bc59474 | 16,664,473,147,446 | de12a61f864303688d2c9e748eb58e319c26e52d | /Deprecated/org.emftext.runtime/src/org/emftext/runtime/resource/impl/ElementBasedTextDiagnostic.java | 15100b4378c5d1042784565d88ad8e7577594eed | [] | no_license | DevBoost/EMFText | https://github.com/DevBoost/EMFText | 800701e60c822b9cea002f3a8ffed18d011d43b1 | 79d1f63411e023c2e4ee75aaba99299c60922b35 | refs/heads/master | 2020-05-22T01:12:40.750000 | 2019-06-02T17:23:44 | 2019-06-02T19:06:28 | 5,324,334 | 6 | 10 | null | false | 2016-03-21T20:05:01 | 2012-08-07T06:36:34 | 2016-02-07T12:44:14 | 2016-03-21T20:05:01 | 309,429 | 9 | 5 | 24 | Java | null | null | /*******************************************************************************
* Copyright (c) 2006-2009
* Software Technology Group, Dresden University of Technology
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Software Technology Group - TU Dresden, Germany
* - initial API and implementation
******************************************************************************/
/**
*
*/
package org.emftext.runtime.resource.impl;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.emftext.runtime.resource.ILocationMap;
import org.emftext.runtime.resource.ITextDiagnostic;
/**
* An implementation of the ITextDiagnostic interface that attaches
* a message to an EObject.
*/
@Deprecated public class ElementBasedTextDiagnostic implements ITextDiagnostic {
private final ILocationMap locationMap;
private final URI uri;
private final EObject element;
private final String message;
protected ElementBasedTextDiagnostic(ILocationMap locationMap,
URI uri,
String message, EObject element) {
super();
this.uri = uri;
this.locationMap = locationMap;
this.element = element;
this.message = message;
}
public String getMessage() {
return message;
}
public String getLocation() {
return uri.toString();
}
public int getCharStart() {
return Math.max(0, locationMap.getCharStart(element));
}
public int getCharEnd() {
return Math.max(0, locationMap.getCharEnd(element));
}
public int getColumn() {
return Math.max(0, locationMap.getColumn(element));
}
public int getLine() {
return Math.max(0, locationMap.getLine(element));
}
public boolean wasCausedBy(EObject element) {
return this.element.equals(element);
}
}
| UTF-8 | Java | 1,952 | java | ElementBasedTextDiagnostic.java | Java | [] | null | [] | /*******************************************************************************
* Copyright (c) 2006-2009
* Software Technology Group, Dresden University of Technology
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Software Technology Group - TU Dresden, Germany
* - initial API and implementation
******************************************************************************/
/**
*
*/
package org.emftext.runtime.resource.impl;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.emftext.runtime.resource.ILocationMap;
import org.emftext.runtime.resource.ITextDiagnostic;
/**
* An implementation of the ITextDiagnostic interface that attaches
* a message to an EObject.
*/
@Deprecated public class ElementBasedTextDiagnostic implements ITextDiagnostic {
private final ILocationMap locationMap;
private final URI uri;
private final EObject element;
private final String message;
protected ElementBasedTextDiagnostic(ILocationMap locationMap,
URI uri,
String message, EObject element) {
super();
this.uri = uri;
this.locationMap = locationMap;
this.element = element;
this.message = message;
}
public String getMessage() {
return message;
}
public String getLocation() {
return uri.toString();
}
public int getCharStart() {
return Math.max(0, locationMap.getCharStart(element));
}
public int getCharEnd() {
return Math.max(0, locationMap.getCharEnd(element));
}
public int getColumn() {
return Math.max(0, locationMap.getColumn(element));
}
public int getLine() {
return Math.max(0, locationMap.getLine(element));
}
public boolean wasCausedBy(EObject element) {
return this.element.equals(element);
}
}
| 1,952 | 0.681865 | 0.673668 | 73 | 25.739725 | 24.214243 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.136986 | false | false | 13 |
e09818ad9ba58120d53f58f44e01221eae3dd592 | 11,330,123,788,043 | 989c9940431684a685923db25e0291cc4ad9d1f0 | /miscellaneous/src/main/java/com/cmuhatia/playground/SockMerchant.java | 7ad6eab778ed1da76c60fb017457f4b575539b8c | [] | no_license | cornelius-muhatia/algorithms-playground | https://github.com/cornelius-muhatia/algorithms-playground | f9a2ab52889124a5ea6834e138942b4bedf571ba | caf4ab4c4d8bae9bc17151867e723e91cf4cad67 | refs/heads/master | 2023-07-06T19:01:36.729000 | 2023-07-01T04:31:06 | 2023-07-01T04:31:06 | 238,579,091 | 0 | 1 | null | false | 2022-06-22T07:30:39 | 2020-02-06T00:51:49 | 2022-01-03T06:57:35 | 2022-06-22T07:30:38 | 261 | 0 | 1 | 0 | Java | false | false | /*
* Copyright 2019 Cornelius M.
*
* 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.cmuhatia.playground;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Cornelius M
* @version 1.0.0 11/23/19
*/
public class SockMerchant {
static int sockMerchant(List<String> aList) {
int p = 0;
for(int i = 0; i < aList.size(); i++){
int i2 = aList.lastIndexOf(aList.get(i));
if( i2 > i) {
p++;
aList.remove(i2);
aList.remove(i);
i = -1;
}
}
return p;
}
public static void main(String[] args){
List<String> ar = new ArrayList<>();
String raw = "1 1 3 1 2 1 3 3 3 3";
String[] arItems = raw.split(" ");
ar.addAll(Arrays.asList(arItems)); // ar[i] = arItem;
System.out.printf("Number of pairs is %d", SockMerchant.sockMerchant(ar));
}
}
| UTF-8 | Java | 1,489 | java | SockMerchant.java | Java | [
{
"context": "/*\n * Copyright 2019 Cornelius M.\n *\n * Licensed under the Apache License, Version",
"end": 32,
"score": 0.9998709559440613,
"start": 21,
"tag": "NAME",
"value": "Cornelius M"
},
{
"context": "til.Arrays;\nimport java.util.List;\n\n/**\n * @author Cornelius M\n * @ve... | null | [] | /*
* Copyright 2019 <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.cmuhatia.playground;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author <NAME>
* @version 1.0.0 11/23/19
*/
public class SockMerchant {
static int sockMerchant(List<String> aList) {
int p = 0;
for(int i = 0; i < aList.size(); i++){
int i2 = aList.lastIndexOf(aList.get(i));
if( i2 > i) {
p++;
aList.remove(i2);
aList.remove(i);
i = -1;
}
}
return p;
}
public static void main(String[] args){
List<String> ar = new ArrayList<>();
String raw = "1 1 3 1 2 1 3 3 3 3";
String[] arItems = raw.split(" ");
ar.addAll(Arrays.asList(arItems)); // ar[i] = arItem;
System.out.printf("Number of pairs is %d", SockMerchant.sockMerchant(ar));
}
}
| 1,479 | 0.604433 | 0.58227 | 52 | 27.634615 | 24.035254 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.480769 | false | false | 13 |
ee746005eb978a17e258ef0e202c7e4187894b1f | 29,497,835,426,324 | dc08c175c38915065c286b91e99246fb94799850 | /src/main/java/by/dubinin/graphqldemo/service/DepartmentService.java | ad620dd791619537b9ecb6cd7c3e6f1a42c70946 | [] | no_license | DubininYS/graphql-demo | https://github.com/DubininYS/graphql-demo | c6272181db4fcf8e895b65317332b03b029e5919 | 11d3b62bfcf9e987ed7677de2d7054c40d1b7c9a | refs/heads/master | 2020-08-31T20:01:05.967000 | 2019-10-31T13:25:18 | 2019-10-31T13:25:18 | 218,773,060 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package by.dubinin.graphqldemo.service;
import by.dubinin.graphqldemo.entity.Department;
import by.dubinin.graphqldemo.entity.Employee;
import by.dubinin.graphqldemo.exception.ResourceNotFoundException;
import by.dubinin.graphqldemo.repository.DepartmentRepository;
import by.dubinin.graphqldemo.repository.EmployeeRepository;
import io.leangen.graphql.annotations.*;
import io.leangen.graphql.spqr.spring.annotation.GraphQLApi;
import io.leangen.graphql.spqr.spring.util.ConcurrentMultiRegistry;
import org.reactivestreams.Publisher;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
@Service
@GraphQLApi
public class DepartmentService {
private final ConcurrentMultiRegistry<Long, FluxSink<Department>> subscribers = new ConcurrentMultiRegistry<>();
private final DepartmentRepository departmentRepository;
private final EmployeeRepository employeeRepository;
public DepartmentService(DepartmentRepository departmentRepository, EmployeeRepository employeeRepository) {
this.departmentRepository = departmentRepository;
this.employeeRepository = employeeRepository;
}
@GraphQLQuery(name = "departments")
public List<Department> getDepartments() {
return departmentRepository.findAll();
}
@GraphQLQuery(name = "department")
public Optional<Department> getDepartmentById(@GraphQLArgument(name = "id") Long id) {
return departmentRepository.findById(id);
}
@GraphQLQuery(name = "employees")
public List<Employee> getEmployeeListByDepartment(@GraphQLContext Department department) {
return department.getEmployeeList();
}
@GraphQLQuery(name = "employeeCount")
public BigDecimal getEmployeeCountByDepartment(@GraphQLContext Department department) {
long count = department.getEmployeeList().stream().count();
return new BigDecimal(count);
}
@GraphQLMutation
public Department addDepartment(@GraphQLArgument(name = "department") Department department) {
return departmentRepository.save(department);
}
@GraphQLMutation
public Department addEmployeeToDepartment(@GraphQLNonNull Long departmentId, @GraphQLNonNull Long employeeId) {
return departmentRepository.findById(departmentId)
.map(department -> {
final Employee employeeById = employeeRepository.findById(employeeId)
.map(employee -> {
employee.setDepartment(department);
return employeeRepository.save(employee);
})
.orElseThrow(() -> new ResourceNotFoundException("EmployeeId " + employeeId + " not found"));
department.getEmployeeList().add(employeeById);
subscribers.get(departmentId).forEach(subscriber -> subscriber.next(department));
return department;
}
)
.orElseThrow(() -> new ResourceNotFoundException("DepartmentId " + departmentId + " not found"));
}
@GraphQLMutation
public void deleteDepartment(@GraphQLArgument(name = "id") Long id) {
final Department department = departmentRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("DepartmentId " + id + " not found"));
departmentRepository.delete(department);
}
@GraphQLSubscription
public Publisher<Department> employeeAdded(@GraphQLArgument(name = "departmentId") Long departmentId) {
return Flux.create(subscriber -> subscribers.add(
departmentId,
subscriber.onDispose(() -> subscribers.remove(departmentId, subscriber))),
FluxSink.OverflowStrategy.LATEST);
}
}
| UTF-8 | Java | 4,014 | java | DepartmentService.java | Java | [] | null | [] | package by.dubinin.graphqldemo.service;
import by.dubinin.graphqldemo.entity.Department;
import by.dubinin.graphqldemo.entity.Employee;
import by.dubinin.graphqldemo.exception.ResourceNotFoundException;
import by.dubinin.graphqldemo.repository.DepartmentRepository;
import by.dubinin.graphqldemo.repository.EmployeeRepository;
import io.leangen.graphql.annotations.*;
import io.leangen.graphql.spqr.spring.annotation.GraphQLApi;
import io.leangen.graphql.spqr.spring.util.ConcurrentMultiRegistry;
import org.reactivestreams.Publisher;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
@Service
@GraphQLApi
public class DepartmentService {
private final ConcurrentMultiRegistry<Long, FluxSink<Department>> subscribers = new ConcurrentMultiRegistry<>();
private final DepartmentRepository departmentRepository;
private final EmployeeRepository employeeRepository;
public DepartmentService(DepartmentRepository departmentRepository, EmployeeRepository employeeRepository) {
this.departmentRepository = departmentRepository;
this.employeeRepository = employeeRepository;
}
@GraphQLQuery(name = "departments")
public List<Department> getDepartments() {
return departmentRepository.findAll();
}
@GraphQLQuery(name = "department")
public Optional<Department> getDepartmentById(@GraphQLArgument(name = "id") Long id) {
return departmentRepository.findById(id);
}
@GraphQLQuery(name = "employees")
public List<Employee> getEmployeeListByDepartment(@GraphQLContext Department department) {
return department.getEmployeeList();
}
@GraphQLQuery(name = "employeeCount")
public BigDecimal getEmployeeCountByDepartment(@GraphQLContext Department department) {
long count = department.getEmployeeList().stream().count();
return new BigDecimal(count);
}
@GraphQLMutation
public Department addDepartment(@GraphQLArgument(name = "department") Department department) {
return departmentRepository.save(department);
}
@GraphQLMutation
public Department addEmployeeToDepartment(@GraphQLNonNull Long departmentId, @GraphQLNonNull Long employeeId) {
return departmentRepository.findById(departmentId)
.map(department -> {
final Employee employeeById = employeeRepository.findById(employeeId)
.map(employee -> {
employee.setDepartment(department);
return employeeRepository.save(employee);
})
.orElseThrow(() -> new ResourceNotFoundException("EmployeeId " + employeeId + " not found"));
department.getEmployeeList().add(employeeById);
subscribers.get(departmentId).forEach(subscriber -> subscriber.next(department));
return department;
}
)
.orElseThrow(() -> new ResourceNotFoundException("DepartmentId " + departmentId + " not found"));
}
@GraphQLMutation
public void deleteDepartment(@GraphQLArgument(name = "id") Long id) {
final Department department = departmentRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("DepartmentId " + id + " not found"));
departmentRepository.delete(department);
}
@GraphQLSubscription
public Publisher<Department> employeeAdded(@GraphQLArgument(name = "departmentId") Long departmentId) {
return Flux.create(subscriber -> subscribers.add(
departmentId,
subscriber.onDispose(() -> subscribers.remove(departmentId, subscriber))),
FluxSink.OverflowStrategy.LATEST);
}
}
| 4,014 | 0.686846 | 0.686846 | 92 | 42.630436 | 34.843349 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.467391 | false | false | 13 |
6d7290f121715a267bdb023a7bf60b1dc35c0977 | 13,065,290,555,398 | 3de4e4c3b6a2f9a1741231f6aaa4c234b3d035ce | /clinglibrary/src/main/java/org/fourthline/cling/transport/spi/NetworkAddressFactory.java | 88ee51264b75298ad43f5b5083915049c0443b9a | [
"Apache-2.0"
] | permissive | 850125665/NespAndroidCling | https://github.com/850125665/NespAndroidCling | b4fc9a1abe0aa21341ac198e93d9ea2feb45b933 | 85fe5cea04ef9981cb9417a1fd6af022aa59f5fb | refs/heads/master | 2020-06-18T15:25:28.567000 | 2019-07-09T03:05:55 | 2019-07-09T03:05:55 | 196,346,429 | 14 | 4 | Apache-2.0 | true | 2019-07-11T07:51:44 | 2019-07-11T07:51:43 | 2019-07-09T03:06:12 | 2019-07-09T03:06:11 | 2,213 | 0 | 0 | 0 | null | false | false | /*
* Copyright (C) 2013 4th Line GmbH, Switzerland
*
* The contents of this file are subject to the terms of either the GNU
* Lesser General Public License Version 2 or later ("LGPL") or the
* Common Development and Distribution License Version 1 or later
* ("CDDL") (collectively, the "License"). You may not use this file
* except in compliance with the License. See LICENSE.txt for more
* information.
*
* 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.
*/
package org.fourthline.cling.transport.spi;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Iterator;
/**
* Configuration utility for network interfaces and addresses.
* <p>
* An implementation has to be thread-safe.
* </p>
*
* @author Christian Bauer
*/
public interface NetworkAddressFactory {
// An implementation can honor these if it wants (the default does)
public static final String SYSTEM_PROPERTY_NET_IFACES = "org.fourthline.cling.network.useInterfaces";
public static final String SYSTEM_PROPERTY_NET_ADDRESSES = "org.fourthline.cling.network.useAddresses";
/**
* @return The UDP multicast group to join.
*/
public InetAddress getMulticastGroup();
/**
* @return The UDP multicast port to listen on.
*/
public int getMulticastPort();
/**
* @return The TCP (HTTP) stream request port to listen on.
*/
public int getStreamListenPort();
/**
* The caller might <code>remove()</code> an interface if initialization fails.
*
* @return The local network interfaces on which multicast groups will be joined.
*/
public Iterator<NetworkInterface> getNetworkInterfaces();
/**
* The caller might <code>remove()</code> an address if initialization fails.
*
* @return The local addresses of the network interfaces bound to
* sockets listening for unicast datagrams and TCP requests.
*/
public Iterator<InetAddress> getBindAddresses();
/**
* @return <code>true</code> if there is at least one usable network interface and bind address.
*/
public boolean hasUsableNetwork();
/**
* @return The network prefix length of this address or <code>null</code>.
*/
public Short getAddressNetworkPrefixLength(InetAddress inetAddress);
/**
* @param inetAddress An address of a local network interface.
* @return The MAC hardware address of the network interface or <code>null</code> if no
* hardware address could be obtained.
*/
public byte[] getHardwareAddress(InetAddress inetAddress);
/**
* @param inetAddress An address of a local network interface.
* @return The broadcast address of the network (interface) or <code>null</code> if no
* broadcast address could be obtained.
*/
public InetAddress getBroadcastAddress(InetAddress inetAddress);
/**
* Best-effort attempt finding a reachable local address for a given remote host.
* <p>
* This method is called whenever a multicast datagram has been received. We need to be
* able to communicate with the sender using UDP unicast and we need to tell the sender
* how we are reachable with TCP requests. We need a local address that is in the same
* subnet as the senders address, that is reachable from the senders point of view.
* </p>
*
* @param networkInterface The network interface to examine.
* @param isIPv6 True if the given remote address is an IPv6 address.
* @param remoteAddress The remote address for which to find a local address in the same subnet.
* @return A local address that is reachable from the given remote address.
* @throws IllegalStateException If no local address reachable by the remote address has been found.
*/
public InetAddress getLocalAddress(NetworkInterface networkInterface,
boolean isIPv6,
InetAddress remoteAddress) throws IllegalStateException;
/**
* For debugging, logs all "usable" network interface(s) details with INFO level.
*/
public void logInterfaceInformation();
}
| UTF-8 | Java | 4,331 | java | NetworkAddressFactory.java | Java | [
{
"context": "ation has to be thread-safe.\n * </p>\n *\n * @author Christian Bauer\n */\npublic interface NetworkAddressFactory {\n\n ",
"end": 901,
"score": 0.9997118711471558,
"start": 886,
"tag": "NAME",
"value": "Christian Bauer"
}
] | null | [] | /*
* Copyright (C) 2013 4th Line GmbH, Switzerland
*
* The contents of this file are subject to the terms of either the GNU
* Lesser General Public License Version 2 or later ("LGPL") or the
* Common Development and Distribution License Version 1 or later
* ("CDDL") (collectively, the "License"). You may not use this file
* except in compliance with the License. See LICENSE.txt for more
* information.
*
* 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.
*/
package org.fourthline.cling.transport.spi;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Iterator;
/**
* Configuration utility for network interfaces and addresses.
* <p>
* An implementation has to be thread-safe.
* </p>
*
* @author <NAME>
*/
public interface NetworkAddressFactory {
// An implementation can honor these if it wants (the default does)
public static final String SYSTEM_PROPERTY_NET_IFACES = "org.fourthline.cling.network.useInterfaces";
public static final String SYSTEM_PROPERTY_NET_ADDRESSES = "org.fourthline.cling.network.useAddresses";
/**
* @return The UDP multicast group to join.
*/
public InetAddress getMulticastGroup();
/**
* @return The UDP multicast port to listen on.
*/
public int getMulticastPort();
/**
* @return The TCP (HTTP) stream request port to listen on.
*/
public int getStreamListenPort();
/**
* The caller might <code>remove()</code> an interface if initialization fails.
*
* @return The local network interfaces on which multicast groups will be joined.
*/
public Iterator<NetworkInterface> getNetworkInterfaces();
/**
* The caller might <code>remove()</code> an address if initialization fails.
*
* @return The local addresses of the network interfaces bound to
* sockets listening for unicast datagrams and TCP requests.
*/
public Iterator<InetAddress> getBindAddresses();
/**
* @return <code>true</code> if there is at least one usable network interface and bind address.
*/
public boolean hasUsableNetwork();
/**
* @return The network prefix length of this address or <code>null</code>.
*/
public Short getAddressNetworkPrefixLength(InetAddress inetAddress);
/**
* @param inetAddress An address of a local network interface.
* @return The MAC hardware address of the network interface or <code>null</code> if no
* hardware address could be obtained.
*/
public byte[] getHardwareAddress(InetAddress inetAddress);
/**
* @param inetAddress An address of a local network interface.
* @return The broadcast address of the network (interface) or <code>null</code> if no
* broadcast address could be obtained.
*/
public InetAddress getBroadcastAddress(InetAddress inetAddress);
/**
* Best-effort attempt finding a reachable local address for a given remote host.
* <p>
* This method is called whenever a multicast datagram has been received. We need to be
* able to communicate with the sender using UDP unicast and we need to tell the sender
* how we are reachable with TCP requests. We need a local address that is in the same
* subnet as the senders address, that is reachable from the senders point of view.
* </p>
*
* @param networkInterface The network interface to examine.
* @param isIPv6 True if the given remote address is an IPv6 address.
* @param remoteAddress The remote address for which to find a local address in the same subnet.
* @return A local address that is reachable from the given remote address.
* @throws IllegalStateException If no local address reachable by the remote address has been found.
*/
public InetAddress getLocalAddress(NetworkInterface networkInterface,
boolean isIPv6,
InetAddress remoteAddress) throws IllegalStateException;
/**
* For debugging, logs all "usable" network interface(s) details with INFO level.
*/
public void logInterfaceInformation();
}
| 4,322 | 0.691526 | 0.689217 | 114 | 36.991226 | 34.547829 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.219298 | false | false | 13 |
7944bc4808caffe08a69da665bed494def4e6b1c | 19,774,029,443,990 | 01446e84a36516da8579041aeef3cdf8c1fae2e2 | /app/src/main/java/com/playcode/runrunrun/fragment/MainFragment.java | 46659ac837d9f84d27d13154712c7327025fa03c | [] | no_license | anpoz/RunRunRun | https://github.com/anpoz/RunRunRun | 7d48b756491f449871d3fa1306c6b7d46eea8e8b | 271f1ecb2a57bc0e75432dd8a831a605f843a659 | refs/heads/master | 2020-02-26T16:42:01.019000 | 2016-07-06T10:44:50 | 2016-07-06T10:44:50 | 58,225,895 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.playcode.runrunrun.fragment;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.playcode.runrunrun.App;
import com.playcode.runrunrun.R;
import com.playcode.runrunrun.model.RecordsEntity;
import com.playcode.runrunrun.utils.APIUtils;
import com.playcode.runrunrun.utils.RetrofitHelper;
import java.util.List;
import java.util.Locale;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* A simple {@link Fragment} subclass.
*/
public class MainFragment extends Fragment {
private TextView distance;
private TextView count;
private TextView time;
public MainFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
initView(rootView);
// initData();
return rootView;
}
private void initData() {
if (App.getServerMode() == App.SERVER_MODE.WITHOUT_SERVER) {
List<RecordsEntity> recordsEntity = RecordsEntity.listAll(RecordsEntity.class);
if (recordsEntity != null && !recordsEntity.isEmpty())
setupData(recordsEntity);
} else {
SharedPreferences setting = getActivity().getSharedPreferences("UserData", 0);
String token = setting.getString("token", "0");
if (token.equals(""))
return;
RetrofitHelper.getInstance()
.getService(APIUtils.class)
.getUserRecords(token)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(userRecordModel -> {
// if (userRecordModel.getResultCode() != 0) {
// Toast.makeText(getActivity(), userRecordModel.getMessage(), Toast.LENGTH_SHORT).show();
// return;
// }
if (userRecordModel.getRecords() != null && userRecordModel.getRecords().size() != 0) {
setupData(userRecordModel.getRecords());
}
});
}
}
private void setupData(List<RecordsEntity> records) {
int size = records.size();
float timeCount = 0;
float distanceCount = 0;
for (int i = 0; i < size; i++) {
RecordsEntity recordsEntity = records.get(i);
timeCount += recordsEntity.getRunTime();
distanceCount += recordsEntity.getDistance();
}
distance.setText(String.format(Locale.getDefault(), "%.2f", distanceCount / 1000));
time.setText(String.format(Locale.getDefault(), "%.2f", timeCount / 3600));
count.setText(String.valueOf(size));
}
@Override
public void onResume() {
super.onResume();
initData();
}
private void initView(View view) {
distance = (TextView) view.findViewById(R.id.tvDistance);
count = (TextView) view.findViewById(R.id.tvCount);
time = (TextView) view.findViewById(R.id.tvTime);
}
}
| UTF-8 | Java | 3,490 | java | MainFragment.java | Java | [] | null | [] | package com.playcode.runrunrun.fragment;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.playcode.runrunrun.App;
import com.playcode.runrunrun.R;
import com.playcode.runrunrun.model.RecordsEntity;
import com.playcode.runrunrun.utils.APIUtils;
import com.playcode.runrunrun.utils.RetrofitHelper;
import java.util.List;
import java.util.Locale;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* A simple {@link Fragment} subclass.
*/
public class MainFragment extends Fragment {
private TextView distance;
private TextView count;
private TextView time;
public MainFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
initView(rootView);
// initData();
return rootView;
}
private void initData() {
if (App.getServerMode() == App.SERVER_MODE.WITHOUT_SERVER) {
List<RecordsEntity> recordsEntity = RecordsEntity.listAll(RecordsEntity.class);
if (recordsEntity != null && !recordsEntity.isEmpty())
setupData(recordsEntity);
} else {
SharedPreferences setting = getActivity().getSharedPreferences("UserData", 0);
String token = setting.getString("token", "0");
if (token.equals(""))
return;
RetrofitHelper.getInstance()
.getService(APIUtils.class)
.getUserRecords(token)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(userRecordModel -> {
// if (userRecordModel.getResultCode() != 0) {
// Toast.makeText(getActivity(), userRecordModel.getMessage(), Toast.LENGTH_SHORT).show();
// return;
// }
if (userRecordModel.getRecords() != null && userRecordModel.getRecords().size() != 0) {
setupData(userRecordModel.getRecords());
}
});
}
}
private void setupData(List<RecordsEntity> records) {
int size = records.size();
float timeCount = 0;
float distanceCount = 0;
for (int i = 0; i < size; i++) {
RecordsEntity recordsEntity = records.get(i);
timeCount += recordsEntity.getRunTime();
distanceCount += recordsEntity.getDistance();
}
distance.setText(String.format(Locale.getDefault(), "%.2f", distanceCount / 1000));
time.setText(String.format(Locale.getDefault(), "%.2f", timeCount / 3600));
count.setText(String.valueOf(size));
}
@Override
public void onResume() {
super.onResume();
initData();
}
private void initView(View view) {
distance = (TextView) view.findViewById(R.id.tvDistance);
count = (TextView) view.findViewById(R.id.tvCount);
time = (TextView) view.findViewById(R.id.tvTime);
}
}
| 3,490 | 0.613181 | 0.608023 | 103 | 32.883495 | 26.550301 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.592233 | false | false | 13 |
11d982e58652152e91dc4b87d7f4e97a4163fda6 | 17,128,329,600,144 | 2c1dc7049d820d2b75811a6c0479bd34eb84ad87 | /vmware-base/src/test/java/com/cloud/hypervisor/vmware/mo/DatastoreMOTest.java | 6e1793a67967533f13aabfb2fa10d4f26a2cfbcc | [
"GPL-2.0-only",
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown"
] | permissive | apache/cloudstack | https://github.com/apache/cloudstack | 3775c9171022dfaf91d655bd166149e36f4caa41 | 819dd7b75c1b61ae444c45476f5834dbfb9094d0 | refs/heads/main | 2023-08-30T15:05:36.976000 | 2023-08-30T09:29:16 | 2023-08-30T09:29:16 | 9,759,448 | 1,468 | 1,232 | Apache-2.0 | false | 2023-09-14T16:57:46 | 2013-04-29T22:27:12 | 2023-09-14T13:24:51 | 2023-09-14T16:57:45 | 569,343 | 1,509 | 1,022 | 372 | 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.cloud.hypervisor.vmware.mo;
import com.cloud.hypervisor.vmware.util.VmwareClient;
import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.vmware.vim25.FileInfo;
import com.vmware.vim25.HostDatastoreBrowserSearchResults;
import com.vmware.vim25.ManagedObjectReference;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockedConstruction;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class DatastoreMOTest {
@Mock
VmwareContext _context ;
@Mock
VmwareClient _client;
@Mock
ManagedObjectReference _mor;
DatastoreMO datastoreMO ;
String fileName = "ROOT-5.vmdk";
MockedConstruction<HostDatastoreBrowserMO> hostDataStoreBrowserMoConstruction;
@Before
public void setUp() throws Exception {
datastoreMO = new DatastoreMO(_context, _mor);
when(_context.getVimClient()).thenReturn(_client);
when(_client.getDynamicProperty(any(ManagedObjectReference.class), eq("name"))).thenReturn(
"252d36c96cfb32f48ce7756ccb79ae37");
ArrayList<HostDatastoreBrowserSearchResults> results = new ArrayList<>();
HostDatastoreBrowserSearchResults r1 = new HostDatastoreBrowserSearchResults();
FileInfo f1 = new FileInfo();
f1.setPath(fileName);
r1.getFile().add(f1);
r1.setFolderPath("[252d36c96cfb32f48ce7756ccb79ae37] .snapshot/hourly.2017-02-23_1705/i-2-5-VM/");
HostDatastoreBrowserSearchResults r2 = new HostDatastoreBrowserSearchResults();
FileInfo f2 = new FileInfo();
f2.setPath(fileName);
r2.getFile().add(f2);
r2.setFolderPath("[252d36c96cfb32f48ce7756ccb79ae37] .snapshot/hourly.2017-02-23_1605/i-2-5-VM/");
HostDatastoreBrowserSearchResults r3 = new HostDatastoreBrowserSearchResults();
FileInfo f3 = new FileInfo();
f3.setPath(fileName);
r3.getFile().add(f3);
r3.setFolderPath("[252d36c96cfb32f48ce7756ccb79ae37] i-2-5-VM/");
results.add(r1);
results.add(r2);
results.add(r3);
hostDataStoreBrowserMoConstruction = Mockito.mockConstruction(HostDatastoreBrowserMO.class, (mock, context) -> {
when(mock.searchDatastore(any(String.class), any(String.class), eq(true))).thenReturn(null);
when(mock.searchDatastoreSubFolders(any(String.class),any(String.class), any(Boolean.class) )).thenReturn(results);
});
}
@After
public void tearDown() throws Exception {
hostDataStoreBrowserMoConstruction.close();
}
@Test
public void testSearchFileInSubFolders() throws Exception {
assertEquals("Unexpected Behavior: search should exclude .snapshot folder",
"[252d36c96cfb32f48ce7756ccb79ae37] i-2-5-VM/ROOT-5.vmdk",
datastoreMO.searchFileInSubFolders(fileName, false, ".snapshot"));
}
@Test
public void testSearchFileInSubFoldersWithExcludeMultipleFolders() throws Exception {
assertEquals("Unexpected Behavior: search should exclude folders",
"[252d36c96cfb32f48ce7756ccb79ae37] .snapshot/hourly.2017-02-23_1605/i-2-5-VM/ROOT-5.vmdk",
datastoreMO.searchFileInSubFolders(fileName, false, "i-2-5-VM, .snapshot/hourly.2017-02-23_1705"));
}
}
| UTF-8 | Java | 4,439 | java | DatastoreMOTest.java | Java | [
{
"context": "ass), eq(\"name\"))).thenReturn(\n \"252d36c96cfb32f48ce7756ccb79ae37\");\n\n ArrayLis",
"end": 2175,
"score": 0.5379319787025452,
"start": 2174,
"tag": "KEY",
"value": "2"
},
{
"context": "s), eq(\"name\"))).thenReturn(\n \"252d36c9... | 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.cloud.hypervisor.vmware.mo;
import com.cloud.hypervisor.vmware.util.VmwareClient;
import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.vmware.vim25.FileInfo;
import com.vmware.vim25.HostDatastoreBrowserSearchResults;
import com.vmware.vim25.ManagedObjectReference;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockedConstruction;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class DatastoreMOTest {
@Mock
VmwareContext _context ;
@Mock
VmwareClient _client;
@Mock
ManagedObjectReference _mor;
DatastoreMO datastoreMO ;
String fileName = "ROOT-5.vmdk";
MockedConstruction<HostDatastoreBrowserMO> hostDataStoreBrowserMoConstruction;
@Before
public void setUp() throws Exception {
datastoreMO = new DatastoreMO(_context, _mor);
when(_context.getVimClient()).thenReturn(_client);
when(_client.getDynamicProperty(any(ManagedObjectReference.class), eq("name"))).thenReturn(
"252d<KEY>");
ArrayList<HostDatastoreBrowserSearchResults> results = new ArrayList<>();
HostDatastoreBrowserSearchResults r1 = new HostDatastoreBrowserSearchResults();
FileInfo f1 = new FileInfo();
f1.setPath(fileName);
r1.getFile().add(f1);
r1.setFolderPath("[252d36c96cfb32f48ce7756ccb79ae37] .snapshot/hourly.2017-02-23_1705/i-2-5-VM/");
HostDatastoreBrowserSearchResults r2 = new HostDatastoreBrowserSearchResults();
FileInfo f2 = new FileInfo();
f2.setPath(fileName);
r2.getFile().add(f2);
r2.setFolderPath("[252d36c96cfb32f48ce7756ccb79ae37] .snapshot/hourly.2017-02-23_1605/i-2-5-VM/");
HostDatastoreBrowserSearchResults r3 = new HostDatastoreBrowserSearchResults();
FileInfo f3 = new FileInfo();
f3.setPath(fileName);
r3.getFile().add(f3);
r3.setFolderPath("[252d36c96cfb32f48ce7756ccb79ae37] i-2-5-VM/");
results.add(r1);
results.add(r2);
results.add(r3);
hostDataStoreBrowserMoConstruction = Mockito.mockConstruction(HostDatastoreBrowserMO.class, (mock, context) -> {
when(mock.searchDatastore(any(String.class), any(String.class), eq(true))).thenReturn(null);
when(mock.searchDatastoreSubFolders(any(String.class),any(String.class), any(Boolean.class) )).thenReturn(results);
});
}
@After
public void tearDown() throws Exception {
hostDataStoreBrowserMoConstruction.close();
}
@Test
public void testSearchFileInSubFolders() throws Exception {
assertEquals("Unexpected Behavior: search should exclude .snapshot folder",
"[252d36c96cfb32f48ce7756ccb79ae37] i-2-5-VM/ROOT-5.vmdk",
datastoreMO.searchFileInSubFolders(fileName, false, ".snapshot"));
}
@Test
public void testSearchFileInSubFoldersWithExcludeMultipleFolders() throws Exception {
assertEquals("Unexpected Behavior: search should exclude folders",
"[252d36c96cfb32f48ce7756ccb79ae37] .snapshot/hourly.2017-02-23_1605/i-2-5-VM/ROOT-5.vmdk",
datastoreMO.searchFileInSubFolders(fileName, false, "i-2-5-VM, .snapshot/hourly.2017-02-23_1705"));
}
}
| 4,416 | 0.723361 | 0.676504 | 113 | 38.283184 | 32.527039 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.663717 | false | false | 13 |
5294702ca4953abd6b04c52b15d63add24bf8c8c | 2,456,721,331,907 | b25a16c1b6c97f3e8056ca4b9fc1165316e88fce | /interview-common/src/main/java/com/lee/interview/common/base/BaseResponse.java | 8bc728bbcfc6d695466b8e06fcdcb0d07b8d900d | [] | no_license | lihaocheng/parent | https://github.com/lihaocheng/parent | f0ec56d809e6d39de5ca903c180b4ed72d1e902f | 2a71fdf8299c693ce9d7e36b98fab06dacedc7d5 | refs/heads/master | 2022-07-04T05:25:41.653000 | 2019-08-10T07:34:58 | 2019-08-10T07:34:58 | 201,596,533 | 1 | 0 | null | false | 2022-06-17T02:24:04 | 2019-08-10T07:34:06 | 2019-08-10T07:36:36 | 2022-06-17T02:24:02 | 957 | 1 | 0 | 1 | HTML | false | false | package com.lee.interview.common.base;
import lombok.Data;
@Data
public class BaseResponse {
private String retCode;
private String retDesc;
}
| UTF-8 | Java | 152 | java | BaseResponse.java | Java | [] | null | [] | package com.lee.interview.common.base;
import lombok.Data;
@Data
public class BaseResponse {
private String retCode;
private String retDesc;
}
| 152 | 0.756579 | 0.756579 | 12 | 11.666667 | 13.167722 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 13 |
f329cec4566e08161e6fb458087a6e4d50f6ad82 | 25,271,587,629,935 | 46eb3999308961c59f498f73cf3672923b8d0842 | /app/src/main/java/minhaaplicacao/ifpb/edu/br/minhaaplicacaoandroid/CadastroActivity.java | dc2a673b6b4740122c43598d28c2a143f72dfb05 | [] | no_license | rhavymaia/MinhaAplicacaoAndroid | https://github.com/rhavymaia/MinhaAplicacaoAndroid | d886f097068a067541f836cc365ed17853021b90 | e89b8c5f3c55fc614e3864d8e740aa0f2e1b3dfa | refs/heads/master | 2021-01-10T05:12:06.394000 | 2015-11-25T01:40:17 | 2015-11-25T01:40:17 | 46,830,107 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package minhaaplicacao.ifpb.edu.br.minhaaplicacaoandroid;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
public class CadastroActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cadastro);
Button button = (Button) findViewById(R.id.notificacaoButton);
button.setOnClickListener(new NotificationOnClickListener());
}
}
| UTF-8 | Java | 541 | java | CadastroActivity.java | Java | [] | null | [] | package minhaaplicacao.ifpb.edu.br.minhaaplicacaoandroid;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
public class CadastroActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cadastro);
Button button = (Button) findViewById(R.id.notificacaoButton);
button.setOnClickListener(new NotificationOnClickListener());
}
}
| 541 | 0.767098 | 0.76525 | 17 | 30.82353 | 26.075085 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false | 13 |
65f4abb3614f7533065325495ed38171b4c056ff | 6,176,163,031,626 | ec0448c27754bed7bf616245ab44c7be2bc686dd | /JavaBrain/src/basicExamples/SimpleAdder.java | 014799f3694a80d04a2bf9edc6bc24f4edf93856 | [] | no_license | rechido/kmove30 | https://github.com/rechido/kmove30 | 1d95116af70b0739081c65ee17b27cc8abbc874d | f4fdaa8acb9171509fec081c5315875c8f8b1964 | refs/heads/master | 2020-03-22T02:32:07.662000 | 2018-09-09T10:04:48 | 2018-09-09T10:04:48 | 139,376,108 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package basicExamples;
public class SimpleAdder {
// public은 자바의 접근제한자(modifier)로 어느곳에서나 접근이 가능
// class는 자바 키워드로 class임을 표시
// SimpleAdder는 식별자로 클래스 이름
// 클래스를 정의하기 위해서는 { } 안에 정의
// class는 세 가지 구성 요소를 가짐 (멤버변수, 멤버메서드, 생성자)
// 자바의 시작점을 나타내는 main()메서드가 프로젝트 내의 어딘가에 있어야만 그곳에서 시작
public static void main(String[] args) {
// static은 클래스메서드임을 나타내는 키워드
// void는 메서드의 실행결과를 반환할 필요가 없음을 나타냄
// main은 식별자로 메서드 이름
// String은 자바가 제공하는 라이브러리의 문자처리클래스인 String클래스임
// 지역변수 num선언
// 지역변수는 메서드 안에서 선언된 변수로 메서드 안에서만 효력이 있음(메서드가 끝나면 메모리에서 사라짐)
int num; // int는 자바의 기본 데이터 형인 정수형을 나타냄(32bit), short는 16bit, long이 64bit
num = 10 + 20; // =은 대입 연산자로 우변의 값을 좌변 num 변수에 저장
System.out.println(num);
// 조건문 if문은 if(관계연산식) { } 형태임
// 관계연산이 true일시만 블록 { } 안의 내용을 실행
if(num>10) {
System.out.println("num은 10보다 큽니다.");
}
if(num>40) {
System.out.println("num은 40보다 큽니다.");
}
num = 1;
/**
* while 문은 while (관계연산식) { } 형태이며
* 관계연산식이 false가 될때까지 블록 안을 반복 실행
*/
while(num < 10) {
System.out.println("num은 10보다 적음");
num = num + 1;
}
//num=15.7;
//num은 int 타입인데 15.7은 double형이므로 에러 발생
int sum ;
// System.out.println(sum);
// sum 변수를 초기화하지 않아 에러 발생
}
}
| UTF-8 | Java | 2,059 | java | SimpleAdder.java | Java | [] | null | [] | package basicExamples;
public class SimpleAdder {
// public은 자바의 접근제한자(modifier)로 어느곳에서나 접근이 가능
// class는 자바 키워드로 class임을 표시
// SimpleAdder는 식별자로 클래스 이름
// 클래스를 정의하기 위해서는 { } 안에 정의
// class는 세 가지 구성 요소를 가짐 (멤버변수, 멤버메서드, 생성자)
// 자바의 시작점을 나타내는 main()메서드가 프로젝트 내의 어딘가에 있어야만 그곳에서 시작
public static void main(String[] args) {
// static은 클래스메서드임을 나타내는 키워드
// void는 메서드의 실행결과를 반환할 필요가 없음을 나타냄
// main은 식별자로 메서드 이름
// String은 자바가 제공하는 라이브러리의 문자처리클래스인 String클래스임
// 지역변수 num선언
// 지역변수는 메서드 안에서 선언된 변수로 메서드 안에서만 효력이 있음(메서드가 끝나면 메모리에서 사라짐)
int num; // int는 자바의 기본 데이터 형인 정수형을 나타냄(32bit), short는 16bit, long이 64bit
num = 10 + 20; // =은 대입 연산자로 우변의 값을 좌변 num 변수에 저장
System.out.println(num);
// 조건문 if문은 if(관계연산식) { } 형태임
// 관계연산이 true일시만 블록 { } 안의 내용을 실행
if(num>10) {
System.out.println("num은 10보다 큽니다.");
}
if(num>40) {
System.out.println("num은 40보다 큽니다.");
}
num = 1;
/**
* while 문은 while (관계연산식) { } 형태이며
* 관계연산식이 false가 될때까지 블록 안을 반복 실행
*/
while(num < 10) {
System.out.println("num은 10보다 적음");
num = num + 1;
}
//num=15.7;
//num은 int 타입인데 15.7은 double형이므로 에러 발생
int sum ;
// System.out.println(sum);
// sum 변수를 초기화하지 않아 에러 발생
}
}
| 2,059 | 0.589466 | 0.566228 | 55 | 21.472727 | 18.653641 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.054545 | false | false | 13 |
b105e6e3cfdcfb85e3a0c9fed3756ae906b60dae | 17,179,937,393 | 3116f7070cc90d33ddd5929536d25a4f54e261e5 | /src/HelloWorld.java | 4299fea4b4b64742ae6f326f593bd1f23154611f | [] | no_license | Shoma-Nishino/java-learning | https://github.com/Shoma-Nishino/java-learning | 170eda8b5096b8f211726c601c38445bdd12d30e | 088f21a0a633d6cf3c64632f801964a6a3f8a9a0 | refs/heads/master | 2020-05-25T11:00:14.527000 | 2019-05-21T06:06:53 | 2019-05-21T06:06:53 | 187,770,708 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class HelloWorld {
public static void main(String[] args) {
count(10);
}
public static void count(int num) {
for(int i = 0; i < num; i++) {
if(i == 5) {
//5回目はスキップする
continue;
//breakにすると4回目で処理が終了する
}
System.out.println(i);
}
}
}
| UTF-8 | Java | 321 | java | HelloWorld.java | Java | [] | null | [] | public class HelloWorld {
public static void main(String[] args) {
count(10);
}
public static void count(int num) {
for(int i = 0; i < num; i++) {
if(i == 5) {
//5回目はスキップする
continue;
//breakにすると4回目で処理が終了する
}
System.out.println(i);
}
}
}
| 321 | 0.570909 | 0.549091 | 17 | 15.176471 | 12.962549 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.411765 | false | false | 13 |
bd1532e9414b0cc150e8aba1f73e07a074c6867d | 17,179,937,602 | 2c31843b618d6ff4bee321f39d2fb8dcdaa12cad | /Archive/InvertedIndexFileReader.java | 79aa4a0a64c27ee90d51ec3a51b68cada7431e2a | [] | no_license | steinbergeradam/SkearchSearchEngine | https://github.com/steinbergeradam/SkearchSearchEngine | 616f3549fd9ad6ee465aa7198d0686a516291391 | 43dea9a1a1329b7f0fc92d69e339766e0f8d6104 | refs/heads/master | 2023-03-17T02:22:47.259000 | 2012-01-07T02:18:17 | 2012-01-07T02:18:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package search.indexserver;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.TreeMap;
import search.common.Timer;
import search.common.Timer.Method;
/**
* Read the Inverted Index file into memory and query the index.
* @author Adam Steinberger, Sam Gunther
*/
public class InvertedIndexFileReader {
// provides random access to the index (e.g. to jump to an offset in the index area)
private RandomAccessFile indexFile;
// provides sequential access to the index (for reading the lex map into memory)
private DataInputStream indexFile1;
// the in-memory lexicon for looking up offsets/ndocs by word
private TreeMap<String, LexMapEntry> lexMap;
private final static Timer timer = new Timer("InvertedIndexFileReader",true);
private boolean verbose;
public boolean isVerbose() {
return verbose;
} // end isVerbose()
public void setVerbose(boolean verbose) {
this.verbose = verbose;
} // end setVerbose()
/**
* Create a new inverted index file reader given a docId.
* Note: There is a bit of a startup delay while reading the lexicon into memory.
* @param docId
*/
public InvertedIndexFileReader(int docId, boolean v) {
// add new method to timer
Method method = timer.addMethod("InvertedIndexFileReader");
try {
// initiate timer
this.verbose = v;
// fire up the random and sequential file readers
timer.startTimer("Open index chunk for reading",method);
String filename = String.format("chunk%1$016x.index", docId);
this.indexFile = new RandomAccessFile(new File(filename), "r");
this.indexFile1 = new DataInputStream(new FileInputStream(new File(filename)));
timer.stopTimer(method);
// read the lexicon into memory (this takes a minute)
timer.startTimer("Read Lexicon Map into Memory",method);
this.lexMap = getLexMap();
timer.stopTimer(method);
} catch (Exception ex) {
System.out.println("! Could not create inverted index file reader.");
System.out.println(ex);
} // end try/catch
} // end InvertedIndexFileReader constructor
/**
* Transfer query words to priority queue based on nDocs size.
* @param words
*/
private PriorityQueue<Word> enqueueWords(ArrayDeque<String> words) {
PriorityQueue<Word> result = new PriorityQueue<Word>();
Iterator<String> it = words.iterator();
// add new method to timer
Method method = timer.addMethod("enqueueWords");
while (it.hasNext()) {
String word = (String) it.next();
int nDocs = lexMap.get(word).nDocs;
Word w = new Word(word,nDocs);
// add word to queue
timer.startTimer("Enqueue \"" + w.getWord() + "\" to priority queue",method);
result.add(w);
timer.stopTimer(method);
} // end while
return result;
} // end enqueueWords()
/**
* Query words ORed together.
* @return
*/
public int[] queryOR(ArrayDeque<String> words, int limit) {
// add new method to timer
Method method = timer.addMethod("queryOR");
// enqueue search words based on nDocs size
timer.startTimer("Enqueue search terms",method);
PriorityQueue<Word> search = enqueueWords(words);
timer.stopTimer(method);
// get docIds for word with smallest nDocs.
Word word = search.poll();
// get docIds for search term
timer.startTimer("Search inverted index for \"" + word.getWord() + "\"",method);
int[] results = getDocIds(word.getWord(),word.getnDocs());
timer.stopTimer(method);
// merge docIds for all other words, so only common docIds remain
while (!search.isEmpty()) {
// get next search term
word = search.poll();
// get docIds for search term
timer.startTimer("Search inverted index for \"" + word.getWord() + "\"",method);
int[] temp = getDocIds(word.getWord(),word.getnDocs());
timer.stopTimer(method);
// merge search results
timer.startTimer("Merge search results",method);
results = mergeOR(temp,results,limit);
timer.stopTimer(method);
} // end while
// return null if no results found.
if (results.length == 0) {
System.out.println("! No results found.");
results = null;
} // end if
return results;
} // end queryOR()
/**
* Merge two int arrays so all unique elements in both arrays are added to new array
* @param t
* @param r
* @return
*/
private int[] mergeOR(int[] t, int[] r, int limit) {
// add new method to timer
Method method = timer.addMethod("mergeOR");
// start timer
timer.startTimer("Add all docIds to results array",method);
int[] result = null;
if (r.length > t.length) {
if (t.length >= limit) {
result = Arrays.copyOf(t,limit);
} else {
int size = limit;
if (t.length + r.length < limit) {
size = t.length + r.length;
} // end if
result = new int [size];
for (int i = 0; i < t.length; i++) {
result[i] = t[i];
} // end for
int index = -1;
for (int i = t.length; i < size; i++) {
int search = -1;
while (search < 0) {
index++;
Arrays.binarySearch(t,r[index]);
} // end while
result[i] = r[index];
} // end for
} // end if
} else {
if (r.length >= limit) {
result = Arrays.copyOf(r,limit);
} else {
int size = limit;
if (r.length + t.length < limit) {
size = r.length + t.length;
} // end if
result = new int [size];
for (int i = 0; i < r.length; i++) {
result[i] = r[i];
} // end for
for (int i = r.length; i < size; i++) {
result[i] = t[i-r.length];
} // end for
} // end if
} // end if
// stop timer
timer.stopTimer(method);
return result;
} // end mergeOR()
/**
* Query words ANDed together.
* @return
*/
public int[] queryAND(ArrayDeque<String> words, int limit) {
// add new method to timer
Method method = timer.addMethod("queryAND");
// enqueue search words based on nDocs size
timer.startTimer("Enqueue search terms",method);
PriorityQueue<Word> search = enqueueWords(words);
timer.stopTimer(method);
// get docIds for word with smallest nDocs.
Word word = search.poll();
// get docIds for search term
timer.startTimer("Search inverted index for \"" + word.getWord() + "\"",method);
int[] results = getDocIds(word.getWord(),word.getnDocs());
timer.stopTimer(method);
// merge docIds for all other words, so only common docIds remain
while (!search.isEmpty()) {
// get next search term
word = search.poll();
// get docIds for search term
timer.startTimer("Search inverted index for \"" + word.getWord() + "\"",method);
int[] temp = getDocIds(word.getWord(),word.getnDocs());
timer.stopTimer(method);
// merge search results
timer.startTimer("Merge search results",method);
results = mergeAND(temp,results,limit);
timer.stopTimer(method);
} // end while
// resize results to results limit
if (results.length > limit) {
// resize results array
timer.startTimer("Resize results array to size " + limit,method);
results = Arrays.copyOf(results, limit);
timer.stopTimer(method);
} // end if
// return null if no results found.
if (results.length == 0) {
System.out.println("! No results found.");
results = null;
} // end if
return results;
} // end queryAND()
/**
* Merge two int arrays so only elements common to both arrays remain
* @param t
* @param r
* @return
*/
private int[] mergeAND(int[] t, int[] r, int limit) {
// add new method to timer
Method method = timer.addMethod("mergeAND");
int size = limit;
if (t.length < limit || r.length < limit) {
size = Math.min(t.length,r.length);
} // end if
// start timer
timer.startTimer("Add all docIds common to both arrays to list",method);
int[] result = new int [size];
int i = 0, j = 0, index = 0;
while ((i < t.length) && (j < r.length) && (index < size)) {
if (t[i] > r[j]) {
j++;
} else if (t[i] < r[j]) {
i++;
} else {
result[index] = t[i];
index++;
i++;
j++;
} // end if
} // end while
// stop timer
timer.stopTimer(method);
return result;
} // end mergeAND()
/**
* Read the Lex Map into Memory.
* @return
*/
@SuppressWarnings("deprecation")
private TreeMap<String, LexMapEntry> getLexMap() {
// add new method to timer
Method method = timer.addMethod("getLexMap");
// create new LexMap
TreeMap<String, LexMapEntry> map = new TreeMap<String, LexMapEntry>();
try {
// the first 8 bytes tell us the offset that we
// should STOP reading the lexicon from (that's the
// end of the lex area and beginning of the index area)
timer.startTimer("Get offset to stop reading lexicon from",method);
byte[] boundaryBytes = new byte[8];
indexFile1.read(boundaryBytes);
long lexMapBoundary = ByteBuffer.wrap(boundaryBytes).getLong();
int offset = 8;
timer.stopTimer(method);
// start timer
timer.startTimer("Read word and nDocs info from lexicon",method);
// now, read the word and its lexmapentry (ndocs-int, offsetToIndexArea-long)
// we keep reading until we reach the end of the lexMap (lexMapBoundary)
String word = "";
while (offset < lexMapBoundary) {
// get the word
word = indexFile1.readLine();
offset+= word.getBytes().length;
// get ndocs, offset
LexMapEntry entry = new LexMapEntry(indexFile1.readInt(),indexFile1.readLong());
map.put(word.toString(), entry);
offset += 12;
} // end while
// stop timer
timer.stopTimer(method);
} catch (Exception ex) {
System.out.println("! Could not read from the lexicon.");
ex.printStackTrace();
} // end try/catch
return map;
} // end getLexMap()
/**
* Return an array of DocIds for single-word query.
* @param word
* @param limit
* @return
*/
public int[] getDocIds(String word, int limit) {
// add new method to timer
Method method = timer.addMethod("getDocIds");
if (limit > 0) {
try {
// get the number of matching docs from the lexicon for this word
int nDocs = lexMap.get(word).nDocs;
// now seek into the index file at the offset we get from the lexicon for this word
timer.startTimer("Seek word pointer for search query in lexicon",method);
indexFile.seek(lexMap.get(word).ptr);
timer.stopTimer(method);
// limit is what we use to stop reading from the index - we stop when we hit the limit given
// at query time, or nDocs if that is smaller than what the user wants
if (nDocs < limit) {
limit = nDocs;
} // end if
// the array of docIds to return
int[] docIds = new int [limit];
int docsFound = 0; // number of docs found so far
int docsSearched = 0; // number of docs searched so far
// start timer
timer.startTimer("Get docIds from the lexicon",method);
// we set done = true once we have enough docs
boolean done = false;
while ((docsFound < limit) && !done) {
docIds[docsFound++] = indexFile.readInt();
if (++docsSearched == limit) {
done = true; // if we have searched enough...
} else {
// now move to next docId - we have to skip over the current docId's
// hitlist to get to the next one
indexFile.seek(indexFile.getFilePointer() + getHitListSize());
} // end if
} // end while
// stop timer
timer.stopTimer(method);
// return the query results
return docIds;
} catch (IOException e) {
System.out.println("! Could not get docIds from lexicon.");
e.printStackTrace();
return null;
} // end try/catch
} else {
System.out.println("! ERROR: Limit must be greater than zero!");
return null;
} // end if
} // end getDocIds()
/**
* Read the HitList for given docId and return size of that hitlist
* @return
*/
private int getHitListSize() {
try {
int hitListSize = (indexFile.readByte() & 0xff);
if (hitListSize < 0xff) {
return (hitListSize & 0xff) * 2 + 1;
} else {
return (indexFile.readShort() * 2) + 3;
} // end if
} catch (Exception e) {
System.out.println("! Could not get hit list size.");
e.printStackTrace();
return -1;
} // end try/catch
} // end getHitListSize()
} // end InvertedIndexFileReader class
/**
* LexMapEntry is what is stored for each word in lexicon.
* How many docs in this index contain the word,
* and pointer to place in index area of inverted index where entries for this word start.
* @author Adam Steinberger, Sam Gunther
*/
class LexMapEntry {
public Integer nDocs;
public Long ptr;
/**
* LexMapEntry constructor.
* @param nd nDocs
* @param pt Pointer
*/
public LexMapEntry(Integer nd, Long pt) {
nDocs = nd;
ptr = pt;
} // end LexMapEntry constructor
} // end LexMapEntry class
| UTF-8 | Java | 13,600 | java | InvertedIndexFileReader.java | Java | [
{
"context": " file into memory and query the index.\r\n * @author Adam Steinberger, Sam Gunther\r\n */\r\npublic class InvertedIndexFile",
"end": 520,
"score": 0.9998812675476074,
"start": 504,
"tag": "NAME",
"value": "Adam Steinberger"
},
{
"context": "and query the index.\r\n * @a... | null | [] | package search.indexserver;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.TreeMap;
import search.common.Timer;
import search.common.Timer.Method;
/**
* Read the Inverted Index file into memory and query the index.
* @author <NAME>, <NAME>
*/
public class InvertedIndexFileReader {
// provides random access to the index (e.g. to jump to an offset in the index area)
private RandomAccessFile indexFile;
// provides sequential access to the index (for reading the lex map into memory)
private DataInputStream indexFile1;
// the in-memory lexicon for looking up offsets/ndocs by word
private TreeMap<String, LexMapEntry> lexMap;
private final static Timer timer = new Timer("InvertedIndexFileReader",true);
private boolean verbose;
public boolean isVerbose() {
return verbose;
} // end isVerbose()
public void setVerbose(boolean verbose) {
this.verbose = verbose;
} // end setVerbose()
/**
* Create a new inverted index file reader given a docId.
* Note: There is a bit of a startup delay while reading the lexicon into memory.
* @param docId
*/
public InvertedIndexFileReader(int docId, boolean v) {
// add new method to timer
Method method = timer.addMethod("InvertedIndexFileReader");
try {
// initiate timer
this.verbose = v;
// fire up the random and sequential file readers
timer.startTimer("Open index chunk for reading",method);
String filename = String.format("chunk%1$016x.index", docId);
this.indexFile = new RandomAccessFile(new File(filename), "r");
this.indexFile1 = new DataInputStream(new FileInputStream(new File(filename)));
timer.stopTimer(method);
// read the lexicon into memory (this takes a minute)
timer.startTimer("Read Lexicon Map into Memory",method);
this.lexMap = getLexMap();
timer.stopTimer(method);
} catch (Exception ex) {
System.out.println("! Could not create inverted index file reader.");
System.out.println(ex);
} // end try/catch
} // end InvertedIndexFileReader constructor
/**
* Transfer query words to priority queue based on nDocs size.
* @param words
*/
private PriorityQueue<Word> enqueueWords(ArrayDeque<String> words) {
PriorityQueue<Word> result = new PriorityQueue<Word>();
Iterator<String> it = words.iterator();
// add new method to timer
Method method = timer.addMethod("enqueueWords");
while (it.hasNext()) {
String word = (String) it.next();
int nDocs = lexMap.get(word).nDocs;
Word w = new Word(word,nDocs);
// add word to queue
timer.startTimer("Enqueue \"" + w.getWord() + "\" to priority queue",method);
result.add(w);
timer.stopTimer(method);
} // end while
return result;
} // end enqueueWords()
/**
* Query words ORed together.
* @return
*/
public int[] queryOR(ArrayDeque<String> words, int limit) {
// add new method to timer
Method method = timer.addMethod("queryOR");
// enqueue search words based on nDocs size
timer.startTimer("Enqueue search terms",method);
PriorityQueue<Word> search = enqueueWords(words);
timer.stopTimer(method);
// get docIds for word with smallest nDocs.
Word word = search.poll();
// get docIds for search term
timer.startTimer("Search inverted index for \"" + word.getWord() + "\"",method);
int[] results = getDocIds(word.getWord(),word.getnDocs());
timer.stopTimer(method);
// merge docIds for all other words, so only common docIds remain
while (!search.isEmpty()) {
// get next search term
word = search.poll();
// get docIds for search term
timer.startTimer("Search inverted index for \"" + word.getWord() + "\"",method);
int[] temp = getDocIds(word.getWord(),word.getnDocs());
timer.stopTimer(method);
// merge search results
timer.startTimer("Merge search results",method);
results = mergeOR(temp,results,limit);
timer.stopTimer(method);
} // end while
// return null if no results found.
if (results.length == 0) {
System.out.println("! No results found.");
results = null;
} // end if
return results;
} // end queryOR()
/**
* Merge two int arrays so all unique elements in both arrays are added to new array
* @param t
* @param r
* @return
*/
private int[] mergeOR(int[] t, int[] r, int limit) {
// add new method to timer
Method method = timer.addMethod("mergeOR");
// start timer
timer.startTimer("Add all docIds to results array",method);
int[] result = null;
if (r.length > t.length) {
if (t.length >= limit) {
result = Arrays.copyOf(t,limit);
} else {
int size = limit;
if (t.length + r.length < limit) {
size = t.length + r.length;
} // end if
result = new int [size];
for (int i = 0; i < t.length; i++) {
result[i] = t[i];
} // end for
int index = -1;
for (int i = t.length; i < size; i++) {
int search = -1;
while (search < 0) {
index++;
Arrays.binarySearch(t,r[index]);
} // end while
result[i] = r[index];
} // end for
} // end if
} else {
if (r.length >= limit) {
result = Arrays.copyOf(r,limit);
} else {
int size = limit;
if (r.length + t.length < limit) {
size = r.length + t.length;
} // end if
result = new int [size];
for (int i = 0; i < r.length; i++) {
result[i] = r[i];
} // end for
for (int i = r.length; i < size; i++) {
result[i] = t[i-r.length];
} // end for
} // end if
} // end if
// stop timer
timer.stopTimer(method);
return result;
} // end mergeOR()
/**
* Query words ANDed together.
* @return
*/
public int[] queryAND(ArrayDeque<String> words, int limit) {
// add new method to timer
Method method = timer.addMethod("queryAND");
// enqueue search words based on nDocs size
timer.startTimer("Enqueue search terms",method);
PriorityQueue<Word> search = enqueueWords(words);
timer.stopTimer(method);
// get docIds for word with smallest nDocs.
Word word = search.poll();
// get docIds for search term
timer.startTimer("Search inverted index for \"" + word.getWord() + "\"",method);
int[] results = getDocIds(word.getWord(),word.getnDocs());
timer.stopTimer(method);
// merge docIds for all other words, so only common docIds remain
while (!search.isEmpty()) {
// get next search term
word = search.poll();
// get docIds for search term
timer.startTimer("Search inverted index for \"" + word.getWord() + "\"",method);
int[] temp = getDocIds(word.getWord(),word.getnDocs());
timer.stopTimer(method);
// merge search results
timer.startTimer("Merge search results",method);
results = mergeAND(temp,results,limit);
timer.stopTimer(method);
} // end while
// resize results to results limit
if (results.length > limit) {
// resize results array
timer.startTimer("Resize results array to size " + limit,method);
results = Arrays.copyOf(results, limit);
timer.stopTimer(method);
} // end if
// return null if no results found.
if (results.length == 0) {
System.out.println("! No results found.");
results = null;
} // end if
return results;
} // end queryAND()
/**
* Merge two int arrays so only elements common to both arrays remain
* @param t
* @param r
* @return
*/
private int[] mergeAND(int[] t, int[] r, int limit) {
// add new method to timer
Method method = timer.addMethod("mergeAND");
int size = limit;
if (t.length < limit || r.length < limit) {
size = Math.min(t.length,r.length);
} // end if
// start timer
timer.startTimer("Add all docIds common to both arrays to list",method);
int[] result = new int [size];
int i = 0, j = 0, index = 0;
while ((i < t.length) && (j < r.length) && (index < size)) {
if (t[i] > r[j]) {
j++;
} else if (t[i] < r[j]) {
i++;
} else {
result[index] = t[i];
index++;
i++;
j++;
} // end if
} // end while
// stop timer
timer.stopTimer(method);
return result;
} // end mergeAND()
/**
* Read the Lex Map into Memory.
* @return
*/
@SuppressWarnings("deprecation")
private TreeMap<String, LexMapEntry> getLexMap() {
// add new method to timer
Method method = timer.addMethod("getLexMap");
// create new LexMap
TreeMap<String, LexMapEntry> map = new TreeMap<String, LexMapEntry>();
try {
// the first 8 bytes tell us the offset that we
// should STOP reading the lexicon from (that's the
// end of the lex area and beginning of the index area)
timer.startTimer("Get offset to stop reading lexicon from",method);
byte[] boundaryBytes = new byte[8];
indexFile1.read(boundaryBytes);
long lexMapBoundary = ByteBuffer.wrap(boundaryBytes).getLong();
int offset = 8;
timer.stopTimer(method);
// start timer
timer.startTimer("Read word and nDocs info from lexicon",method);
// now, read the word and its lexmapentry (ndocs-int, offsetToIndexArea-long)
// we keep reading until we reach the end of the lexMap (lexMapBoundary)
String word = "";
while (offset < lexMapBoundary) {
// get the word
word = indexFile1.readLine();
offset+= word.getBytes().length;
// get ndocs, offset
LexMapEntry entry = new LexMapEntry(indexFile1.readInt(),indexFile1.readLong());
map.put(word.toString(), entry);
offset += 12;
} // end while
// stop timer
timer.stopTimer(method);
} catch (Exception ex) {
System.out.println("! Could not read from the lexicon.");
ex.printStackTrace();
} // end try/catch
return map;
} // end getLexMap()
/**
* Return an array of DocIds for single-word query.
* @param word
* @param limit
* @return
*/
public int[] getDocIds(String word, int limit) {
// add new method to timer
Method method = timer.addMethod("getDocIds");
if (limit > 0) {
try {
// get the number of matching docs from the lexicon for this word
int nDocs = lexMap.get(word).nDocs;
// now seek into the index file at the offset we get from the lexicon for this word
timer.startTimer("Seek word pointer for search query in lexicon",method);
indexFile.seek(lexMap.get(word).ptr);
timer.stopTimer(method);
// limit is what we use to stop reading from the index - we stop when we hit the limit given
// at query time, or nDocs if that is smaller than what the user wants
if (nDocs < limit) {
limit = nDocs;
} // end if
// the array of docIds to return
int[] docIds = new int [limit];
int docsFound = 0; // number of docs found so far
int docsSearched = 0; // number of docs searched so far
// start timer
timer.startTimer("Get docIds from the lexicon",method);
// we set done = true once we have enough docs
boolean done = false;
while ((docsFound < limit) && !done) {
docIds[docsFound++] = indexFile.readInt();
if (++docsSearched == limit) {
done = true; // if we have searched enough...
} else {
// now move to next docId - we have to skip over the current docId's
// hitlist to get to the next one
indexFile.seek(indexFile.getFilePointer() + getHitListSize());
} // end if
} // end while
// stop timer
timer.stopTimer(method);
// return the query results
return docIds;
} catch (IOException e) {
System.out.println("! Could not get docIds from lexicon.");
e.printStackTrace();
return null;
} // end try/catch
} else {
System.out.println("! ERROR: Limit must be greater than zero!");
return null;
} // end if
} // end getDocIds()
/**
* Read the HitList for given docId and return size of that hitlist
* @return
*/
private int getHitListSize() {
try {
int hitListSize = (indexFile.readByte() & 0xff);
if (hitListSize < 0xff) {
return (hitListSize & 0xff) * 2 + 1;
} else {
return (indexFile.readShort() * 2) + 3;
} // end if
} catch (Exception e) {
System.out.println("! Could not get hit list size.");
e.printStackTrace();
return -1;
} // end try/catch
} // end getHitListSize()
} // end InvertedIndexFileReader class
/**
* LexMapEntry is what is stored for each word in lexicon.
* How many docs in this index contain the word,
* and pointer to place in index area of inverted index where entries for this word start.
* @author <NAME>, <NAME>
*/
class LexMapEntry {
public Integer nDocs;
public Long ptr;
/**
* LexMapEntry constructor.
* @param nd nDocs
* @param pt Pointer
*/
public LexMapEntry(Integer nd, Long pt) {
nDocs = nd;
ptr = pt;
} // end LexMapEntry constructor
} // end LexMapEntry class
| 13,570 | 0.617059 | 0.614412 | 490 | 25.755102 | 21.955828 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.828571 | false | false | 13 |
f9a86dd7f38653fb43fdd4799dbb5f777667dd70 | 32,212,254,771,341 | e1ebedf970bdda5ad3e6e48de4a3cf8355cc161b | /app/src/main/java/com/sinostar/assistant/ui/basecontrol/baseControlActivity.java | 87946f8b7a9a1163122b4fd78413231597557dc9 | [] | no_license | fazhongxu/SmugglerCaseApp | https://github.com/fazhongxu/SmugglerCaseApp | 05c468a284ba23009e5954ce11227798f8b82570 | 8536f66d450d0f47df6e530141bf0c180d5c4ae0 | refs/heads/master | 2022-01-11T20:40:23.180000 | 2019-03-18T09:54:36 | 2019-03-18T09:54:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sinostar.assistant.ui.basecontrol;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.siberiadante.customdialoglib.CustomDialog;
import com.sinostar.assistant.R;
import org.w3c.dom.Text;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import static com.sinostar.assistant.base.ApplicationUtil.getContext;
public class baseControlActivity extends AppCompatActivity {
@BindView( R.id.spinner )
Spinner rSpinner;
@BindView(R.id.button)
Button rButton;
int TAG1401 = 1000;
int TAG1402 = 2000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_base_control );
ButterKnife.bind( this );
String[] ctype = new String[]{"全部", "游戏", "电影", "娱乐", "图书"};
//创建一个数组适配器
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ctype);
//设置下拉列表框的下拉选项样式
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
rSpinner.setAdapter(adapter);
}
@OnClick({R.id.button,R.id.buttonDialog,R.id.loginDialogButton,R.id.login2DialogButton,R.id.login3DialogButton})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.button:
Toast.makeText(this,"弹出框信息", Toast.LENGTH_LONG).show();
break;
case R.id.buttonDialog:
final android.app.AlertDialog alertDialog1 = new android.app.AlertDialog.Builder(this)
.setTitle("提示标题")
.setMessage("提示内容")
.setIcon(R.mipmap.ic_launcher)
.setPositiveButton( "确定按钮", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(baseControlActivity.this,"进入确认按钮事件", Toast.LENGTH_LONG).show();
dialog.cancel();
}
} )
.setNegativeButton( "取消按钮", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText( baseControlActivity.this, "进入取消按钮事件", Toast.LENGTH_LONG ).show();
dialog.cancel();
}
})
.setNeutralButton( "第三个按钮", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText( baseControlActivity.this, "进入第三个按钮事件", Toast.LENGTH_SHORT ).show();
dialog.cancel();
}
} )
.create();
alertDialog1.show();
break;
case R.id.loginDialogButton:
loginDialogButtonClick();
break;
case R.id.login2DialogButton:
login2DialogButtonClick();
break;
case R.id.login3DialogButton:
login3DialogButtonClick();
break;
}
}
public void login3DialogButtonClick()
{
AlertDialog.Builder editDialog = new AlertDialog.Builder(this);
View view = View.inflate(baseControlActivity.this,R.layout.activity_login, null);
editDialog.setView(view);
final AlertDialog alertDialog = editDialog.create();
alertDialog.show();
}
public void loginDialogButtonClick()
{
final EditText editText=new EditText( this );
AlertDialog.Builder editDialog = new AlertDialog.Builder(this);
editDialog.setTitle("弹出登录页面");
editDialog.setIcon(R.mipmap.ic_launcher);
//设置dialog布局
editDialog.setView(editText);
//设置按钮
editDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(baseControlActivity.this,
editText.getText().toString().trim(),Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
editDialog.create().show();
}
public void login2DialogButtonClick()
{
WindowManager wm = (WindowManager) getContext()
.getSystemService(Context.WINDOW_SERVICE);
int width = wm.getDefaultDisplay().getWidth();
int height = wm.getDefaultDisplay().getHeight();
final RelativeLayout relativeLayout222=new RelativeLayout( this );
relativeLayout222.setMinimumWidth( width );
relativeLayout222.setPadding( 40,40,40,40 );
final RelativeLayout relativeLayout=new RelativeLayout( this );
relativeLayout.setMinimumWidth( width );
//relativeLayout.setGravity( Gravity.FILL_VERTICAL );
final LinearLayout linearLayout=new LinearLayout( this );
linearLayout.setMinimumWidth(width);
final TextView textView=new TextView(this);
textView.setText("用户名:");
final EditText editText=new EditText( this );
editText.setId(TAG1401 );
editText.setWidth( 650 );
linearLayout.addView( textView );
linearLayout.addView( editText );
relativeLayout.addView( linearLayout );
final RelativeLayout relativeLayout1=new RelativeLayout( this );
relativeLayout1.setMinimumWidth( width );
relativeLayout1.setPadding( 0,40,0,0 );
final LinearLayout linearLayout1=new LinearLayout( this );
linearLayout1.setMinimumWidth(width);
final TextView textView1=new TextView(this);
textView1.setText("密码:");
final EditText editText1=new EditText( this );
editText1.setId(TAG1402 );
editText1.setWidth( 650 );
linearLayout1.addView( textView1 );
linearLayout1.addView( editText1 );
relativeLayout1.addView( linearLayout1 );
// final EditText editText2=new EditText( this );
// linearLayout.addView( editText );
// linearLayout.addView( editText2 );
AlertDialog.Builder editDialog = new AlertDialog.Builder(this);
editDialog.setTitle("弹出登录页面");
editDialog.setIcon(R.mipmap.ic_launcher);
relativeLayout222.addView( relativeLayout );
relativeLayout222.addView( relativeLayout1 );
//设置dialog布局
editDialog.setView(relativeLayout222);
//设置按钮
editDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(baseControlActivity.this,
editText.getText().toString().trim(),Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
editDialog.create().show();
}
}
| UTF-8 | Java | 8,045 | java | baseControlActivity.java | Java | [] | null | [] | package com.sinostar.assistant.ui.basecontrol;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.siberiadante.customdialoglib.CustomDialog;
import com.sinostar.assistant.R;
import org.w3c.dom.Text;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import static com.sinostar.assistant.base.ApplicationUtil.getContext;
public class baseControlActivity extends AppCompatActivity {
@BindView( R.id.spinner )
Spinner rSpinner;
@BindView(R.id.button)
Button rButton;
int TAG1401 = 1000;
int TAG1402 = 2000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_base_control );
ButterKnife.bind( this );
String[] ctype = new String[]{"全部", "游戏", "电影", "娱乐", "图书"};
//创建一个数组适配器
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ctype);
//设置下拉列表框的下拉选项样式
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
rSpinner.setAdapter(adapter);
}
@OnClick({R.id.button,R.id.buttonDialog,R.id.loginDialogButton,R.id.login2DialogButton,R.id.login3DialogButton})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.button:
Toast.makeText(this,"弹出框信息", Toast.LENGTH_LONG).show();
break;
case R.id.buttonDialog:
final android.app.AlertDialog alertDialog1 = new android.app.AlertDialog.Builder(this)
.setTitle("提示标题")
.setMessage("提示内容")
.setIcon(R.mipmap.ic_launcher)
.setPositiveButton( "确定按钮", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(baseControlActivity.this,"进入确认按钮事件", Toast.LENGTH_LONG).show();
dialog.cancel();
}
} )
.setNegativeButton( "取消按钮", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText( baseControlActivity.this, "进入取消按钮事件", Toast.LENGTH_LONG ).show();
dialog.cancel();
}
})
.setNeutralButton( "第三个按钮", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText( baseControlActivity.this, "进入第三个按钮事件", Toast.LENGTH_SHORT ).show();
dialog.cancel();
}
} )
.create();
alertDialog1.show();
break;
case R.id.loginDialogButton:
loginDialogButtonClick();
break;
case R.id.login2DialogButton:
login2DialogButtonClick();
break;
case R.id.login3DialogButton:
login3DialogButtonClick();
break;
}
}
public void login3DialogButtonClick()
{
AlertDialog.Builder editDialog = new AlertDialog.Builder(this);
View view = View.inflate(baseControlActivity.this,R.layout.activity_login, null);
editDialog.setView(view);
final AlertDialog alertDialog = editDialog.create();
alertDialog.show();
}
public void loginDialogButtonClick()
{
final EditText editText=new EditText( this );
AlertDialog.Builder editDialog = new AlertDialog.Builder(this);
editDialog.setTitle("弹出登录页面");
editDialog.setIcon(R.mipmap.ic_launcher);
//设置dialog布局
editDialog.setView(editText);
//设置按钮
editDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(baseControlActivity.this,
editText.getText().toString().trim(),Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
editDialog.create().show();
}
public void login2DialogButtonClick()
{
WindowManager wm = (WindowManager) getContext()
.getSystemService(Context.WINDOW_SERVICE);
int width = wm.getDefaultDisplay().getWidth();
int height = wm.getDefaultDisplay().getHeight();
final RelativeLayout relativeLayout222=new RelativeLayout( this );
relativeLayout222.setMinimumWidth( width );
relativeLayout222.setPadding( 40,40,40,40 );
final RelativeLayout relativeLayout=new RelativeLayout( this );
relativeLayout.setMinimumWidth( width );
//relativeLayout.setGravity( Gravity.FILL_VERTICAL );
final LinearLayout linearLayout=new LinearLayout( this );
linearLayout.setMinimumWidth(width);
final TextView textView=new TextView(this);
textView.setText("用户名:");
final EditText editText=new EditText( this );
editText.setId(TAG1401 );
editText.setWidth( 650 );
linearLayout.addView( textView );
linearLayout.addView( editText );
relativeLayout.addView( linearLayout );
final RelativeLayout relativeLayout1=new RelativeLayout( this );
relativeLayout1.setMinimumWidth( width );
relativeLayout1.setPadding( 0,40,0,0 );
final LinearLayout linearLayout1=new LinearLayout( this );
linearLayout1.setMinimumWidth(width);
final TextView textView1=new TextView(this);
textView1.setText("密码:");
final EditText editText1=new EditText( this );
editText1.setId(TAG1402 );
editText1.setWidth( 650 );
linearLayout1.addView( textView1 );
linearLayout1.addView( editText1 );
relativeLayout1.addView( linearLayout1 );
// final EditText editText2=new EditText( this );
// linearLayout.addView( editText );
// linearLayout.addView( editText2 );
AlertDialog.Builder editDialog = new AlertDialog.Builder(this);
editDialog.setTitle("弹出登录页面");
editDialog.setIcon(R.mipmap.ic_launcher);
relativeLayout222.addView( relativeLayout );
relativeLayout222.addView( relativeLayout1 );
//设置dialog布局
editDialog.setView(relativeLayout222);
//设置按钮
editDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(baseControlActivity.this,
editText.getText().toString().trim(),Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
editDialog.create().show();
}
}
| 8,045 | 0.606433 | 0.594515 | 202 | 37.628712 | 27.070055 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.747525 | false | false | 13 |
aa9eb043d5c8a94ae6745462487bc4d555e1285e | 13,245,679,177,091 | 69996b11d12d5bb4d75f5bc18066f5298fe13183 | /src/main/java/com/section9/rubbel/models/Player.java | 0fb7d98f5dce92109637a4000ac67dc83593167f | [] | no_license | PBProgrammer/rubbel-app-backend | https://github.com/PBProgrammer/rubbel-app-backend | 89effb9b93367e6667a19b18c40a2ca37dea5025 | 8af824085cec5cec8f52cd34ce69a72570ae4a0e | refs/heads/master | 2022-12-27T08:56:30.190000 | 2020-10-13T18:37:35 | 2020-10-13T18:37:35 | 303,796,169 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.section9.rubbel.models;
import com.section9.rubbel.services.StaticValues;
import com.section9.rubbel.services.Util;
import java.util.List;
import java.util.UUID;
public class Player {
private String name;
private UUID id;
private int score;
private boolean ready;
private boolean host;
private String icon;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public boolean isReady() {
return ready;
}
public void setReady(boolean ready) {
this.ready = ready;
}
public boolean isHost() {
return host;
}
public void setHost(boolean host) {
this.host = host;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public static Player create(Player basePlayer) {
return create(basePlayer, false);
}
public static Player create(Player basePlayer, boolean keepIcon) {
Player player = new Player();
player.setHost(basePlayer.isHost());
player.setScore(0);
if(keepIcon) {
player.setIcon(basePlayer.getIcon());
}else{
player.setIcon(StaticValues.getRandomIcon());
}
if(basePlayer.getName() != null) {
player.setName(basePlayer.getName());
}else{
player.setName(Util.getRandomPlayerName());
}
if(basePlayer.getId() != null) {
player.setId(basePlayer.getId());
}else{
player.setId(UUID.randomUUID());
}
return player;
}
}
| UTF-8 | Java | 1,923 | java | Player.java | Java | [] | null | [] | package com.section9.rubbel.models;
import com.section9.rubbel.services.StaticValues;
import com.section9.rubbel.services.Util;
import java.util.List;
import java.util.UUID;
public class Player {
private String name;
private UUID id;
private int score;
private boolean ready;
private boolean host;
private String icon;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public boolean isReady() {
return ready;
}
public void setReady(boolean ready) {
this.ready = ready;
}
public boolean isHost() {
return host;
}
public void setHost(boolean host) {
this.host = host;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public static Player create(Player basePlayer) {
return create(basePlayer, false);
}
public static Player create(Player basePlayer, boolean keepIcon) {
Player player = new Player();
player.setHost(basePlayer.isHost());
player.setScore(0);
if(keepIcon) {
player.setIcon(basePlayer.getIcon());
}else{
player.setIcon(StaticValues.getRandomIcon());
}
if(basePlayer.getName() != null) {
player.setName(basePlayer.getName());
}else{
player.setName(Util.getRandomPlayerName());
}
if(basePlayer.getId() != null) {
player.setId(basePlayer.getId());
}else{
player.setId(UUID.randomUUID());
}
return player;
}
}
| 1,923 | 0.577223 | 0.575143 | 92 | 19.902174 | 17.106482 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.391304 | false | false | 13 |
f62efc2f8a2c3c427c44d0b5be6777af009606f5 | 1,786,706,461,919 | 56ba68783e087aaeed5a61a7724b412c9593e581 | /workspace_java/bank_Interface/src/bank_Interface/employee_interface.java | 6a2864ae38f9ddc97111ac29cf18871a64d4877a | [] | no_license | vkalambe/Core-Java | https://github.com/vkalambe/Core-Java | 061354fd59fab10a799ab446b3d478dcc4d7e7d1 | 2a9a8420fe9a742270e21556f1c35bd7421e75a3 | refs/heads/master | 2021-01-12T11:29:16.368000 | 2016-11-15T08:20:28 | 2016-11-15T08:20:28 | 72,935,775 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bank_Interface;
public class employee_interface {
int empId;
String name;
public employee_interface(int empId, String name) {
super();
this.empId = empId;
this.name = name;
}
public void display()
{
System.out.println("base");
}
public static void main(String[] argc)
{
}
}
| UTF-8 | Java | 334 | java | employee_interface.java | Java | [] | null | [] | package bank_Interface;
public class employee_interface {
int empId;
String name;
public employee_interface(int empId, String name) {
super();
this.empId = empId;
this.name = name;
}
public void display()
{
System.out.println("base");
}
public static void main(String[] argc)
{
}
}
| 334 | 0.613772 | 0.613772 | 21 | 13.904762 | 14.520609 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.285714 | false | false | 13 |
70ca3c13803dc8077985e412b01f238b975fec1e | 11,347,303,608,652 | c0542546866385891c196b665d65a8bfa810f1a3 | /app-decompiled/ClockworkAmbient/src/android/support/v4/view/ViewCompatLollipop.java | 219d3844435e1556b889c8a8a7c533acec7b0181 | [] | no_license | auxor/android-wear-decompile | https://github.com/auxor/android-wear-decompile | 6892f3564d316b1f436757b72690864936dd1a82 | eb8ad0d8003c5a3b5623918c79334290f143a2a8 | refs/heads/master | 2016-09-08T02:32:48.433000 | 2015-10-12T02:17:27 | 2015-10-12T02:19:32 | 42,517,868 | 5 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package android.support.v4.view;
import android.view.View;
class ViewCompatLollipop {
public static void stopNestedScroll(View view) {
view.stopNestedScroll();
}
}
| UTF-8 | Java | 182 | java | ViewCompatLollipop.java | Java | [] | null | [] | package android.support.v4.view;
import android.view.View;
class ViewCompatLollipop {
public static void stopNestedScroll(View view) {
view.stopNestedScroll();
}
}
| 182 | 0.71978 | 0.714286 | 9 | 19.222221 | 17.491444 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 13 |
c912381b6487bba0cb471dad5d718461de14bd22 | 15,942,918,670,834 | 08c72d69c5916f693cc81d49197f87b1d32fbd0e | /src/java/persistencia/TurnosDao.java | 9d98146ca1f22298e0412f2a2efd7dc78c4e59f8 | [] | no_license | gimenezsergio/paraChirino | https://github.com/gimenezsergio/paraChirino | 68969db0685c61c46b219e71ae9b780e9154996f | c53bf848697139914be92499d8217245120b7c00 | refs/heads/master | 2020-05-06T15:14:53.175000 | 2019-04-08T15:27:51 | 2019-04-08T15:27:51 | 180,178,414 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package persistencia;
import entidades.DB;
import entidades.Turno;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class TurnosDao {
private TurnosDao() throws ClassNotFoundException,
IOException, SQLException {
}
private static TurnosDao INSTANCE = null;
public static TurnosDao getInstance() throws ClassNotFoundException,
IOException, SQLException {
if (INSTANCE == null) {
INSTANCE = new TurnosDao();
}
return INSTANCE;
}
private final static String TURNOS_SELECT_ALL = "SELECT turnos_id, turnos_id_paciente, turnos_id_grilla, turnos_desde, turnos_hasta, pacientes.paci_nombre FROM public.turnos INNER JOIN pacientes ON turnos_id_paciente = pacientes.paci_id ;";
public ArrayList<Turno> obtener() throws ClassNotFoundException, IOException, SQLException {
ArrayList<Turno> listaTurnos = new ArrayList();
Connection con = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
con = DB.getInstance().getConnection();
pstm = con.prepareStatement(TURNOS_SELECT_ALL);
rs = pstm.executeQuery();
while (rs.next()){
Turno miTurno = new Turno(
rs.getString("paci_nombre"),
rs.getString("turnos_id_grilla"),
rs.getString("turnos_desde"),
rs.getString("turnos_hasta"));
listaTurnos.add(miTurno);
}
// } catch (Exception ex) {
// ex.printStackTrace();
// System.out.println("Exeption: " + ex.getMessage());
// throw ex;
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return listaTurnos;
}
}
| UTF-8 | Java | 2,092 | java | TurnosDao.java | Java | [] | null | [] | package persistencia;
import entidades.DB;
import entidades.Turno;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class TurnosDao {
private TurnosDao() throws ClassNotFoundException,
IOException, SQLException {
}
private static TurnosDao INSTANCE = null;
public static TurnosDao getInstance() throws ClassNotFoundException,
IOException, SQLException {
if (INSTANCE == null) {
INSTANCE = new TurnosDao();
}
return INSTANCE;
}
private final static String TURNOS_SELECT_ALL = "SELECT turnos_id, turnos_id_paciente, turnos_id_grilla, turnos_desde, turnos_hasta, pacientes.paci_nombre FROM public.turnos INNER JOIN pacientes ON turnos_id_paciente = pacientes.paci_id ;";
public ArrayList<Turno> obtener() throws ClassNotFoundException, IOException, SQLException {
ArrayList<Turno> listaTurnos = new ArrayList();
Connection con = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
con = DB.getInstance().getConnection();
pstm = con.prepareStatement(TURNOS_SELECT_ALL);
rs = pstm.executeQuery();
while (rs.next()){
Turno miTurno = new Turno(
rs.getString("paci_nombre"),
rs.getString("turnos_id_grilla"),
rs.getString("turnos_desde"),
rs.getString("turnos_hasta"));
listaTurnos.add(miTurno);
}
// } catch (Exception ex) {
// ex.printStackTrace();
// System.out.println("Exeption: " + ex.getMessage());
// throw ex;
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return listaTurnos;
}
}
| 2,092 | 0.574092 | 0.574092 | 63 | 32.206348 | 33.659904 | 244 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.68254 | false | false | 13 |
00383a59976fb81bfdc9829cfa17638804f12b8a | 16,518,444,234,589 | 8b9fcdede4cfbe4e53a19a2e3f8df08ba2e2e739 | /BoEC1-war/src/java/search/ItemFacade.java | 82bbad0029ccd8ca2930b34f99ce92176e21bb31 | [] | no_license | lemanh1997/BoEC_DA | https://github.com/lemanh1997/BoEC_DA | e0fa8515042cb57821d5f504b7371b9414eabdb8 | 1aad43a6c019e9e532ffaec27d08d7604e0f8c44 | refs/heads/master | 2020-05-23T10:33:18.072000 | 2019-05-09T23:53:29 | 2019-05-09T23:53:29 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package search;
import entity.Clothes;
import java.util.List;
/**
*
* facade pattern
*/
public class ItemFacade {
private static final ItemFacade INSTANCE = new ItemFacade();
private ClothesCriteria clothesCri;
private ItemFacade() {
clothesCri = new ClothesCriteria();
}
public static ItemFacade getInstance() {
return INSTANCE;
}
public List<Clothes> searchByName(String name) {
return clothesCri.meetCriteria(name);
}
// public ItemFacade(ClothesCriteria clothes) {
// this.clothesCri = clothes;
// }
}
| UTF-8 | Java | 784 | java | ItemFacade.java | Java | [] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package search;
import entity.Clothes;
import java.util.List;
/**
*
* facade pattern
*/
public class ItemFacade {
private static final ItemFacade INSTANCE = new ItemFacade();
private ClothesCriteria clothesCri;
private ItemFacade() {
clothesCri = new ClothesCriteria();
}
public static ItemFacade getInstance() {
return INSTANCE;
}
public List<Clothes> searchByName(String name) {
return clothesCri.meetCriteria(name);
}
// public ItemFacade(ClothesCriteria clothes) {
// this.clothesCri = clothes;
// }
}
| 784 | 0.668367 | 0.668367 | 37 | 20.18919 | 21.700464 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.324324 | false | false | 13 |
4b194c1660a86ada5eee32d6d8bce9054b1f7ecf | 19,868,518,726,818 | fff9021b46d778e7aa254213e079528180e51204 | /app/src/main/java/com/fwheart/androidsnippet/sample/SampleActivity.java | d82344cd96ac3874fa58c2028ed61c2652a6e07a | [] | no_license | YeomanYe/android-snippet | https://github.com/YeomanYe/android-snippet | 166e5d86d286e4d62f4659f70f4dad2a1f03ed72 | 71e0dde090a990c8f207223bdf2fc6f71b63c0aa | refs/heads/master | 2020-03-22T16:06:33.301000 | 2018-08-10T07:45:05 | 2018-08-10T07:45:05 | 140,303,422 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fwheart.androidsnippet.sample;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.fwheart.androidsnippet.R;
import com.fwheart.androidsnippet.helper.AssetHelper;
import com.fwheart.androidsnippet.helper.StatusBarHelper;
import com.fwheart.androidsnippet.widget.tab.ASTabBar;
import com.fwheart.androidsnippet.widget.tab.ASTabPage;
public class SampleActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle drawerToggle;
private ListView mDrawerList;
ViewPager pager;
private String[] titles = new String[]{"Sample Tab 1", "Sample Tab 2", "Sample Tab 3", "Sample Tab 4"
, "Sample Tab 5", "Sample Tab 6", "Sample Tab 7", "Sample Tab 8"};
private String[] titles2 = new String[]{"Sample Tab1","Sample Tab2"};
private Toolbar toolbar;
ASTabBar slidingTabLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.navdrawer);
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_ab_drawer);
}
final ASTabPage asTabPage = (ASTabPage) findViewById(R.id.asTabPage);
ASTabPage.TextIconItem item1 = new ASTabPage.TextIconItem("List",R.mipmap.ic_launcher,R.drawable.ic_launcher,TestFragment.newInstance(0));
ASTabPage.TextIconItem item2 = new ASTabPage.TextIconItem("Dialog",R.mipmap.ic_launcher,R.drawable.ic_launcher,TestFragment.newInstance(1));
ASTabPage.TextIconItem item3 = new ASTabPage.TextIconItem("Other",R.mipmap.ic_launcher,R.drawable.ic_launcher,TestFragment.newInstance(2));
asTabPage.init(this,item1,item2,item3);
drawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name, R.string.app_name);
mDrawerLayout.setDrawerListener(drawerToggle);
String[] values = new String[]{
"DEFAULT", "RED", "BLUE", "MATERIAL GREY"
};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
mDrawerList.setAdapter(adapter);
StatusBarHelper.translucent(this);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int color = 0;
switch (position) {
case 0:
color = AssetHelper.getColor(getApplication(),R.color.material_deep_teal_500);
break;
case 1:
color = AssetHelper.getColor(getApplication(),R.color.red);
break;
case 2:
color = AssetHelper.getColor(getApplication(),R.color.blue);
break;
case 3:
color = AssetHelper.getColor(getApplication(),R.color.material_blue_grey_800);
break;
}
asTabPage.setTabBackground(color);
mDrawerList.setBackgroundColor(color);
toolbar.setBackgroundColor(color);
mDrawerLayout.closeDrawer(Gravity.START);
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(Gravity.START);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
| UTF-8 | Java | 4,839 | java | SampleActivity.java | Java | [] | null | [] | package com.fwheart.androidsnippet.sample;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.fwheart.androidsnippet.R;
import com.fwheart.androidsnippet.helper.AssetHelper;
import com.fwheart.androidsnippet.helper.StatusBarHelper;
import com.fwheart.androidsnippet.widget.tab.ASTabBar;
import com.fwheart.androidsnippet.widget.tab.ASTabPage;
public class SampleActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle drawerToggle;
private ListView mDrawerList;
ViewPager pager;
private String[] titles = new String[]{"Sample Tab 1", "Sample Tab 2", "Sample Tab 3", "Sample Tab 4"
, "Sample Tab 5", "Sample Tab 6", "Sample Tab 7", "Sample Tab 8"};
private String[] titles2 = new String[]{"Sample Tab1","Sample Tab2"};
private Toolbar toolbar;
ASTabBar slidingTabLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.navdrawer);
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_ab_drawer);
}
final ASTabPage asTabPage = (ASTabPage) findViewById(R.id.asTabPage);
ASTabPage.TextIconItem item1 = new ASTabPage.TextIconItem("List",R.mipmap.ic_launcher,R.drawable.ic_launcher,TestFragment.newInstance(0));
ASTabPage.TextIconItem item2 = new ASTabPage.TextIconItem("Dialog",R.mipmap.ic_launcher,R.drawable.ic_launcher,TestFragment.newInstance(1));
ASTabPage.TextIconItem item3 = new ASTabPage.TextIconItem("Other",R.mipmap.ic_launcher,R.drawable.ic_launcher,TestFragment.newInstance(2));
asTabPage.init(this,item1,item2,item3);
drawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name, R.string.app_name);
mDrawerLayout.setDrawerListener(drawerToggle);
String[] values = new String[]{
"DEFAULT", "RED", "BLUE", "MATERIAL GREY"
};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
mDrawerList.setAdapter(adapter);
StatusBarHelper.translucent(this);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int color = 0;
switch (position) {
case 0:
color = AssetHelper.getColor(getApplication(),R.color.material_deep_teal_500);
break;
case 1:
color = AssetHelper.getColor(getApplication(),R.color.red);
break;
case 2:
color = AssetHelper.getColor(getApplication(),R.color.blue);
break;
case 3:
color = AssetHelper.getColor(getApplication(),R.color.material_blue_grey_800);
break;
}
asTabPage.setTabBackground(color);
mDrawerList.setBackgroundColor(color);
toolbar.setBackgroundColor(color);
mDrawerLayout.closeDrawer(Gravity.START);
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(Gravity.START);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
| 4,839 | 0.652408 | 0.644555 | 124 | 38.024193 | 31.700071 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.83871 | false | false | 13 |
fb27bb9df103fb4e53db1fa05692723133308fa3 | 23,235,773,090,113 | abdeac78d40c44585924cd6c63e4e604b8b9b680 | /src/main/java/com/apirest/controller/ClienteController.java | cc2b265c875a6bf6a735d6af869c507f2ae49a22 | [] | no_license | kyaraaraujo/APIRest-CRM | https://github.com/kyaraaraujo/APIRest-CRM | 743e4f31b87c70167483d8cb9d053d9ea99118bb | 193233abaa0b7d2fd5775950162b85b6326f3a5d | refs/heads/main | 2023-07-30T17:31:33.616000 | 2021-09-17T21:19:39 | 2021-09-17T21:19:39 | 407,553,836 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.apirest.controller;
import com.apirest.model.Cliente;
import com.apirest.repository.ClienteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
@RestController
@RequestMapping("/clientes")
public class ClienteController {
@Autowired
private ClienteRepository clienteRepository;
@GetMapping
public List<Cliente> listarClientes(){
return clienteRepository.findAll();
}
@GetMapping(path = "/{id}")
public Cliente enccontrarClientePeloIdOuRetornarErro(@PathVariable Long id){
return clienteRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Cliente não existe"));
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED) // ao invés do OK 200, retornará 201
public Cliente cadastrarCliente(@RequestBody Cliente cliente){
return clienteRepository.save(cliente);
}
@DeleteMapping(path = "/{id}")
public void removerCliente(@PathVariable Long id){
clienteRepository.delete(enccontrarClientePeloIdOuRetornarErro(id));
}
@PutMapping
public void atualizarCliente(@RequestBody Cliente cliente){
Cliente clienteAlterado = enccontrarClientePeloIdOuRetornarErro(cliente.getId());
clienteAlterado.setId(cliente.getId());
clienteAlterado.setNome(cliente.getNome());
clienteRepository.save(clienteAlterado);
}
}
| UTF-8 | Java | 1,615 | java | ClienteController.java | Java | [] | null | [] | package com.apirest.controller;
import com.apirest.model.Cliente;
import com.apirest.repository.ClienteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
@RestController
@RequestMapping("/clientes")
public class ClienteController {
@Autowired
private ClienteRepository clienteRepository;
@GetMapping
public List<Cliente> listarClientes(){
return clienteRepository.findAll();
}
@GetMapping(path = "/{id}")
public Cliente enccontrarClientePeloIdOuRetornarErro(@PathVariable Long id){
return clienteRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Cliente não existe"));
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED) // ao invés do OK 200, retornará 201
public Cliente cadastrarCliente(@RequestBody Cliente cliente){
return clienteRepository.save(cliente);
}
@DeleteMapping(path = "/{id}")
public void removerCliente(@PathVariable Long id){
clienteRepository.delete(enccontrarClientePeloIdOuRetornarErro(id));
}
@PutMapping
public void atualizarCliente(@RequestBody Cliente cliente){
Cliente clienteAlterado = enccontrarClientePeloIdOuRetornarErro(cliente.getId());
clienteAlterado.setId(cliente.getId());
clienteAlterado.setNome(cliente.getNome());
clienteRepository.save(clienteAlterado);
}
}
| 1,615 | 0.741935 | 0.738213 | 51 | 30.607843 | 28.233673 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.372549 | false | false | 13 |
87758a70e1f66de369bbf803fe97bc89bd84550e | 32,392,643,367,804 | 37ec82804dc7fbbb768d707cfc7f85605486efe2 | /app/src/main/java/com/pspdfkit/catalog/examples/java/activities/AnnotationSelectionCustomizationActivity.java | 7593a84a7d42d2bdf21ded4ada2a232c65f14ad0 | [
"BSD-3-Clause"
] | permissive | lightnomyus/pspdfkit-android-catalog | https://github.com/lightnomyus/pspdfkit-android-catalog | ae7561cde3df3a167d5a2f4ea1768a8897757077 | a9a92f847925270cd1429e409e6904f80df5bf74 | refs/heads/master | 2023-05-05T19:47:38.144000 | 2021-05-20T12:25:41 | 2021-05-20T12:25:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright © 2014-2021 PSPDFKit GmbH. All rights reserved.
*
* The PSPDFKit Sample applications are licensed with a modified BSD license.
* Please see License for details. This notice may not be removed from this file.
*/
package com.pspdfkit.catalog.examples.java.activities;
import android.os.Bundle;
import androidx.annotation.NonNull;
import com.pspdfkit.annotations.Annotation;
import com.pspdfkit.ui.PdfActivity;
import com.pspdfkit.ui.special_mode.controller.AnnotationSelectionController;
import com.pspdfkit.ui.special_mode.manager.AnnotationManager;
/**
* Shows how to use {@link AnnotationSelectionController} to control annotation selection.
*/
public class AnnotationSelectionCustomizationActivity extends PdfActivity implements AnnotationManager.OnAnnotationSelectedListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Register annotation selection listener.
getPdfFragment().addOnAnnotationSelectedListener(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
getPdfFragment().removeOnAnnotationSelectedListener(this);
}
@Override
public boolean onPrepareAnnotationSelection(@NonNull AnnotationSelectionController controller, @NonNull Annotation annotation, boolean annotationCreated) {
switch (annotation.getType()) {
case STAMP:
// Allow dragging and resizing stamp annotations only when being created. Afterwards they are fixed in place.
if (!annotationCreated) {
// Disable resizing and dragging for selected stamp annotation.
controller.setResizeEnabled(false);
controller.setDraggingEnabled(false);
}
break;
case INK:
// Keep aspect ratio when resizing ink annotations.
controller.setKeepAspectRatioEnabled(true);
break;
case FREETEXT:
// Prevent selection for free-text annotations that are not being created.
return annotationCreated;
default:
}
// Return true here to proceed with selection. Returning false will prevent the selection.
return true;
}
@Override
public void onAnnotationSelected(@NonNull Annotation annotation, boolean annotationCreated) {
// Nothing to do here.
}
}
| UTF-8 | Java | 2,483 | java | AnnotationSelectionCustomizationActivity.java | Java | [] | null | [] | /*
* Copyright © 2014-2021 PSPDFKit GmbH. All rights reserved.
*
* The PSPDFKit Sample applications are licensed with a modified BSD license.
* Please see License for details. This notice may not be removed from this file.
*/
package com.pspdfkit.catalog.examples.java.activities;
import android.os.Bundle;
import androidx.annotation.NonNull;
import com.pspdfkit.annotations.Annotation;
import com.pspdfkit.ui.PdfActivity;
import com.pspdfkit.ui.special_mode.controller.AnnotationSelectionController;
import com.pspdfkit.ui.special_mode.manager.AnnotationManager;
/**
* Shows how to use {@link AnnotationSelectionController} to control annotation selection.
*/
public class AnnotationSelectionCustomizationActivity extends PdfActivity implements AnnotationManager.OnAnnotationSelectedListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Register annotation selection listener.
getPdfFragment().addOnAnnotationSelectedListener(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
getPdfFragment().removeOnAnnotationSelectedListener(this);
}
@Override
public boolean onPrepareAnnotationSelection(@NonNull AnnotationSelectionController controller, @NonNull Annotation annotation, boolean annotationCreated) {
switch (annotation.getType()) {
case STAMP:
// Allow dragging and resizing stamp annotations only when being created. Afterwards they are fixed in place.
if (!annotationCreated) {
// Disable resizing and dragging for selected stamp annotation.
controller.setResizeEnabled(false);
controller.setDraggingEnabled(false);
}
break;
case INK:
// Keep aspect ratio when resizing ink annotations.
controller.setKeepAspectRatioEnabled(true);
break;
case FREETEXT:
// Prevent selection for free-text annotations that are not being created.
return annotationCreated;
default:
}
// Return true here to proceed with selection. Returning false will prevent the selection.
return true;
}
@Override
public void onAnnotationSelected(@NonNull Annotation annotation, boolean annotationCreated) {
// Nothing to do here.
}
}
| 2,483 | 0.688558 | 0.685334 | 64 | 37.78125 | 36.600662 | 159 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.328125 | false | false | 13 |
207bc875cc578cb07115120da4fcfe4f6c586061 | 1,675,037,269,556 | e8626f9f64a8bb90008015b06856d3da16eeecad | /indexing-service/src/main/java/org/apache/druid/indexing/overlord/hrtr/HttpRemoteTaskRunner.java | 4fa1d21d3d5a172421eda962cbba84906cd91435 | [
"EPL-1.0",
"Classpath-exception-2.0",
"ISC",
"GPL-2.0-only",
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-generic-cla",
"0BSD",
"LicenseRef-scancode-sun-no-high-risk-activities",
"LicenseRef-scancode-free-unknown",
"JSON",
"LicenseRef-scancode-unico... | permissive | apache/druid | https://github.com/apache/druid | bb1b20be5104882e4eeb045d109b559f396086c0 | d4e972e1e4b798d7e057e910deea4d192fe57952 | refs/heads/master | 2023-09-05T02:41:03.009000 | 2023-09-04T07:48:55 | 2023-09-04T07:48:55 | 6,358,188 | 4,364 | 1,629 | Apache-2.0 | false | 2023-09-14T21:04:46 | 2012-10-23T19:08:07 | 2023-09-14T21:04:40 | 2023-09-14T21:04:46 | 324,885 | 12,839 | 3,591 | 1,383 | Java | false | false | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.indexing.overlord.hrtr;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableScheduledFuture;
import com.google.common.util.concurrent.ListeningScheduledExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.druid.concurrent.LifecycleLock;
import org.apache.druid.discovery.DiscoveryDruidNode;
import org.apache.druid.discovery.DruidNodeDiscovery;
import org.apache.druid.discovery.DruidNodeDiscoveryProvider;
import org.apache.druid.discovery.WorkerNodeService;
import org.apache.druid.indexer.RunnerTaskState;
import org.apache.druid.indexer.TaskLocation;
import org.apache.druid.indexer.TaskState;
import org.apache.druid.indexer.TaskStatus;
import org.apache.druid.indexing.common.task.IndexTaskUtils;
import org.apache.druid.indexing.common.task.Task;
import org.apache.druid.indexing.overlord.ImmutableWorkerInfo;
import org.apache.druid.indexing.overlord.RemoteTaskRunnerWorkItem;
import org.apache.druid.indexing.overlord.TaskRunnerListener;
import org.apache.druid.indexing.overlord.TaskRunnerUtils;
import org.apache.druid.indexing.overlord.TaskRunnerWorkItem;
import org.apache.druid.indexing.overlord.TaskStorage;
import org.apache.druid.indexing.overlord.WorkerTaskRunner;
import org.apache.druid.indexing.overlord.autoscaling.ProvisioningService;
import org.apache.druid.indexing.overlord.autoscaling.ProvisioningStrategy;
import org.apache.druid.indexing.overlord.autoscaling.ScalingStats;
import org.apache.druid.indexing.overlord.config.HttpRemoteTaskRunnerConfig;
import org.apache.druid.indexing.overlord.config.WorkerTaskRunnerConfig;
import org.apache.druid.indexing.overlord.setup.WorkerBehaviorConfig;
import org.apache.druid.indexing.overlord.setup.WorkerSelectStrategy;
import org.apache.druid.indexing.worker.TaskAnnouncement;
import org.apache.druid.indexing.worker.Worker;
import org.apache.druid.indexing.worker.config.WorkerConfig;
import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.Pair;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.concurrent.Execs;
import org.apache.druid.java.util.common.concurrent.ScheduledExecutors;
import org.apache.druid.java.util.common.lifecycle.LifecycleStart;
import org.apache.druid.java.util.common.lifecycle.LifecycleStop;
import org.apache.druid.java.util.emitter.EmittingLogger;
import org.apache.druid.java.util.emitter.service.ServiceEmitter;
import org.apache.druid.java.util.emitter.service.ServiceMetricEvent;
import org.apache.druid.java.util.http.client.HttpClient;
import org.apache.druid.java.util.http.client.Request;
import org.apache.druid.java.util.http.client.response.InputStreamResponseHandler;
import org.apache.druid.server.initialization.IndexerZkConfig;
import org.apache.druid.tasklogs.TaskLogStreamer;
import org.apache.zookeeper.KeeperException;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.joda.time.Duration;
import org.joda.time.Period;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* A Remote TaskRunner to manage tasks on Middle Manager nodes using internal-discovery({@link DruidNodeDiscoveryProvider})
* to discover them and Http.
* Middle Managers manages list of assigned/completed tasks on disk and expose 3 HTTP endpoints
* 1. POST request for assigning a task
* 2. POST request for shutting down a task
* 3. GET request for getting list of assigned, running, completed tasks on Middle Manager and its enable/disable status.
* This endpoint is implemented to support long poll and holds the request till there is a change. This class
* sends the next request immediately as the previous finishes to keep the state up-to-date.
* <p>
* ZK_CLEANUP_TODO : As of 0.11.1, it is required to cleanup task status paths from ZK which are created by the
* workers to support deprecated RemoteTaskRunner. So a method "scheduleCompletedTaskStatusCleanupFromZk()" is added'
* which should be removed in the release that removes RemoteTaskRunner legacy ZK updation WorkerTaskMonitor class.
*/
public class HttpRemoteTaskRunner implements WorkerTaskRunner, TaskLogStreamer
{
private static final EmittingLogger log = new EmittingLogger(HttpRemoteTaskRunner.class);
private final LifecycleLock lifecycleLock = new LifecycleLock();
// Executor for assigning pending tasks to workers.
private final ExecutorService pendingTasksExec;
// All known tasks, TaskID -> HttpRemoteTaskRunnerWorkItem
// This is a ConcurrentMap as some of the reads are done without holding the lock.
@GuardedBy("statusLock")
private final ConcurrentMap<String, HttpRemoteTaskRunnerWorkItem> tasks = new ConcurrentHashMap<>();
// This is the list of pending tasks in the order they arrived, exclusively manipulated/used by thread that
// gives a new task to this class and threads in pendingTasksExec that are responsible for assigning tasks to
// workers.
@GuardedBy("statusLock")
private final List<String> pendingTaskIds = new ArrayList<>();
// All discovered workers, "host:port" -> WorkerHolder
private final ConcurrentMap<String, WorkerHolder> workers = new ConcurrentHashMap<>();
// Executor for syncing state of each worker.
private final ScheduledExecutorService workersSyncExec;
// Workers that have been marked as lazy. these workers are not running any tasks and can be terminated safely by the scaling policy.
private final ConcurrentMap<String, WorkerHolder> lazyWorkers = new ConcurrentHashMap<>();
// Workers that have been blacklisted.
private final ConcurrentHashMap<String, WorkerHolder> blackListedWorkers = new ConcurrentHashMap<>();
// workers which were assigned a task and are yet to acknowledge same.
// Map: workerId -> taskId
// all writes are guarded
@GuardedBy("statusLock")
private final ConcurrentMap<String, String> workersWithUnacknowledgedTask = new ConcurrentHashMap<>();
// Executor to complete cleanup of workers which have disappeared.
private final ListeningScheduledExecutorService cleanupExec;
private final ConcurrentMap<String, ScheduledFuture> removedWorkerCleanups = new ConcurrentHashMap<>();
private final Object statusLock = new Object();
// task runner listeners
private final CopyOnWriteArrayList<Pair<TaskRunnerListener, Executor>> listeners = new CopyOnWriteArrayList<>();
private final ProvisioningStrategy<WorkerTaskRunner> provisioningStrategy;
private ProvisioningService provisioningService;
private final DruidNodeDiscoveryProvider druidNodeDiscoveryProvider;
private final HttpClient httpClient;
private final ObjectMapper smileMapper;
private final Supplier<WorkerBehaviorConfig> workerConfigRef;
private final HttpRemoteTaskRunnerConfig config;
private final TaskStorage taskStorage;
private final ServiceEmitter emitter;
// ZK_CLEANUP_TODO : Remove these when RemoteTaskRunner and WorkerTaskMonitor are removed.
private static final Joiner JOINER = Joiner.on("/");
@Nullable // Null, if zk is disabled
private final CuratorFramework cf;
@Nullable // Null, if zk is disabled
private final ScheduledExecutorService zkCleanupExec;
private final IndexerZkConfig indexerZkConfig;
private volatile DruidNodeDiscovery.Listener nodeDiscoveryListener;
public HttpRemoteTaskRunner(
ObjectMapper smileMapper,
HttpRemoteTaskRunnerConfig config,
HttpClient httpClient,
Supplier<WorkerBehaviorConfig> workerConfigRef,
ProvisioningStrategy<WorkerTaskRunner> provisioningStrategy,
DruidNodeDiscoveryProvider druidNodeDiscoveryProvider,
TaskStorage taskStorage,
@Nullable CuratorFramework cf,
IndexerZkConfig indexerZkConfig,
ServiceEmitter emitter
)
{
this.smileMapper = smileMapper;
this.config = config;
this.httpClient = httpClient;
this.druidNodeDiscoveryProvider = druidNodeDiscoveryProvider;
this.taskStorage = taskStorage;
this.workerConfigRef = workerConfigRef;
this.emitter = emitter;
this.pendingTasksExec = Execs.multiThreaded(
config.getPendingTasksRunnerNumThreads(),
"hrtr-pending-tasks-runner-%d"
);
this.workersSyncExec = ScheduledExecutors.fixed(
config.getWorkerSyncNumThreads(),
"HttpRemoteTaskRunner-worker-sync-%d"
);
this.cleanupExec = MoreExecutors.listeningDecorator(
ScheduledExecutors.fixed(1, "HttpRemoteTaskRunner-Worker-Cleanup-%d")
);
if (cf != null) {
this.cf = cf;
this.zkCleanupExec = ScheduledExecutors.fixed(
1,
"HttpRemoteTaskRunner-zk-cleanup-%d"
);
} else {
this.cf = null;
this.zkCleanupExec = null;
}
this.indexerZkConfig = indexerZkConfig;
this.provisioningStrategy = provisioningStrategy;
}
@Override
@LifecycleStart
public void start()
{
if (!lifecycleLock.canStart()) {
return;
}
try {
log.info("Starting...");
scheduleCompletedTaskStatusCleanupFromZk();
startWorkersHandling();
ScheduledExecutors.scheduleAtFixedRate(
cleanupExec,
Period.ZERO.toStandardDuration(),
config.getWorkerBlackListCleanupPeriod().toStandardDuration(),
this::checkAndRemoveWorkersFromBlackList
);
provisioningService = provisioningStrategy.makeProvisioningService(this);
scheduleSyncMonitoring();
startPendingTaskHandling();
lifecycleLock.started();
log.info("Started.");
}
catch (Exception e) {
throw new RuntimeException(e);
}
finally {
lifecycleLock.exitStart();
}
}
private void scheduleCompletedTaskStatusCleanupFromZk()
{
if (cf == null) {
return;
}
zkCleanupExec.scheduleAtFixedRate(
() -> {
try {
List<String> workers;
try {
workers = cf.getChildren().forPath(indexerZkConfig.getStatusPath());
}
catch (KeeperException.NoNodeException e) {
// statusPath doesn't exist yet; can occur if no middleManagers have started.
workers = ImmutableList.of();
}
Set<String> knownActiveTaskIds = new HashSet<>();
if (!workers.isEmpty()) {
for (Task task : taskStorage.getActiveTasks()) {
knownActiveTaskIds.add(task.getId());
}
}
for (String workerId : workers) {
String workerStatusPath = JOINER.join(indexerZkConfig.getStatusPath(), workerId);
List<String> taskIds;
try {
taskIds = cf.getChildren().forPath(workerStatusPath);
}
catch (KeeperException.NoNodeException e) {
taskIds = ImmutableList.of();
}
for (String taskId : taskIds) {
if (!knownActiveTaskIds.contains(taskId)) {
String taskStatusPath = JOINER.join(workerStatusPath, taskId);
try {
cf.delete().guaranteed().forPath(taskStatusPath);
}
catch (KeeperException.NoNodeException e) {
log.info("Failed to delete taskStatusPath[%s].", taskStatusPath);
}
}
}
}
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
catch (Exception ex) {
log.error(ex, "Unknown error while doing task status cleanup in ZK.");
}
},
1,
5,
TimeUnit.MINUTES
);
}
/**
* Must not be used outside of this class and {@link HttpRemoteTaskRunnerResource}
*/
@SuppressWarnings("GuardedBy") // Read on workersWithUnacknowledgedTask is safe
Map<String, ImmutableWorkerInfo> getWorkersEligibleToRunTasks()
{
// In this class, this method is called with statusLock held.
// writes to workersWithUnacknowledgedTask are always guarded by statusLock.
// however writes to lazyWorker/blacklistedWorkers aren't necessarily guarded by same lock, so technically there
// could be races in that a task could get assigned to a worker which in another thread is concurrently being
// marked lazy/blacklisted , but that is ok because that is equivalent to this worker being picked for task and
// being assigned lazy/blacklisted right after even when the two threads hold a mutually exclusive lock.
return Maps.transformEntries(
Maps.filterEntries(
workers,
input -> !lazyWorkers.containsKey(input.getKey()) &&
!workersWithUnacknowledgedTask.containsKey(input.getKey()) &&
!blackListedWorkers.containsKey(input.getKey()) &&
input.getValue().isInitialized() &&
input.getValue().isEnabled()
),
(String key, WorkerHolder value) -> value.toImmutable()
);
}
private ImmutableWorkerInfo findWorkerToRunTask(Task task)
{
WorkerBehaviorConfig workerConfig = workerConfigRef.get();
WorkerSelectStrategy strategy;
if (workerConfig == null || workerConfig.getSelectStrategy() == null) {
strategy = WorkerBehaviorConfig.DEFAULT_STRATEGY;
log.debug("No worker selection strategy set. Using default of [%s]", strategy.getClass().getSimpleName());
} else {
strategy = workerConfig.getSelectStrategy();
}
return strategy.findWorkerForTask(
config,
ImmutableMap.copyOf(getWorkersEligibleToRunTasks()),
task
);
}
private boolean runTaskOnWorker(
final HttpRemoteTaskRunnerWorkItem workItem,
final String workerHost
) throws InterruptedException
{
String taskId = workItem.getTaskId();
WorkerHolder workerHolder = workers.get(workerHost);
if (workerHolder == null || lazyWorkers.containsKey(workerHost) || blackListedWorkers.containsKey(workerHost)) {
log.info("Not assigning task[%s] to removed or marked lazy/blacklisted worker[%s]", taskId, workerHost);
return false;
}
log.info("Assigning task [%s] to worker [%s]", taskId, workerHost);
if (workerHolder.assignTask(workItem.getTask())) {
// Don't assign new tasks until the task we just assigned is actually running
// on a worker - this avoids overflowing a worker with tasks
long waitMs = config.getTaskAssignmentTimeout().toStandardDuration().getMillis();
long waitStart = System.currentTimeMillis();
boolean isTaskAssignmentTimedOut = false;
synchronized (statusLock) {
while (tasks.containsKey(taskId) && tasks.get(taskId).getState().isPending()) {
long remaining = waitMs - (System.currentTimeMillis() - waitStart);
if (remaining > 0) {
statusLock.wait(remaining);
} else {
isTaskAssignmentTimedOut = true;
break;
}
}
}
if (isTaskAssignmentTimedOut) {
log.makeAlert(
"Task assignment timed out on worker [%s], never ran task [%s] in timeout[%s]!",
workerHost,
taskId,
config.getTaskAssignmentTimeout()
).emit();
// taskComplete(..) must be called outside of statusLock, see comments on method.
taskComplete(
workItem,
workerHolder,
TaskStatus.failure(
taskId,
StringUtils.format(
"The worker that this task is assigned did not start it in timeout[%s]. "
+ "See overlord and middleManager/indexer logs for more details.",
config.getTaskAssignmentTimeout()
)
)
);
}
return true;
} else {
return false;
}
}
// CAUTION: This method calls RemoteTaskRunnerWorkItem.setResult(..) which results in TaskQueue.notifyStatus() being called
// because that is attached by TaskQueue to task result future. So, this method must not be called with "statusLock"
// held. See https://github.com/apache/druid/issues/6201
private void taskComplete(
HttpRemoteTaskRunnerWorkItem taskRunnerWorkItem,
WorkerHolder workerHolder,
TaskStatus taskStatus
)
{
Preconditions.checkState(!Thread.holdsLock(statusLock), "Current thread must not hold statusLock.");
Preconditions.checkNotNull(taskRunnerWorkItem, "taskRunnerWorkItem");
Preconditions.checkNotNull(taskStatus, "taskStatus");
if (workerHolder != null) {
log.info(
"Worker[%s] completed task[%s] with status[%s]",
workerHolder.getWorker().getHost(),
taskStatus.getId(),
taskStatus.getStatusCode()
);
// Worker is done with this task
workerHolder.setLastCompletedTaskTime(DateTimes.nowUtc());
}
if (taskRunnerWorkItem.getResult().isDone()) {
// This is not the first complete event.
try {
TaskState lastKnownState = taskRunnerWorkItem.getResult().get().getStatusCode();
if (taskStatus.getStatusCode() != lastKnownState) {
log.warn(
"The state of the new task complete event is different from its last known state. "
+ "New state[%s], last known state[%s]",
taskStatus.getStatusCode(),
lastKnownState
);
}
}
catch (InterruptedException e) {
log.warn(e, "Interrupted while getting the last known task status.");
Thread.currentThread().interrupt();
}
catch (ExecutionException e) {
// This case should not really happen.
log.warn(e, "Failed to get the last known task status. Ignoring this failure.");
}
} else {
// Notify interested parties
taskRunnerWorkItem.setResult(taskStatus);
TaskRunnerUtils.notifyStatusChanged(listeners, taskStatus.getId(), taskStatus);
// Update success/failure counters, Blacklist node if there are too many failures.
if (workerHolder != null) {
blacklistWorkerIfNeeded(taskStatus, workerHolder);
}
}
synchronized (statusLock) {
statusLock.notifyAll();
}
}
private void startWorkersHandling() throws InterruptedException
{
final CountDownLatch workerViewInitialized = new CountDownLatch(1);
DruidNodeDiscovery druidNodeDiscovery =
druidNodeDiscoveryProvider.getForService(WorkerNodeService.DISCOVERY_SERVICE_KEY);
this.nodeDiscoveryListener = new DruidNodeDiscovery.Listener()
{
@Override
public void nodesAdded(Collection<DiscoveryDruidNode> nodes)
{
nodes.forEach(node -> addWorker(toWorker(node)));
}
@Override
public void nodesRemoved(Collection<DiscoveryDruidNode> nodes)
{
nodes.forEach(node -> removeWorker(toWorker(node)));
}
@Override
public void nodeViewInitialized()
{
//CountDownLatch.countDown() does nothing when count has already reached 0.
workerViewInitialized.countDown();
}
};
druidNodeDiscovery.registerListener(nodeDiscoveryListener);
long workerDiscoveryStartTime = System.currentTimeMillis();
while (!workerViewInitialized.await(30, TimeUnit.SECONDS)) {
if (System.currentTimeMillis() - workerDiscoveryStartTime > TimeUnit.MINUTES.toMillis(5)) {
throw new ISE("Couldn't discover workers.");
} else {
log.info("Waiting for worker discovery...");
}
}
log.info("[%s] Workers are discovered.", workers.size());
// Wait till all worker state is sync'd so that we know which worker is running/completed what tasks or else
// We would start assigning tasks which are pretty soon going to be reported by discovered workers.
for (WorkerHolder worker : workers.values()) {
log.info("Waiting for worker[%s] to sync state...", worker.getWorker().getHost());
worker.waitForInitialization();
}
log.info("Workers have sync'd state successfully.");
}
private Worker toWorker(DiscoveryDruidNode node)
{
final WorkerNodeService workerNodeService = node.getService(WorkerNodeService.DISCOVERY_SERVICE_KEY, WorkerNodeService.class);
if (workerNodeService == null) {
// this shouldn't typically happen, but just in case it does, make a dummy worker to allow the callbacks to
// continue since addWorker/removeWorker only need worker.getHost()
return new Worker(
node.getDruidNode().getServiceScheme(),
node.getDruidNode().getHostAndPortToUse(),
null,
0,
"",
WorkerConfig.DEFAULT_CATEGORY
);
}
return new Worker(
node.getDruidNode().getServiceScheme(),
node.getDruidNode().getHostAndPortToUse(),
workerNodeService.getIp(),
workerNodeService.getCapacity(),
workerNodeService.getVersion(),
workerNodeService.getCategory()
);
}
@VisibleForTesting
void addWorker(final Worker worker)
{
synchronized (workers) {
log.info("Worker[%s] reportin' for duty!", worker.getHost());
cancelWorkerCleanup(worker.getHost());
WorkerHolder holder = workers.get(worker.getHost());
if (holder == null) {
List<TaskAnnouncement> expectedAnnouncements = new ArrayList<>();
synchronized (statusLock) {
// It might be a worker that existed before, temporarily went away and came back. We might have a set of
// tasks that we think are running on this worker. Provide that information to WorkerHolder that
// manages the task syncing with that worker.
for (Map.Entry<String, HttpRemoteTaskRunnerWorkItem> e : tasks.entrySet()) {
if (e.getValue().getState() == HttpRemoteTaskRunnerWorkItem.State.RUNNING) {
Worker w = e.getValue().getWorker();
if (w != null && w.getHost().equals(worker.getHost()) && e.getValue().getTask() != null) {
expectedAnnouncements.add(
TaskAnnouncement.create(
e.getValue().getTask(),
TaskStatus.running(e.getKey()),
e.getValue().getLocation()
)
);
}
}
}
}
holder = createWorkerHolder(
smileMapper,
httpClient,
config,
workersSyncExec,
this::taskAddedOrUpdated,
worker,
expectedAnnouncements
);
holder.start();
workers.put(worker.getHost(), holder);
} else {
log.info("Worker[%s] already exists.", worker.getHost());
}
}
synchronized (statusLock) {
statusLock.notifyAll();
}
}
protected WorkerHolder createWorkerHolder(
ObjectMapper smileMapper,
HttpClient httpClient,
HttpRemoteTaskRunnerConfig config,
ScheduledExecutorService workersSyncExec,
WorkerHolder.Listener listener,
Worker worker,
List<TaskAnnouncement> knownAnnouncements
)
{
return new WorkerHolder(smileMapper, httpClient, config, workersSyncExec, listener, worker, knownAnnouncements);
}
private void removeWorker(final Worker worker)
{
synchronized (workers) {
log.info("Kaboom! Worker[%s] removed!", worker.getHost());
WorkerHolder workerHolder = workers.remove(worker.getHost());
if (workerHolder != null) {
try {
workerHolder.stop();
scheduleTasksCleanupForWorker(worker.getHost());
}
catch (Exception e) {
throw new RuntimeException(e);
}
finally {
checkAndRemoveWorkersFromBlackList();
}
}
lazyWorkers.remove(worker.getHost());
}
}
private boolean cancelWorkerCleanup(String workerHost)
{
ScheduledFuture previousCleanup = removedWorkerCleanups.remove(workerHost);
if (previousCleanup != null) {
log.info("Cancelling Worker[%s] scheduled task cleanup", workerHost);
previousCleanup.cancel(false);
}
return previousCleanup != null;
}
private void scheduleTasksCleanupForWorker(final String workerHostAndPort)
{
cancelWorkerCleanup(workerHostAndPort);
final ListenableScheduledFuture<?> cleanupTask = cleanupExec.schedule(
() -> {
log.info("Running scheduled cleanup for Worker[%s]", workerHostAndPort);
try {
Set<HttpRemoteTaskRunnerWorkItem> tasksToFail = new HashSet<>();
synchronized (statusLock) {
for (Map.Entry<String, HttpRemoteTaskRunnerWorkItem> e : tasks.entrySet()) {
if (e.getValue().getState() == HttpRemoteTaskRunnerWorkItem.State.RUNNING) {
Worker w = e.getValue().getWorker();
if (w != null && w.getHost().equals(workerHostAndPort)) {
tasksToFail.add(e.getValue());
}
}
}
}
for (HttpRemoteTaskRunnerWorkItem taskItem : tasksToFail) {
if (!taskItem.getResult().isDone()) {
log.warn(
"Failing task[%s] because worker[%s] disappeared and did not report within cleanup timeout[%s].",
workerHostAndPort,
taskItem.getTaskId(),
config.getTaskCleanupTimeout()
);
// taskComplete(..) must be called outside of statusLock, see comments on method.
taskComplete(
taskItem,
null,
TaskStatus.failure(
taskItem.getTaskId(),
StringUtils.format(
"The worker that this task was assigned disappeared and "
+ "did not report cleanup within timeout[%s]. "
+ "See overlord and middleManager/indexer logs for more details.",
config.getTaskCleanupTimeout()
)
)
);
}
}
}
catch (Exception e) {
log.makeAlert("Exception while cleaning up worker[%s]", workerHostAndPort).emit();
throw new RuntimeException(e);
}
},
config.getTaskCleanupTimeout().toStandardDuration().getMillis(),
TimeUnit.MILLISECONDS
);
removedWorkerCleanups.put(workerHostAndPort, cleanupTask);
// Remove this entry from removedWorkerCleanups when done, if it's actually the one in there.
Futures.addCallback(
cleanupTask,
new FutureCallback<Object>()
{
@Override
public void onSuccess(Object result)
{
removedWorkerCleanups.remove(workerHostAndPort, cleanupTask);
}
@Override
public void onFailure(Throwable t)
{
removedWorkerCleanups.remove(workerHostAndPort, cleanupTask);
}
},
MoreExecutors.directExecutor()
);
}
private void scheduleSyncMonitoring()
{
workersSyncExec.scheduleAtFixedRate(
() -> {
log.debug("Running the Sync Monitoring.");
try {
syncMonitoring();
}
catch (Exception ex) {
if (ex instanceof InterruptedException) {
Thread.currentThread().interrupt();
} else {
log.makeAlert(ex, "Exception in sync monitoring.").emit();
}
}
},
1,
5,
TimeUnit.MINUTES
);
}
@VisibleForTesting
void syncMonitoring()
{
// Ensure that the collection is not being modified during iteration. Iterate over a copy
final Set<Map.Entry<String, WorkerHolder>> workerEntrySet = ImmutableSet.copyOf(workers.entrySet());
for (Map.Entry<String, WorkerHolder> e : workerEntrySet) {
WorkerHolder workerHolder = e.getValue();
if (workerHolder.getUnderlyingSyncer().needsReset()) {
synchronized (workers) {
// check again that server is still there and only then reset.
if (workers.containsKey(e.getKey())) {
log.makeAlert(
"Worker[%s] is not syncing properly. Current state is [%s]. Resetting it.",
workerHolder.getWorker().getHost(),
workerHolder.getUnderlyingSyncer().getDebugInfo()
).emit();
removeWorker(workerHolder.getWorker());
addWorker(workerHolder.getWorker());
}
}
}
}
}
/**
* This method returns the debugging information exposed by {@link HttpRemoteTaskRunnerResource} and meant
* for that use only. It must not be used for any other purpose.
*/
Map<String, Object> getWorkerSyncerDebugInfo()
{
Preconditions.checkArgument(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS));
Map<String, Object> result = Maps.newHashMapWithExpectedSize(workers.size());
for (Map.Entry<String, WorkerHolder> e : workers.entrySet()) {
WorkerHolder serverHolder = e.getValue();
result.put(
e.getKey(),
serverHolder.getUnderlyingSyncer().getDebugInfo()
);
}
return result;
}
private void checkAndRemoveWorkersFromBlackList()
{
boolean shouldRunPendingTasks = false;
Iterator<Map.Entry<String, WorkerHolder>> iterator = blackListedWorkers.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, WorkerHolder> e = iterator.next();
if (shouldRemoveNodeFromBlackList(e.getValue())) {
iterator.remove();
e.getValue().resetContinuouslyFailedTasksCount();
e.getValue().setBlacklistedUntil(null);
shouldRunPendingTasks = true;
}
}
if (shouldRunPendingTasks) {
synchronized (statusLock) {
statusLock.notifyAll();
}
}
}
private boolean shouldRemoveNodeFromBlackList(WorkerHolder workerHolder)
{
if (!workers.containsKey(workerHolder.getWorker().getHost())) {
return true;
}
if (blackListedWorkers.size() > workers.size() * (config.getMaxPercentageBlacklistWorkers() / 100.0)) {
log.info(
"Removing [%s] from blacklist because percentage of blacklisted workers exceeds [%d]",
workerHolder.getWorker(),
config.getMaxPercentageBlacklistWorkers()
);
return true;
}
long remainingMillis = workerHolder.getBlacklistedUntil().getMillis() - System.currentTimeMillis();
if (remainingMillis <= 0) {
log.info("Removing [%s] from blacklist because backoff time elapsed", workerHolder.getWorker());
return true;
}
log.info("[%s] still blacklisted for [%,ds]", workerHolder.getWorker(), remainingMillis / 1000);
return false;
}
private void blacklistWorkerIfNeeded(TaskStatus taskStatus, WorkerHolder workerHolder)
{
synchronized (blackListedWorkers) {
if (taskStatus.isSuccess()) {
workerHolder.resetContinuouslyFailedTasksCount();
if (blackListedWorkers.remove(workerHolder.getWorker().getHost()) != null) {
workerHolder.setBlacklistedUntil(null);
log.info("[%s] removed from blacklist because a task finished with SUCCESS", workerHolder.getWorker());
}
} else if (taskStatus.isFailure()) {
workerHolder.incrementContinuouslyFailedTasksCount();
}
if (workerHolder.getContinuouslyFailedTasksCount() > config.getMaxRetriesBeforeBlacklist() &&
blackListedWorkers.size() <= workers.size() * (config.getMaxPercentageBlacklistWorkers() / 100.0) - 1) {
workerHolder.setBlacklistedUntil(DateTimes.nowUtc().plus(config.getWorkerBlackListBackoffTime()));
if (blackListedWorkers.put(workerHolder.getWorker().getHost(), workerHolder) == null) {
log.info(
"Blacklisting [%s] until [%s] after [%,d] failed tasks in a row.",
workerHolder.getWorker(),
workerHolder.getBlacklistedUntil(),
workerHolder.getContinuouslyFailedTasksCount()
);
}
}
}
}
@Override
public Collection<ImmutableWorkerInfo> getWorkers()
{
return workers.values().stream().map(worker -> worker.toImmutable()).collect(Collectors.toList());
}
@VisibleForTesting
ConcurrentMap<String, WorkerHolder> getWorkersForTestingReadOnly()
{
return workers;
}
@Override
public Collection<Worker> getLazyWorkers()
{
return lazyWorkers.values().stream().map(holder -> holder.getWorker()).collect(Collectors.toList());
}
@Override
public Collection<Worker> markWorkersLazy(Predicate<ImmutableWorkerInfo> isLazyWorker, int maxLazyWorkers)
{
// skip the lock and bail early if we should not mark any workers lazy (e.g. number
// of current workers is at or below the minNumWorkers of autoscaler config)
if (lazyWorkers.size() >= maxLazyWorkers) {
return getLazyWorkers();
}
// Search for new workers to mark lazy.
// Status lock is used to prevent any tasks being assigned to workers while we mark them lazy
synchronized (statusLock) {
for (Map.Entry<String, WorkerHolder> worker : workers.entrySet()) {
if (lazyWorkers.size() >= maxLazyWorkers) {
break;
}
final WorkerHolder workerHolder = worker.getValue();
try {
if (isWorkerOkForMarkingLazy(workerHolder.getWorker()) && isLazyWorker.apply(workerHolder.toImmutable())) {
log.info("Adding Worker[%s] to lazySet!", workerHolder.getWorker().getHost());
lazyWorkers.put(worker.getKey(), workerHolder);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
return getLazyWorkers();
}
private boolean isWorkerOkForMarkingLazy(Worker worker)
{
// Check that worker is not running any tasks and no task is being assigned to it.
synchronized (statusLock) {
if (workersWithUnacknowledgedTask.containsKey(worker.getHost())) {
return false;
}
for (Map.Entry<String, HttpRemoteTaskRunnerWorkItem> e : tasks.entrySet()) {
if (e.getValue().getState() == HttpRemoteTaskRunnerWorkItem.State.RUNNING) {
Worker w = e.getValue().getWorker();
if (w != null && w.getHost().equals(worker.getHost())) {
return false;
}
}
}
return true;
}
}
@Override
public WorkerTaskRunnerConfig getConfig()
{
return config;
}
@Override
public Collection<Task> getPendingTaskPayloads()
{
synchronized (statusLock) {
return tasks.values()
.stream()
.filter(item -> item.getState().isPending())
.map(HttpRemoteTaskRunnerWorkItem::getTask)
.collect(Collectors.toList());
}
}
@Override
public Optional<InputStream> streamTaskLog(String taskId, long offset) throws IOException
{
@SuppressWarnings("GuardedBy") // Read on tasks is safe
HttpRemoteTaskRunnerWorkItem taskRunnerWorkItem = tasks.get(taskId);
Worker worker = null;
if (taskRunnerWorkItem != null && taskRunnerWorkItem.getState() != HttpRemoteTaskRunnerWorkItem.State.COMPLETE) {
worker = taskRunnerWorkItem.getWorker();
}
if (worker == null || !workers.containsKey(worker.getHost())) {
// Worker is not running this task, it might be available in deep storage
return Optional.absent();
} else {
// Worker is still running this task
final URL url = TaskRunnerUtils.makeWorkerURL(
worker,
"/druid/worker/v1/task/%s/log?offset=%s",
taskId,
Long.toString(offset)
);
try {
return Optional.of(httpClient.go(
new Request(HttpMethod.GET, url),
new InputStreamResponseHandler()
).get());
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
catch (ExecutionException e) {
// Unwrap if possible
Throwables.propagateIfPossible(e.getCause(), IOException.class);
throw new RuntimeException(e);
}
}
}
@Override
public Optional<InputStream> streamTaskReports(String taskId) throws IOException
{
@SuppressWarnings("GuardedBy") // Read on tasks is safe
HttpRemoteTaskRunnerWorkItem taskRunnerWorkItem = tasks.get(taskId);
Worker worker = null;
if (taskRunnerWorkItem != null && taskRunnerWorkItem.getState() != HttpRemoteTaskRunnerWorkItem.State.COMPLETE) {
worker = taskRunnerWorkItem.getWorker();
}
if (worker == null || !workers.containsKey(worker.getHost())) {
// Worker is not running this task, it might be available in deep storage
return Optional.absent();
} else {
// Worker is still running this task
TaskLocation taskLocation = taskRunnerWorkItem.getLocation();
if (TaskLocation.unknown().equals(taskLocation)) {
// No location known for this task. It may have not been assigned a location yet.
return Optional.absent();
}
final URL url = TaskRunnerUtils.makeTaskLocationURL(
taskLocation,
"/druid/worker/v1/chat/%s/liveReports",
taskId
);
try {
return Optional.of(httpClient.go(
new Request(HttpMethod.GET, url),
new InputStreamResponseHandler()
).get());
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
catch (ExecutionException e) {
// Unwrap if possible
Throwables.propagateIfPossible(e.getCause(), IOException.class);
throw new RuntimeException(e);
}
}
}
@Override
public List<Pair<Task, ListenableFuture<TaskStatus>>> restore()
{
return ImmutableList.of();
}
@Override
public void registerListener(TaskRunnerListener listener, Executor executor)
{
for (Pair<TaskRunnerListener, Executor> pair : listeners) {
if (pair.lhs.getListenerId().equals(listener.getListenerId())) {
throw new ISE("Listener [%s] already registered", listener.getListenerId());
}
}
final Pair<TaskRunnerListener, Executor> listenerPair = Pair.of(listener, executor);
synchronized (statusLock) {
for (Map.Entry<String, HttpRemoteTaskRunnerWorkItem> entry : tasks.entrySet()) {
if (entry.getValue().getState() == HttpRemoteTaskRunnerWorkItem.State.RUNNING) {
TaskRunnerUtils.notifyLocationChanged(
ImmutableList.of(listenerPair),
entry.getKey(),
entry.getValue().getLocation()
);
}
}
log.info("Registered listener [%s]", listener.getListenerId());
listeners.add(listenerPair);
}
}
@Override
public void unregisterListener(String listenerId)
{
for (Pair<TaskRunnerListener, Executor> pair : listeners) {
if (pair.lhs.getListenerId().equals(listenerId)) {
listeners.remove(pair);
log.info("Unregistered listener [%s]", listenerId);
return;
}
}
}
@Override
public ListenableFuture<TaskStatus> run(Task task)
{
Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS), "not started");
synchronized (statusLock) {
HttpRemoteTaskRunnerWorkItem existing = tasks.get(task.getId());
if (existing != null) {
log.info("Assigned a task[%s] that is known already. Ignored.", task.getId());
if (existing.getTask() == null) {
// in case it was discovered from a worker on start() and TaskAnnouncement does not have Task instance
// in it.
existing.setTask(task);
}
return existing.getResult();
} else {
log.info("Adding pending task[%s].", task.getId());
HttpRemoteTaskRunnerWorkItem taskRunnerWorkItem = new HttpRemoteTaskRunnerWorkItem(
task.getId(),
null,
null,
task,
task.getType(),
HttpRemoteTaskRunnerWorkItem.State.PENDING
);
tasks.put(task.getId(), taskRunnerWorkItem);
pendingTaskIds.add(task.getId());
statusLock.notifyAll();
return taskRunnerWorkItem.getResult();
}
}
}
private void startPendingTaskHandling()
{
for (int i = 0; i < config.getPendingTasksRunnerNumThreads(); i++) {
pendingTasksExec.submit(
() -> {
try {
if (!lifecycleLock.awaitStarted()) {
log.makeAlert("Lifecycle not started, PendingTaskExecution loop will not run.").emit();
return;
}
pendingTasksExecutionLoop();
}
catch (Throwable t) {
log.makeAlert(t, "Error while waiting for lifecycle start. PendingTaskExecution loop will not run")
.emit();
}
finally {
log.info("PendingTaskExecution loop exited.");
}
}
);
}
}
private void pendingTasksExecutionLoop()
{
while (!Thread.interrupted() && lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS)) {
try {
// Find one pending task to run and a worker to run on
HttpRemoteTaskRunnerWorkItem taskItem = null;
ImmutableWorkerInfo immutableWorker = null;
synchronized (statusLock) {
Iterator<String> iter = pendingTaskIds.iterator();
while (iter.hasNext()) {
String taskId = iter.next();
HttpRemoteTaskRunnerWorkItem ti = tasks.get(taskId);
if (ti == null || !ti.getState().isPending()) {
// happens if the task was shutdown, failed or observed running by a worker
iter.remove();
continue;
}
if (ti.getState() == HttpRemoteTaskRunnerWorkItem.State.PENDING_WORKER_ASSIGN) {
// picked up by another pending task executor thread which is in the process of trying to
// run it on a worker, skip to next.
continue;
}
if (ti.getTask() == null) {
// this is not supposed to happen except for a bug, we want to mark this task failed but
// taskComplete(..) can not be called while holding statusLock. See the javadoc on that
// method.
// so this will get marked failed afterwards outside of current synchronized block.
taskItem = ti;
break;
}
immutableWorker = findWorkerToRunTask(ti.getTask());
if (immutableWorker == null) {
continue;
}
String prevUnackedTaskId = workersWithUnacknowledgedTask.putIfAbsent(
immutableWorker.getWorker().getHost(),
taskId
);
if (prevUnackedTaskId != null) {
log.makeAlert(
"Found worker[%s] with unacked task[%s] but still was identified to run task[%s].",
immutableWorker.getWorker().getHost(),
prevUnackedTaskId,
taskId
).emit();
}
// set state to PENDING_WORKER_ASSIGN before releasing the lock so that this task item is not picked
// up by another task execution thread.
// note that we can't simply delete this task item from pendingTaskIds or else we would have to add it
// back if this thread couldn't run this task for any reason, which we will know at some later time
// and also we will need to add it back to its old position in the list. that becomes complex quickly.
// Instead we keep the PENDING_WORKER_ASSIGN to notify other task execution threads not to pick this one up.
// And, it is automatically removed by any of the task execution threads when they notice that
// ti.getState().isPending() is false (at the beginning of this loop)
ti.setState(HttpRemoteTaskRunnerWorkItem.State.PENDING_WORKER_ASSIGN);
taskItem = ti;
break;
}
if (taskItem == null) {
// Either no pending task is found or no suitable worker is found for any of the pending tasks.
// statusLock.notifyAll() is called whenever a new task shows up or if there is a possibility for a task
// to successfully get worker to run, for example when a new worker shows up, a task slot opens up
// because some task completed etc.
statusLock.wait(TimeUnit.MINUTES.toMillis(1));
continue;
}
}
String taskId = taskItem.getTaskId();
if (taskItem.getTask() == null) {
log.makeAlert("No Task obj found in TaskItem for taskID[%s]. Failed.", taskId).emit();
// taskComplete(..) must be called outside of statusLock, see comments on method.
taskComplete(
taskItem,
null,
TaskStatus.failure(
taskId,
"No payload found for this task. "
+ "See overlord logs and middleManager/indexer logs for more details."
)
);
continue;
}
if (immutableWorker == null) {
throw new ISE("Unexpected state: null immutableWorker");
}
try {
// this will send HTTP request to worker for assigning task
if (!runTaskOnWorker(taskItem, immutableWorker.getWorker().getHost())) {
if (taskItem.getState() == HttpRemoteTaskRunnerWorkItem.State.PENDING_WORKER_ASSIGN) {
taskItem.revertStateFromPendingWorkerAssignToPending();
}
}
}
catch (InterruptedException ex) {
log.info("Got InterruptedException while assigning task[%s].", taskId);
throw ex;
}
catch (Throwable th) {
log.makeAlert(th, "Exception while trying to assign task")
.addData("taskId", taskId)
.emit();
// taskComplete(..) must be called outside of statusLock, see comments on method.
taskComplete(
taskItem,
null,
TaskStatus.failure(taskId, "Failed to assign this task. See overlord logs for more details.")
);
}
finally {
synchronized (statusLock) {
workersWithUnacknowledgedTask.remove(immutableWorker.getWorker().getHost());
statusLock.notifyAll();
}
}
}
catch (InterruptedException ex) {
log.info("Interrupted, will Exit.");
Thread.currentThread().interrupt();
}
catch (Throwable th) {
log.makeAlert(th, "Unknown Exception while trying to assign tasks.").emit();
}
}
}
/**
* Must not be used outside of this class and {@link HttpRemoteTaskRunnerResource}
*/
List<String> getPendingTasksList()
{
synchronized (statusLock) {
return ImmutableList.copyOf(pendingTaskIds);
}
}
@Override
public void shutdown(String taskId, String reason)
{
if (!lifecycleLock.awaitStarted(1, TimeUnit.SECONDS)) {
log.info("This TaskRunner is stopped or not yet started. Ignoring shutdown command for task: %s", taskId);
return;
}
WorkerHolder workerHolderRunningTask = null;
synchronized (statusLock) {
log.info("Shutdown [%s] because: [%s]", taskId, reason);
HttpRemoteTaskRunnerWorkItem taskRunnerWorkItem = tasks.get(taskId);
if (taskRunnerWorkItem != null) {
if (taskRunnerWorkItem.getState() == HttpRemoteTaskRunnerWorkItem.State.RUNNING) {
workerHolderRunningTask = workers.get(taskRunnerWorkItem.getWorker().getHost());
if (workerHolderRunningTask == null) {
log.info("Can't shutdown! No worker running task[%s]", taskId);
}
} else if (taskRunnerWorkItem.getState() == HttpRemoteTaskRunnerWorkItem.State.COMPLETE) {
tasks.remove(taskId);
}
} else {
log.info("Received shutdown task[%s], but can't find it. Ignored.", taskId);
}
}
//shutdown is called outside of lock as we don't want to hold the lock while sending http request
//to worker.
if (workerHolderRunningTask != null) {
log.debug(
"Got shutdown request for task[%s]. Asking worker[%s] to kill it.",
taskId,
workerHolderRunningTask.getWorker().getHost()
);
workerHolderRunningTask.shutdownTask(taskId);
}
}
@Override
@LifecycleStop
public void stop()
{
if (!lifecycleLock.canStop()) {
throw new ISE("can't stop.");
}
try {
log.info("Stopping...");
if (provisioningService != null) {
provisioningService.close();
}
pendingTasksExec.shutdownNow();
workersSyncExec.shutdownNow();
cleanupExec.shutdown();
log.info("Removing listener");
DruidNodeDiscovery druidNodeDiscovery =
druidNodeDiscoveryProvider.getForService(WorkerNodeService.DISCOVERY_SERVICE_KEY);
druidNodeDiscovery.removeListener(nodeDiscoveryListener);
log.info("Stopping worker holders");
synchronized (workers) {
workers.values().forEach(w -> {
try {
w.stop();
}
catch (Exception e) {
log.error(e, e.getMessage());
}
});
}
}
finally {
lifecycleLock.exitStop();
}
log.info("Stopped.");
}
@Override
@SuppressWarnings("GuardedBy") // Read on tasks is safe
public Collection<? extends TaskRunnerWorkItem> getRunningTasks()
{
return tasks.values()
.stream()
.filter(item -> item.getState() == HttpRemoteTaskRunnerWorkItem.State.RUNNING)
.collect(Collectors.toList());
}
@Override
@SuppressWarnings("GuardedBy") // Read on tasks is safe
public Collection<? extends TaskRunnerWorkItem> getPendingTasks()
{
return tasks.values()
.stream()
.filter(item -> item.getState().isPending())
.collect(Collectors.toList());
}
@Override
@SuppressWarnings("GuardedBy") // Read on tasks is safe
public Collection<? extends TaskRunnerWorkItem> getKnownTasks()
{
return ImmutableList.copyOf(tasks.values());
}
@SuppressWarnings("GuardedBy") // Read on tasks is safe
public Collection<? extends TaskRunnerWorkItem> getCompletedTasks()
{
return tasks.values()
.stream()
.filter(item -> item.getState() == HttpRemoteTaskRunnerWorkItem.State.COMPLETE)
.collect(Collectors.toList());
}
@Nullable
@Override
@SuppressWarnings("GuardedBy") // Read on tasks is safe
public RunnerTaskState getRunnerTaskState(String taskId)
{
final HttpRemoteTaskRunnerWorkItem workItem = tasks.get(taskId);
if (workItem == null) {
return null;
} else {
return workItem.getState().toRunnerTaskState();
}
}
@Override
@SuppressWarnings("GuardedBy") // Read on tasks is safe
public TaskLocation getTaskLocation(String taskId)
{
final HttpRemoteTaskRunnerWorkItem workItem = tasks.get(taskId);
if (workItem == null) {
return TaskLocation.unknown();
} else {
return workItem.getLocation();
}
}
public List<String> getBlacklistedWorkers()
{
return blackListedWorkers.values().stream().map(
(holder) -> holder.getWorker().getHost()
).collect(Collectors.toList());
}
public Collection<ImmutableWorkerInfo> getBlackListedWorkers()
{
return ImmutableList.copyOf(Collections2.transform(blackListedWorkers.values(), WorkerHolder::toImmutable));
}
/**
* Must not be used outside of this class and {@link HttpRemoteTaskRunnerResource} , used for read only.
*/
@SuppressWarnings("GuardedBy")
Map<String, String> getWorkersWithUnacknowledgedTasks()
{
return workersWithUnacknowledgedTask;
}
@Override
public Optional<ScalingStats> getScalingStats()
{
return Optional.fromNullable(provisioningService.getStats());
}
@VisibleForTesting
public void taskAddedOrUpdated(final TaskAnnouncement announcement, final WorkerHolder workerHolder)
{
final String taskId = announcement.getTaskId();
final Worker worker = workerHolder.getWorker();
log.debug(
"Worker[%s] wrote [%s] status for task [%s] on [%s]",
worker.getHost(),
announcement.getTaskStatus().getStatusCode(),
taskId,
announcement.getTaskLocation()
);
HttpRemoteTaskRunnerWorkItem taskItem;
boolean shouldShutdownTask = false;
boolean isTaskCompleted = false;
synchronized (statusLock) {
taskItem = tasks.get(taskId);
if (taskItem == null) {
// Try to find information about it in the TaskStorage
Optional<TaskStatus> knownStatusInStorage = taskStorage.getStatus(taskId);
if (knownStatusInStorage.isPresent()) {
switch (knownStatusInStorage.get().getStatusCode()) {
case RUNNING:
taskItem = new HttpRemoteTaskRunnerWorkItem(
taskId,
worker,
TaskLocation.unknown(),
null,
announcement.getTaskType(),
HttpRemoteTaskRunnerWorkItem.State.RUNNING
);
tasks.put(taskId, taskItem);
break;
case SUCCESS:
case FAILED:
if (!announcement.getTaskStatus().isComplete()) {
log.info(
"Worker[%s] reported status for completed, known from taskStorage, task[%s]. Ignored.",
worker.getHost(),
taskId
);
}
break;
default:
log.makeAlert(
"Found unrecognized state[%s] of task[%s] in taskStorage. Notification[%s] from worker[%s] is ignored.",
knownStatusInStorage.get().getStatusCode(),
taskId,
announcement,
worker.getHost()
).emit();
}
} else {
log.warn(
"Worker[%s] reported status[%s] for unknown task[%s]. Ignored.",
worker.getHost(),
announcement.getStatus(),
taskId
);
}
}
if (taskItem == null) {
if (!announcement.getTaskStatus().isComplete()) {
shouldShutdownTask = true;
}
} else {
switch (announcement.getTaskStatus().getStatusCode()) {
case RUNNING:
switch (taskItem.getState()) {
case PENDING:
case PENDING_WORKER_ASSIGN:
taskItem.setWorker(worker);
taskItem.setState(HttpRemoteTaskRunnerWorkItem.State.RUNNING);
log.info("Task[%s] started RUNNING on worker[%s].", taskId, worker.getHost());
final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder();
IndexTaskUtils.setTaskDimensions(metricBuilder, taskItem.getTask());
emitter.emit(metricBuilder.setMetric(
"task/pending/time",
new Duration(taskItem.getCreatedTime(), DateTimes.nowUtc()).getMillis())
);
// fall through
case RUNNING:
if (worker.getHost().equals(taskItem.getWorker().getHost())) {
if (!announcement.getTaskLocation().equals(taskItem.getLocation())) {
log.info(
"Task[%s] location changed on worker[%s]. new location[%s].",
taskId,
worker.getHost(),
announcement.getTaskLocation()
);
taskItem.setLocation(announcement.getTaskLocation());
TaskRunnerUtils.notifyLocationChanged(listeners, taskId, announcement.getTaskLocation());
}
} else {
log.warn(
"Found worker[%s] running task[%s] which is being run by another worker[%s]. Notification ignored.",
worker.getHost(),
taskId,
taskItem.getWorker().getHost()
);
shouldShutdownTask = true;
}
break;
case COMPLETE:
log.warn(
"Worker[%s] reported status for completed task[%s]. Ignored.",
worker.getHost(),
taskId
);
shouldShutdownTask = true;
break;
default:
log.makeAlert(
"Found unrecognized state[%s] of task[%s]. Notification[%s] from worker[%s] is ignored.",
taskItem.getState(),
taskId,
announcement,
worker.getHost()
).emit();
}
break;
case FAILED:
case SUCCESS:
switch (taskItem.getState()) {
case PENDING:
case PENDING_WORKER_ASSIGN:
taskItem.setWorker(worker);
taskItem.setState(HttpRemoteTaskRunnerWorkItem.State.RUNNING);
log.info("Task[%s] finished on worker[%s].", taskId, worker.getHost());
// fall through
case RUNNING:
if (worker.getHost().equals(taskItem.getWorker().getHost())) {
if (!announcement.getTaskLocation().equals(taskItem.getLocation())) {
log.info(
"Task[%s] location changed on worker[%s]. new location[%s].",
taskId,
worker.getHost(),
announcement.getTaskLocation()
);
taskItem.setLocation(announcement.getTaskLocation());
TaskRunnerUtils.notifyLocationChanged(listeners, taskId, announcement.getTaskLocation());
}
isTaskCompleted = true;
} else {
log.warn(
"Worker[%s] reported completed task[%s] which is being run by another worker[%s]. Notification ignored.",
worker.getHost(),
taskId,
taskItem.getWorker().getHost()
);
}
break;
case COMPLETE:
// this can happen when a worker is restarted and reports its list of completed tasks again.
break;
default:
log.makeAlert(
"Found unrecognized state[%s] of task[%s]. Notification[%s] from worker[%s] is ignored.",
taskItem.getState(),
taskId,
announcement,
worker.getHost()
).emit();
}
break;
default:
log.makeAlert(
"Worker[%s] reported unrecognized state[%s] for task[%s].",
worker.getHost(),
announcement.getTaskStatus().getStatusCode(),
taskId
).emit();
}
}
}
if (isTaskCompleted) {
// taskComplete(..) must be called outside of statusLock, see comments on method.
taskComplete(taskItem, workerHolder, announcement.getTaskStatus());
}
if (shouldShutdownTask) {
log.warn("Killing task[%s] on worker[%s].", taskId, worker.getHost());
workerHolder.shutdownTask(taskId);
}
synchronized (statusLock) {
statusLock.notifyAll();
}
}
@Override
public Map<String, Long> getTotalTaskSlotCount()
{
Map<String, Long> totalPeons = new HashMap<>();
for (ImmutableWorkerInfo worker : getWorkers()) {
String workerCategory = worker.getWorker().getCategory();
int workerCapacity = worker.getWorker().getCapacity();
totalPeons.compute(
workerCategory,
(category, totalCapacity) -> totalCapacity == null ? workerCapacity : totalCapacity + workerCapacity
);
}
return totalPeons;
}
@Override
public Map<String, Long> getIdleTaskSlotCount()
{
Map<String, Long> totalIdlePeons = new HashMap<>();
for (ImmutableWorkerInfo worker : getWorkersEligibleToRunTasks().values()) {
String workerCategory = worker.getWorker().getCategory();
int workerAvailableCapacity = worker.getAvailableCapacity();
totalIdlePeons.compute(
workerCategory,
(category, availableCapacity) -> availableCapacity == null ? workerAvailableCapacity : availableCapacity + workerAvailableCapacity
);
}
return totalIdlePeons;
}
@Override
public Map<String, Long> getUsedTaskSlotCount()
{
Map<String, Long> totalUsedPeons = new HashMap<>();
for (ImmutableWorkerInfo worker : getWorkers()) {
String workerCategory = worker.getWorker().getCategory();
int workerUsedCapacity = worker.getCurrCapacityUsed();
totalUsedPeons.compute(
workerCategory,
(category, usedCapacity) -> usedCapacity == null ? workerUsedCapacity : usedCapacity + workerUsedCapacity
);
}
return totalUsedPeons;
}
@Override
public Map<String, Long> getLazyTaskSlotCount()
{
Map<String, Long> totalLazyPeons = new HashMap<>();
for (Worker worker : getLazyWorkers()) {
String workerCategory = worker.getCategory();
int workerLazyPeons = worker.getCapacity();
totalLazyPeons.compute(
workerCategory,
(category, lazyPeons) -> lazyPeons == null ? workerLazyPeons : lazyPeons + workerLazyPeons
);
}
return totalLazyPeons;
}
@Override
public Map<String, Long> getBlacklistedTaskSlotCount()
{
Map<String, Long> totalBlacklistedPeons = new HashMap<>();
for (ImmutableWorkerInfo worker : getBlackListedWorkers()) {
String workerCategory = worker.getWorker().getCategory();
int workerBlacklistedPeons = worker.getWorker().getCapacity();
totalBlacklistedPeons.compute(
workerCategory,
(category, blacklistedPeons) -> blacklistedPeons == null ? workerBlacklistedPeons : blacklistedPeons + workerBlacklistedPeons
);
}
return totalBlacklistedPeons;
}
@Override
public int getTotalCapacity()
{
return getWorkers().stream().mapToInt(workerInfo -> workerInfo.getWorker().getCapacity()).sum();
}
@Override
public int getUsedCapacity()
{
return getWorkers().stream().mapToInt(ImmutableWorkerInfo::getCurrCapacityUsed).sum();
}
private static class HttpRemoteTaskRunnerWorkItem extends RemoteTaskRunnerWorkItem
{
enum State
{
// Task has been given to HRTR, but a worker to run this task hasn't been identified yet.
PENDING(0, true, RunnerTaskState.PENDING),
// A Worker has been identified to run this task, but request to run task hasn't been made to worker yet
// or worker hasn't acknowledged the task yet.
PENDING_WORKER_ASSIGN(1, true, RunnerTaskState.PENDING),
RUNNING(2, false, RunnerTaskState.RUNNING),
COMPLETE(3, false, RunnerTaskState.NONE);
private final int index;
private final boolean isPending;
private final RunnerTaskState runnerTaskState;
State(int index, boolean isPending, RunnerTaskState runnerTaskState)
{
this.index = index;
this.isPending = isPending;
this.runnerTaskState = runnerTaskState;
}
boolean isPending()
{
return isPending;
}
RunnerTaskState toRunnerTaskState()
{
return runnerTaskState;
}
}
private Task task;
private State state;
HttpRemoteTaskRunnerWorkItem(
String taskId,
Worker worker,
TaskLocation location,
@Nullable Task task,
String taskType,
State state
)
{
super(taskId, task == null ? null : task.getType(), worker, location, task == null ? null : task.getDataSource());
this.state = Preconditions.checkNotNull(state);
Preconditions.checkArgument(task == null || taskType == null || taskType.equals(task.getType()));
// It is possible to have it null when the TaskRunner is just started and discovered this taskId from a worker,
// notifications don't contain whole Task instance but just metadata about the task.
this.task = task;
}
public Task getTask()
{
return task;
}
public void setTask(Task task)
{
this.task = task;
if (getTaskType() == null) {
setTaskType(task.getType());
} else {
Preconditions.checkArgument(getTaskType().equals(task.getType()));
}
}
@JsonProperty
public State getState()
{
return state;
}
@Override
public void setResult(TaskStatus status)
{
setState(State.COMPLETE);
super.setResult(status);
}
public void setState(State state)
{
Preconditions.checkArgument(
state.index - this.state.index > 0,
"Invalid state transition from [%s] to [%s]",
this.state,
state
);
setStateUnconditionally(state);
}
public void revertStateFromPendingWorkerAssignToPending()
{
Preconditions.checkState(
this.state == State.PENDING_WORKER_ASSIGN,
"Can't move state from [%s] to [%s]",
this.state,
State.PENDING
);
setStateUnconditionally(State.PENDING);
}
private void setStateUnconditionally(State state)
{
if (log.isDebugEnabled()) {
// Exception is logged to know what led to this call.
log.debug(
new RuntimeException("Stacktrace..."),
"Setting task[%s] work item state from [%s] to [%s].",
getTaskId(),
this.state,
state
);
}
this.state = state;
}
}
}
| UTF-8 | Java | 68,789 | java | HttpRemoteTaskRunner.java | Java | [
{
"context": "th \"statusLock\"\n // held. See https://github.com/apache/druid/issues/6201\n private void taskComplete(\n ",
"end": 18631,
"score": 0.9946539402008057,
"start": 18625,
"tag": "USERNAME",
"value": "apache"
}
] | null | [] | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.indexing.overlord.hrtr;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableScheduledFuture;
import com.google.common.util.concurrent.ListeningScheduledExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.druid.concurrent.LifecycleLock;
import org.apache.druid.discovery.DiscoveryDruidNode;
import org.apache.druid.discovery.DruidNodeDiscovery;
import org.apache.druid.discovery.DruidNodeDiscoveryProvider;
import org.apache.druid.discovery.WorkerNodeService;
import org.apache.druid.indexer.RunnerTaskState;
import org.apache.druid.indexer.TaskLocation;
import org.apache.druid.indexer.TaskState;
import org.apache.druid.indexer.TaskStatus;
import org.apache.druid.indexing.common.task.IndexTaskUtils;
import org.apache.druid.indexing.common.task.Task;
import org.apache.druid.indexing.overlord.ImmutableWorkerInfo;
import org.apache.druid.indexing.overlord.RemoteTaskRunnerWorkItem;
import org.apache.druid.indexing.overlord.TaskRunnerListener;
import org.apache.druid.indexing.overlord.TaskRunnerUtils;
import org.apache.druid.indexing.overlord.TaskRunnerWorkItem;
import org.apache.druid.indexing.overlord.TaskStorage;
import org.apache.druid.indexing.overlord.WorkerTaskRunner;
import org.apache.druid.indexing.overlord.autoscaling.ProvisioningService;
import org.apache.druid.indexing.overlord.autoscaling.ProvisioningStrategy;
import org.apache.druid.indexing.overlord.autoscaling.ScalingStats;
import org.apache.druid.indexing.overlord.config.HttpRemoteTaskRunnerConfig;
import org.apache.druid.indexing.overlord.config.WorkerTaskRunnerConfig;
import org.apache.druid.indexing.overlord.setup.WorkerBehaviorConfig;
import org.apache.druid.indexing.overlord.setup.WorkerSelectStrategy;
import org.apache.druid.indexing.worker.TaskAnnouncement;
import org.apache.druid.indexing.worker.Worker;
import org.apache.druid.indexing.worker.config.WorkerConfig;
import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.Pair;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.concurrent.Execs;
import org.apache.druid.java.util.common.concurrent.ScheduledExecutors;
import org.apache.druid.java.util.common.lifecycle.LifecycleStart;
import org.apache.druid.java.util.common.lifecycle.LifecycleStop;
import org.apache.druid.java.util.emitter.EmittingLogger;
import org.apache.druid.java.util.emitter.service.ServiceEmitter;
import org.apache.druid.java.util.emitter.service.ServiceMetricEvent;
import org.apache.druid.java.util.http.client.HttpClient;
import org.apache.druid.java.util.http.client.Request;
import org.apache.druid.java.util.http.client.response.InputStreamResponseHandler;
import org.apache.druid.server.initialization.IndexerZkConfig;
import org.apache.druid.tasklogs.TaskLogStreamer;
import org.apache.zookeeper.KeeperException;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.joda.time.Duration;
import org.joda.time.Period;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* A Remote TaskRunner to manage tasks on Middle Manager nodes using internal-discovery({@link DruidNodeDiscoveryProvider})
* to discover them and Http.
* Middle Managers manages list of assigned/completed tasks on disk and expose 3 HTTP endpoints
* 1. POST request for assigning a task
* 2. POST request for shutting down a task
* 3. GET request for getting list of assigned, running, completed tasks on Middle Manager and its enable/disable status.
* This endpoint is implemented to support long poll and holds the request till there is a change. This class
* sends the next request immediately as the previous finishes to keep the state up-to-date.
* <p>
* ZK_CLEANUP_TODO : As of 0.11.1, it is required to cleanup task status paths from ZK which are created by the
* workers to support deprecated RemoteTaskRunner. So a method "scheduleCompletedTaskStatusCleanupFromZk()" is added'
* which should be removed in the release that removes RemoteTaskRunner legacy ZK updation WorkerTaskMonitor class.
*/
public class HttpRemoteTaskRunner implements WorkerTaskRunner, TaskLogStreamer
{
private static final EmittingLogger log = new EmittingLogger(HttpRemoteTaskRunner.class);
private final LifecycleLock lifecycleLock = new LifecycleLock();
// Executor for assigning pending tasks to workers.
private final ExecutorService pendingTasksExec;
// All known tasks, TaskID -> HttpRemoteTaskRunnerWorkItem
// This is a ConcurrentMap as some of the reads are done without holding the lock.
@GuardedBy("statusLock")
private final ConcurrentMap<String, HttpRemoteTaskRunnerWorkItem> tasks = new ConcurrentHashMap<>();
// This is the list of pending tasks in the order they arrived, exclusively manipulated/used by thread that
// gives a new task to this class and threads in pendingTasksExec that are responsible for assigning tasks to
// workers.
@GuardedBy("statusLock")
private final List<String> pendingTaskIds = new ArrayList<>();
// All discovered workers, "host:port" -> WorkerHolder
private final ConcurrentMap<String, WorkerHolder> workers = new ConcurrentHashMap<>();
// Executor for syncing state of each worker.
private final ScheduledExecutorService workersSyncExec;
// Workers that have been marked as lazy. these workers are not running any tasks and can be terminated safely by the scaling policy.
private final ConcurrentMap<String, WorkerHolder> lazyWorkers = new ConcurrentHashMap<>();
// Workers that have been blacklisted.
private final ConcurrentHashMap<String, WorkerHolder> blackListedWorkers = new ConcurrentHashMap<>();
// workers which were assigned a task and are yet to acknowledge same.
// Map: workerId -> taskId
// all writes are guarded
@GuardedBy("statusLock")
private final ConcurrentMap<String, String> workersWithUnacknowledgedTask = new ConcurrentHashMap<>();
// Executor to complete cleanup of workers which have disappeared.
private final ListeningScheduledExecutorService cleanupExec;
private final ConcurrentMap<String, ScheduledFuture> removedWorkerCleanups = new ConcurrentHashMap<>();
private final Object statusLock = new Object();
// task runner listeners
private final CopyOnWriteArrayList<Pair<TaskRunnerListener, Executor>> listeners = new CopyOnWriteArrayList<>();
private final ProvisioningStrategy<WorkerTaskRunner> provisioningStrategy;
private ProvisioningService provisioningService;
private final DruidNodeDiscoveryProvider druidNodeDiscoveryProvider;
private final HttpClient httpClient;
private final ObjectMapper smileMapper;
private final Supplier<WorkerBehaviorConfig> workerConfigRef;
private final HttpRemoteTaskRunnerConfig config;
private final TaskStorage taskStorage;
private final ServiceEmitter emitter;
// ZK_CLEANUP_TODO : Remove these when RemoteTaskRunner and WorkerTaskMonitor are removed.
private static final Joiner JOINER = Joiner.on("/");
@Nullable // Null, if zk is disabled
private final CuratorFramework cf;
@Nullable // Null, if zk is disabled
private final ScheduledExecutorService zkCleanupExec;
private final IndexerZkConfig indexerZkConfig;
private volatile DruidNodeDiscovery.Listener nodeDiscoveryListener;
public HttpRemoteTaskRunner(
ObjectMapper smileMapper,
HttpRemoteTaskRunnerConfig config,
HttpClient httpClient,
Supplier<WorkerBehaviorConfig> workerConfigRef,
ProvisioningStrategy<WorkerTaskRunner> provisioningStrategy,
DruidNodeDiscoveryProvider druidNodeDiscoveryProvider,
TaskStorage taskStorage,
@Nullable CuratorFramework cf,
IndexerZkConfig indexerZkConfig,
ServiceEmitter emitter
)
{
this.smileMapper = smileMapper;
this.config = config;
this.httpClient = httpClient;
this.druidNodeDiscoveryProvider = druidNodeDiscoveryProvider;
this.taskStorage = taskStorage;
this.workerConfigRef = workerConfigRef;
this.emitter = emitter;
this.pendingTasksExec = Execs.multiThreaded(
config.getPendingTasksRunnerNumThreads(),
"hrtr-pending-tasks-runner-%d"
);
this.workersSyncExec = ScheduledExecutors.fixed(
config.getWorkerSyncNumThreads(),
"HttpRemoteTaskRunner-worker-sync-%d"
);
this.cleanupExec = MoreExecutors.listeningDecorator(
ScheduledExecutors.fixed(1, "HttpRemoteTaskRunner-Worker-Cleanup-%d")
);
if (cf != null) {
this.cf = cf;
this.zkCleanupExec = ScheduledExecutors.fixed(
1,
"HttpRemoteTaskRunner-zk-cleanup-%d"
);
} else {
this.cf = null;
this.zkCleanupExec = null;
}
this.indexerZkConfig = indexerZkConfig;
this.provisioningStrategy = provisioningStrategy;
}
@Override
@LifecycleStart
public void start()
{
if (!lifecycleLock.canStart()) {
return;
}
try {
log.info("Starting...");
scheduleCompletedTaskStatusCleanupFromZk();
startWorkersHandling();
ScheduledExecutors.scheduleAtFixedRate(
cleanupExec,
Period.ZERO.toStandardDuration(),
config.getWorkerBlackListCleanupPeriod().toStandardDuration(),
this::checkAndRemoveWorkersFromBlackList
);
provisioningService = provisioningStrategy.makeProvisioningService(this);
scheduleSyncMonitoring();
startPendingTaskHandling();
lifecycleLock.started();
log.info("Started.");
}
catch (Exception e) {
throw new RuntimeException(e);
}
finally {
lifecycleLock.exitStart();
}
}
private void scheduleCompletedTaskStatusCleanupFromZk()
{
if (cf == null) {
return;
}
zkCleanupExec.scheduleAtFixedRate(
() -> {
try {
List<String> workers;
try {
workers = cf.getChildren().forPath(indexerZkConfig.getStatusPath());
}
catch (KeeperException.NoNodeException e) {
// statusPath doesn't exist yet; can occur if no middleManagers have started.
workers = ImmutableList.of();
}
Set<String> knownActiveTaskIds = new HashSet<>();
if (!workers.isEmpty()) {
for (Task task : taskStorage.getActiveTasks()) {
knownActiveTaskIds.add(task.getId());
}
}
for (String workerId : workers) {
String workerStatusPath = JOINER.join(indexerZkConfig.getStatusPath(), workerId);
List<String> taskIds;
try {
taskIds = cf.getChildren().forPath(workerStatusPath);
}
catch (KeeperException.NoNodeException e) {
taskIds = ImmutableList.of();
}
for (String taskId : taskIds) {
if (!knownActiveTaskIds.contains(taskId)) {
String taskStatusPath = JOINER.join(workerStatusPath, taskId);
try {
cf.delete().guaranteed().forPath(taskStatusPath);
}
catch (KeeperException.NoNodeException e) {
log.info("Failed to delete taskStatusPath[%s].", taskStatusPath);
}
}
}
}
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
catch (Exception ex) {
log.error(ex, "Unknown error while doing task status cleanup in ZK.");
}
},
1,
5,
TimeUnit.MINUTES
);
}
/**
* Must not be used outside of this class and {@link HttpRemoteTaskRunnerResource}
*/
@SuppressWarnings("GuardedBy") // Read on workersWithUnacknowledgedTask is safe
Map<String, ImmutableWorkerInfo> getWorkersEligibleToRunTasks()
{
// In this class, this method is called with statusLock held.
// writes to workersWithUnacknowledgedTask are always guarded by statusLock.
// however writes to lazyWorker/blacklistedWorkers aren't necessarily guarded by same lock, so technically there
// could be races in that a task could get assigned to a worker which in another thread is concurrently being
// marked lazy/blacklisted , but that is ok because that is equivalent to this worker being picked for task and
// being assigned lazy/blacklisted right after even when the two threads hold a mutually exclusive lock.
return Maps.transformEntries(
Maps.filterEntries(
workers,
input -> !lazyWorkers.containsKey(input.getKey()) &&
!workersWithUnacknowledgedTask.containsKey(input.getKey()) &&
!blackListedWorkers.containsKey(input.getKey()) &&
input.getValue().isInitialized() &&
input.getValue().isEnabled()
),
(String key, WorkerHolder value) -> value.toImmutable()
);
}
private ImmutableWorkerInfo findWorkerToRunTask(Task task)
{
WorkerBehaviorConfig workerConfig = workerConfigRef.get();
WorkerSelectStrategy strategy;
if (workerConfig == null || workerConfig.getSelectStrategy() == null) {
strategy = WorkerBehaviorConfig.DEFAULT_STRATEGY;
log.debug("No worker selection strategy set. Using default of [%s]", strategy.getClass().getSimpleName());
} else {
strategy = workerConfig.getSelectStrategy();
}
return strategy.findWorkerForTask(
config,
ImmutableMap.copyOf(getWorkersEligibleToRunTasks()),
task
);
}
private boolean runTaskOnWorker(
final HttpRemoteTaskRunnerWorkItem workItem,
final String workerHost
) throws InterruptedException
{
String taskId = workItem.getTaskId();
WorkerHolder workerHolder = workers.get(workerHost);
if (workerHolder == null || lazyWorkers.containsKey(workerHost) || blackListedWorkers.containsKey(workerHost)) {
log.info("Not assigning task[%s] to removed or marked lazy/blacklisted worker[%s]", taskId, workerHost);
return false;
}
log.info("Assigning task [%s] to worker [%s]", taskId, workerHost);
if (workerHolder.assignTask(workItem.getTask())) {
// Don't assign new tasks until the task we just assigned is actually running
// on a worker - this avoids overflowing a worker with tasks
long waitMs = config.getTaskAssignmentTimeout().toStandardDuration().getMillis();
long waitStart = System.currentTimeMillis();
boolean isTaskAssignmentTimedOut = false;
synchronized (statusLock) {
while (tasks.containsKey(taskId) && tasks.get(taskId).getState().isPending()) {
long remaining = waitMs - (System.currentTimeMillis() - waitStart);
if (remaining > 0) {
statusLock.wait(remaining);
} else {
isTaskAssignmentTimedOut = true;
break;
}
}
}
if (isTaskAssignmentTimedOut) {
log.makeAlert(
"Task assignment timed out on worker [%s], never ran task [%s] in timeout[%s]!",
workerHost,
taskId,
config.getTaskAssignmentTimeout()
).emit();
// taskComplete(..) must be called outside of statusLock, see comments on method.
taskComplete(
workItem,
workerHolder,
TaskStatus.failure(
taskId,
StringUtils.format(
"The worker that this task is assigned did not start it in timeout[%s]. "
+ "See overlord and middleManager/indexer logs for more details.",
config.getTaskAssignmentTimeout()
)
)
);
}
return true;
} else {
return false;
}
}
// CAUTION: This method calls RemoteTaskRunnerWorkItem.setResult(..) which results in TaskQueue.notifyStatus() being called
// because that is attached by TaskQueue to task result future. So, this method must not be called with "statusLock"
// held. See https://github.com/apache/druid/issues/6201
private void taskComplete(
HttpRemoteTaskRunnerWorkItem taskRunnerWorkItem,
WorkerHolder workerHolder,
TaskStatus taskStatus
)
{
Preconditions.checkState(!Thread.holdsLock(statusLock), "Current thread must not hold statusLock.");
Preconditions.checkNotNull(taskRunnerWorkItem, "taskRunnerWorkItem");
Preconditions.checkNotNull(taskStatus, "taskStatus");
if (workerHolder != null) {
log.info(
"Worker[%s] completed task[%s] with status[%s]",
workerHolder.getWorker().getHost(),
taskStatus.getId(),
taskStatus.getStatusCode()
);
// Worker is done with this task
workerHolder.setLastCompletedTaskTime(DateTimes.nowUtc());
}
if (taskRunnerWorkItem.getResult().isDone()) {
// This is not the first complete event.
try {
TaskState lastKnownState = taskRunnerWorkItem.getResult().get().getStatusCode();
if (taskStatus.getStatusCode() != lastKnownState) {
log.warn(
"The state of the new task complete event is different from its last known state. "
+ "New state[%s], last known state[%s]",
taskStatus.getStatusCode(),
lastKnownState
);
}
}
catch (InterruptedException e) {
log.warn(e, "Interrupted while getting the last known task status.");
Thread.currentThread().interrupt();
}
catch (ExecutionException e) {
// This case should not really happen.
log.warn(e, "Failed to get the last known task status. Ignoring this failure.");
}
} else {
// Notify interested parties
taskRunnerWorkItem.setResult(taskStatus);
TaskRunnerUtils.notifyStatusChanged(listeners, taskStatus.getId(), taskStatus);
// Update success/failure counters, Blacklist node if there are too many failures.
if (workerHolder != null) {
blacklistWorkerIfNeeded(taskStatus, workerHolder);
}
}
synchronized (statusLock) {
statusLock.notifyAll();
}
}
private void startWorkersHandling() throws InterruptedException
{
final CountDownLatch workerViewInitialized = new CountDownLatch(1);
DruidNodeDiscovery druidNodeDiscovery =
druidNodeDiscoveryProvider.getForService(WorkerNodeService.DISCOVERY_SERVICE_KEY);
this.nodeDiscoveryListener = new DruidNodeDiscovery.Listener()
{
@Override
public void nodesAdded(Collection<DiscoveryDruidNode> nodes)
{
nodes.forEach(node -> addWorker(toWorker(node)));
}
@Override
public void nodesRemoved(Collection<DiscoveryDruidNode> nodes)
{
nodes.forEach(node -> removeWorker(toWorker(node)));
}
@Override
public void nodeViewInitialized()
{
//CountDownLatch.countDown() does nothing when count has already reached 0.
workerViewInitialized.countDown();
}
};
druidNodeDiscovery.registerListener(nodeDiscoveryListener);
long workerDiscoveryStartTime = System.currentTimeMillis();
while (!workerViewInitialized.await(30, TimeUnit.SECONDS)) {
if (System.currentTimeMillis() - workerDiscoveryStartTime > TimeUnit.MINUTES.toMillis(5)) {
throw new ISE("Couldn't discover workers.");
} else {
log.info("Waiting for worker discovery...");
}
}
log.info("[%s] Workers are discovered.", workers.size());
// Wait till all worker state is sync'd so that we know which worker is running/completed what tasks or else
// We would start assigning tasks which are pretty soon going to be reported by discovered workers.
for (WorkerHolder worker : workers.values()) {
log.info("Waiting for worker[%s] to sync state...", worker.getWorker().getHost());
worker.waitForInitialization();
}
log.info("Workers have sync'd state successfully.");
}
private Worker toWorker(DiscoveryDruidNode node)
{
final WorkerNodeService workerNodeService = node.getService(WorkerNodeService.DISCOVERY_SERVICE_KEY, WorkerNodeService.class);
if (workerNodeService == null) {
// this shouldn't typically happen, but just in case it does, make a dummy worker to allow the callbacks to
// continue since addWorker/removeWorker only need worker.getHost()
return new Worker(
node.getDruidNode().getServiceScheme(),
node.getDruidNode().getHostAndPortToUse(),
null,
0,
"",
WorkerConfig.DEFAULT_CATEGORY
);
}
return new Worker(
node.getDruidNode().getServiceScheme(),
node.getDruidNode().getHostAndPortToUse(),
workerNodeService.getIp(),
workerNodeService.getCapacity(),
workerNodeService.getVersion(),
workerNodeService.getCategory()
);
}
@VisibleForTesting
void addWorker(final Worker worker)
{
synchronized (workers) {
log.info("Worker[%s] reportin' for duty!", worker.getHost());
cancelWorkerCleanup(worker.getHost());
WorkerHolder holder = workers.get(worker.getHost());
if (holder == null) {
List<TaskAnnouncement> expectedAnnouncements = new ArrayList<>();
synchronized (statusLock) {
// It might be a worker that existed before, temporarily went away and came back. We might have a set of
// tasks that we think are running on this worker. Provide that information to WorkerHolder that
// manages the task syncing with that worker.
for (Map.Entry<String, HttpRemoteTaskRunnerWorkItem> e : tasks.entrySet()) {
if (e.getValue().getState() == HttpRemoteTaskRunnerWorkItem.State.RUNNING) {
Worker w = e.getValue().getWorker();
if (w != null && w.getHost().equals(worker.getHost()) && e.getValue().getTask() != null) {
expectedAnnouncements.add(
TaskAnnouncement.create(
e.getValue().getTask(),
TaskStatus.running(e.getKey()),
e.getValue().getLocation()
)
);
}
}
}
}
holder = createWorkerHolder(
smileMapper,
httpClient,
config,
workersSyncExec,
this::taskAddedOrUpdated,
worker,
expectedAnnouncements
);
holder.start();
workers.put(worker.getHost(), holder);
} else {
log.info("Worker[%s] already exists.", worker.getHost());
}
}
synchronized (statusLock) {
statusLock.notifyAll();
}
}
protected WorkerHolder createWorkerHolder(
ObjectMapper smileMapper,
HttpClient httpClient,
HttpRemoteTaskRunnerConfig config,
ScheduledExecutorService workersSyncExec,
WorkerHolder.Listener listener,
Worker worker,
List<TaskAnnouncement> knownAnnouncements
)
{
return new WorkerHolder(smileMapper, httpClient, config, workersSyncExec, listener, worker, knownAnnouncements);
}
private void removeWorker(final Worker worker)
{
synchronized (workers) {
log.info("Kaboom! Worker[%s] removed!", worker.getHost());
WorkerHolder workerHolder = workers.remove(worker.getHost());
if (workerHolder != null) {
try {
workerHolder.stop();
scheduleTasksCleanupForWorker(worker.getHost());
}
catch (Exception e) {
throw new RuntimeException(e);
}
finally {
checkAndRemoveWorkersFromBlackList();
}
}
lazyWorkers.remove(worker.getHost());
}
}
private boolean cancelWorkerCleanup(String workerHost)
{
ScheduledFuture previousCleanup = removedWorkerCleanups.remove(workerHost);
if (previousCleanup != null) {
log.info("Cancelling Worker[%s] scheduled task cleanup", workerHost);
previousCleanup.cancel(false);
}
return previousCleanup != null;
}
private void scheduleTasksCleanupForWorker(final String workerHostAndPort)
{
cancelWorkerCleanup(workerHostAndPort);
final ListenableScheduledFuture<?> cleanupTask = cleanupExec.schedule(
() -> {
log.info("Running scheduled cleanup for Worker[%s]", workerHostAndPort);
try {
Set<HttpRemoteTaskRunnerWorkItem> tasksToFail = new HashSet<>();
synchronized (statusLock) {
for (Map.Entry<String, HttpRemoteTaskRunnerWorkItem> e : tasks.entrySet()) {
if (e.getValue().getState() == HttpRemoteTaskRunnerWorkItem.State.RUNNING) {
Worker w = e.getValue().getWorker();
if (w != null && w.getHost().equals(workerHostAndPort)) {
tasksToFail.add(e.getValue());
}
}
}
}
for (HttpRemoteTaskRunnerWorkItem taskItem : tasksToFail) {
if (!taskItem.getResult().isDone()) {
log.warn(
"Failing task[%s] because worker[%s] disappeared and did not report within cleanup timeout[%s].",
workerHostAndPort,
taskItem.getTaskId(),
config.getTaskCleanupTimeout()
);
// taskComplete(..) must be called outside of statusLock, see comments on method.
taskComplete(
taskItem,
null,
TaskStatus.failure(
taskItem.getTaskId(),
StringUtils.format(
"The worker that this task was assigned disappeared and "
+ "did not report cleanup within timeout[%s]. "
+ "See overlord and middleManager/indexer logs for more details.",
config.getTaskCleanupTimeout()
)
)
);
}
}
}
catch (Exception e) {
log.makeAlert("Exception while cleaning up worker[%s]", workerHostAndPort).emit();
throw new RuntimeException(e);
}
},
config.getTaskCleanupTimeout().toStandardDuration().getMillis(),
TimeUnit.MILLISECONDS
);
removedWorkerCleanups.put(workerHostAndPort, cleanupTask);
// Remove this entry from removedWorkerCleanups when done, if it's actually the one in there.
Futures.addCallback(
cleanupTask,
new FutureCallback<Object>()
{
@Override
public void onSuccess(Object result)
{
removedWorkerCleanups.remove(workerHostAndPort, cleanupTask);
}
@Override
public void onFailure(Throwable t)
{
removedWorkerCleanups.remove(workerHostAndPort, cleanupTask);
}
},
MoreExecutors.directExecutor()
);
}
private void scheduleSyncMonitoring()
{
workersSyncExec.scheduleAtFixedRate(
() -> {
log.debug("Running the Sync Monitoring.");
try {
syncMonitoring();
}
catch (Exception ex) {
if (ex instanceof InterruptedException) {
Thread.currentThread().interrupt();
} else {
log.makeAlert(ex, "Exception in sync monitoring.").emit();
}
}
},
1,
5,
TimeUnit.MINUTES
);
}
@VisibleForTesting
void syncMonitoring()
{
// Ensure that the collection is not being modified during iteration. Iterate over a copy
final Set<Map.Entry<String, WorkerHolder>> workerEntrySet = ImmutableSet.copyOf(workers.entrySet());
for (Map.Entry<String, WorkerHolder> e : workerEntrySet) {
WorkerHolder workerHolder = e.getValue();
if (workerHolder.getUnderlyingSyncer().needsReset()) {
synchronized (workers) {
// check again that server is still there and only then reset.
if (workers.containsKey(e.getKey())) {
log.makeAlert(
"Worker[%s] is not syncing properly. Current state is [%s]. Resetting it.",
workerHolder.getWorker().getHost(),
workerHolder.getUnderlyingSyncer().getDebugInfo()
).emit();
removeWorker(workerHolder.getWorker());
addWorker(workerHolder.getWorker());
}
}
}
}
}
/**
* This method returns the debugging information exposed by {@link HttpRemoteTaskRunnerResource} and meant
* for that use only. It must not be used for any other purpose.
*/
Map<String, Object> getWorkerSyncerDebugInfo()
{
Preconditions.checkArgument(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS));
Map<String, Object> result = Maps.newHashMapWithExpectedSize(workers.size());
for (Map.Entry<String, WorkerHolder> e : workers.entrySet()) {
WorkerHolder serverHolder = e.getValue();
result.put(
e.getKey(),
serverHolder.getUnderlyingSyncer().getDebugInfo()
);
}
return result;
}
private void checkAndRemoveWorkersFromBlackList()
{
boolean shouldRunPendingTasks = false;
Iterator<Map.Entry<String, WorkerHolder>> iterator = blackListedWorkers.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, WorkerHolder> e = iterator.next();
if (shouldRemoveNodeFromBlackList(e.getValue())) {
iterator.remove();
e.getValue().resetContinuouslyFailedTasksCount();
e.getValue().setBlacklistedUntil(null);
shouldRunPendingTasks = true;
}
}
if (shouldRunPendingTasks) {
synchronized (statusLock) {
statusLock.notifyAll();
}
}
}
private boolean shouldRemoveNodeFromBlackList(WorkerHolder workerHolder)
{
if (!workers.containsKey(workerHolder.getWorker().getHost())) {
return true;
}
if (blackListedWorkers.size() > workers.size() * (config.getMaxPercentageBlacklistWorkers() / 100.0)) {
log.info(
"Removing [%s] from blacklist because percentage of blacklisted workers exceeds [%d]",
workerHolder.getWorker(),
config.getMaxPercentageBlacklistWorkers()
);
return true;
}
long remainingMillis = workerHolder.getBlacklistedUntil().getMillis() - System.currentTimeMillis();
if (remainingMillis <= 0) {
log.info("Removing [%s] from blacklist because backoff time elapsed", workerHolder.getWorker());
return true;
}
log.info("[%s] still blacklisted for [%,ds]", workerHolder.getWorker(), remainingMillis / 1000);
return false;
}
private void blacklistWorkerIfNeeded(TaskStatus taskStatus, WorkerHolder workerHolder)
{
synchronized (blackListedWorkers) {
if (taskStatus.isSuccess()) {
workerHolder.resetContinuouslyFailedTasksCount();
if (blackListedWorkers.remove(workerHolder.getWorker().getHost()) != null) {
workerHolder.setBlacklistedUntil(null);
log.info("[%s] removed from blacklist because a task finished with SUCCESS", workerHolder.getWorker());
}
} else if (taskStatus.isFailure()) {
workerHolder.incrementContinuouslyFailedTasksCount();
}
if (workerHolder.getContinuouslyFailedTasksCount() > config.getMaxRetriesBeforeBlacklist() &&
blackListedWorkers.size() <= workers.size() * (config.getMaxPercentageBlacklistWorkers() / 100.0) - 1) {
workerHolder.setBlacklistedUntil(DateTimes.nowUtc().plus(config.getWorkerBlackListBackoffTime()));
if (blackListedWorkers.put(workerHolder.getWorker().getHost(), workerHolder) == null) {
log.info(
"Blacklisting [%s] until [%s] after [%,d] failed tasks in a row.",
workerHolder.getWorker(),
workerHolder.getBlacklistedUntil(),
workerHolder.getContinuouslyFailedTasksCount()
);
}
}
}
}
@Override
public Collection<ImmutableWorkerInfo> getWorkers()
{
return workers.values().stream().map(worker -> worker.toImmutable()).collect(Collectors.toList());
}
@VisibleForTesting
ConcurrentMap<String, WorkerHolder> getWorkersForTestingReadOnly()
{
return workers;
}
@Override
public Collection<Worker> getLazyWorkers()
{
return lazyWorkers.values().stream().map(holder -> holder.getWorker()).collect(Collectors.toList());
}
@Override
public Collection<Worker> markWorkersLazy(Predicate<ImmutableWorkerInfo> isLazyWorker, int maxLazyWorkers)
{
// skip the lock and bail early if we should not mark any workers lazy (e.g. number
// of current workers is at or below the minNumWorkers of autoscaler config)
if (lazyWorkers.size() >= maxLazyWorkers) {
return getLazyWorkers();
}
// Search for new workers to mark lazy.
// Status lock is used to prevent any tasks being assigned to workers while we mark them lazy
synchronized (statusLock) {
for (Map.Entry<String, WorkerHolder> worker : workers.entrySet()) {
if (lazyWorkers.size() >= maxLazyWorkers) {
break;
}
final WorkerHolder workerHolder = worker.getValue();
try {
if (isWorkerOkForMarkingLazy(workerHolder.getWorker()) && isLazyWorker.apply(workerHolder.toImmutable())) {
log.info("Adding Worker[%s] to lazySet!", workerHolder.getWorker().getHost());
lazyWorkers.put(worker.getKey(), workerHolder);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
return getLazyWorkers();
}
private boolean isWorkerOkForMarkingLazy(Worker worker)
{
// Check that worker is not running any tasks and no task is being assigned to it.
synchronized (statusLock) {
if (workersWithUnacknowledgedTask.containsKey(worker.getHost())) {
return false;
}
for (Map.Entry<String, HttpRemoteTaskRunnerWorkItem> e : tasks.entrySet()) {
if (e.getValue().getState() == HttpRemoteTaskRunnerWorkItem.State.RUNNING) {
Worker w = e.getValue().getWorker();
if (w != null && w.getHost().equals(worker.getHost())) {
return false;
}
}
}
return true;
}
}
@Override
public WorkerTaskRunnerConfig getConfig()
{
return config;
}
@Override
public Collection<Task> getPendingTaskPayloads()
{
synchronized (statusLock) {
return tasks.values()
.stream()
.filter(item -> item.getState().isPending())
.map(HttpRemoteTaskRunnerWorkItem::getTask)
.collect(Collectors.toList());
}
}
@Override
public Optional<InputStream> streamTaskLog(String taskId, long offset) throws IOException
{
@SuppressWarnings("GuardedBy") // Read on tasks is safe
HttpRemoteTaskRunnerWorkItem taskRunnerWorkItem = tasks.get(taskId);
Worker worker = null;
if (taskRunnerWorkItem != null && taskRunnerWorkItem.getState() != HttpRemoteTaskRunnerWorkItem.State.COMPLETE) {
worker = taskRunnerWorkItem.getWorker();
}
if (worker == null || !workers.containsKey(worker.getHost())) {
// Worker is not running this task, it might be available in deep storage
return Optional.absent();
} else {
// Worker is still running this task
final URL url = TaskRunnerUtils.makeWorkerURL(
worker,
"/druid/worker/v1/task/%s/log?offset=%s",
taskId,
Long.toString(offset)
);
try {
return Optional.of(httpClient.go(
new Request(HttpMethod.GET, url),
new InputStreamResponseHandler()
).get());
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
catch (ExecutionException e) {
// Unwrap if possible
Throwables.propagateIfPossible(e.getCause(), IOException.class);
throw new RuntimeException(e);
}
}
}
@Override
public Optional<InputStream> streamTaskReports(String taskId) throws IOException
{
@SuppressWarnings("GuardedBy") // Read on tasks is safe
HttpRemoteTaskRunnerWorkItem taskRunnerWorkItem = tasks.get(taskId);
Worker worker = null;
if (taskRunnerWorkItem != null && taskRunnerWorkItem.getState() != HttpRemoteTaskRunnerWorkItem.State.COMPLETE) {
worker = taskRunnerWorkItem.getWorker();
}
if (worker == null || !workers.containsKey(worker.getHost())) {
// Worker is not running this task, it might be available in deep storage
return Optional.absent();
} else {
// Worker is still running this task
TaskLocation taskLocation = taskRunnerWorkItem.getLocation();
if (TaskLocation.unknown().equals(taskLocation)) {
// No location known for this task. It may have not been assigned a location yet.
return Optional.absent();
}
final URL url = TaskRunnerUtils.makeTaskLocationURL(
taskLocation,
"/druid/worker/v1/chat/%s/liveReports",
taskId
);
try {
return Optional.of(httpClient.go(
new Request(HttpMethod.GET, url),
new InputStreamResponseHandler()
).get());
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
catch (ExecutionException e) {
// Unwrap if possible
Throwables.propagateIfPossible(e.getCause(), IOException.class);
throw new RuntimeException(e);
}
}
}
@Override
public List<Pair<Task, ListenableFuture<TaskStatus>>> restore()
{
return ImmutableList.of();
}
@Override
public void registerListener(TaskRunnerListener listener, Executor executor)
{
for (Pair<TaskRunnerListener, Executor> pair : listeners) {
if (pair.lhs.getListenerId().equals(listener.getListenerId())) {
throw new ISE("Listener [%s] already registered", listener.getListenerId());
}
}
final Pair<TaskRunnerListener, Executor> listenerPair = Pair.of(listener, executor);
synchronized (statusLock) {
for (Map.Entry<String, HttpRemoteTaskRunnerWorkItem> entry : tasks.entrySet()) {
if (entry.getValue().getState() == HttpRemoteTaskRunnerWorkItem.State.RUNNING) {
TaskRunnerUtils.notifyLocationChanged(
ImmutableList.of(listenerPair),
entry.getKey(),
entry.getValue().getLocation()
);
}
}
log.info("Registered listener [%s]", listener.getListenerId());
listeners.add(listenerPair);
}
}
@Override
public void unregisterListener(String listenerId)
{
for (Pair<TaskRunnerListener, Executor> pair : listeners) {
if (pair.lhs.getListenerId().equals(listenerId)) {
listeners.remove(pair);
log.info("Unregistered listener [%s]", listenerId);
return;
}
}
}
@Override
public ListenableFuture<TaskStatus> run(Task task)
{
Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS), "not started");
synchronized (statusLock) {
HttpRemoteTaskRunnerWorkItem existing = tasks.get(task.getId());
if (existing != null) {
log.info("Assigned a task[%s] that is known already. Ignored.", task.getId());
if (existing.getTask() == null) {
// in case it was discovered from a worker on start() and TaskAnnouncement does not have Task instance
// in it.
existing.setTask(task);
}
return existing.getResult();
} else {
log.info("Adding pending task[%s].", task.getId());
HttpRemoteTaskRunnerWorkItem taskRunnerWorkItem = new HttpRemoteTaskRunnerWorkItem(
task.getId(),
null,
null,
task,
task.getType(),
HttpRemoteTaskRunnerWorkItem.State.PENDING
);
tasks.put(task.getId(), taskRunnerWorkItem);
pendingTaskIds.add(task.getId());
statusLock.notifyAll();
return taskRunnerWorkItem.getResult();
}
}
}
private void startPendingTaskHandling()
{
for (int i = 0; i < config.getPendingTasksRunnerNumThreads(); i++) {
pendingTasksExec.submit(
() -> {
try {
if (!lifecycleLock.awaitStarted()) {
log.makeAlert("Lifecycle not started, PendingTaskExecution loop will not run.").emit();
return;
}
pendingTasksExecutionLoop();
}
catch (Throwable t) {
log.makeAlert(t, "Error while waiting for lifecycle start. PendingTaskExecution loop will not run")
.emit();
}
finally {
log.info("PendingTaskExecution loop exited.");
}
}
);
}
}
private void pendingTasksExecutionLoop()
{
while (!Thread.interrupted() && lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS)) {
try {
// Find one pending task to run and a worker to run on
HttpRemoteTaskRunnerWorkItem taskItem = null;
ImmutableWorkerInfo immutableWorker = null;
synchronized (statusLock) {
Iterator<String> iter = pendingTaskIds.iterator();
while (iter.hasNext()) {
String taskId = iter.next();
HttpRemoteTaskRunnerWorkItem ti = tasks.get(taskId);
if (ti == null || !ti.getState().isPending()) {
// happens if the task was shutdown, failed or observed running by a worker
iter.remove();
continue;
}
if (ti.getState() == HttpRemoteTaskRunnerWorkItem.State.PENDING_WORKER_ASSIGN) {
// picked up by another pending task executor thread which is in the process of trying to
// run it on a worker, skip to next.
continue;
}
if (ti.getTask() == null) {
// this is not supposed to happen except for a bug, we want to mark this task failed but
// taskComplete(..) can not be called while holding statusLock. See the javadoc on that
// method.
// so this will get marked failed afterwards outside of current synchronized block.
taskItem = ti;
break;
}
immutableWorker = findWorkerToRunTask(ti.getTask());
if (immutableWorker == null) {
continue;
}
String prevUnackedTaskId = workersWithUnacknowledgedTask.putIfAbsent(
immutableWorker.getWorker().getHost(),
taskId
);
if (prevUnackedTaskId != null) {
log.makeAlert(
"Found worker[%s] with unacked task[%s] but still was identified to run task[%s].",
immutableWorker.getWorker().getHost(),
prevUnackedTaskId,
taskId
).emit();
}
// set state to PENDING_WORKER_ASSIGN before releasing the lock so that this task item is not picked
// up by another task execution thread.
// note that we can't simply delete this task item from pendingTaskIds or else we would have to add it
// back if this thread couldn't run this task for any reason, which we will know at some later time
// and also we will need to add it back to its old position in the list. that becomes complex quickly.
// Instead we keep the PENDING_WORKER_ASSIGN to notify other task execution threads not to pick this one up.
// And, it is automatically removed by any of the task execution threads when they notice that
// ti.getState().isPending() is false (at the beginning of this loop)
ti.setState(HttpRemoteTaskRunnerWorkItem.State.PENDING_WORKER_ASSIGN);
taskItem = ti;
break;
}
if (taskItem == null) {
// Either no pending task is found or no suitable worker is found for any of the pending tasks.
// statusLock.notifyAll() is called whenever a new task shows up or if there is a possibility for a task
// to successfully get worker to run, for example when a new worker shows up, a task slot opens up
// because some task completed etc.
statusLock.wait(TimeUnit.MINUTES.toMillis(1));
continue;
}
}
String taskId = taskItem.getTaskId();
if (taskItem.getTask() == null) {
log.makeAlert("No Task obj found in TaskItem for taskID[%s]. Failed.", taskId).emit();
// taskComplete(..) must be called outside of statusLock, see comments on method.
taskComplete(
taskItem,
null,
TaskStatus.failure(
taskId,
"No payload found for this task. "
+ "See overlord logs and middleManager/indexer logs for more details."
)
);
continue;
}
if (immutableWorker == null) {
throw new ISE("Unexpected state: null immutableWorker");
}
try {
// this will send HTTP request to worker for assigning task
if (!runTaskOnWorker(taskItem, immutableWorker.getWorker().getHost())) {
if (taskItem.getState() == HttpRemoteTaskRunnerWorkItem.State.PENDING_WORKER_ASSIGN) {
taskItem.revertStateFromPendingWorkerAssignToPending();
}
}
}
catch (InterruptedException ex) {
log.info("Got InterruptedException while assigning task[%s].", taskId);
throw ex;
}
catch (Throwable th) {
log.makeAlert(th, "Exception while trying to assign task")
.addData("taskId", taskId)
.emit();
// taskComplete(..) must be called outside of statusLock, see comments on method.
taskComplete(
taskItem,
null,
TaskStatus.failure(taskId, "Failed to assign this task. See overlord logs for more details.")
);
}
finally {
synchronized (statusLock) {
workersWithUnacknowledgedTask.remove(immutableWorker.getWorker().getHost());
statusLock.notifyAll();
}
}
}
catch (InterruptedException ex) {
log.info("Interrupted, will Exit.");
Thread.currentThread().interrupt();
}
catch (Throwable th) {
log.makeAlert(th, "Unknown Exception while trying to assign tasks.").emit();
}
}
}
/**
* Must not be used outside of this class and {@link HttpRemoteTaskRunnerResource}
*/
List<String> getPendingTasksList()
{
synchronized (statusLock) {
return ImmutableList.copyOf(pendingTaskIds);
}
}
@Override
public void shutdown(String taskId, String reason)
{
if (!lifecycleLock.awaitStarted(1, TimeUnit.SECONDS)) {
log.info("This TaskRunner is stopped or not yet started. Ignoring shutdown command for task: %s", taskId);
return;
}
WorkerHolder workerHolderRunningTask = null;
synchronized (statusLock) {
log.info("Shutdown [%s] because: [%s]", taskId, reason);
HttpRemoteTaskRunnerWorkItem taskRunnerWorkItem = tasks.get(taskId);
if (taskRunnerWorkItem != null) {
if (taskRunnerWorkItem.getState() == HttpRemoteTaskRunnerWorkItem.State.RUNNING) {
workerHolderRunningTask = workers.get(taskRunnerWorkItem.getWorker().getHost());
if (workerHolderRunningTask == null) {
log.info("Can't shutdown! No worker running task[%s]", taskId);
}
} else if (taskRunnerWorkItem.getState() == HttpRemoteTaskRunnerWorkItem.State.COMPLETE) {
tasks.remove(taskId);
}
} else {
log.info("Received shutdown task[%s], but can't find it. Ignored.", taskId);
}
}
//shutdown is called outside of lock as we don't want to hold the lock while sending http request
//to worker.
if (workerHolderRunningTask != null) {
log.debug(
"Got shutdown request for task[%s]. Asking worker[%s] to kill it.",
taskId,
workerHolderRunningTask.getWorker().getHost()
);
workerHolderRunningTask.shutdownTask(taskId);
}
}
@Override
@LifecycleStop
public void stop()
{
if (!lifecycleLock.canStop()) {
throw new ISE("can't stop.");
}
try {
log.info("Stopping...");
if (provisioningService != null) {
provisioningService.close();
}
pendingTasksExec.shutdownNow();
workersSyncExec.shutdownNow();
cleanupExec.shutdown();
log.info("Removing listener");
DruidNodeDiscovery druidNodeDiscovery =
druidNodeDiscoveryProvider.getForService(WorkerNodeService.DISCOVERY_SERVICE_KEY);
druidNodeDiscovery.removeListener(nodeDiscoveryListener);
log.info("Stopping worker holders");
synchronized (workers) {
workers.values().forEach(w -> {
try {
w.stop();
}
catch (Exception e) {
log.error(e, e.getMessage());
}
});
}
}
finally {
lifecycleLock.exitStop();
}
log.info("Stopped.");
}
@Override
@SuppressWarnings("GuardedBy") // Read on tasks is safe
public Collection<? extends TaskRunnerWorkItem> getRunningTasks()
{
return tasks.values()
.stream()
.filter(item -> item.getState() == HttpRemoteTaskRunnerWorkItem.State.RUNNING)
.collect(Collectors.toList());
}
@Override
@SuppressWarnings("GuardedBy") // Read on tasks is safe
public Collection<? extends TaskRunnerWorkItem> getPendingTasks()
{
return tasks.values()
.stream()
.filter(item -> item.getState().isPending())
.collect(Collectors.toList());
}
@Override
@SuppressWarnings("GuardedBy") // Read on tasks is safe
public Collection<? extends TaskRunnerWorkItem> getKnownTasks()
{
return ImmutableList.copyOf(tasks.values());
}
@SuppressWarnings("GuardedBy") // Read on tasks is safe
public Collection<? extends TaskRunnerWorkItem> getCompletedTasks()
{
return tasks.values()
.stream()
.filter(item -> item.getState() == HttpRemoteTaskRunnerWorkItem.State.COMPLETE)
.collect(Collectors.toList());
}
@Nullable
@Override
@SuppressWarnings("GuardedBy") // Read on tasks is safe
public RunnerTaskState getRunnerTaskState(String taskId)
{
final HttpRemoteTaskRunnerWorkItem workItem = tasks.get(taskId);
if (workItem == null) {
return null;
} else {
return workItem.getState().toRunnerTaskState();
}
}
@Override
@SuppressWarnings("GuardedBy") // Read on tasks is safe
public TaskLocation getTaskLocation(String taskId)
{
final HttpRemoteTaskRunnerWorkItem workItem = tasks.get(taskId);
if (workItem == null) {
return TaskLocation.unknown();
} else {
return workItem.getLocation();
}
}
public List<String> getBlacklistedWorkers()
{
return blackListedWorkers.values().stream().map(
(holder) -> holder.getWorker().getHost()
).collect(Collectors.toList());
}
public Collection<ImmutableWorkerInfo> getBlackListedWorkers()
{
return ImmutableList.copyOf(Collections2.transform(blackListedWorkers.values(), WorkerHolder::toImmutable));
}
/**
* Must not be used outside of this class and {@link HttpRemoteTaskRunnerResource} , used for read only.
*/
@SuppressWarnings("GuardedBy")
Map<String, String> getWorkersWithUnacknowledgedTasks()
{
return workersWithUnacknowledgedTask;
}
@Override
public Optional<ScalingStats> getScalingStats()
{
return Optional.fromNullable(provisioningService.getStats());
}
@VisibleForTesting
public void taskAddedOrUpdated(final TaskAnnouncement announcement, final WorkerHolder workerHolder)
{
final String taskId = announcement.getTaskId();
final Worker worker = workerHolder.getWorker();
log.debug(
"Worker[%s] wrote [%s] status for task [%s] on [%s]",
worker.getHost(),
announcement.getTaskStatus().getStatusCode(),
taskId,
announcement.getTaskLocation()
);
HttpRemoteTaskRunnerWorkItem taskItem;
boolean shouldShutdownTask = false;
boolean isTaskCompleted = false;
synchronized (statusLock) {
taskItem = tasks.get(taskId);
if (taskItem == null) {
// Try to find information about it in the TaskStorage
Optional<TaskStatus> knownStatusInStorage = taskStorage.getStatus(taskId);
if (knownStatusInStorage.isPresent()) {
switch (knownStatusInStorage.get().getStatusCode()) {
case RUNNING:
taskItem = new HttpRemoteTaskRunnerWorkItem(
taskId,
worker,
TaskLocation.unknown(),
null,
announcement.getTaskType(),
HttpRemoteTaskRunnerWorkItem.State.RUNNING
);
tasks.put(taskId, taskItem);
break;
case SUCCESS:
case FAILED:
if (!announcement.getTaskStatus().isComplete()) {
log.info(
"Worker[%s] reported status for completed, known from taskStorage, task[%s]. Ignored.",
worker.getHost(),
taskId
);
}
break;
default:
log.makeAlert(
"Found unrecognized state[%s] of task[%s] in taskStorage. Notification[%s] from worker[%s] is ignored.",
knownStatusInStorage.get().getStatusCode(),
taskId,
announcement,
worker.getHost()
).emit();
}
} else {
log.warn(
"Worker[%s] reported status[%s] for unknown task[%s]. Ignored.",
worker.getHost(),
announcement.getStatus(),
taskId
);
}
}
if (taskItem == null) {
if (!announcement.getTaskStatus().isComplete()) {
shouldShutdownTask = true;
}
} else {
switch (announcement.getTaskStatus().getStatusCode()) {
case RUNNING:
switch (taskItem.getState()) {
case PENDING:
case PENDING_WORKER_ASSIGN:
taskItem.setWorker(worker);
taskItem.setState(HttpRemoteTaskRunnerWorkItem.State.RUNNING);
log.info("Task[%s] started RUNNING on worker[%s].", taskId, worker.getHost());
final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder();
IndexTaskUtils.setTaskDimensions(metricBuilder, taskItem.getTask());
emitter.emit(metricBuilder.setMetric(
"task/pending/time",
new Duration(taskItem.getCreatedTime(), DateTimes.nowUtc()).getMillis())
);
// fall through
case RUNNING:
if (worker.getHost().equals(taskItem.getWorker().getHost())) {
if (!announcement.getTaskLocation().equals(taskItem.getLocation())) {
log.info(
"Task[%s] location changed on worker[%s]. new location[%s].",
taskId,
worker.getHost(),
announcement.getTaskLocation()
);
taskItem.setLocation(announcement.getTaskLocation());
TaskRunnerUtils.notifyLocationChanged(listeners, taskId, announcement.getTaskLocation());
}
} else {
log.warn(
"Found worker[%s] running task[%s] which is being run by another worker[%s]. Notification ignored.",
worker.getHost(),
taskId,
taskItem.getWorker().getHost()
);
shouldShutdownTask = true;
}
break;
case COMPLETE:
log.warn(
"Worker[%s] reported status for completed task[%s]. Ignored.",
worker.getHost(),
taskId
);
shouldShutdownTask = true;
break;
default:
log.makeAlert(
"Found unrecognized state[%s] of task[%s]. Notification[%s] from worker[%s] is ignored.",
taskItem.getState(),
taskId,
announcement,
worker.getHost()
).emit();
}
break;
case FAILED:
case SUCCESS:
switch (taskItem.getState()) {
case PENDING:
case PENDING_WORKER_ASSIGN:
taskItem.setWorker(worker);
taskItem.setState(HttpRemoteTaskRunnerWorkItem.State.RUNNING);
log.info("Task[%s] finished on worker[%s].", taskId, worker.getHost());
// fall through
case RUNNING:
if (worker.getHost().equals(taskItem.getWorker().getHost())) {
if (!announcement.getTaskLocation().equals(taskItem.getLocation())) {
log.info(
"Task[%s] location changed on worker[%s]. new location[%s].",
taskId,
worker.getHost(),
announcement.getTaskLocation()
);
taskItem.setLocation(announcement.getTaskLocation());
TaskRunnerUtils.notifyLocationChanged(listeners, taskId, announcement.getTaskLocation());
}
isTaskCompleted = true;
} else {
log.warn(
"Worker[%s] reported completed task[%s] which is being run by another worker[%s]. Notification ignored.",
worker.getHost(),
taskId,
taskItem.getWorker().getHost()
);
}
break;
case COMPLETE:
// this can happen when a worker is restarted and reports its list of completed tasks again.
break;
default:
log.makeAlert(
"Found unrecognized state[%s] of task[%s]. Notification[%s] from worker[%s] is ignored.",
taskItem.getState(),
taskId,
announcement,
worker.getHost()
).emit();
}
break;
default:
log.makeAlert(
"Worker[%s] reported unrecognized state[%s] for task[%s].",
worker.getHost(),
announcement.getTaskStatus().getStatusCode(),
taskId
).emit();
}
}
}
if (isTaskCompleted) {
// taskComplete(..) must be called outside of statusLock, see comments on method.
taskComplete(taskItem, workerHolder, announcement.getTaskStatus());
}
if (shouldShutdownTask) {
log.warn("Killing task[%s] on worker[%s].", taskId, worker.getHost());
workerHolder.shutdownTask(taskId);
}
synchronized (statusLock) {
statusLock.notifyAll();
}
}
@Override
public Map<String, Long> getTotalTaskSlotCount()
{
Map<String, Long> totalPeons = new HashMap<>();
for (ImmutableWorkerInfo worker : getWorkers()) {
String workerCategory = worker.getWorker().getCategory();
int workerCapacity = worker.getWorker().getCapacity();
totalPeons.compute(
workerCategory,
(category, totalCapacity) -> totalCapacity == null ? workerCapacity : totalCapacity + workerCapacity
);
}
return totalPeons;
}
@Override
public Map<String, Long> getIdleTaskSlotCount()
{
Map<String, Long> totalIdlePeons = new HashMap<>();
for (ImmutableWorkerInfo worker : getWorkersEligibleToRunTasks().values()) {
String workerCategory = worker.getWorker().getCategory();
int workerAvailableCapacity = worker.getAvailableCapacity();
totalIdlePeons.compute(
workerCategory,
(category, availableCapacity) -> availableCapacity == null ? workerAvailableCapacity : availableCapacity + workerAvailableCapacity
);
}
return totalIdlePeons;
}
@Override
public Map<String, Long> getUsedTaskSlotCount()
{
Map<String, Long> totalUsedPeons = new HashMap<>();
for (ImmutableWorkerInfo worker : getWorkers()) {
String workerCategory = worker.getWorker().getCategory();
int workerUsedCapacity = worker.getCurrCapacityUsed();
totalUsedPeons.compute(
workerCategory,
(category, usedCapacity) -> usedCapacity == null ? workerUsedCapacity : usedCapacity + workerUsedCapacity
);
}
return totalUsedPeons;
}
@Override
public Map<String, Long> getLazyTaskSlotCount()
{
Map<String, Long> totalLazyPeons = new HashMap<>();
for (Worker worker : getLazyWorkers()) {
String workerCategory = worker.getCategory();
int workerLazyPeons = worker.getCapacity();
totalLazyPeons.compute(
workerCategory,
(category, lazyPeons) -> lazyPeons == null ? workerLazyPeons : lazyPeons + workerLazyPeons
);
}
return totalLazyPeons;
}
@Override
public Map<String, Long> getBlacklistedTaskSlotCount()
{
Map<String, Long> totalBlacklistedPeons = new HashMap<>();
for (ImmutableWorkerInfo worker : getBlackListedWorkers()) {
String workerCategory = worker.getWorker().getCategory();
int workerBlacklistedPeons = worker.getWorker().getCapacity();
totalBlacklistedPeons.compute(
workerCategory,
(category, blacklistedPeons) -> blacklistedPeons == null ? workerBlacklistedPeons : blacklistedPeons + workerBlacklistedPeons
);
}
return totalBlacklistedPeons;
}
@Override
public int getTotalCapacity()
{
return getWorkers().stream().mapToInt(workerInfo -> workerInfo.getWorker().getCapacity()).sum();
}
@Override
public int getUsedCapacity()
{
return getWorkers().stream().mapToInt(ImmutableWorkerInfo::getCurrCapacityUsed).sum();
}
private static class HttpRemoteTaskRunnerWorkItem extends RemoteTaskRunnerWorkItem
{
enum State
{
// Task has been given to HRTR, but a worker to run this task hasn't been identified yet.
PENDING(0, true, RunnerTaskState.PENDING),
// A Worker has been identified to run this task, but request to run task hasn't been made to worker yet
// or worker hasn't acknowledged the task yet.
PENDING_WORKER_ASSIGN(1, true, RunnerTaskState.PENDING),
RUNNING(2, false, RunnerTaskState.RUNNING),
COMPLETE(3, false, RunnerTaskState.NONE);
private final int index;
private final boolean isPending;
private final RunnerTaskState runnerTaskState;
State(int index, boolean isPending, RunnerTaskState runnerTaskState)
{
this.index = index;
this.isPending = isPending;
this.runnerTaskState = runnerTaskState;
}
boolean isPending()
{
return isPending;
}
RunnerTaskState toRunnerTaskState()
{
return runnerTaskState;
}
}
private Task task;
private State state;
HttpRemoteTaskRunnerWorkItem(
String taskId,
Worker worker,
TaskLocation location,
@Nullable Task task,
String taskType,
State state
)
{
super(taskId, task == null ? null : task.getType(), worker, location, task == null ? null : task.getDataSource());
this.state = Preconditions.checkNotNull(state);
Preconditions.checkArgument(task == null || taskType == null || taskType.equals(task.getType()));
// It is possible to have it null when the TaskRunner is just started and discovered this taskId from a worker,
// notifications don't contain whole Task instance but just metadata about the task.
this.task = task;
}
public Task getTask()
{
return task;
}
public void setTask(Task task)
{
this.task = task;
if (getTaskType() == null) {
setTaskType(task.getType());
} else {
Preconditions.checkArgument(getTaskType().equals(task.getType()));
}
}
@JsonProperty
public State getState()
{
return state;
}
@Override
public void setResult(TaskStatus status)
{
setState(State.COMPLETE);
super.setResult(status);
}
public void setState(State state)
{
Preconditions.checkArgument(
state.index - this.state.index > 0,
"Invalid state transition from [%s] to [%s]",
this.state,
state
);
setStateUnconditionally(state);
}
public void revertStateFromPendingWorkerAssignToPending()
{
Preconditions.checkState(
this.state == State.PENDING_WORKER_ASSIGN,
"Can't move state from [%s] to [%s]",
this.state,
State.PENDING
);
setStateUnconditionally(State.PENDING);
}
private void setStateUnconditionally(State state)
{
if (log.isDebugEnabled()) {
// Exception is logged to know what led to this call.
log.debug(
new RuntimeException("Stacktrace..."),
"Setting task[%s] work item state from [%s] to [%s].",
getTaskId(),
this.state,
state
);
}
this.state = state;
}
}
}
| 68,789 | 0.63641 | 0.635567 | 1,918 | 34.864964 | 30.650831 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.486966 | false | false | 13 |
1a5336eba5bfb3ecb6b3bff42c5b954086b38a12 | 13,503,377,193,052 | 38da41451a538da0c19f9357b1cd9d66e6d1365e | /src/ua/nure/moisieiev/summaryTask4/util/DBManager.java | 486d0e166f183540f2cfc3f56916353b78bfe43c | [] | no_license | JavaEz/avia | https://github.com/JavaEz/avia | 939e507fcc4d783249987a40a9f8a21ce009b3a4 | d46b7bc82003726756a91b0058f852ce12b6b955 | refs/heads/master | 2022-06-17T04:16:38.162000 | 2020-05-06T21:22:23 | 2020-05-06T21:22:23 | 250,015,528 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ua.nure.moisieiev.summaryTask4.util;
import org.apache.log4j.Logger;
import ua.nure.moisieiev.summaryTask4.entity.*;
import ua.nure.moisieiev.summaryTask4.exception.DBException;
import ua.nure.moisieiev.summaryTask4.exception.Messages;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class DBManager {
private static final Logger LOG = Logger.getLogger(DBManager.class);
// //////////////////////////////////////////////////////////
// singleton
// //////////////////////////////////////////////////////////
private static DBManager instance;
public static synchronized DBManager getInstance() throws DBException {
if (instance == null) {
instance = new DBManager();
}
return instance;
}
private DBManager() throws DBException {
try {
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
// FINALTASK - the name of data source
ds = (DataSource) envContext.lookup("jdbc/FINALTASK");
LOG.trace("Data source ==> " + ds);
} catch (NamingException ex) {
LOG.error(Messages.ERR_CANNOT_OBTAIN_DATA_SOURCE, ex);
throw new DBException(Messages.ERR_CANNOT_OBTAIN_DATA_SOURCE, ex);
}
}
private DataSource ds;
public Connection getConnection() throws DBException {
Connection con = null;
try {
con = ds.getConnection();
} catch (SQLException ex) {
LOG.error(Messages.ERR_CANNOT_OBTAIN_CONNECTION, ex);
throw new DBException(Messages.ERR_CANNOT_OBTAIN_CONNECTION, ex);
}
return con;
}
// //////////////////////////////////////////////////////////
// SQL
// //////////////////////////////////////////////////////////
private static final String SQL_FIND_USER_BY_LOGIN = "SELECT * FROM users WHERE login=?";
private static final String SQL_FIND_ALL_FLIGHTS = "SELECT * FROM flights";
private static final String SQL_DELETE_FLIGHT_BY_ID = "DELETE FROM flights WHERE id = ?";
private static final String SQL_FIND_FLIGHT_BY_ID = "SELECT * FROM flights WHERE id = ?";
private static final String SQL_FIND_ALL_FLIGHTS_BY_PARAM = "SELECT * FROM flights WHERE whence = ? AND whereto = ? AND date = ?";
private static final String SQL_UPDATE_FLIGHT_BY_ID = "UPDATE flights SET flight_name = ?, whence = ?," +
"whereto = ?, date = ?, flight_status = ?, crew_id = ? WHERE id = ?";
private static final String SQL_CREATE_FLIGHT = "INSERT INTO flights" +
"(flight_name, whence, whereto, date, flight_status, crew_id)" +
"VALUES(?, ?, ?, ?, ?, ? )";
private static final String SQL_FIND_ALL_STAFF = "SELECT * FROM staff";
private static final String SQL_DELETE_STAFF_BY_ID = "DELETE FROM staff WHERE id = ?";
private static final String SQL_FIND_STAFF_BY_ID = "SELECT * FROM staff WHERE id = ?";
private static final String SQL_UPDATE_STAFF_BY_ID = "UPDATE staff SET staff_fname = ?, staff_lname = ?," +
"departament_id = ?, crew_id = ? WHERE id = ?";
private static final String SQL_CREATE_STAFF = "INSERT INTO STAFF (staff_fname, staff_lname, departament_id, crew_id)" +
"VALUES(?, ?, ?, ?)";
private static final String SQL_FIND_ALL_CREW = "SELECT * FROM crew";
private static final String SQL_DELETE_CREW_BY_ID = "DELETE FROM crew WHERE id = ?";
private static final String SQL_FIND_CREW_BY_ID = "SELECT * FROM crew WHERE id = ?";
private static final String SQL_SET_DEFAULT_CREW_TO_STAFF = "UPDATE staff SET staff.crew_id = 0 WHERE staff.crew_id = ?";
private static final String SQL_FIND_ALL_FREE_STAFF = "SELECT * FROM staff WHERE staff.crew_id = 0";
private static final String SQL_CREATE_CREW = "INSERT INTO crew VALUES(default, default)";
private static final String SQL_FIND_ALL_STAFF_BY_CREW_ID = "SELECT * FROM staff WHERE staff.crew_id = ?";
private static final String SQL_FIND_ALL_REQUESTS = "SELECT * FROM request";
private static final String SQL_CREATE_REQUEST = "INSERT INTO request VALUES(default, ?, ?, ?, ?, default)";
private static final String SQL_FIND_REQUEST_BY_ID = "SELECT * FROM request WHERE id = ?";
private static final String SQL_UPDATE_REQUEST_STATUS = "UPDATE request SET request_status = ? WHERE id = ?";
private static final String SQL_FIND_ALL_FREE_CREW = "SELECT * FROM crew WHERE crew.crewstatus_id = 3";
private static final String SQL_UPDATE_CREW_BY_ID = "UPDATE crew SET crewstatus_id = ? WHERE id = ?";
private static final String SQL_FIND_FLIGHT_BY_CREW_ID = "SELECT * FROM flights WHERE flights.crew_id = ?";
/**
* Returns a user with the given login.
*
* @param login User login.
* @return User entity.
* @throws DBException
*/
public User findUserByLogin(String login) throws DBException, SQLException {
User user = null;
PreparedStatement statement = null;
ResultSet rs = null;
Connection con = null;
try {
con = getConnection();
statement = con.prepareStatement(SQL_FIND_USER_BY_LOGIN);
statement.setString(1, login);
rs = statement.executeQuery();
if (rs.next()) {
user = extractUser(rs);
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_OBTAIN_USER_BY_LOGIN, e);
throw new DBException(Messages.ERR_CANNOT_OBTAIN_USER_BY_LOGIN, e);
} finally {
close(con, statement, rs);
}
return user;
}
/**
* Returns all flight.
*
* @return List of flight entities.
*/
public List<Flight> findAllFlights() throws DBException, SQLException {
List<Flight> flightList = new ArrayList<Flight>();
Statement stmt = null;
ResultSet rs = null;
Connection con = null;
try {
con = getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(SQL_FIND_ALL_FLIGHTS);
while (rs.next()) {
flightList.add(extractFlight(rs));
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_ALL_FLIGHTS, e);
throw new DBException(Messages.ERR_CANNOT_GET_ALL_FLIGHTS, e);
} finally {
close(con, stmt, rs);
}
return flightList;
}
/**
* Delete flight by flight id.
*
* @param id;
*/
public void deleteFlightById(int id) throws DBException, SQLException {
PreparedStatement statement = null;
Connection con = null;
try {
con = getConnection();
statement = con.prepareStatement(SQL_DELETE_FLIGHT_BY_ID);
statement.setInt(1, id);
statement.executeUpdate();
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_DELETE_FLIGHT);
throw new DBException(Messages.ERR_CANNOT_DELETE_FLIGHT, e);
} finally {
close(con);
close(statement);
}
}
/**
* Find flight by flight id.
*
* @param id;
*/
public Flight findFlightById(int id) throws DBException, SQLException {
Flight flight = null;
PreparedStatement statement = null;
ResultSet rs = null;
Connection con = null;
try {
con = getConnection();
statement = con.prepareStatement(SQL_FIND_FLIGHT_BY_ID);
statement.setInt(1, id);
rs = statement.executeQuery();
if (rs.next()) {
flight = extractFlight(rs);
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_FLIGHT_BY_ID, e);
throw new DBException(Messages.ERR_CANNOT_GET_FLIGHT_BY_ID, e);
} finally {
close(con, statement, rs);
}
return flight;
}
/**
* Find flight by crew id.
*
* @param id;
*/
public Flight findFLightByCrewId(int id) throws SQLException, DBException {
Flight flight = null;
PreparedStatement statement = null;
ResultSet rs = null;
Connection con = null;
try {
con = getConnection();
statement = con.prepareStatement(SQL_FIND_FLIGHT_BY_CREW_ID);
statement.setInt(1, id);
rs = statement.executeQuery();
if (rs.next()) {
flight = extractFlight(rs);
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_FLIGHT_BY_CREW_ID, e);
throw new DBException(Messages.ERR_CANNOT_GET_FLIGHT_BY_CREW_ID, e);
} finally {
close(con, statement, rs);
}
return flight;
}
/**
* Update flight.
*
* @param flight;
*/
public void updateFlightById(Flight flight) throws SQLException, DBException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_UPDATE_FLIGHT_BY_ID);
int k = 1;
pstmt.setString(k++, flight.getFlightName());
pstmt.setString(k++, flight.getWhence());
pstmt.setString(k++, flight.getWhereto());
pstmt.setDate(k++, flight.getDate());
pstmt.setInt(k++, flight.getFlightStatusId());
pstmt.setInt(k++, flight.getCrewId());
pstmt.setInt(k, flight.getId());
pstmt.executeUpdate();
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_UPDATE_FLIGHT);
throw new DBException(Messages.ERR_CANNOT_UPDATE_FLIGHT, e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Create flight.
*
* @param flight;
*/
public void createFlight(Flight flight) throws DBException, SQLException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_CREATE_FLIGHT, Statement.RETURN_GENERATED_KEYS);
int k = 1;
pstmt.setString(k++, flight.getFlightName());
pstmt.setString(k++, flight.getWhence());
pstmt.setString(k++, flight.getWhereto());
pstmt.setDate(k++, flight.getDate());
pstmt.setInt(k++, flight.getFlightStatusId());
pstmt.setInt(k, flight.getCrewId());
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
flight.setId(rs.getInt(1));
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_CREATE_FLIGHT);
throw new DBException(Messages.ERR_CANNOT_CREATE_FLIGHT, e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Returns all staff list.
*
* @return List of staff entities.
*/
public List<Staff> findAllStaff() throws SQLException, DBException {
List<Staff> staffList = new ArrayList<>();
Statement stmt = null;
ResultSet rs = null;
Connection con = null;
try {
con = getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(SQL_FIND_ALL_STAFF);
while (rs.next()) {
staffList.add(extractStaff(rs));
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_ALL_STAFF, e);
throw new DBException(Messages.ERR_CANNOT_GET_ALL_STAFF, e);
} finally {
close(con, stmt, rs);
}
return staffList;
}
/**
* Delete staff by staff id.
*
* @param id;
*/
public void deleteStaffById(int id) throws DBException, SQLException {
PreparedStatement pstmt = null;
Connection con = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_DELETE_STAFF_BY_ID);
pstmt.setInt(1, id);
pstmt.executeUpdate();
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_DELETE_STAFF);
throw new DBException(Messages.ERR_CANNOT_DELETE_STAFF, e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Find staff by staff id.
*
* @param id;
*/
public Staff findStaffById(int id) throws DBException, SQLException {
Staff staff = null;
PreparedStatement pstmt = null;
Connection con = null;
ResultSet rs = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_FIND_STAFF_BY_ID);
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
if (rs.next()) {
staff = extractStaff(rs);
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_STAFF_BY_ID);
throw new DBException(Messages.ERR_CANNOT_GET_STAFF_BY_ID, e);
} finally {
close(con, pstmt, rs);
}
return staff;
}
/**
* Update staff.
*
* @param staff;
*/
public void updateStaff(Staff staff) throws DBException, SQLException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_UPDATE_STAFF_BY_ID);
int k = 1;
pstmt.setString(k++, staff.getFirstName());
pstmt.setString(k++, staff.getLastName());
pstmt.setInt(k++, staff.getDepartamenId());
pstmt.setInt(k++, staff.getCrewId());
pstmt.setInt(k, staff.getId());
pstmt.executeUpdate();
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_UPDATE_STAFF);
throw new DBException(Messages.ERR_CANNOT_UPDATE_STAFF, e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Create staff.
*
* @param staff;
*/
public void createStaff(Staff staff) throws SQLException, DBException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_CREATE_STAFF);
int k = 1;
pstmt.setString(k++, staff.getFirstName());
pstmt.setString(k++, staff.getLastName());
pstmt.setInt(k++, staff.getDepartamenId());
pstmt.setInt(k, staff.getCrewId());
pstmt.executeUpdate();
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_CREATE_STAFF);
throw new DBException(Messages.ERR_CANNOT_CREATE_STAFF, e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Returns all crew list.
*
* @return List of crew entities.
*/
public List<Crew> findAllCrew() throws DBException, SQLException {
List<Crew> crewList = new ArrayList<>();
Statement stmt = null;
ResultSet rs = null;
Connection con = null;
try {
con = getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(SQL_FIND_ALL_CREW);
while (rs.next()) {
crewList.add(extractCrew(rs));
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_ALL_CREW);
throw new DBException(Messages.ERR_CANNOT_GET_ALL_CREW, e);
} finally {
close(con, stmt, rs);
}
return crewList;
}
public List<Staff> findAllFreeStaff() throws DBException, SQLException {
List<Staff> staffList = new ArrayList<>();
Statement stmt = null;
ResultSet rs = null;
Connection con = null;
try {
con = getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(SQL_FIND_ALL_FREE_STAFF);
while (rs.next()) {
staffList.add(extractStaff(rs));
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error("Cannot find free staff", e);
throw new DBException("Cannot find free staff", e);
} finally {
close(con, stmt, rs);
}
return staffList;
}
/**
* Delete crew by crew id.
*
* @param id;
*/
public void deleteCrewById(int id) throws DBException, SQLException {
PreparedStatement pstmt = null;
Connection con = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_DELETE_CREW_BY_ID);
pstmt.setInt(1, id);
pstmt.executeUpdate();
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_DELETE_CREW);
throw new DBException(Messages.ERR_CANNOT_DELETE_CREW, e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Find crew by crew id.
*
* @param id;
*/
public Crew findCrewById(int id) throws SQLException, DBException {
Crew crew = null;
PreparedStatement pstmt = null;
Connection con = null;
ResultSet rs = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_FIND_CREW_BY_ID);
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
if (rs.next()) {
crew = extractCrew(rs);
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_CREW_BY_ID);
throw new DBException(Messages.ERR_CANNOT_GET_CREW_BY_ID, e);
} finally {
close(con, pstmt, rs);
}
return crew;
}
public void addDefaultCrewToStaff(int id) throws DBException, SQLException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_SET_DEFAULT_CREW_TO_STAFF);
pstmt.setInt(1, id);
pstmt.executeUpdate();
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error("CANT SET DEFAULT CREW TO STAFF");
throw new DBException(Messages.ERR_CANNOT_UPDATE_STAFF, e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Create crew.
*
* @param crew;
*/
public void createCrew(Crew crew) throws DBException, SQLException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_CREATE_CREW, Statement.RETURN_GENERATED_KEYS);
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
crew.setId(rs.getInt(1));
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error("CANNOT CREATE CREW");
throw new DBException("CANNOT CREATE CREW", e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Update crew.
*
* @param crew;
*/
public void updateCrew(Crew crew) throws SQLException, DBException {
Connection con = null;
PreparedStatement pstmt = null;
try{
con = getConnection();
pstmt = con.prepareStatement(SQL_UPDATE_CREW_BY_ID);
int k = 1;
pstmt.setInt(k++, crew.getCrewStatusId());
pstmt.setInt(k, crew.getId());
pstmt.executeUpdate();
con.commit();
} catch (SQLException e){
con.rollback();
LOG.error(Messages.ERR_CANNOT_UPDATE_CREW);
throw new DBException(Messages.ERR_CANNOT_UPDATE_CREW, e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Find staff by crew id in staff.
*
* @param id;
*/
public List<Staff> findAllStaffByCrewId(int id) throws SQLException, DBException {
List<Staff> staffList = new ArrayList<>();
PreparedStatement pstmt = null;
Connection con = null;
ResultSet rs = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_FIND_ALL_STAFF_BY_CREW_ID);
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
while (rs.next()) {
staffList.add(extractStaff(rs));
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_STAFF_LIST_BY_CREW_ID, e);
throw new DBException(Messages.ERR_CANNOT_GET_STAFF_LIST_BY_CREW_ID, e);
} finally {
close(con, pstmt, rs);
}
return staffList;
}
public List<Flight> findAllFlightsByParameters(String from, String to, Date date) throws DBException, SQLException {
List<Flight> flightList = new ArrayList<>();
PreparedStatement statement = null;
ResultSet rs = null;
Connection con = null;
try {
int k = 1;
con = getConnection();
statement = con.prepareStatement(SQL_FIND_ALL_FLIGHTS_BY_PARAM);
statement.setString(k++, from);
statement.setString(k++, to);
statement.setDate(k, date);
rs = statement.executeQuery();
while (rs.next()) {
flightList.add(extractFlight(rs));
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_ALL_FLIGHTS_BY_PARAM);
throw new DBException(Messages.ERR_CANNOT_GET_ALL_FLIGHTS_BY_PARAM, e);
} finally {
close(con, statement, rs);
}
return flightList;
}
/**
* Returns all requests.
*
* @return List of request entities.
*/
public List<Request> findAllRequests() throws DBException, SQLException {
List<Request> requestList = new ArrayList<>();
Statement stmt = null;
ResultSet rs = null;
Connection con = null;
try {
con = getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(SQL_FIND_ALL_REQUESTS);
while (rs.next()) {
requestList.add(extractRequest(rs));
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_ALL_REQUESTS);
throw new DBException(Messages.ERR_CANNOT_GET_ALL_REQUESTS, e);
} finally {
close(con, stmt, rs);
}
return requestList;
}
/**
* Create request.
*
* @param request;
*/
public void createRequest(Request request) throws DBException, SQLException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_CREATE_REQUEST, Statement.RETURN_GENERATED_KEYS);
int k = 1;
pstmt.setInt(k++, request.getIdPilot());
pstmt.setInt(k++, request.getIdNavigator());
pstmt.setInt(k++, request.getIdSpark());
pstmt.setInt(k, request.getIdSteward());
pstmt.executeUpdate();
// ResultSet rs = pstmt.getGeneratedKeys();
// if (rs.next()) {
// request.setId(rs.getInt(1)); можно удалить
// }
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_CREATE_REQUEST);
throw new DBException(Messages.ERR_CANNOT_CREATE_REQUEST, e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Find flight by flight id.
*
* @param id;
*/
public Request findRequestById(int id) throws DBException, SQLException {
Request request = null;
PreparedStatement statement = null;
ResultSet rs = null;
Connection con = null;
try {
con = getConnection();
statement = con.prepareStatement(SQL_FIND_REQUEST_BY_ID);
statement.setInt(1, id);
rs = statement.executeQuery();
if (rs.next()) {
request = extractRequest(rs);
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_REQUEST_BY_ID, e);
throw new DBException(Messages.ERR_CANNOT_GET_REQUEST_BY_ID, e);
} finally {
close(con, statement, rs);
}
return request;
}
/**
* Update request.
*
* @param request;
*/
public void updateRequestStatusById(Request request) throws SQLException, DBException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_UPDATE_REQUEST_STATUS);
int k = 1;
pstmt.setInt(k++, request.getRequestStatusId());
pstmt.setInt(k, request.getId());
pstmt.executeUpdate();
con.commit();
} catch (SQLException e){
con.rollback();
LOG.error(Messages.ERR_CANNOT_UPDATE_REQUEST_STATUS);
throw new DBException(Messages.ERR_CANNOT_UPDATE_REQUEST_STATUS, e);
} finally {
close(con);
close(pstmt);
}
}
public List<Crew> findAllFreeCrew() throws DBException, SQLException {
List<Crew> crewList = new ArrayList<>();
Statement stmt = null;
ResultSet rs = null;
Connection con = null;
try{
con = getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(SQL_FIND_ALL_FREE_CREW);
while (rs.next()){
crewList.add(extractCrew(rs));
}
con.commit();
}catch (SQLException e){
con.rollback();
LOG.error("Cannot find free crew", e);
throw new DBException("Cannot find free crew", e);
} finally {
close(con, stmt, rs);
}
return crewList;
}
/**
* Extracts a user entity from the result set.
*
* @param rs Result set from which a user entity will be extracted.
* @return User entity
*/
private User extractUser(ResultSet rs) throws SQLException {
User user = new User();
user.setId(rs.getInt(Fields.ENTITY_ID));
user.setLogin(rs.getString(Fields.USER_LOGIN));
user.setPassword(rs.getString(Fields.USER_PASSWORD));
user.setFirstName(rs.getString(Fields.USER_FIRST_NAME));
user.setLastName(rs.getString(Fields.USER_LAST_NAME));
user.setUserRoleId(rs.getInt(Fields.USER_ROLE_ID));
return user;
}
/**
* Extracts a flight entity from the result set.
*
* @param rs Result set from which a Flight entity will be extracted.
* @return Flight entity
*/
private Flight extractFlight(ResultSet rs) throws SQLException {
Flight flight = new Flight();
flight.setId(rs.getInt(Fields.ENTITY_ID));
flight.setFlightName(rs.getString(Fields.FLIGHT_NAME));
flight.setWhence(rs.getString(Fields.FLIGHT_FROM_WHERE));
flight.setWhereto(rs.getString(Fields.FLIGHT_WHERE_TO));
flight.setDate(rs.getDate(Fields.FLIGHT_DATE));
flight.setFlightStatusId(rs.getInt(Fields.FLIGHT_STATUS));
flight.setCrewId(rs.getInt(Fields.CREW_ID_IN_FLIGHT));
return flight;
}
/**
* Extracts a staff entity from the result set.
*
* @param rs Result set from which a Staff entity will be extracted.
* @return Staff entity
*/
private Staff extractStaff(ResultSet rs) throws SQLException {
Staff staff = new Staff();
staff.setId(rs.getInt(Fields.ENTITY_ID));
staff.setFirstName(rs.getString(Fields.STAFF_FIRST_NAME));
staff.setLastName(rs.getString(Fields.STAFF_LAST_NAME));
staff.setDepartamenId(rs.getInt(Fields.STAFF_DEPARTAMENT_ID));
staff.setCrewId(rs.getInt(Fields.STAFF_CREW_ID));
return staff;
}
/**
* Extracts a crew entity from the result set.
*
* @param rs Result set from which a Crew entity will be extracted.
* @return Crew entity
*/
private Crew extractCrew(ResultSet rs) throws SQLException {
Crew crew = new Crew();
crew.setId(rs.getInt(Fields.ENTITY_ID));
crew.setCrewStatusId(rs.getInt(Fields.CREW_STATUS));
return crew;
}
/**
* Extracts a request entity from the result set.
*
* @param rs Result set from which a Request entity will be extracted.
* @return Request entity
*/
private Request extractRequest(ResultSet rs) throws SQLException {
Request request = new Request();
request.setId(rs.getInt(Fields.ENTITY_ID));
request.setIdPilot(rs.getInt(Fields.REQUEST_PILOT_ID));
request.setIdNavigator(rs.getInt(Fields.REQUEST_NAVIGATOR_ID));
request.setIdSpark(rs.getInt(Fields.REQUEST_SPARK_ID));
request.setIdSteward(rs.getInt(Fields.REQUEST_STEWARD_ID));
request.setRequestStatusId(rs.getInt(Fields.REQUEST_STATUS));
return request;
}
/**
* Closes a connection.
*
* @param con Connection to be closed.
*/
private void close(Connection con) {
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
LOG.error(Messages.ERR_CANNOT_CLOSE_CONNECTION, ex);
}
}
}
/**
* Closes a statement object.
*/
private void close(Statement stmt) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {
LOG.error(Messages.ERR_CANNOT_CLOSE_STATEMENT, ex);
}
}
}
/**
* Closes a result set object.
*/
private void close(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
LOG.error(Messages.ERR_CANNOT_CLOSE_RESULTSET, ex);
}
}
}
/**
* Closes resources.
*/
private void close(Connection con, Statement stmt, ResultSet rs) {
close(rs);
close(stmt);
close(con);
}
}
| UTF-8 | Java | 32,095 | java | DBManager.java | Java | [] | null | [] | package ua.nure.moisieiev.summaryTask4.util;
import org.apache.log4j.Logger;
import ua.nure.moisieiev.summaryTask4.entity.*;
import ua.nure.moisieiev.summaryTask4.exception.DBException;
import ua.nure.moisieiev.summaryTask4.exception.Messages;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class DBManager {
private static final Logger LOG = Logger.getLogger(DBManager.class);
// //////////////////////////////////////////////////////////
// singleton
// //////////////////////////////////////////////////////////
private static DBManager instance;
public static synchronized DBManager getInstance() throws DBException {
if (instance == null) {
instance = new DBManager();
}
return instance;
}
private DBManager() throws DBException {
try {
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
// FINALTASK - the name of data source
ds = (DataSource) envContext.lookup("jdbc/FINALTASK");
LOG.trace("Data source ==> " + ds);
} catch (NamingException ex) {
LOG.error(Messages.ERR_CANNOT_OBTAIN_DATA_SOURCE, ex);
throw new DBException(Messages.ERR_CANNOT_OBTAIN_DATA_SOURCE, ex);
}
}
private DataSource ds;
public Connection getConnection() throws DBException {
Connection con = null;
try {
con = ds.getConnection();
} catch (SQLException ex) {
LOG.error(Messages.ERR_CANNOT_OBTAIN_CONNECTION, ex);
throw new DBException(Messages.ERR_CANNOT_OBTAIN_CONNECTION, ex);
}
return con;
}
// //////////////////////////////////////////////////////////
// SQL
// //////////////////////////////////////////////////////////
private static final String SQL_FIND_USER_BY_LOGIN = "SELECT * FROM users WHERE login=?";
private static final String SQL_FIND_ALL_FLIGHTS = "SELECT * FROM flights";
private static final String SQL_DELETE_FLIGHT_BY_ID = "DELETE FROM flights WHERE id = ?";
private static final String SQL_FIND_FLIGHT_BY_ID = "SELECT * FROM flights WHERE id = ?";
private static final String SQL_FIND_ALL_FLIGHTS_BY_PARAM = "SELECT * FROM flights WHERE whence = ? AND whereto = ? AND date = ?";
private static final String SQL_UPDATE_FLIGHT_BY_ID = "UPDATE flights SET flight_name = ?, whence = ?," +
"whereto = ?, date = ?, flight_status = ?, crew_id = ? WHERE id = ?";
private static final String SQL_CREATE_FLIGHT = "INSERT INTO flights" +
"(flight_name, whence, whereto, date, flight_status, crew_id)" +
"VALUES(?, ?, ?, ?, ?, ? )";
private static final String SQL_FIND_ALL_STAFF = "SELECT * FROM staff";
private static final String SQL_DELETE_STAFF_BY_ID = "DELETE FROM staff WHERE id = ?";
private static final String SQL_FIND_STAFF_BY_ID = "SELECT * FROM staff WHERE id = ?";
private static final String SQL_UPDATE_STAFF_BY_ID = "UPDATE staff SET staff_fname = ?, staff_lname = ?," +
"departament_id = ?, crew_id = ? WHERE id = ?";
private static final String SQL_CREATE_STAFF = "INSERT INTO STAFF (staff_fname, staff_lname, departament_id, crew_id)" +
"VALUES(?, ?, ?, ?)";
private static final String SQL_FIND_ALL_CREW = "SELECT * FROM crew";
private static final String SQL_DELETE_CREW_BY_ID = "DELETE FROM crew WHERE id = ?";
private static final String SQL_FIND_CREW_BY_ID = "SELECT * FROM crew WHERE id = ?";
private static final String SQL_SET_DEFAULT_CREW_TO_STAFF = "UPDATE staff SET staff.crew_id = 0 WHERE staff.crew_id = ?";
private static final String SQL_FIND_ALL_FREE_STAFF = "SELECT * FROM staff WHERE staff.crew_id = 0";
private static final String SQL_CREATE_CREW = "INSERT INTO crew VALUES(default, default)";
private static final String SQL_FIND_ALL_STAFF_BY_CREW_ID = "SELECT * FROM staff WHERE staff.crew_id = ?";
private static final String SQL_FIND_ALL_REQUESTS = "SELECT * FROM request";
private static final String SQL_CREATE_REQUEST = "INSERT INTO request VALUES(default, ?, ?, ?, ?, default)";
private static final String SQL_FIND_REQUEST_BY_ID = "SELECT * FROM request WHERE id = ?";
private static final String SQL_UPDATE_REQUEST_STATUS = "UPDATE request SET request_status = ? WHERE id = ?";
private static final String SQL_FIND_ALL_FREE_CREW = "SELECT * FROM crew WHERE crew.crewstatus_id = 3";
private static final String SQL_UPDATE_CREW_BY_ID = "UPDATE crew SET crewstatus_id = ? WHERE id = ?";
private static final String SQL_FIND_FLIGHT_BY_CREW_ID = "SELECT * FROM flights WHERE flights.crew_id = ?";
/**
* Returns a user with the given login.
*
* @param login User login.
* @return User entity.
* @throws DBException
*/
public User findUserByLogin(String login) throws DBException, SQLException {
User user = null;
PreparedStatement statement = null;
ResultSet rs = null;
Connection con = null;
try {
con = getConnection();
statement = con.prepareStatement(SQL_FIND_USER_BY_LOGIN);
statement.setString(1, login);
rs = statement.executeQuery();
if (rs.next()) {
user = extractUser(rs);
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_OBTAIN_USER_BY_LOGIN, e);
throw new DBException(Messages.ERR_CANNOT_OBTAIN_USER_BY_LOGIN, e);
} finally {
close(con, statement, rs);
}
return user;
}
/**
* Returns all flight.
*
* @return List of flight entities.
*/
public List<Flight> findAllFlights() throws DBException, SQLException {
List<Flight> flightList = new ArrayList<Flight>();
Statement stmt = null;
ResultSet rs = null;
Connection con = null;
try {
con = getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(SQL_FIND_ALL_FLIGHTS);
while (rs.next()) {
flightList.add(extractFlight(rs));
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_ALL_FLIGHTS, e);
throw new DBException(Messages.ERR_CANNOT_GET_ALL_FLIGHTS, e);
} finally {
close(con, stmt, rs);
}
return flightList;
}
/**
* Delete flight by flight id.
*
* @param id;
*/
public void deleteFlightById(int id) throws DBException, SQLException {
PreparedStatement statement = null;
Connection con = null;
try {
con = getConnection();
statement = con.prepareStatement(SQL_DELETE_FLIGHT_BY_ID);
statement.setInt(1, id);
statement.executeUpdate();
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_DELETE_FLIGHT);
throw new DBException(Messages.ERR_CANNOT_DELETE_FLIGHT, e);
} finally {
close(con);
close(statement);
}
}
/**
* Find flight by flight id.
*
* @param id;
*/
public Flight findFlightById(int id) throws DBException, SQLException {
Flight flight = null;
PreparedStatement statement = null;
ResultSet rs = null;
Connection con = null;
try {
con = getConnection();
statement = con.prepareStatement(SQL_FIND_FLIGHT_BY_ID);
statement.setInt(1, id);
rs = statement.executeQuery();
if (rs.next()) {
flight = extractFlight(rs);
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_FLIGHT_BY_ID, e);
throw new DBException(Messages.ERR_CANNOT_GET_FLIGHT_BY_ID, e);
} finally {
close(con, statement, rs);
}
return flight;
}
/**
* Find flight by crew id.
*
* @param id;
*/
public Flight findFLightByCrewId(int id) throws SQLException, DBException {
Flight flight = null;
PreparedStatement statement = null;
ResultSet rs = null;
Connection con = null;
try {
con = getConnection();
statement = con.prepareStatement(SQL_FIND_FLIGHT_BY_CREW_ID);
statement.setInt(1, id);
rs = statement.executeQuery();
if (rs.next()) {
flight = extractFlight(rs);
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_FLIGHT_BY_CREW_ID, e);
throw new DBException(Messages.ERR_CANNOT_GET_FLIGHT_BY_CREW_ID, e);
} finally {
close(con, statement, rs);
}
return flight;
}
/**
* Update flight.
*
* @param flight;
*/
public void updateFlightById(Flight flight) throws SQLException, DBException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_UPDATE_FLIGHT_BY_ID);
int k = 1;
pstmt.setString(k++, flight.getFlightName());
pstmt.setString(k++, flight.getWhence());
pstmt.setString(k++, flight.getWhereto());
pstmt.setDate(k++, flight.getDate());
pstmt.setInt(k++, flight.getFlightStatusId());
pstmt.setInt(k++, flight.getCrewId());
pstmt.setInt(k, flight.getId());
pstmt.executeUpdate();
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_UPDATE_FLIGHT);
throw new DBException(Messages.ERR_CANNOT_UPDATE_FLIGHT, e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Create flight.
*
* @param flight;
*/
public void createFlight(Flight flight) throws DBException, SQLException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_CREATE_FLIGHT, Statement.RETURN_GENERATED_KEYS);
int k = 1;
pstmt.setString(k++, flight.getFlightName());
pstmt.setString(k++, flight.getWhence());
pstmt.setString(k++, flight.getWhereto());
pstmt.setDate(k++, flight.getDate());
pstmt.setInt(k++, flight.getFlightStatusId());
pstmt.setInt(k, flight.getCrewId());
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
flight.setId(rs.getInt(1));
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_CREATE_FLIGHT);
throw new DBException(Messages.ERR_CANNOT_CREATE_FLIGHT, e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Returns all staff list.
*
* @return List of staff entities.
*/
public List<Staff> findAllStaff() throws SQLException, DBException {
List<Staff> staffList = new ArrayList<>();
Statement stmt = null;
ResultSet rs = null;
Connection con = null;
try {
con = getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(SQL_FIND_ALL_STAFF);
while (rs.next()) {
staffList.add(extractStaff(rs));
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_ALL_STAFF, e);
throw new DBException(Messages.ERR_CANNOT_GET_ALL_STAFF, e);
} finally {
close(con, stmt, rs);
}
return staffList;
}
/**
* Delete staff by staff id.
*
* @param id;
*/
public void deleteStaffById(int id) throws DBException, SQLException {
PreparedStatement pstmt = null;
Connection con = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_DELETE_STAFF_BY_ID);
pstmt.setInt(1, id);
pstmt.executeUpdate();
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_DELETE_STAFF);
throw new DBException(Messages.ERR_CANNOT_DELETE_STAFF, e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Find staff by staff id.
*
* @param id;
*/
public Staff findStaffById(int id) throws DBException, SQLException {
Staff staff = null;
PreparedStatement pstmt = null;
Connection con = null;
ResultSet rs = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_FIND_STAFF_BY_ID);
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
if (rs.next()) {
staff = extractStaff(rs);
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_STAFF_BY_ID);
throw new DBException(Messages.ERR_CANNOT_GET_STAFF_BY_ID, e);
} finally {
close(con, pstmt, rs);
}
return staff;
}
/**
* Update staff.
*
* @param staff;
*/
public void updateStaff(Staff staff) throws DBException, SQLException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_UPDATE_STAFF_BY_ID);
int k = 1;
pstmt.setString(k++, staff.getFirstName());
pstmt.setString(k++, staff.getLastName());
pstmt.setInt(k++, staff.getDepartamenId());
pstmt.setInt(k++, staff.getCrewId());
pstmt.setInt(k, staff.getId());
pstmt.executeUpdate();
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_UPDATE_STAFF);
throw new DBException(Messages.ERR_CANNOT_UPDATE_STAFF, e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Create staff.
*
* @param staff;
*/
public void createStaff(Staff staff) throws SQLException, DBException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_CREATE_STAFF);
int k = 1;
pstmt.setString(k++, staff.getFirstName());
pstmt.setString(k++, staff.getLastName());
pstmt.setInt(k++, staff.getDepartamenId());
pstmt.setInt(k, staff.getCrewId());
pstmt.executeUpdate();
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_CREATE_STAFF);
throw new DBException(Messages.ERR_CANNOT_CREATE_STAFF, e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Returns all crew list.
*
* @return List of crew entities.
*/
public List<Crew> findAllCrew() throws DBException, SQLException {
List<Crew> crewList = new ArrayList<>();
Statement stmt = null;
ResultSet rs = null;
Connection con = null;
try {
con = getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(SQL_FIND_ALL_CREW);
while (rs.next()) {
crewList.add(extractCrew(rs));
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_ALL_CREW);
throw new DBException(Messages.ERR_CANNOT_GET_ALL_CREW, e);
} finally {
close(con, stmt, rs);
}
return crewList;
}
public List<Staff> findAllFreeStaff() throws DBException, SQLException {
List<Staff> staffList = new ArrayList<>();
Statement stmt = null;
ResultSet rs = null;
Connection con = null;
try {
con = getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(SQL_FIND_ALL_FREE_STAFF);
while (rs.next()) {
staffList.add(extractStaff(rs));
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error("Cannot find free staff", e);
throw new DBException("Cannot find free staff", e);
} finally {
close(con, stmt, rs);
}
return staffList;
}
/**
* Delete crew by crew id.
*
* @param id;
*/
public void deleteCrewById(int id) throws DBException, SQLException {
PreparedStatement pstmt = null;
Connection con = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_DELETE_CREW_BY_ID);
pstmt.setInt(1, id);
pstmt.executeUpdate();
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_DELETE_CREW);
throw new DBException(Messages.ERR_CANNOT_DELETE_CREW, e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Find crew by crew id.
*
* @param id;
*/
public Crew findCrewById(int id) throws SQLException, DBException {
Crew crew = null;
PreparedStatement pstmt = null;
Connection con = null;
ResultSet rs = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_FIND_CREW_BY_ID);
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
if (rs.next()) {
crew = extractCrew(rs);
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_CREW_BY_ID);
throw new DBException(Messages.ERR_CANNOT_GET_CREW_BY_ID, e);
} finally {
close(con, pstmt, rs);
}
return crew;
}
public void addDefaultCrewToStaff(int id) throws DBException, SQLException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_SET_DEFAULT_CREW_TO_STAFF);
pstmt.setInt(1, id);
pstmt.executeUpdate();
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error("CANT SET DEFAULT CREW TO STAFF");
throw new DBException(Messages.ERR_CANNOT_UPDATE_STAFF, e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Create crew.
*
* @param crew;
*/
public void createCrew(Crew crew) throws DBException, SQLException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_CREATE_CREW, Statement.RETURN_GENERATED_KEYS);
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
crew.setId(rs.getInt(1));
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error("CANNOT CREATE CREW");
throw new DBException("CANNOT CREATE CREW", e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Update crew.
*
* @param crew;
*/
public void updateCrew(Crew crew) throws SQLException, DBException {
Connection con = null;
PreparedStatement pstmt = null;
try{
con = getConnection();
pstmt = con.prepareStatement(SQL_UPDATE_CREW_BY_ID);
int k = 1;
pstmt.setInt(k++, crew.getCrewStatusId());
pstmt.setInt(k, crew.getId());
pstmt.executeUpdate();
con.commit();
} catch (SQLException e){
con.rollback();
LOG.error(Messages.ERR_CANNOT_UPDATE_CREW);
throw new DBException(Messages.ERR_CANNOT_UPDATE_CREW, e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Find staff by crew id in staff.
*
* @param id;
*/
public List<Staff> findAllStaffByCrewId(int id) throws SQLException, DBException {
List<Staff> staffList = new ArrayList<>();
PreparedStatement pstmt = null;
Connection con = null;
ResultSet rs = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_FIND_ALL_STAFF_BY_CREW_ID);
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
while (rs.next()) {
staffList.add(extractStaff(rs));
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_STAFF_LIST_BY_CREW_ID, e);
throw new DBException(Messages.ERR_CANNOT_GET_STAFF_LIST_BY_CREW_ID, e);
} finally {
close(con, pstmt, rs);
}
return staffList;
}
public List<Flight> findAllFlightsByParameters(String from, String to, Date date) throws DBException, SQLException {
List<Flight> flightList = new ArrayList<>();
PreparedStatement statement = null;
ResultSet rs = null;
Connection con = null;
try {
int k = 1;
con = getConnection();
statement = con.prepareStatement(SQL_FIND_ALL_FLIGHTS_BY_PARAM);
statement.setString(k++, from);
statement.setString(k++, to);
statement.setDate(k, date);
rs = statement.executeQuery();
while (rs.next()) {
flightList.add(extractFlight(rs));
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_ALL_FLIGHTS_BY_PARAM);
throw new DBException(Messages.ERR_CANNOT_GET_ALL_FLIGHTS_BY_PARAM, e);
} finally {
close(con, statement, rs);
}
return flightList;
}
/**
* Returns all requests.
*
* @return List of request entities.
*/
public List<Request> findAllRequests() throws DBException, SQLException {
List<Request> requestList = new ArrayList<>();
Statement stmt = null;
ResultSet rs = null;
Connection con = null;
try {
con = getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(SQL_FIND_ALL_REQUESTS);
while (rs.next()) {
requestList.add(extractRequest(rs));
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_ALL_REQUESTS);
throw new DBException(Messages.ERR_CANNOT_GET_ALL_REQUESTS, e);
} finally {
close(con, stmt, rs);
}
return requestList;
}
/**
* Create request.
*
* @param request;
*/
public void createRequest(Request request) throws DBException, SQLException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_CREATE_REQUEST, Statement.RETURN_GENERATED_KEYS);
int k = 1;
pstmt.setInt(k++, request.getIdPilot());
pstmt.setInt(k++, request.getIdNavigator());
pstmt.setInt(k++, request.getIdSpark());
pstmt.setInt(k, request.getIdSteward());
pstmt.executeUpdate();
// ResultSet rs = pstmt.getGeneratedKeys();
// if (rs.next()) {
// request.setId(rs.getInt(1)); можно удалить
// }
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_CREATE_REQUEST);
throw new DBException(Messages.ERR_CANNOT_CREATE_REQUEST, e);
} finally {
close(con);
close(pstmt);
}
}
/**
* Find flight by flight id.
*
* @param id;
*/
public Request findRequestById(int id) throws DBException, SQLException {
Request request = null;
PreparedStatement statement = null;
ResultSet rs = null;
Connection con = null;
try {
con = getConnection();
statement = con.prepareStatement(SQL_FIND_REQUEST_BY_ID);
statement.setInt(1, id);
rs = statement.executeQuery();
if (rs.next()) {
request = extractRequest(rs);
}
con.commit();
} catch (SQLException e) {
con.rollback();
LOG.error(Messages.ERR_CANNOT_GET_REQUEST_BY_ID, e);
throw new DBException(Messages.ERR_CANNOT_GET_REQUEST_BY_ID, e);
} finally {
close(con, statement, rs);
}
return request;
}
/**
* Update request.
*
* @param request;
*/
public void updateRequestStatusById(Request request) throws SQLException, DBException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(SQL_UPDATE_REQUEST_STATUS);
int k = 1;
pstmt.setInt(k++, request.getRequestStatusId());
pstmt.setInt(k, request.getId());
pstmt.executeUpdate();
con.commit();
} catch (SQLException e){
con.rollback();
LOG.error(Messages.ERR_CANNOT_UPDATE_REQUEST_STATUS);
throw new DBException(Messages.ERR_CANNOT_UPDATE_REQUEST_STATUS, e);
} finally {
close(con);
close(pstmt);
}
}
public List<Crew> findAllFreeCrew() throws DBException, SQLException {
List<Crew> crewList = new ArrayList<>();
Statement stmt = null;
ResultSet rs = null;
Connection con = null;
try{
con = getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(SQL_FIND_ALL_FREE_CREW);
while (rs.next()){
crewList.add(extractCrew(rs));
}
con.commit();
}catch (SQLException e){
con.rollback();
LOG.error("Cannot find free crew", e);
throw new DBException("Cannot find free crew", e);
} finally {
close(con, stmt, rs);
}
return crewList;
}
/**
* Extracts a user entity from the result set.
*
* @param rs Result set from which a user entity will be extracted.
* @return User entity
*/
private User extractUser(ResultSet rs) throws SQLException {
User user = new User();
user.setId(rs.getInt(Fields.ENTITY_ID));
user.setLogin(rs.getString(Fields.USER_LOGIN));
user.setPassword(rs.getString(Fields.USER_PASSWORD));
user.setFirstName(rs.getString(Fields.USER_FIRST_NAME));
user.setLastName(rs.getString(Fields.USER_LAST_NAME));
user.setUserRoleId(rs.getInt(Fields.USER_ROLE_ID));
return user;
}
/**
* Extracts a flight entity from the result set.
*
* @param rs Result set from which a Flight entity will be extracted.
* @return Flight entity
*/
private Flight extractFlight(ResultSet rs) throws SQLException {
Flight flight = new Flight();
flight.setId(rs.getInt(Fields.ENTITY_ID));
flight.setFlightName(rs.getString(Fields.FLIGHT_NAME));
flight.setWhence(rs.getString(Fields.FLIGHT_FROM_WHERE));
flight.setWhereto(rs.getString(Fields.FLIGHT_WHERE_TO));
flight.setDate(rs.getDate(Fields.FLIGHT_DATE));
flight.setFlightStatusId(rs.getInt(Fields.FLIGHT_STATUS));
flight.setCrewId(rs.getInt(Fields.CREW_ID_IN_FLIGHT));
return flight;
}
/**
* Extracts a staff entity from the result set.
*
* @param rs Result set from which a Staff entity will be extracted.
* @return Staff entity
*/
private Staff extractStaff(ResultSet rs) throws SQLException {
Staff staff = new Staff();
staff.setId(rs.getInt(Fields.ENTITY_ID));
staff.setFirstName(rs.getString(Fields.STAFF_FIRST_NAME));
staff.setLastName(rs.getString(Fields.STAFF_LAST_NAME));
staff.setDepartamenId(rs.getInt(Fields.STAFF_DEPARTAMENT_ID));
staff.setCrewId(rs.getInt(Fields.STAFF_CREW_ID));
return staff;
}
/**
* Extracts a crew entity from the result set.
*
* @param rs Result set from which a Crew entity will be extracted.
* @return Crew entity
*/
private Crew extractCrew(ResultSet rs) throws SQLException {
Crew crew = new Crew();
crew.setId(rs.getInt(Fields.ENTITY_ID));
crew.setCrewStatusId(rs.getInt(Fields.CREW_STATUS));
return crew;
}
/**
* Extracts a request entity from the result set.
*
* @param rs Result set from which a Request entity will be extracted.
* @return Request entity
*/
private Request extractRequest(ResultSet rs) throws SQLException {
Request request = new Request();
request.setId(rs.getInt(Fields.ENTITY_ID));
request.setIdPilot(rs.getInt(Fields.REQUEST_PILOT_ID));
request.setIdNavigator(rs.getInt(Fields.REQUEST_NAVIGATOR_ID));
request.setIdSpark(rs.getInt(Fields.REQUEST_SPARK_ID));
request.setIdSteward(rs.getInt(Fields.REQUEST_STEWARD_ID));
request.setRequestStatusId(rs.getInt(Fields.REQUEST_STATUS));
return request;
}
/**
* Closes a connection.
*
* @param con Connection to be closed.
*/
private void close(Connection con) {
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
LOG.error(Messages.ERR_CANNOT_CLOSE_CONNECTION, ex);
}
}
}
/**
* Closes a statement object.
*/
private void close(Statement stmt) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {
LOG.error(Messages.ERR_CANNOT_CLOSE_STATEMENT, ex);
}
}
}
/**
* Closes a result set object.
*/
private void close(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
LOG.error(Messages.ERR_CANNOT_CLOSE_RESULTSET, ex);
}
}
}
/**
* Closes resources.
*/
private void close(Connection con, Statement stmt, ResultSet rs) {
close(rs);
close(stmt);
close(con);
}
}
| 32,095 | 0.550104 | 0.549169 | 963 | 32.315681 | 24.700659 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.705088 | false | false | 13 |
cfc6fd7040b768d9936301b6460142bd083104ce | 19,679,540,173,031 | 70ed2bb5845f0d056cfb39f85e45e04d28f75173 | /homework/assignment3/OptimalElevator.java | 081bfd0c850dfd5eb01f51b07905ddab3d20d688 | [] | no_license | rosacry/214-Class | https://github.com/rosacry/214-Class | e3b5073eb801485071552801bcc99bc0402ea372 | 381f674127d40a449789099c185412a11f24cbfc | refs/heads/main | 2023-07-14T19:48:35.929000 | 2021-08-17T17:31:31 | 2021-08-17T17:31:31 | 397,339,943 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* This class represents an elevator object that accepts Requests from the
* RequestQueue queue
*
* @author Christopher Rosales
* @ID #114328928
* @Assignment #3, Elevator
*/
public class OptimalElevator extends RequestQueue {
private final String IDLE = "IDLE";
private final String TO_SOUCE = "TO_SOURCE";
private final String TO_DESTINATION = "TO_DESTINATION";
private String elevatorState; // figure what to do with this
private int currentFloor;
private Request request;
/**
* Description: A constructor that initializes the Elevator object
*/
public OptimalElevator() {
request = null;
elevatorState = IDLE;
currentFloor = 1;
}
/**
* Description: Retrieves the state of the elevator
*
* @return Returns the state of the elevator
*/
public String getElevatorState() {
return elevatorState;
}
/**
* Description: Retrieves the current floor of the elevator
*
* @return Returns the current floor of the elevator
*/
public int getCurrentFloor() {
return currentFloor;
}
/**
* Description: Retrieves the current request of the elevator object
*
* @return Returns the request assigned to the elevator object
*/
public Request getRequest() {
return request;
}
public void pickupPassengers() {
for (int i = 0; i < this.size(); i++) { // loop through the queue
if ((this.get(i).passengerGoingDown() && this.getRequest().passengerGoingDown())
&& this.get(i).getSourceFloor() == this.getCurrentFloor()) {
// then we pick up the passengers that are only going down
} else if (!(this.get(i).passengerGoingDown() && this.getRequest().passengerGoingDown())
&& this.get(i).getSourceFloor() == this.getCurrentFloor()) {
// then we pick up the passengers that are only going up
}
}
}
public boolean elevatorGoingDown() {
if (getRequest().passengerGoingDown())
return true;
return false;
}
/**
* Description: Changes the elevator state to idle
*/
public void changeToIdle() {
elevatorState = IDLE;
}
/**
* Description: Changes the elevator state to to_Source
*/
public void changeToSource() {
elevatorState = TO_SOUCE;
}
/**
* Description: Changes the elevator state to to_Destination
*/
public void changeToDestination() {
elevatorState = TO_DESTINATION;
}
/**
* Description: Sets the current floor to an inputted floor
*
* @param newFloor The new current floor
*/
public void setCurrentFloor(int newFloor) {
currentFloor = newFloor;
}
/**
* Description: Sets the current request to a new request
*
* @param newRequest The new current request
*
*/
public void setRequest(Request newRequest) {
request = newRequest;
}
}
| UTF-8 | Java | 2,818 | java | OptimalElevator.java | Java | [
{
"context": "ests from the\n * RequestQueue queue\n * \n * @author Christopher Rosales\n * @ID #114328928\n * @Assignment #3, Elevator\n */",
"end": 135,
"score": 0.9997183084487915,
"start": 116,
"tag": "NAME",
"value": "Christopher Rosales"
}
] | null | [] | /**
* This class represents an elevator object that accepts Requests from the
* RequestQueue queue
*
* @author <NAME>
* @ID #114328928
* @Assignment #3, Elevator
*/
public class OptimalElevator extends RequestQueue {
private final String IDLE = "IDLE";
private final String TO_SOUCE = "TO_SOURCE";
private final String TO_DESTINATION = "TO_DESTINATION";
private String elevatorState; // figure what to do with this
private int currentFloor;
private Request request;
/**
* Description: A constructor that initializes the Elevator object
*/
public OptimalElevator() {
request = null;
elevatorState = IDLE;
currentFloor = 1;
}
/**
* Description: Retrieves the state of the elevator
*
* @return Returns the state of the elevator
*/
public String getElevatorState() {
return elevatorState;
}
/**
* Description: Retrieves the current floor of the elevator
*
* @return Returns the current floor of the elevator
*/
public int getCurrentFloor() {
return currentFloor;
}
/**
* Description: Retrieves the current request of the elevator object
*
* @return Returns the request assigned to the elevator object
*/
public Request getRequest() {
return request;
}
public void pickupPassengers() {
for (int i = 0; i < this.size(); i++) { // loop through the queue
if ((this.get(i).passengerGoingDown() && this.getRequest().passengerGoingDown())
&& this.get(i).getSourceFloor() == this.getCurrentFloor()) {
// then we pick up the passengers that are only going down
} else if (!(this.get(i).passengerGoingDown() && this.getRequest().passengerGoingDown())
&& this.get(i).getSourceFloor() == this.getCurrentFloor()) {
// then we pick up the passengers that are only going up
}
}
}
public boolean elevatorGoingDown() {
if (getRequest().passengerGoingDown())
return true;
return false;
}
/**
* Description: Changes the elevator state to idle
*/
public void changeToIdle() {
elevatorState = IDLE;
}
/**
* Description: Changes the elevator state to to_Source
*/
public void changeToSource() {
elevatorState = TO_SOUCE;
}
/**
* Description: Changes the elevator state to to_Destination
*/
public void changeToDestination() {
elevatorState = TO_DESTINATION;
}
/**
* Description: Sets the current floor to an inputted floor
*
* @param newFloor The new current floor
*/
public void setCurrentFloor(int newFloor) {
currentFloor = newFloor;
}
/**
* Description: Sets the current request to a new request
*
* @param newRequest The new current request
*
*/
public void setRequest(Request newRequest) {
request = newRequest;
}
}
| 2,805 | 0.660043 | 0.655784 | 111 | 24.387388 | 24.398039 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.198198 | false | false | 13 |
16a49e727f6802d66a850f41873fbf4e989b35b0 | 6,064,493,846,065 | 307c8afcea1932697993d452e9916e0251c91354 | /src/java/lab1/controller/CalculatorServiceController1.java | e07215266d710b57ba2f2db71e0d4ba6d54c07a1 | [] | no_license | PvtPancakes/CalculatorLab | https://github.com/PvtPancakes/CalculatorLab | f75f760c5856e075c4b13cce00a2f2ef9d183e93 | f1e0d4440a9388c866e5ae422eb42bbe397a6bf5 | refs/heads/master | 2021-05-28T07:12:24.342000 | 2015-02-02T02:44:28 | 2015-02-02T02:44:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lab1.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lab1.model.CalculatorService1;
/**
*
* @author eennis
*/
@WebServlet(name = "CalculatorServiceController", urlPatterns = {"/calculator"})
public class CalculatorServiceController1 extends HttpServlet {
private static final String RESULT_PAGE = "lab1/Lab1Page.jsp";
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String result;
response.setContentType("text/html;charset=UTF-8");
try{
double length = Double.parseDouble(request.getParameter("length"));
double width = Double.parseDouble(request.getParameter("width"));
CalculatorService1 cs = new CalculatorService1();
result = cs.calcAreaSquare(length, width) + "";
}catch(IllegalArgumentException e){
result = "Invalid Input";
}
request.setAttribute("result", result);
RequestDispatcher view =
request.getRequestDispatcher(RESULT_PAGE);
view.forward(request, response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| UTF-8 | Java | 3,401 | java | CalculatorServiceController1.java | Java | [
{
"context": "1.model.CalculatorService1;\r\n\r\n/**\r\n *\r\n * @author eennis\r\n */\r\n@WebServlet(name = \"CalculatorServiceContro",
"end": 604,
"score": 0.9115838408470154,
"start": 598,
"tag": "USERNAME",
"value": "eennis"
}
] | 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 lab1.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lab1.model.CalculatorService1;
/**
*
* @author eennis
*/
@WebServlet(name = "CalculatorServiceController", urlPatterns = {"/calculator"})
public class CalculatorServiceController1 extends HttpServlet {
private static final String RESULT_PAGE = "lab1/Lab1Page.jsp";
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String result;
response.setContentType("text/html;charset=UTF-8");
try{
double length = Double.parseDouble(request.getParameter("length"));
double width = Double.parseDouble(request.getParameter("width"));
CalculatorService1 cs = new CalculatorService1();
result = cs.calcAreaSquare(length, width) + "";
}catch(IllegalArgumentException e){
result = "Invalid Input";
}
request.setAttribute("result", result);
RequestDispatcher view =
request.getRequestDispatcher(RESULT_PAGE);
view.forward(request, response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| 3,401 | 0.647751 | 0.645104 | 100 | 32.009998 | 26.576868 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 13 |
819853eddc06ec4a101620076cd677e285d70a59 | 9,062,381,020,821 | d2389f16f0bcee71d3cf8dd5102cb13e5eb55ebf | /src/volunteer/data/method/Coolsms_Restapi.java | fb4293691c004983e89c58f57ef6dc38fe7bd87d | [] | no_license | justyou78/volunteer | https://github.com/justyou78/volunteer | 26bc2acdd4250d3f229ff93578133b3ac062a3bc | 6b1240cd2abef46307c14c186c263067e35473b9 | refs/heads/master | 2022-12-25T05:39:17.463000 | 2020-01-16T00:59:07 | 2020-01-16T00:59:07 | 224,793,457 | 1 | 1 | null | false | 2022-12-16T10:00:38 | 2019-11-29T06:45:51 | 2020-01-16T00:59:38 | 2022-12-16T10:00:35 | 11,382 | 1 | 0 | 7 | Java | false | false | package volunteer.data.method;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.apache.http.client.ClientProtocolException;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import antlr.collections.Stack;
import net.nurigo.java_sdk.api.Message;
import net.nurigo.java_sdk.exceptions.CoolsmsException;
import volunteer.data.dao.ConnectDAOImpl;
import volunteer.data.dao.MemberDAOImpl;
import volunteer.data.vo.MemberVO;
@Repository
public class Coolsms_Restapi {
@Autowired
MemberDAOImpl memberDao;
@Autowired
ConnectDAOImpl connectDao;
// '구'를 기준으로 봉사자에게 메세지를 전송합니다.
public String sendSMS(HttpSession session, String vol_time) {
String id = (String) session.getAttribute("id");
MemberVO vo = memberDao.selectAll(id);
String address = vo.getAddress();
int count = 0;
String subAddress = "";
// '구' 단위까지 내 주소 구해서 subAddress에 기입.
for (int i = 0; i < address.length(); i++) {
if (address.charAt(i) == ' ') {
count++;
}
if (count == 2) {
subAddress = address.substring(0, i);
break;
}
}
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("address", subAddress);
hm.put("id", id);
//내아이디아닌 다른사람들의 주소값 가져오기
List<MemberVO> list = memberDao.selectVolFromAddress(hm);
String api_key = "NCSRNAH39QXAD7TJ";
String api_secret = "7LIOUPAO3LSDW1ZSNHULWNFSCHOOQRBJ";
Message coolsms = new Message(api_key, api_secret);
// 4 params(to, from, type, text) are mandatory. must be filled
HashMap<String, String> params = new HashMap<String, String>();
params.put("from", "01037656597");
params.put("type", "SMS");
params.put("text", "(" + vol_time
+ "시간)\n http://192.168.0.48:8081/volunteer/volunteer/connect.vol?disabled_id=" + id);
params.put("app_version", "test app 1.2"); // application name and version
System.out.println("봉사요청! (" + vol_time
+ "시간)\n http://192.168.0.48:8081/volunteer/volunteer/connect.vol?disabled_id=" + id);
if (list.size() == 0) {
return "fail";
} else {
for (int i = 0; i < list.size(); i++) {
params.put("to", String.valueOf(list.get(i).getCallnumber()));
//connect 테이블에 정보 담기.
connectDao.insert(id, list.get(i).getId());
//메세지 전송.
// try {
// JSONObject obj = (JSONObject) coolsms.send(params);
// System.out.println(obj.toString());
// } catch (CoolsmsException e) {
// System.out.println(e.getMessage());
// System.out.println(e.getCode());
// }
}
return "success";
}
}
//장애인이 확인버튼을 클릭 후, 연결된 봉사자 한명에게 문자보내기.
public String sendSMSOne(String id, String myId) throws ClientProtocolException, IOException {
String api_key = "NCSRNAH39QXAD7TJ";
String api_secret = "7LIOUPAO3LSDW1ZSNHULWNFSCHOOQRBJ";
Message coolsms = new Message(api_key, api_secret);
MemberVO vo = memberDao.selectAll(id);
MemberVO myvo = memberDao.selectAll(myId);
kakao_http_client kakaoClient = new kakao_http_client();
HashMap<String, String>hm = kakaoClient.get(myvo);
String x = hm.get("x");
String y = hm.get("y");
//카카오 지도를 통해서 장애인 위치 공유하기.
HashMap<String, String> params = new HashMap<String, String>();
String url = "https://map.kakao.com/link/to/"+myvo.getAddress()+","+y+","+x;
url =url.replaceAll(" ", "");
url = url.replaceAll("\"", "");
params.put("from", "01037656597");
params.put("type", "SMS");
//주소 넣어야해.
params.put("text", url+"\n연결완료");
params.put("app_version", "test app 1.2"); // application name and version
params.put("to", String.valueOf(vo.getCallnumber()));
//메시지 전송.
// try {
// JSONObject obj = (JSONObject) coolsms.send(params);
// System.out.println(obj.toString());
// } catch (CoolsmsException e) {
// System.out.println(e.getMessage());
// System.out.println(e.getCode());
// }
return "success";
}
}
| UTF-8 | Java | 4,224 | java | Coolsms_Restapi.java | Java | [
{
"context": "_key = \"NCSRNAH39QXAD7TJ\";\n\t\tString api_secret = \"7LIOUPAO3LSDW1ZSNHULWNFSCHOOQRBJ\";\n\t\tMessage coolsms = new",
"end": 1496,
"score": 0.9991700053215027,
"start": 1488,
"tag": "KEY",
"value": "7LIOUPAO"
},
{
"context": "ms.put(\"text\", \"(\" + vol_time\n\t\t\t... | null | [] | package volunteer.data.method;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.apache.http.client.ClientProtocolException;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import antlr.collections.Stack;
import net.nurigo.java_sdk.api.Message;
import net.nurigo.java_sdk.exceptions.CoolsmsException;
import volunteer.data.dao.ConnectDAOImpl;
import volunteer.data.dao.MemberDAOImpl;
import volunteer.data.vo.MemberVO;
@Repository
public class Coolsms_Restapi {
@Autowired
MemberDAOImpl memberDao;
@Autowired
ConnectDAOImpl connectDao;
// '구'를 기준으로 봉사자에게 메세지를 전송합니다.
public String sendSMS(HttpSession session, String vol_time) {
String id = (String) session.getAttribute("id");
MemberVO vo = memberDao.selectAll(id);
String address = vo.getAddress();
int count = 0;
String subAddress = "";
// '구' 단위까지 내 주소 구해서 subAddress에 기입.
for (int i = 0; i < address.length(); i++) {
if (address.charAt(i) == ' ') {
count++;
}
if (count == 2) {
subAddress = address.substring(0, i);
break;
}
}
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("address", subAddress);
hm.put("id", id);
//내아이디아닌 다른사람들의 주소값 가져오기
List<MemberVO> list = memberDao.selectVolFromAddress(hm);
String api_key = "NCSRNAH39QXAD7TJ";
String api_secret = "7LIOUPAO3LSDW1ZSNHULWNFSCHOOQRBJ";
Message coolsms = new Message(api_key, api_secret);
// 4 params(to, from, type, text) are mandatory. must be filled
HashMap<String, String> params = new HashMap<String, String>();
params.put("from", "01037656597");
params.put("type", "SMS");
params.put("text", "(" + vol_time
+ "시간)\n http://192.168.0.48:8081/volunteer/volunteer/connect.vol?disabled_id=" + id);
params.put("app_version", "test app 1.2"); // application name and version
System.out.println("봉사요청! (" + vol_time
+ "시간)\n http://192.168.0.48:8081/volunteer/volunteer/connect.vol?disabled_id=" + id);
if (list.size() == 0) {
return "fail";
} else {
for (int i = 0; i < list.size(); i++) {
params.put("to", String.valueOf(list.get(i).getCallnumber()));
//connect 테이블에 정보 담기.
connectDao.insert(id, list.get(i).getId());
//메세지 전송.
// try {
// JSONObject obj = (JSONObject) coolsms.send(params);
// System.out.println(obj.toString());
// } catch (CoolsmsException e) {
// System.out.println(e.getMessage());
// System.out.println(e.getCode());
// }
}
return "success";
}
}
//장애인이 확인버튼을 클릭 후, 연결된 봉사자 한명에게 문자보내기.
public String sendSMSOne(String id, String myId) throws ClientProtocolException, IOException {
String api_key = "<KEY>";
String api_secret = "<KEY>";
Message coolsms = new Message(api_key, api_secret);
MemberVO vo = memberDao.selectAll(id);
MemberVO myvo = memberDao.selectAll(myId);
kakao_http_client kakaoClient = new kakao_http_client();
HashMap<String, String>hm = kakaoClient.get(myvo);
String x = hm.get("x");
String y = hm.get("y");
//카카오 지도를 통해서 장애인 위치 공유하기.
HashMap<String, String> params = new HashMap<String, String>();
String url = "https://map.kakao.com/link/to/"+myvo.getAddress()+","+y+","+x;
url =url.replaceAll(" ", "");
url = url.replaceAll("\"", "");
params.put("from", "01037656597");
params.put("type", "SMS");
//주소 넣어야해.
params.put("text", url+"\n연결완료");
params.put("app_version", "test app 1.2"); // application name and version
params.put("to", String.valueOf(vo.getCallnumber()));
//메시지 전송.
// try {
// JSONObject obj = (JSONObject) coolsms.send(params);
// System.out.println(obj.toString());
// } catch (CoolsmsException e) {
// System.out.println(e.getMessage());
// System.out.println(e.getCode());
// }
return "success";
}
}
| 4,186 | 0.671385 | 0.653438 | 133 | 28.74436 | 23.221928 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.56391 | false | false | 13 |
2ffeb4100ca3f0e6503b67b71fef0b9a8b659a1a | 14,877,766,742,526 | 3782dc755432007daddccbca327c47c0e4c881be | /src/Clases/Conectar.java | 7e092fdf226abe2f357b9d01c7e3d73bca80f352 | [] | no_license | joseman1991/kenin | https://github.com/joseman1991/kenin | aa45d154d02fd9653213b0d13a57c9db6da2cff4 | bc484875de6e26d9b3ac4d7abb90ff431ebb6e06 | refs/heads/master | 2020-05-02T16:27:33.990000 | 2019-03-30T21:37:12 | 2019-03-30T21:37:12 | 178,068,835 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Clases;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public class Conectar {
Connection conn = null;
public Connection conexion() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/citas?autoReconnect=true&useSSL=false", "root", "mysql");
//JOptionPane.showMessageDialog(null,"Conexion correcta");
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex, "Error en la conexión a la base de datos: " + ex.getMessage(), JOptionPane.ERROR_MESSAGE);
conn = null;
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex, "Error en la conexión a la base de datos: " + ex.getMessage(), JOptionPane.ERROR_MESSAGE);
System.out.println(ex.getMessage());
conn = null;
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex, "Error en la conexión a la base de datos: " + ex.getMessage(), JOptionPane.ERROR_MESSAGE);
conn = null;
} finally {
//System.out.println("Conexión en linea");
if (conn != null) {
System.out.println("Conexion en linea");
} else {
System.out.println("Error de Conexion");
}
try {
return conn;
} catch (Exception e) {
}
}
return null;
}
public void desconectar() {
conn = null;
System.out.println("Conexion Cerrada");
}
}
| UTF-8 | Java | 1,721 | java | Conectar.java | Java | [] | null | [] | package Clases;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public class Conectar {
Connection conn = null;
public Connection conexion() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/citas?autoReconnect=true&useSSL=false", "root", "mysql");
//JOptionPane.showMessageDialog(null,"Conexion correcta");
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex, "Error en la conexión a la base de datos: " + ex.getMessage(), JOptionPane.ERROR_MESSAGE);
conn = null;
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex, "Error en la conexión a la base de datos: " + ex.getMessage(), JOptionPane.ERROR_MESSAGE);
System.out.println(ex.getMessage());
conn = null;
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex, "Error en la conexión a la base de datos: " + ex.getMessage(), JOptionPane.ERROR_MESSAGE);
conn = null;
} finally {
//System.out.println("Conexión en linea");
if (conn != null) {
System.out.println("Conexion en linea");
} else {
System.out.println("Error de Conexion");
}
try {
return conn;
} catch (Exception e) {
}
}
return null;
}
public void desconectar() {
conn = null;
System.out.println("Conexion Cerrada");
}
}
| 1,721 | 0.569598 | 0.567268 | 48 | 33.770832 | 36.266514 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.729167 | false | false | 13 |
025f75bec01b22abafbfe95a83a1dc9e6372e8be | 8,933,531,999,454 | ea611b439f5bb5b199ef05b8a03ffc7609dce314 | /src/Telas/TelaDeFundo.java | cc243e9ac8387415622ce864b77bd26c1221e5c2 | [] | no_license | GabrielEu/TrabalhoCRUD | https://github.com/GabrielEu/TrabalhoCRUD | eae93c31a3be6ca091e129dfc3858258b356f44a | 8e95595d4514e639c48a094f87bd4a70f9eb4c89 | refs/heads/master | 2020-03-21T21:27:48.463000 | 2018-06-28T20:19:11 | 2018-06-28T20:19:11 | 139,064,545 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Telas;
import java.net.URL;
import java.security.Principal;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.net.URL;
import java.security.Principal;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import Acoes.DadosEMetodos;
public class TelaDeFundo {
public TelaDeFundo() {
// Dar status LIVRE aos computadores
DadosEMetodos d = new DadosEMetodos();
d.atribuirBoolean();
// Obtendo a imagem
URL urlImagem = Principal.class.getResource("/Imagens/wallpaper.jpg");
ImageIcon imagem = new ImageIcon(urlImagem);
// Tela para inserir a imagem
JFrame construtor = new JFrame();
construtor.setUndecorated(true);
construtor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
construtor.setLocationRelativeTo(null);
construtor.getContentPane().setLayout(null);
construtor.setResizable(false);
construtor.setExtendedState(JFrame.MAXIMIZED_BOTH);
// Inserindo imagem
JLabel exibirImagem = new JLabel(imagem);
exibirImagem.setBounds(0, 0, 1600, 800);
// Adicionar componentes
construtor.add(exibirImagem);
// Tornar visível
construtor.setVisible(true);
}
}
| WINDOWS-1250 | Java | 1,250 | java | TelaDeFundo.java | Java | [] | null | [] | package Telas;
import java.net.URL;
import java.security.Principal;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.net.URL;
import java.security.Principal;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import Acoes.DadosEMetodos;
public class TelaDeFundo {
public TelaDeFundo() {
// Dar status LIVRE aos computadores
DadosEMetodos d = new DadosEMetodos();
d.atribuirBoolean();
// Obtendo a imagem
URL urlImagem = Principal.class.getResource("/Imagens/wallpaper.jpg");
ImageIcon imagem = new ImageIcon(urlImagem);
// Tela para inserir a imagem
JFrame construtor = new JFrame();
construtor.setUndecorated(true);
construtor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
construtor.setLocationRelativeTo(null);
construtor.getContentPane().setLayout(null);
construtor.setResizable(false);
construtor.setExtendedState(JFrame.MAXIMIZED_BOTH);
// Inserindo imagem
JLabel exibirImagem = new JLabel(imagem);
exibirImagem.setBounds(0, 0, 1600, 800);
// Adicionar componentes
construtor.add(exibirImagem);
// Tornar visível
construtor.setVisible(true);
}
}
| 1,250 | 0.728583 | 0.721377 | 52 | 22.01923 | 18.026146 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5 | false | false | 13 |
a83516b8468151f10d093cb7a8ac3ca57adfb284 | 21,680,994,932,168 | 3510ae8d1698d4ad3b323b73a8ac669862504589 | /src/main/java/com/honglekai/study/dpStrategy/Comparable.java | 17143e98b34f62b8b3aec84f2f59ce802cec3943 | [] | no_license | aicc2015/design-pattern | https://github.com/aicc2015/design-pattern | c6e25ccc39690246e74a7ed964023e7145eb4051 | 86381f4509be42b88b86c21d559d1ed075c3b854 | refs/heads/master | 2020-04-23T19:56:01.161000 | 2019-02-26T09:36:30 | 2019-02-26T09:36:30 | 171,422,120 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.honglekai.study.dpStrategy;
/**
* description
* company YH
*
* @Author hcc
* modifyBy
* createTime 2019/1/9 23:55
* modifyTime
*/
public interface Comparable {
int compareTo(Object o);
}
| UTF-8 | Java | 213 | java | Comparable.java | Java | [
{
"context": "y;\n\n/**\n * description\n * company YH\n *\n * @Author hcc\n * modifyBy\n * createTime 2019/1/9 23:55\n * modif",
"end": 91,
"score": 0.9996432065963745,
"start": 88,
"tag": "USERNAME",
"value": "hcc"
}
] | null | [] | package com.honglekai.study.dpStrategy;
/**
* description
* company YH
*
* @Author hcc
* modifyBy
* createTime 2019/1/9 23:55
* modifyTime
*/
public interface Comparable {
int compareTo(Object o);
}
| 213 | 0.680751 | 0.633803 | 15 | 13.2 | 12.084149 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.133333 | false | false | 13 |
e47fb83f4b2a5074e94fb0922a06edcf8fd288ba | 19,275,813,252,141 | 0c9f812cf4d3cca1af19ffd0652edfe25f73011f | /src/main/java/ru/stoloto/core/httpclient/DataBase_conn.java | f05f251a966d61f986e265e29be85e5cf4a3f5e5 | [] | no_license | newStringBuilder/Jtools | https://github.com/newStringBuilder/Jtools | 68938642b9c9c292af5cf52d79e19273c88b8b57 | 7592d64a84394dcf550c5390f31065643ac4125e | refs/heads/master | 2016-04-22T03:55:59.680000 | 2015-12-29T07:23:49 | 2015-12-29T07:23:49 | 46,173,990 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.stoloto.core.httpclient;
import java.sql.*;
public class DataBase_conn {
String url = "jdbc:derby:C:/soft/apache-jmeter/bin/gt_POS";
Connection conn = null;
ResultSet trn = null;
Statement statement = null;
long transaction = 0;
DataBase_conn(){
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
conn = DriverManager.getConnection(url, "", "");
conn.setAutoCommit(true);
conn.setTransactionIsolation(1);
statement = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public String TRN() throws SQLException {
statement.executeUpdate("INSERT INTO TTRANSACTION_IS (SPEC) VALUES ('1')");
trn = statement.executeQuery("SELECT MAX(TRN_ID) FROM TTRANSACTION_IS");
try {
while (trn.next()) {
transaction = trn.getLong(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return String.valueOf(transaction);
}
}
| UTF-8 | Java | 1,279 | java | DataBase_conn.java | Java | [] | null | [] | package ru.stoloto.core.httpclient;
import java.sql.*;
public class DataBase_conn {
String url = "jdbc:derby:C:/soft/apache-jmeter/bin/gt_POS";
Connection conn = null;
ResultSet trn = null;
Statement statement = null;
long transaction = 0;
DataBase_conn(){
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
conn = DriverManager.getConnection(url, "", "");
conn.setAutoCommit(true);
conn.setTransactionIsolation(1);
statement = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public String TRN() throws SQLException {
statement.executeUpdate("INSERT INTO TTRANSACTION_IS (SPEC) VALUES ('1')");
trn = statement.executeQuery("SELECT MAX(TRN_ID) FROM TTRANSACTION_IS");
try {
while (trn.next()) {
transaction = trn.getLong(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return String.valueOf(transaction);
}
}
| 1,279 | 0.527756 | 0.524629 | 54 | 21.611111 | 23.216705 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.