blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
sequence | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
unknown | revision_date
unknown | committer_date
unknown | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
unknown | gha_created_at
unknown | gha_updated_at
unknown | gha_pushed_at
unknown | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
sequence | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
62a65610b84969b65c400ca6808c1f7ff5f86671 | 19,224,273,679,936 | 1fdea7b0444bdf349b7420d7e9b40383b09bd1af | /CCServiceDiscovery/src/main/java/com/itc/trn/mis/CcServiceDiscoveryApplication.java | 79fa68943437003a4638ce4ead9320a03405c54f | [] | no_license | sebastin666/microservices-CCServiceDiscovery | https://github.com/sebastin666/microservices-CCServiceDiscovery | 1210fba956ec6797f11ab96f21cf6c01e896231c | 168ac9d1e9907e220680c3973e3a01dbc764c97d | refs/heads/master | "2020-06-28T08:25:48.161000" | "2019-08-02T07:30:15" | "2019-08-02T07:30:15" | 200,187,720 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.itc.trn.mis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class CcServiceDiscoveryApplication {
public static void main(String[] args) {
SpringApplication.run(CcServiceDiscoveryApplication.class, args);
}
}
| UTF-8 | Java | 427 | java | CcServiceDiscoveryApplication.java | Java | [] | null | [] | package com.itc.trn.mis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class CcServiceDiscoveryApplication {
public static void main(String[] args) {
SpringApplication.run(CcServiceDiscoveryApplication.class, args);
}
}
| 427 | 0.840749 | 0.840749 | 15 | 27.466667 | 26.852354 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 9 |
77cd2b4b74032fcaae5d5420b62936c9bbd588a8 | 23,201,413,401,405 | e9fd48a4bcbd356e6da42263959ea2f72c08f554 | /LibGdx-Core/src/main/java/libgdx/bf/menu/GameMenuHandler.java | e1c5c78b83e094729cf8ce11d0e1ab7658c0e956 | [] | no_license | IDemiurge/Eidolons | https://github.com/IDemiurge/Eidolons | 453e74ab31cfdd12749cffddab0f7c2ff8e1b0d5 | 95398e80e18fbf566a5172c8e6343f38524fc7ec | refs/heads/dev | "2023-09-01T03:15:22.424000" | "2023-08-27T21:13:12" | "2023-08-27T21:13:12" | 71,926,671 | 6 | 0 | null | false | "2023-08-25T16:11:05" | "2016-10-25T18:25:50" | "2021-10-27T17:14:14" | "2023-08-25T16:11:05" | 66,676 | 9 | 0 | 17 | Java | false | false | package libgdx.bf.menu;
import eidolons.game.battlecraft.logic.meta.scenario.dialogue.DialogueManager;
import eidolons.game.core.Core;
import eidolons.game.core.game.DC_Game;
import libgdx.bf.menu.GameMenu.GAME_MENU_ITEM;
import eidolons.system.text.HelpMaster;
import main.system.GuiEventManager;
import main.system.GuiEventType;
/**
* Created by JustMe on 11/24/2017.
*/
public class GameMenuHandler {
private final GameMenu menu;
public GameMenuHandler(GameMenu gameMenu) {
menu = gameMenu;
}
public Boolean clicked(GAME_MENU_ITEM sub) {
switch (sub) {
case QUICK_HELP:
GuiEventManager.trigger(GuiEventType.SHOW_TEXT_CENTERED,
HelpMaster.getHelpText());
break;
case TUTORIAL_RECAP:
DialogueManager.tutorialJournal();
break;
case MANUAL:
GuiEventManager.trigger(GuiEventType.SHOW_MANUAL_PANEL,
HelpMaster.getHelpText());
break;
case HERO_INFO:
GuiEventManager.trigger(GuiEventType.SHOW_TEXT_CENTERED,
HelpMaster.getWelcomeText());
break;
case MAP_INFO:
GuiEventManager.trigger(GuiEventType.SHOW_TEXT_CENTERED,
DC_Game.game.getMetaMaster().getDungeonInfo());
break;
case OUTER_WORLD:
//TODO save and send log!
Core.exitGame();
case EXIT:
case MAIN_MENU:
// DC_Game.game.getBattleMaster().getOutcomeManager().next();
// DC_Game.game.exit(true);
Core.exitToMenu();
// GuiEventManager.trigger(GuiEventType.DISPOSE_TEXTURES);
return false;
// case QUESTS:
// Eidolons.onThisOrNonGdxThread(() -> {
// if (QuestMaster.TEST_MODE) {
// Eidolons.getGame().getMetaMaster().getQuestMaster().initQuests();
// Eidolons.getGame().getMetaMaster().getQuestMaster().startedQuests();
// Eidolons.getGame().getMetaMaster().getQuestMaster().updateQuests();
// } else {
// GuiEventManager.trigger(GuiEventType.SHOW_QUESTS_INFO,
// Eidolons.getGame().getMetaMaster().getQuestMaster().getQuests() );
// }
// });
// return null;
case PASS_TIME:
Core.getGame().getDungeonMaster().getExplorationMaster()
.getTimeMaster().playerWaits();
break;
// case LOAD:
// GameMenu.menuOpen = false;
// Loader.load();
// break;
case SAVE:
// GameMenu.menuOpen = false;
// Saver.save();
break;
case ACHIEVEMENTS:
GuiEventManager.trigger(GuiEventType.SHOW_ACHIEVEMENTS);
GameMenu.menuOpen = false;
break;
case RESUME:
case LAUNCH_GAME:
case ABOUT:
case WEBSITE:
break;
case OPTIONS:
// OptionsMaster.openMenu();
menu.openOptionsMenu();
// GuiEventManager.trigger(GuiEventType.OPEN_OPTIONS, MainMenuStage.class);
return null;
}
return null;
}
}
| UTF-8 | Java | 3,566 | java | GameMenuHandler.java | Java | [
{
"context": "mport main.system.GuiEventType;\n\n/**\n * Created by JustMe on 11/24/2017.\n */\npublic class GameMenuHandler {",
"end": 357,
"score": 0.9994091987609863,
"start": 351,
"tag": "USERNAME",
"value": "JustMe"
}
] | null | [] | package libgdx.bf.menu;
import eidolons.game.battlecraft.logic.meta.scenario.dialogue.DialogueManager;
import eidolons.game.core.Core;
import eidolons.game.core.game.DC_Game;
import libgdx.bf.menu.GameMenu.GAME_MENU_ITEM;
import eidolons.system.text.HelpMaster;
import main.system.GuiEventManager;
import main.system.GuiEventType;
/**
* Created by JustMe on 11/24/2017.
*/
public class GameMenuHandler {
private final GameMenu menu;
public GameMenuHandler(GameMenu gameMenu) {
menu = gameMenu;
}
public Boolean clicked(GAME_MENU_ITEM sub) {
switch (sub) {
case QUICK_HELP:
GuiEventManager.trigger(GuiEventType.SHOW_TEXT_CENTERED,
HelpMaster.getHelpText());
break;
case TUTORIAL_RECAP:
DialogueManager.tutorialJournal();
break;
case MANUAL:
GuiEventManager.trigger(GuiEventType.SHOW_MANUAL_PANEL,
HelpMaster.getHelpText());
break;
case HERO_INFO:
GuiEventManager.trigger(GuiEventType.SHOW_TEXT_CENTERED,
HelpMaster.getWelcomeText());
break;
case MAP_INFO:
GuiEventManager.trigger(GuiEventType.SHOW_TEXT_CENTERED,
DC_Game.game.getMetaMaster().getDungeonInfo());
break;
case OUTER_WORLD:
//TODO save and send log!
Core.exitGame();
case EXIT:
case MAIN_MENU:
// DC_Game.game.getBattleMaster().getOutcomeManager().next();
// DC_Game.game.exit(true);
Core.exitToMenu();
// GuiEventManager.trigger(GuiEventType.DISPOSE_TEXTURES);
return false;
// case QUESTS:
// Eidolons.onThisOrNonGdxThread(() -> {
// if (QuestMaster.TEST_MODE) {
// Eidolons.getGame().getMetaMaster().getQuestMaster().initQuests();
// Eidolons.getGame().getMetaMaster().getQuestMaster().startedQuests();
// Eidolons.getGame().getMetaMaster().getQuestMaster().updateQuests();
// } else {
// GuiEventManager.trigger(GuiEventType.SHOW_QUESTS_INFO,
// Eidolons.getGame().getMetaMaster().getQuestMaster().getQuests() );
// }
// });
// return null;
case PASS_TIME:
Core.getGame().getDungeonMaster().getExplorationMaster()
.getTimeMaster().playerWaits();
break;
// case LOAD:
// GameMenu.menuOpen = false;
// Loader.load();
// break;
case SAVE:
// GameMenu.menuOpen = false;
// Saver.save();
break;
case ACHIEVEMENTS:
GuiEventManager.trigger(GuiEventType.SHOW_ACHIEVEMENTS);
GameMenu.menuOpen = false;
break;
case RESUME:
case LAUNCH_GAME:
case ABOUT:
case WEBSITE:
break;
case OPTIONS:
// OptionsMaster.openMenu();
menu.openOptionsMenu();
// GuiEventManager.trigger(GuiEventType.OPEN_OPTIONS, MainMenuStage.class);
return null;
}
return null;
}
}
| 3,566 | 0.518789 | 0.516545 | 95 | 36.536842 | 24.364691 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578947 | false | false | 9 |
5a079780189e7c093d97778dea8a37616fc1e643 | 31,894,427,207,775 | dbce4ff06327db83a9c7eebd3ded3e7e36246f3d | /creditVoteReject/src/net/dfrz/control/lawful/Case2_lowful.java | 46704b9be7e927761077ba5f24ce709f41e0d65f | [] | no_license | fadaiyoona/gitstorage | https://github.com/fadaiyoona/gitstorage | 463bfbf0f5fb9bcc5c842ab53b12683c26bcfe8b | 738e30d3fcc1bc06fa254278dae885b6f53461a8 | refs/heads/master | "2021-01-19T11:04:22.002000" | "2017-04-12T15:06:01" | "2017-04-12T15:06:01" | 87,925,123 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.dfrz.control.lawful;
import java.util.ArrayList;
import java.util.List;
import net.dfrz.domain.User;
import net.dfrz.model.UserDao;
import net.dfrz.model.impl.UserImpl;
public class Case2_lowful {
// 判断公司名字的合法性
public static int comName(String comName) {
if (comName.isEmpty()) {
// System.out.println("没有输入公司-请重新输入");
return 1;
} else if (comName.matches("[\u4E00-\u9FA5]+") && comName.length() >= 2
&& comName.length() <= 10) {
// meetDetail.setCompany(comName);
return 0;
} else {
// System.out.println("输入的公司名必须为汉字,字数2-10位,请重新输入");
return 2;
}
}
// 判断公司地址的合法性
public static int comAddress(String comAddress) {
if (comAddress.isEmpty()) {
// System.out.println("没有输入公司-请重新输入");
return 1;
} else if (comAddress.matches("[1-9]")) {
// meetDetail.setAddress(meetDetail.getAddressName(comAddress));
return 0;
} else {
// System.out.println("输入的公司名必须为1-9之间的阿拉伯数字,请重新输入");
return 2;
}
}
// 判断贷款金额的合法性
public static int money(String money) {
if (money.isEmpty()) {
// System.out.println("没有输入贷款金额-请重新输入");
return 1;
} else if (money.matches("[1-9][0-9]+") || money.matches("[1-9]")) {
// meetDetail.setMoney(money);
return 0;
} else {
// System.out.println("输入的贷款金额必须为正数,请重新输入");
return 2;
}
}
// 判断公司类型的合法性
public static int comType(String comType) {
if (comType.isEmpty()) {
// System.out.println("没有输入企业类型-请重新输入");
return 1;
} else if (comType.matches("[1-3]")) {
return 0;
} else {
// System.out.println("输入的企业类型必须为1或2或3,请重新输入");
return 2;
}
}
// 判断原因的合法性
public static int reason(String reason) {
if (reason.isEmpty()) {
// System.out.println("没有输入审批理由-请重新输入");
return 1;
} else if (reason.length() >= 6) {
// meetDetail.setReason(reason);
return 0;
} else {
// System.out.println("输入的审批理由必须为6个以上字符,请重新输入");
return 2;
}
}
// 判断多人会签行长登录名是否合法
public static List<String> rounders(String[] logNames) {
List<String> result = new ArrayList<String>();
for (String logName : logNames) {
if (isRounderExist(logName)) {
continue;
} else {
result.add(logName);
}
}
return result;
}
// 判断是否存在该行长的登录名
private static boolean isRounderExist(String logName) {
UserDao userDao = new UserImpl();
List<User> list = new ArrayList<User>();
list = userDao.quaryRounders(logName);
if (list.size() > 0) {
return true;
}
return false;
}
}
| GB18030 | Java | 3,018 | java | Case2_lowful.java | Java | [] | null | [] | package net.dfrz.control.lawful;
import java.util.ArrayList;
import java.util.List;
import net.dfrz.domain.User;
import net.dfrz.model.UserDao;
import net.dfrz.model.impl.UserImpl;
public class Case2_lowful {
// 判断公司名字的合法性
public static int comName(String comName) {
if (comName.isEmpty()) {
// System.out.println("没有输入公司-请重新输入");
return 1;
} else if (comName.matches("[\u4E00-\u9FA5]+") && comName.length() >= 2
&& comName.length() <= 10) {
// meetDetail.setCompany(comName);
return 0;
} else {
// System.out.println("输入的公司名必须为汉字,字数2-10位,请重新输入");
return 2;
}
}
// 判断公司地址的合法性
public static int comAddress(String comAddress) {
if (comAddress.isEmpty()) {
// System.out.println("没有输入公司-请重新输入");
return 1;
} else if (comAddress.matches("[1-9]")) {
// meetDetail.setAddress(meetDetail.getAddressName(comAddress));
return 0;
} else {
// System.out.println("输入的公司名必须为1-9之间的阿拉伯数字,请重新输入");
return 2;
}
}
// 判断贷款金额的合法性
public static int money(String money) {
if (money.isEmpty()) {
// System.out.println("没有输入贷款金额-请重新输入");
return 1;
} else if (money.matches("[1-9][0-9]+") || money.matches("[1-9]")) {
// meetDetail.setMoney(money);
return 0;
} else {
// System.out.println("输入的贷款金额必须为正数,请重新输入");
return 2;
}
}
// 判断公司类型的合法性
public static int comType(String comType) {
if (comType.isEmpty()) {
// System.out.println("没有输入企业类型-请重新输入");
return 1;
} else if (comType.matches("[1-3]")) {
return 0;
} else {
// System.out.println("输入的企业类型必须为1或2或3,请重新输入");
return 2;
}
}
// 判断原因的合法性
public static int reason(String reason) {
if (reason.isEmpty()) {
// System.out.println("没有输入审批理由-请重新输入");
return 1;
} else if (reason.length() >= 6) {
// meetDetail.setReason(reason);
return 0;
} else {
// System.out.println("输入的审批理由必须为6个以上字符,请重新输入");
return 2;
}
}
// 判断多人会签行长登录名是否合法
public static List<String> rounders(String[] logNames) {
List<String> result = new ArrayList<String>();
for (String logName : logNames) {
if (isRounderExist(logName)) {
continue;
} else {
result.add(logName);
}
}
return result;
}
// 判断是否存在该行长的登录名
private static boolean isRounderExist(String logName) {
UserDao userDao = new UserImpl();
List<User> list = new ArrayList<User>();
list = userDao.quaryRounders(logName);
if (list.size() > 0) {
return true;
}
return false;
}
}
| 3,018 | 0.616444 | 0.598741 | 109 | 21.3211 | 18.657158 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.183486 | false | false | 9 |
a34919ec77268bdf4e2b30eaaae02c90352cddad | 13,898,514,234,815 | 773f2cff40c046fba84623d6c89ffb53cb26458d | /app/src/main/java/com/example/cattask/View/UpdatePictureFragment.java | 3273f35f5ae44c111f16c59d6dffe27c002a4fd5 | [] | no_license | xxqxpxx/CatTask | https://github.com/xxqxpxx/CatTask | bbc04db2e10596157cc08a5078cb994df1a14155 | 61d044c625d93b523923e540c50f977b11b1250c | refs/heads/master | "2020-03-12T13:30:47.072000" | "2018-04-26T20:21:49" | "2018-04-26T20:21:49" | 130,643,928 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.cattask.View;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.example.cattask.Controller.FileUtils;
import com.example.cattask.Controller.ServiceGenerator;
import com.example.cattask.Model.Image;
import com.example.cattask.R;
import com.example.cattask.WebService.Api;
import java.io.ByteArrayOutputStream;
import java.io.File;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.example.cattask.View.MainActivity.userdata;
public class UpdatePictureFragment extends Fragment {
Button selectUploadButton;
private static final String TAG = MainActivity.class.getSimpleName();
private static final int REQUEST_GALLERY_CODE = 200;
private static final int READ_REQUEST_CODE = 300;
private static final String SERVER_PATH = "Path_to_your_server";
private Uri uri;
public UpdatePictureFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_update_picture, container, false);
selectUploadButton = view.findViewById(R.id.select_image);
selectUploadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (EasyPermissions.hasPermissions(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
Intent openGalleryIntent = new Intent(Intent.ACTION_PICK);
openGalleryIntent.setType("image/*");
startActivityForResult(openGalleryIntent, REQUEST_GALLERY_CODE);
} else {
// Do not have permissions, request them now
EasyPermissions.requestPermissions(getActivity(), "Gallery Permission",
READ_REQUEST_CODE, Manifest.permission.READ_EXTERNAL_STORAGE);
}
}
});
return view;
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
private void uploadFile(Uri fileUri) {
// create upload service client
Api service =
ServiceGenerator.createService(Api.class);
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = FileUtils.getFile(getContext(), fileUri);
// File imagefile = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() ,file.getAbsolutePath() );
Bitmap selectedImage = BitmapFactory.decodeFile(file.getAbsolutePath() );
ByteArrayOutputStream stream = new ByteArrayOutputStream();
selectedImage.compress(Bitmap.CompressFormat.JPEG, 30, stream);
byte[] byteArray = stream.toByteArray();
String strBase64=Base64.encodeToString(byteArray, 0);
Image image = new Image();
image.setImage_profile(strBase64);
Call<Object> call = service.uploadPicture(userdata.getId().toString() , image);
call.enqueue(new Callback<Object>() {
@Override
public void onResponse(Call<Object> call,
Response<Object> response) {
Log.v("Upload", "success");
Toast.makeText(getActivity(), response.body().toString() , Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<Object> call, Throwable t) {
Log.e("Upload error:", t.getMessage());
Toast.makeText(getActivity(), "Check internet", Toast.LENGTH_LONG).show();
}
});
}
public static String encodeToBase64(Bitmap image, Bitmap.CompressFormat compressFormat, int quality) {
ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
image.compress(compressFormat, quality, byteArrayOS);
return Base64.encodeToString(byteArrayOS.toByteArray(), Base64.NO_WRAP);
}
private String getRealPathFromURIPath(Uri contentURI, Activity activity) {
Cursor cursor = activity.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_GALLERY_CODE && resultCode == Activity.RESULT_OK){
uri = data.getData();
uploadFile(uri);
}
}
}
| UTF-8 | Java | 5,828 | java | UpdatePictureFragment.java | Java | [
{
"context": "ervice(Api.class);\n\n // https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipa",
"end": 3335,
"score": 0.9984351992607117,
"start": 3327,
"tag": "USERNAME",
"value": "iPaulPro"
},
{
"context": "FileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java\n // use ",
"end": 3390,
"score": 0.5830467343330383,
"start": 3387,
"tag": "USERNAME",
"value": "pro"
}
] | null | [] | package com.example.cattask.View;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.example.cattask.Controller.FileUtils;
import com.example.cattask.Controller.ServiceGenerator;
import com.example.cattask.Model.Image;
import com.example.cattask.R;
import com.example.cattask.WebService.Api;
import java.io.ByteArrayOutputStream;
import java.io.File;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.example.cattask.View.MainActivity.userdata;
public class UpdatePictureFragment extends Fragment {
Button selectUploadButton;
private static final String TAG = MainActivity.class.getSimpleName();
private static final int REQUEST_GALLERY_CODE = 200;
private static final int READ_REQUEST_CODE = 300;
private static final String SERVER_PATH = "Path_to_your_server";
private Uri uri;
public UpdatePictureFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_update_picture, container, false);
selectUploadButton = view.findViewById(R.id.select_image);
selectUploadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (EasyPermissions.hasPermissions(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
Intent openGalleryIntent = new Intent(Intent.ACTION_PICK);
openGalleryIntent.setType("image/*");
startActivityForResult(openGalleryIntent, REQUEST_GALLERY_CODE);
} else {
// Do not have permissions, request them now
EasyPermissions.requestPermissions(getActivity(), "Gallery Permission",
READ_REQUEST_CODE, Manifest.permission.READ_EXTERNAL_STORAGE);
}
}
});
return view;
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
private void uploadFile(Uri fileUri) {
// create upload service client
Api service =
ServiceGenerator.createService(Api.class);
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = FileUtils.getFile(getContext(), fileUri);
// File imagefile = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() ,file.getAbsolutePath() );
Bitmap selectedImage = BitmapFactory.decodeFile(file.getAbsolutePath() );
ByteArrayOutputStream stream = new ByteArrayOutputStream();
selectedImage.compress(Bitmap.CompressFormat.JPEG, 30, stream);
byte[] byteArray = stream.toByteArray();
String strBase64=Base64.encodeToString(byteArray, 0);
Image image = new Image();
image.setImage_profile(strBase64);
Call<Object> call = service.uploadPicture(userdata.getId().toString() , image);
call.enqueue(new Callback<Object>() {
@Override
public void onResponse(Call<Object> call,
Response<Object> response) {
Log.v("Upload", "success");
Toast.makeText(getActivity(), response.body().toString() , Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<Object> call, Throwable t) {
Log.e("Upload error:", t.getMessage());
Toast.makeText(getActivity(), "Check internet", Toast.LENGTH_LONG).show();
}
});
}
public static String encodeToBase64(Bitmap image, Bitmap.CompressFormat compressFormat, int quality) {
ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
image.compress(compressFormat, quality, byteArrayOS);
return Base64.encodeToString(byteArrayOS.toByteArray(), Base64.NO_WRAP);
}
private String getRealPathFromURIPath(Uri contentURI, Activity activity) {
Cursor cursor = activity.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_GALLERY_CODE && resultCode == Activity.RESULT_OK){
uri = data.getData();
uploadFile(uri);
}
}
}
| 5,828 | 0.674502 | 0.66987 | 160 | 35.424999 | 31.584124 | 127 | false | false | 0 | 0 | 0 | 0 | 96 | 0.016472 | 0.725 | false | false | 9 |
1692baec3147cebc010fa1985c3be775b6165d00 | 12,378,095,812,974 | 519b32d0c9df910c33db7311265b9ea8672dc4dc | /Set4v2/src/com/example/set4v1/Node.java | 0bfb99cd8d00dc6281ab4d8c2d0d87ca7440a27e | [] | no_license | rashrag/android_set4 | https://github.com/rashrag/android_set4 | 6a9649bb64d5890101564223f902befeef808f06 | fae70c2200872abead9e6418427a923c9c0fdc68 | refs/heads/master | "2021-01-23T08:56:48.194000" | "2014-09-29T15:15:32" | "2014-09-29T15:15:32" | 24,537,400 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.set4v1;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author lenovo
*/
public class Node {
String key;
Node link;
public Node(String s)
{
this.key=s;
this.link=null;
}
}
| UTF-8 | Java | 298 | java | Node.java | Java | [
{
"context": "the template in the editor.\n */\n\n/**\n *\n * @author lenovo\n */\npublic class Node {\n String key;\n Node ",
"end": 153,
"score": 0.9994910955429077,
"start": 147,
"tag": "USERNAME",
"value": "lenovo"
}
] | null | [] | package com.example.set4v1;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author lenovo
*/
public class Node {
String key;
Node link;
public Node(String s)
{
this.key=s;
this.link=null;
}
}
| 298 | 0.580537 | 0.573825 | 20 | 13.9 | 13.743726 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35 | false | false | 9 |
96a9b0e401b5fd5ae563cfc9fd68b8279b6ae55a | 12,378,095,815,341 | 32b72e1dc8b6ee1be2e80bb70a03a021c83db550 | /ast_results/AnySoftKeyboard_AnySoftKeyboard/base/src/main/java/com/anysoftkeyboard/base/utils/OptionalCompat.java | 0a2ee6155883477213f0b003d8219f497c052d78 | [] | no_license | cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning | https://github.com/cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning | d90c41a17e88fcd99d543124eeb6e93f9133cb4a | 0564143d92f8024ff5fa6b659c2baebf827582b1 | refs/heads/master | "2020-07-13T13:53:40.297000" | "2019-01-11T11:51:18" | "2019-01-11T11:51:18" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // isComment
package com.anysoftkeyboard.base.utils;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public class isClassOrIsInterface<T> {
public static <T> OptionalCompat<T> isMethod(@Nullable T isParameter) {
return new OptionalCompat<>(isNameExpr);
}
@Nullable
private final T isVariable;
private isConstructor(T isParameter) {
isNameExpr = isNameExpr;
}
@Nullable
public T isMethod() {
return isNameExpr;
}
public boolean isMethod() {
return isNameExpr != null;
}
public boolean isMethod() {
return isNameExpr == null;
}
@NonNull
public T isMethod(@NonNull T isParameter) {
if (isNameExpr == null)
return isNameExpr;
else
return isNameExpr;
}
@Override
public boolean isMethod(Object isParameter) {
if (isNameExpr == null) {
return true;
}
if (this == isNameExpr) {
return true;
}
if (!(isNameExpr instanceof OptionalCompat)) {
return true;
}
OptionalCompat<?> isVariable = (OptionalCompat<?>) isNameExpr;
if (isNameExpr.isMethod() && isMethod()) {
return true;
}
if (isNameExpr.isFieldAccessExpr == isNameExpr) {
return true;
}
return (isNameExpr.isFieldAccessExpr != null && isNameExpr.isFieldAccessExpr.isMethod(isNameExpr));
}
@Override
public int isMethod() {
return isNameExpr == null ? isIntegerConstant : isNameExpr.isMethod() + isIntegerConstant;
}
}
| UTF-8 | Java | 1,647 | java | OptionalCompat.java | Java | [] | null | [] | // isComment
package com.anysoftkeyboard.base.utils;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public class isClassOrIsInterface<T> {
public static <T> OptionalCompat<T> isMethod(@Nullable T isParameter) {
return new OptionalCompat<>(isNameExpr);
}
@Nullable
private final T isVariable;
private isConstructor(T isParameter) {
isNameExpr = isNameExpr;
}
@Nullable
public T isMethod() {
return isNameExpr;
}
public boolean isMethod() {
return isNameExpr != null;
}
public boolean isMethod() {
return isNameExpr == null;
}
@NonNull
public T isMethod(@NonNull T isParameter) {
if (isNameExpr == null)
return isNameExpr;
else
return isNameExpr;
}
@Override
public boolean isMethod(Object isParameter) {
if (isNameExpr == null) {
return true;
}
if (this == isNameExpr) {
return true;
}
if (!(isNameExpr instanceof OptionalCompat)) {
return true;
}
OptionalCompat<?> isVariable = (OptionalCompat<?>) isNameExpr;
if (isNameExpr.isMethod() && isMethod()) {
return true;
}
if (isNameExpr.isFieldAccessExpr == isNameExpr) {
return true;
}
return (isNameExpr.isFieldAccessExpr != null && isNameExpr.isFieldAccessExpr.isMethod(isNameExpr));
}
@Override
public int isMethod() {
return isNameExpr == null ? isIntegerConstant : isNameExpr.isMethod() + isIntegerConstant;
}
}
| 1,647 | 0.603522 | 0.603522 | 66 | 23.954546 | 23.162426 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.287879 | false | false | 9 |
a80d1f5b969d089fd3a5a22d7df7b096e3c38e9d | 10,746,008,238,960 | 7d1fc44f24154599a5ae7f689bc8e43bdade94da | /deprecated/reverseengineering/org.sidiff.bug.localization.dataset/src/org/sidiff/bug/localization/dataset/model/util/DataSetStorage.java | 70eb2e9744e20cd4183acd8e564659b8fe724a22 | [] | no_license | gelareh1985/buglocalization | https://github.com/gelareh1985/buglocalization | 4561d595d80b18c82f2bd3bf6ac294d28c1866d0 | b03a9c9bad941219ec86fa29b03f64cddd602ae9 | refs/heads/master | "2023-09-05T12:52:59.667000" | "2021-11-18T17:44:22" | "2021-11-18T17:44:22" | 267,834,568 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.sidiff.bug.localization.dataset.model.util;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.sidiff.bug.localization.common.utilities.json.JsonUtil;
import org.sidiff.bug.localization.dataset.changes.model.LineChange;
import org.sidiff.bug.localization.dataset.changes.model.json.JsonLineChangeDeserializer;
import org.sidiff.bug.localization.dataset.changes.model.json.JsonLineChangeSerializer;
import org.sidiff.bug.localization.dataset.model.DataSet;
import com.google.gson.GsonBuilder;
public class DataSetStorage {
private static final String TIMESTAMP_SEPARATOR = "_";
public static Path save(Path datasetPath, DataSet dataset, boolean appendTimestamp) throws IOException {
GsonBuilder builder = JsonUtil.createBuilderInstance();
builder.registerTypeAdapter(LineChange.class, new JsonLineChangeDeserializer());
builder.registerTypeAdapter(LineChange.class, new JsonLineChangeSerializer());
if (appendTimestamp) {
String filename = datasetPath.getFileName().toString();
String stampedFilename = filename.substring(0, filename.lastIndexOf(".")) + TIMESTAMP_SEPARATOR + dataset.createTimestamp();
stampedFilename = stampedFilename + "." + filename.substring(filename.lastIndexOf(".") + 1, filename.length());
datasetPath = Paths.get(datasetPath.getParent().toString(), stampedFilename);
}
JsonUtil.save(dataset, datasetPath, builder);
return datasetPath;
}
public static DataSet load(Path datasetPath) throws FileNotFoundException {
GsonBuilder builder = JsonUtil.createBuilderInstance();
builder.registerTypeAdapter(LineChange.class, new JsonLineChangeDeserializer());
builder.registerTypeAdapter(LineChange.class, new JsonLineChangeSerializer());
return JsonUtil.parse(datasetPath, DataSet.class, builder);
}
}
| UTF-8 | Java | 1,874 | java | DataSetStorage.java | Java | [] | null | [] | package org.sidiff.bug.localization.dataset.model.util;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.sidiff.bug.localization.common.utilities.json.JsonUtil;
import org.sidiff.bug.localization.dataset.changes.model.LineChange;
import org.sidiff.bug.localization.dataset.changes.model.json.JsonLineChangeDeserializer;
import org.sidiff.bug.localization.dataset.changes.model.json.JsonLineChangeSerializer;
import org.sidiff.bug.localization.dataset.model.DataSet;
import com.google.gson.GsonBuilder;
public class DataSetStorage {
private static final String TIMESTAMP_SEPARATOR = "_";
public static Path save(Path datasetPath, DataSet dataset, boolean appendTimestamp) throws IOException {
GsonBuilder builder = JsonUtil.createBuilderInstance();
builder.registerTypeAdapter(LineChange.class, new JsonLineChangeDeserializer());
builder.registerTypeAdapter(LineChange.class, new JsonLineChangeSerializer());
if (appendTimestamp) {
String filename = datasetPath.getFileName().toString();
String stampedFilename = filename.substring(0, filename.lastIndexOf(".")) + TIMESTAMP_SEPARATOR + dataset.createTimestamp();
stampedFilename = stampedFilename + "." + filename.substring(filename.lastIndexOf(".") + 1, filename.length());
datasetPath = Paths.get(datasetPath.getParent().toString(), stampedFilename);
}
JsonUtil.save(dataset, datasetPath, builder);
return datasetPath;
}
public static DataSet load(Path datasetPath) throws FileNotFoundException {
GsonBuilder builder = JsonUtil.createBuilderInstance();
builder.registerTypeAdapter(LineChange.class, new JsonLineChangeDeserializer());
builder.registerTypeAdapter(LineChange.class, new JsonLineChangeSerializer());
return JsonUtil.parse(datasetPath, DataSet.class, builder);
}
}
| 1,874 | 0.796158 | 0.795091 | 45 | 40.644444 | 36.642509 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.977778 | false | false | 9 |
b42ccf969e5d367bbf781b94edc6c5bc8d1402d8 | 20,366,734,930,475 | 7d87fd88c2d18a284e7a21f0d4fca63e2a20afd6 | /src/oop/aufgaben/auto/Fahrzeug.java | 3f00dc396520136660f184578980f4fb7ec6fd53 | [] | no_license | crazzle/fom-code-oop | https://github.com/crazzle/fom-code-oop | 7380b769556a5f839b509d82d415adb372d408b9 | 52f6f417ae869cdb1f769b1bf5852f3ead585b11 | refs/heads/master | "2021-06-04T08:31:53.030000" | "2016-09-18T17:21:36" | "2016-09-18T17:21:36" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package oop.aufgaben.auto;
/**
* Abstrakte Klasse Fahrzeug
*
* @author keinmark
*
*/
public abstract class Fahrzeug {
protected String besitzer;
/**
* Konstruktor mit Besitzer als Parameter
*
* @param besitzer
*/
public Fahrzeug(String besitzer) {
this.besitzer = besitzer;
}
/**
* Konstruktor ohne Besitzer, der Besitzer ist daher "Anonym"
*/
public Fahrzeug() {
this.besitzer = "Anonym";
}
/**
* Getter für besitzer
*
* @return
*/
public String getBesitzer() {
return besitzer;
}
/**
* Setter für besitzer
*
* @param besitzer
*/
public void setBesitzer(String besitzer) {
this.besitzer = besitzer;
}
/**
* Diese Methode ist nur als Kopf vorhanden und daher abstrakt. Sie muss von
* einer Kind-Klasse implementiert werden
*/
public abstract void zeigeDaten();
}
| UTF-8 | Java | 839 | java | Fahrzeug.java | Java | [
{
"context": ";\n\n/**\n * Abstrakte Klasse Fahrzeug\n * \n * @author keinmark\n * \n */\npublic abstract class Fahrzeug {\n\tprotect",
"end": 84,
"score": 0.9990827441215515,
"start": 76,
"tag": "USERNAME",
"value": "keinmark"
}
] | null | [] | package oop.aufgaben.auto;
/**
* Abstrakte Klasse Fahrzeug
*
* @author keinmark
*
*/
public abstract class Fahrzeug {
protected String besitzer;
/**
* Konstruktor mit Besitzer als Parameter
*
* @param besitzer
*/
public Fahrzeug(String besitzer) {
this.besitzer = besitzer;
}
/**
* Konstruktor ohne Besitzer, der Besitzer ist daher "Anonym"
*/
public Fahrzeug() {
this.besitzer = "Anonym";
}
/**
* Getter für besitzer
*
* @return
*/
public String getBesitzer() {
return besitzer;
}
/**
* Setter für besitzer
*
* @param besitzer
*/
public void setBesitzer(String besitzer) {
this.besitzer = besitzer;
}
/**
* Diese Methode ist nur als Kopf vorhanden und daher abstrakt. Sie muss von
* einer Kind-Klasse implementiert werden
*/
public abstract void zeigeDaten();
}
| 839 | 0.658303 | 0.658303 | 52 | 15.096154 | 17.151205 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.923077 | false | false | 9 |
9b3a61c2f1b23490259e6f9eba54a6a47efa3eb9 | 26,482,768,411,100 | 1d94a107f3716637f276fbef940212eae33169ca | /src/main/java/com/gionee/gnif3/exception/OptimisticLockingException.java | d3585951802e2125325d3a267fa234d6c843b120 | [] | no_license | yeqingyun/gnif3 | https://github.com/yeqingyun/gnif3 | 90b97b1e99a25fef97830986b3d8d7c859371fbf | 883e6e3a10f772b58218daf79b8aac0fbce58bbd | refs/heads/master | "2021-04-15T06:53:09.670000" | "2018-03-23T02:57:20" | "2018-03-23T02:57:20" | 126,424,852 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gionee.gnif3.exception;
/**
* Created by Leon.Yu on 2016/10/13.
*/
public class OptimisticLockingException extends GnifRuntimeException {
public OptimisticLockingException() {
}
public OptimisticLockingException(String message) {
}
public OptimisticLockingException(String message, Throwable throwable) {
}
}
| UTF-8 | Java | 353 | java | OptimisticLockingException.java | Java | [
{
"context": "age com.gionee.gnif3.exception;\n\n/**\n * Created by Leon.Yu on 2016/10/13.\n */\npublic class OptimisticLocking",
"end": 62,
"score": 0.9997501373291016,
"start": 55,
"tag": "NAME",
"value": "Leon.Yu"
}
] | null | [] | package com.gionee.gnif3.exception;
/**
* Created by Leon.Yu on 2016/10/13.
*/
public class OptimisticLockingException extends GnifRuntimeException {
public OptimisticLockingException() {
}
public OptimisticLockingException(String message) {
}
public OptimisticLockingException(String message, Throwable throwable) {
}
}
| 353 | 0.733711 | 0.708215 | 18 | 18.611111 | 25.56286 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.111111 | false | false | 9 |
d23b099d49aa1db05a75ee098a9177624bea4c50 | 25,099,788,900,504 | 595af3ec372ac777b31802d823e0e379420ddeff | /javaApp/src/hr/java/vjezbe/entitet/Profesor.java | 7eeb8b3800502098da70d8cde50a6a9703b79fc3 | [] | no_license | dkrizak/javaApp | https://github.com/dkrizak/javaApp | f3b2a0dbb46af329a08341f7f1232cfb3deeb9e1 | b613c79b50f9170171557f875a34265fdbd492d1 | refs/heads/master | "2020-04-21T14:09:43.199000" | "2019-02-07T19:15:26" | "2019-02-07T19:15:26" | 169,622,624 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hr.java.vjezbe.entitet;
/**
* Predstavlja profesora koji je definiran šifrom, imenom, prezimenom i titulom.
*
* @author Denis Križak
*
*/
public class Profesor extends Osoba{
private static final long serialVersionUID = -1213882983260791233L;
private String sifra, titula;
/**
* Inicijalizira podatke o profesoru.
*
* @param sifra šifra profesora.
* @param ime ime profesora.
* @param prezime prezime profesora.
* @param titula titula profesora u obrazovnoj ustanovi.
*/
public Profesor(Long id, String sifra, String ime, String prezime, String titula) {
super(id, ime, prezime);
this.sifra = sifra;
this.titula = titula;
}
/**
* Dohvaća šifru profesora.
*
* @return šifru profesora.
*/
public String getSifra() {
return sifra;
}
/**
* Postavlja šifru na novu vrijednost.
*
* @param sifra nova vrijednost šifre.
*/
public void setSifra(String sifra) {
this.sifra = sifra;
}
/**
* Dohvaća titulu profesora.
*
* @return titulu profesora.
*/
public String getTitula() {
return titula;
}
/**
* Postavlja vrijednost titule na novu vrijednost.
*
* @param titula nova vrijednost titule.
*/
public void setTitula(String titula) {
this.titula = titula;
}
}
| WINDOWS-1250 | Java | 1,314 | java | Profesor.java | Java | [
{
"context": "om, imenom, prezimenom i titulom.\r\n * \r\n * @author Denis Križak\r\n *\r\n */\r\npublic class Profesor extends Osoba{\r\n\t",
"end": 148,
"score": 0.9997513890266418,
"start": 136,
"tag": "NAME",
"value": "Denis Križak"
}
] | null | [] | package hr.java.vjezbe.entitet;
/**
* Predstavlja profesora koji je definiran šifrom, imenom, prezimenom i titulom.
*
* @author <NAME>
*
*/
public class Profesor extends Osoba{
private static final long serialVersionUID = -1213882983260791233L;
private String sifra, titula;
/**
* Inicijalizira podatke o profesoru.
*
* @param sifra šifra profesora.
* @param ime ime profesora.
* @param prezime prezime profesora.
* @param titula titula profesora u obrazovnoj ustanovi.
*/
public Profesor(Long id, String sifra, String ime, String prezime, String titula) {
super(id, ime, prezime);
this.sifra = sifra;
this.titula = titula;
}
/**
* Dohvaća šifru profesora.
*
* @return šifru profesora.
*/
public String getSifra() {
return sifra;
}
/**
* Postavlja šifru na novu vrijednost.
*
* @param sifra nova vrijednost šifre.
*/
public void setSifra(String sifra) {
this.sifra = sifra;
}
/**
* Dohvaća titulu profesora.
*
* @return titulu profesora.
*/
public String getTitula() {
return titula;
}
/**
* Postavlja vrijednost titule na novu vrijednost.
*
* @param titula nova vrijednost titule.
*/
public void setTitula(String titula) {
this.titula = titula;
}
}
| 1,307 | 0.650575 | 0.636015 | 58 | 20.5 | 20.235893 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.275862 | false | false | 9 |
8ba25aefe4a664073075fc78b6203fd9644268f8 | 2,302,102,501,777 | b45db213abb2b3f8d6132ebd0b548d0cbfce5583 | /src/main/java/com/ufgov/sssfm/socket/utils/XMLUtil.java | 616c6ca684110d9a799256486c2871bdf19451b3 | [] | no_license | a4goku/fm_nj | https://github.com/a4goku/fm_nj | 8235e8829c66648cd1526248bd5836fa5edc32c0 | 3ec9ba3972889d9f7c44704f26f560eb0c634324 | refs/heads/master | "2020-03-30T03:18:59.428000" | "2018-09-28T06:16:59" | "2018-09-28T06:16:59" | 150,681,867 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ufgov.sssfm.socket.utils;
import com.ufgov.sssfm.socket.dao.BaseDAO;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class XMLUtil {
/*
* 获取公共域报文
*/
public Document getPensionData(String typeCode, String typeName)
throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element root = document.createElement("pensiondata");
document.appendChild(root);
Element version = document.createElement("version");
version.setTextContent("v1.0");
root.appendChild(version);
Element TypeName = document.createElement("typename");
TypeName.setTextContent(typeName);
Element DataSetType = document.createElement("datasettype");
root.appendChild(DataSetType);
DataSetType.appendChild(TypeName);
Element TypeCode = document.createElement("typecode");
TypeCode.setTextContent(typeCode);
DataSetType.appendChild(TypeCode);
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat df1 = new SimpleDateFormat("HHmmss");
Date date = new Date();
Element SendDate = document.createElement("senddate");
SendDate.setTextContent(df.format(date));
root.appendChild(SendDate);
Element ReceiveCode = document.createElement("receivecode");
ReceiveCode.setTextContent("v1.0");
root.appendChild(ReceiveCode);
Element SendTime = document.createElement("sendtime");
SendTime.setTextContent(df1.format(date));
root.appendChild(SendTime);
Element SendCode = document.createElement("sendcode");
SendCode.setTextContent("v1.0");
root.appendChild(SendCode);
return document;
}
/*
* 获取反馈报文
*/
public Document getReturnXML(String xml, String appcode, String appmsg)
throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Document doc = null;
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(xml)));
NodeList e = doc.getElementsByTagName("receivecode");
String receivecode = e.item(0).getTextContent();
e = doc.getElementsByTagName("sendcode");
String sendcode = e.item(0).getTextContent();
e = doc.getElementsByTagName("typecode");
String typecode = e.item(0).getTextContent();
e = doc.getElementsByTagName("typename");
String typename = e.item(0).getTextContent();
e = doc.getElementsByTagName("appseriono");
String appseriono = e.item(0).getTextContent();
Element root = document.createElement("pensiondata");
document.appendChild(root);
Element version = document.createElement("version");
version.setTextContent("v1.0");
root.appendChild(version);
Element AppCode = document.createElement("appcode");
AppCode.setTextContent(appcode);
root.appendChild(AppCode);
Element AppMsg = document.createElement("appmsg");
AppMsg.setTextContent(appmsg);
root.appendChild(AppMsg);
Element TypeName = document.createElement("typename");
TypeName.setTextContent(typename);
Element DataSetType = document.createElement("datasettype");
root.appendChild(DataSetType);
DataSetType.appendChild(TypeName);
Element TypeCode = document.createElement("typecode");
TypeCode.setTextContent(typecode);
DataSetType.appendChild(TypeCode);
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat df1 = new SimpleDateFormat("HHmmss");
Date date = new Date();
Element SendDate = document.createElement("senddate");
SendDate.setTextContent(df.format(date));
root.appendChild(SendDate);
Element ReceiveCode = document.createElement("receivecode");
ReceiveCode.setTextContent(receivecode);
root.appendChild(ReceiveCode);
Element SendTime = document.createElement("sendtime");
SendTime.setTextContent(df1.format(date));
root.appendChild(SendTime);
Element SendCode = document.createElement("sendcode");
SendCode.setTextContent(sendcode);
root.appendChild(SendCode);
Element PensionInfo = document.createElement("PensionInfo");
root.appendChild(PensionInfo);
Element appserionoele = document.createElement("appseriono");
appserionoele.setTextContent(appseriono);
PensionInfo.appendChild(appserionoele);
return document;
}
/*
* 划款结果信息
*/
public Document getContrRecord(List<Map<String, String>> lists,
Map<String, String> map, Document document) {
Element root = document.getDocumentElement();
Element total = document.createElement("PensionInfo");
root.appendChild(total);
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssms");
Date date = new Date();
Element appseriono = document.createElement("appseriono");
appseriono.setTextContent(df.format(date) + map.get("appseriono"));
total.appendChild(appseriono);
Element total_code = document.createElement("total_code");
total_code.setTextContent(map.get("total_code"));
total.appendChild(total_code);
Element areamanagecode = document.createElement("areamanagecode");
areamanagecode.setTextContent(map.get("areamanagecode"));
total.appendChild(areamanagecode);
Element areamanagename = document.createElement("areamanagename");
areamanagename.setTextContent(map.get("areamanagename"));
total.appendChild(areamanagename);
Element type = document.createElement("type");
type.setTextContent(map.get("type"));
total.appendChild(type);
Element transfer_mon_date = document.createElement("transfer_mon_date");
transfer_mon_date.setTextContent(map.get("transfer_mon_date"));
total.appendChild(transfer_mon_date);
Element contr_total = document.createElement("contr_total");
contr_total.setTextContent(map.get("contr_total"));
total.appendChild(contr_total);
Element memo = document.createElement("memo");
memo.setTextContent(map.get("memo"));
total.appendChild(memo);
Element rows = document.createElement("rows");
total.appendChild(rows);
for (Map<String, String> map2 : lists) {
Element corp = document.createElement("row");
rows.appendChild(corp);
Element total_code1 = document.createElement("total_code");
total_code1.setTextContent(map2.get("total_code"));
corp.appendChild(total_code1);
Element contr_serial_no = document.createElement("contr_serial_no");
contr_serial_no.setTextContent(map2.get("contr_serial_no"));
corp.appendChild(contr_serial_no);
Element corp_jgb_unique_code = document
.createElement("corp_jgb_unique_code");
corp_jgb_unique_code.setTextContent(map2
.get("corp_jgb_unique_code"));
corp.appendChild(corp_jgb_unique_code);
Element corp_name = document.createElement("corp_name");
corp_name.setTextContent(map2.get("corp_name"));
corp.appendChild(corp_name);
Element contr_balance = document.createElement("contr_balance");
contr_balance.setTextContent(map2.get("contr_balance"));
corp.appendChild(contr_balance);
Element memo1 = document.createElement("memo");
memo1.setTextContent(map2.get("memo"));
corp.appendChild(memo1);
}
return document;
}
/*
* 到账信息
*/
public Document getTotalContrRecord(Map<String, String> map,
Document document) {
Element root = document.getDocumentElement();
Element total = document.createElement("PensionInfo");
root.appendChild(total);
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssms");
Date date = new Date();
Element appseriono = document.createElement("appseriono");
appseriono.setTextContent(df.format(date) + map.get("appseriono"));
total.appendChild(appseriono);
Element trancode = document.createElement("trancode");
trancode.setTextContent(map.get("trancode"));
total.appendChild(trancode);
Element total_code = document.createElement("total_serial_no");
total_code.setTextContent(map.get("total_serial_no"));
total.appendChild(total_code);
Element areamanagecode = document.createElement("areamanagecode");
areamanagecode.setTextContent(map.get("areamanagecode"));
total.appendChild(areamanagecode);
Element areamanagename = document.createElement("areamanagename");
areamanagename.setTextContent(map.get("areamanagename"));
total.appendChild(areamanagename);
Element type = document.createElement("type");
type.setTextContent(map.get("type"));
total.appendChild(type);
Element transfer_mon_date = document.createElement("transfer_mon_date");
transfer_mon_date.setTextContent(map.get("transfer_mon_date"));
total.appendChild(transfer_mon_date);
Element total_date = document.createElement("total_date");
total_date.setTextContent(map.get("total_date"));
total.appendChild(total_date);
Element contr_state = document.createElement("contr_state");
contr_state.setTextContent(map.get("contr_state"));
total.appendChild(contr_state);
Element contr_total = document.createElement("contr_total");
contr_total.setTextContent(map.get("contr_total"));
total.appendChild(contr_total);
Element actual_cash = document.createElement("actual_cash");
actual_cash.setTextContent(map.get("actual_cash"));
total.appendChild(actual_cash);
Element memo = document.createElement("memo");
memo.setTextContent(map.get("memo"));
total.appendChild(memo);
return document;
}
/*
* 缴费汇总定长包
*/
public String analysisTotalContrXml(byte[] bytes)
throws UnsupportedEncodingException {
BaseDAO dao = new BaseDAO();
String trancode = getStr(bytes, 0, 4);
if (trancode != null && trancode.equals("2100")) {
return "0000";
}
String total_serial_no = getStr(bytes, 4, 20);
String transfer_mon_date = getStr(bytes, 174, 8);
String contr_state = getStr(bytes, 204, 2);
String actual_cash = getStr(bytes, 206, 14);
String result = dao.updateContr(total_serial_no, transfer_mon_date,
actual_cash, contr_state);
return result;
}
public static String getStr(byte[] bytes, int start, int len) {
byte[] temp = new byte[len];
for (int i = 0; i < len; i++) {
temp[i] = bytes[start + i];
}
return new String(temp);
}
/*
* 缴费汇总定长包
*/
public String getTotalContrRecordToYH(Map<String, String> map)
throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
sb.append(fillField(map.get("trancode"), "char", 4));
sb.append(fillField(map.get("total_serial_no"), "char", 20));
sb.append(fillField(map.get("areamanagecode"), "char", 20));
sb.append(fillField(map.get("areamanagename"), "char", 128));
sb.append(fillField(map.get("type"), "char", 2));
sb.append(fillField(map.get("transfer_mon_date"), "char", 8));
sb.append(fillField(map.get("total_date"), "char", 8));
sb.append(fillField(map.get("contr_total"), "decimal", 14));
sb.append(fillField(map.get("contr_state"), "char", 2));
sb.append(fillField(map.get("actual_cash"), "decimal", 14));
sb.append(fillField(map.get("memo"), "char", 128));
return sb.toString();
}
public static String fillField(String value, String dataType, int len)
throws UnsupportedEncodingException {
int fileLen = 0;
if (value != null) {
fileLen = len - value.getBytes("gbk").length;
} else {
fileLen = len;
}
StringBuilder fillValue = new StringBuilder();
if (fileLen < 0) {
value = value.substring(0, len);
}
if ("char".equalsIgnoreCase(dataType)) {
if (value != null) {
fillValue.append(value);
}
for (int i = 0; i < fileLen; i++) {
fillValue.append(" ");
}
} else if ("int".equalsIgnoreCase(dataType)
|| "decimal".equalsIgnoreCase(dataType)) {
for (int i = 0; i < fileLen; i++) {
fillValue.append(" ");
}
fillValue.append(value);
} else if ("date".equalsIgnoreCase(dataType)) {
if (value == null || value.trim().equals("")) {
value = "19000101";
}
fillValue.append(value);
}
return fillValue.toString();
}
/*
* 资金划款指令
*/
public Document getInstructRecord(Map<String, String> map, Document document) {
Element root = document.getDocumentElement();
Element total = document.createElement("PensionInfo");
root.appendChild(total);
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssms");
Date date = new Date();
Element appseriono = document.createElement("appseriono");
appseriono.setTextContent(df.format(date) + map.get("appseriono"));
total.appendChild(appseriono);
Element instruct_code = document.createElement("instruct_code");
instruct_code.setTextContent(map.get("instruct_code"));
total.appendChild(instruct_code);
Element instruct_date = document.createElement("instruct_date");
instruct_date.setTextContent(map.get("instruct_date"));
total.appendChild(instruct_date);
Element paybankaccname = document.createElement("paybankaccname");
paybankaccname.setTextContent(map.get("paybankaccname"));
total.appendChild(paybankaccname);
Element paybankaccno = document.createElement("paybankaccno");
paybankaccno.setTextContent(map.get("paybankaccno"));
total.appendChild(paybankaccno);
Element paybank = document.createElement("paybank");
paybank.setTextContent(map.get("paybank"));
total.appendChild(paybank);
Element gatheraccname = document.createElement("gatheraccname");
gatheraccname.setTextContent(map.get("gatheraccname"));
total.appendChild(gatheraccname);
Element gatherbankno = document.createElement("gatherbankno");
gatherbankno.setTextContent(map.get("gatherbankno"));
total.appendChild(gatherbankno);
Element gatherbank = document.createElement("gatherbank");
gatherbank.setTextContent(map.get("gatherbank"));
total.appendChild(gatherbank);
Element contrbalance = document.createElement("contrbalance");
contrbalance.setTextContent(map.get("contrbalance"));
total.appendChild(contrbalance);
Element memo = document.createElement("memo");
memo.setTextContent(map.get("memo"));
total.appendChild(memo);
return document;
}
/*
* 缴费汇总单
*/
public String analysisTotalContrXml(String xml) {
BaseDAO dao = new BaseDAO();
Document doc = null;
try {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(xml)));
} catch (Exception e) {
dao.insertLog(xml, "报文解析错误," + e.getMessage(), "", "", "");
}
NodeList e = doc.getElementsByTagName("total_serial_no");
String total_serial_no = e.item(0).getTextContent();
e = doc.getElementsByTagName("areamanagecode");
String areamanagecode = e.item(0).getTextContent();
e = doc.getElementsByTagName("areamanagename");
String areamanagename = e.item(0).getTextContent();
e = doc.getElementsByTagName("trancode");
String trancode = e.item(0).getTextContent();
e = doc.getElementsByTagName("type");
String type = e.item(0).getTextContent();
e = doc.getElementsByTagName("transfer_mon_date");
String transfer_mon_date = e.item(0).getTextContent();
e = doc.getElementsByTagName("total_date");
String total_date = e.item(0).getTextContent();
e = doc.getElementsByTagName("contr_state");
String contr_state = e.item(0).getTextContent();
e = doc.getElementsByTagName("contr_total");
String contr_total = e.item(0).getTextContent();
e = doc.getElementsByTagName("actual_cash");
String actual_cash = e.item(0).getTextContent();
e = doc.getElementsByTagName("memo");
String memo = e.item(0).getTextContent();
e = doc.getElementsByTagName("typecode");
String typecode = e.item(0).getTextContent();
String result = dao.insertTotalContr(total_serial_no, areamanagecode,
areamanagename, type, transfer_mon_date, total_date,
contr_state, contr_total, actual_cash, memo, trancode);
dao.insertLog(xml, result, typecode, "", total_serial_no);
return result;
}
/**
* 解析到账标识
*
* @param xml
* @return
*/
public String analysisTypeCode(String xml) {
BaseDAO dao = new BaseDAO();
Document doc = null;
String typecode = null;
try {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
NodeList e = doc.getElementsByTagName("typecode");
typecode = e.item(0).getTextContent();
} catch (Exception e) {
dao.insertLog(xml, "报文解析错误," + e.getMessage(), "", "", "");
}
return typecode;
}
public String analysisFileName(String xml) {
BaseDAO dao = new BaseDAO();
Document doc = null;
String filename = null;
try {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
NodeList e = doc.getElementsByTagName("filename");
filename = e.item(0).getTextContent();
} catch (Exception e) {
dao.insertLog(xml, "报文解析错误," + e.getMessage(), "", "", "");
}
return filename;
}
/*
* 资金划款指令
*/
public String analysisInstructXml(String xml) {
BaseDAO dao = new BaseDAO();
Document doc = null;
try {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(xml)));
} catch (Exception e) {
dao.insertLog(xml, "报文解析错误," + e.getMessage(), "", "", "");
}
NodeList e = doc.getElementsByTagName("instruct_code");
String instruct_code = e.item(0).getTextContent();
e = doc.getElementsByTagName("instruct_date");
String instruct_date = e.item(0).getTextContent();
e = doc.getElementsByTagName("paybankaccname");
String paybankaccname = e.item(0).getTextContent();
e = doc.getElementsByTagName("paybankaccno");
String paybankaccno = e.item(0).getTextContent();
e = doc.getElementsByTagName("paybank");
String paybank = e.item(0).getTextContent();
e = doc.getElementsByTagName("gatheraccname");
String gatheraccname = e.item(0).getTextContent();
e = doc.getElementsByTagName("gatherbankno");
String gatherbankno = e.item(0).getTextContent();
e = doc.getElementsByTagName("gatherbank");
String gatherbank = e.item(0).getTextContent();
e = doc.getElementsByTagName("contrbalance");
String contrbalance = e.item(0).getTextContent();
e = doc.getElementsByTagName("memo");
String memo = e.item(0).getTextContent();
e = doc.getElementsByTagName("typecode");
String typecode = e.item(0).getTextContent();
String result = dao.insertInstruct(instruct_code, instruct_date,
paybankaccname, paybankaccno, paybank, gatheraccname,
gatherbankno, gatherbank, contrbalance, memo);
dao.insertLog(xml, result, typecode, "", instruct_code);
return result;
}
public Map<String, String> analysisgetPensionData(String xml)
throws SAXException, IOException, ParserConfigurationException {
Map<String, String> map = new HashMap<String, String>();
Document doc = null;
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(xml)));
NodeList e = doc.getElementsByTagName("appcode");
String appcode = e.item(0).getTextContent();
map.put(appcode, appcode);
e = doc.getElementsByTagName("appmsg");
String appmsg = e.item(0).getTextContent();
map.put(appmsg, appmsg);
return map;
}
}
| UTF-8 | Java | 22,439 | java | XMLUtil.java | Java | [] | null | [] | package com.ufgov.sssfm.socket.utils;
import com.ufgov.sssfm.socket.dao.BaseDAO;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class XMLUtil {
/*
* 获取公共域报文
*/
public Document getPensionData(String typeCode, String typeName)
throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element root = document.createElement("pensiondata");
document.appendChild(root);
Element version = document.createElement("version");
version.setTextContent("v1.0");
root.appendChild(version);
Element TypeName = document.createElement("typename");
TypeName.setTextContent(typeName);
Element DataSetType = document.createElement("datasettype");
root.appendChild(DataSetType);
DataSetType.appendChild(TypeName);
Element TypeCode = document.createElement("typecode");
TypeCode.setTextContent(typeCode);
DataSetType.appendChild(TypeCode);
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat df1 = new SimpleDateFormat("HHmmss");
Date date = new Date();
Element SendDate = document.createElement("senddate");
SendDate.setTextContent(df.format(date));
root.appendChild(SendDate);
Element ReceiveCode = document.createElement("receivecode");
ReceiveCode.setTextContent("v1.0");
root.appendChild(ReceiveCode);
Element SendTime = document.createElement("sendtime");
SendTime.setTextContent(df1.format(date));
root.appendChild(SendTime);
Element SendCode = document.createElement("sendcode");
SendCode.setTextContent("v1.0");
root.appendChild(SendCode);
return document;
}
/*
* 获取反馈报文
*/
public Document getReturnXML(String xml, String appcode, String appmsg)
throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Document doc = null;
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(xml)));
NodeList e = doc.getElementsByTagName("receivecode");
String receivecode = e.item(0).getTextContent();
e = doc.getElementsByTagName("sendcode");
String sendcode = e.item(0).getTextContent();
e = doc.getElementsByTagName("typecode");
String typecode = e.item(0).getTextContent();
e = doc.getElementsByTagName("typename");
String typename = e.item(0).getTextContent();
e = doc.getElementsByTagName("appseriono");
String appseriono = e.item(0).getTextContent();
Element root = document.createElement("pensiondata");
document.appendChild(root);
Element version = document.createElement("version");
version.setTextContent("v1.0");
root.appendChild(version);
Element AppCode = document.createElement("appcode");
AppCode.setTextContent(appcode);
root.appendChild(AppCode);
Element AppMsg = document.createElement("appmsg");
AppMsg.setTextContent(appmsg);
root.appendChild(AppMsg);
Element TypeName = document.createElement("typename");
TypeName.setTextContent(typename);
Element DataSetType = document.createElement("datasettype");
root.appendChild(DataSetType);
DataSetType.appendChild(TypeName);
Element TypeCode = document.createElement("typecode");
TypeCode.setTextContent(typecode);
DataSetType.appendChild(TypeCode);
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat df1 = new SimpleDateFormat("HHmmss");
Date date = new Date();
Element SendDate = document.createElement("senddate");
SendDate.setTextContent(df.format(date));
root.appendChild(SendDate);
Element ReceiveCode = document.createElement("receivecode");
ReceiveCode.setTextContent(receivecode);
root.appendChild(ReceiveCode);
Element SendTime = document.createElement("sendtime");
SendTime.setTextContent(df1.format(date));
root.appendChild(SendTime);
Element SendCode = document.createElement("sendcode");
SendCode.setTextContent(sendcode);
root.appendChild(SendCode);
Element PensionInfo = document.createElement("PensionInfo");
root.appendChild(PensionInfo);
Element appserionoele = document.createElement("appseriono");
appserionoele.setTextContent(appseriono);
PensionInfo.appendChild(appserionoele);
return document;
}
/*
* 划款结果信息
*/
public Document getContrRecord(List<Map<String, String>> lists,
Map<String, String> map, Document document) {
Element root = document.getDocumentElement();
Element total = document.createElement("PensionInfo");
root.appendChild(total);
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssms");
Date date = new Date();
Element appseriono = document.createElement("appseriono");
appseriono.setTextContent(df.format(date) + map.get("appseriono"));
total.appendChild(appseriono);
Element total_code = document.createElement("total_code");
total_code.setTextContent(map.get("total_code"));
total.appendChild(total_code);
Element areamanagecode = document.createElement("areamanagecode");
areamanagecode.setTextContent(map.get("areamanagecode"));
total.appendChild(areamanagecode);
Element areamanagename = document.createElement("areamanagename");
areamanagename.setTextContent(map.get("areamanagename"));
total.appendChild(areamanagename);
Element type = document.createElement("type");
type.setTextContent(map.get("type"));
total.appendChild(type);
Element transfer_mon_date = document.createElement("transfer_mon_date");
transfer_mon_date.setTextContent(map.get("transfer_mon_date"));
total.appendChild(transfer_mon_date);
Element contr_total = document.createElement("contr_total");
contr_total.setTextContent(map.get("contr_total"));
total.appendChild(contr_total);
Element memo = document.createElement("memo");
memo.setTextContent(map.get("memo"));
total.appendChild(memo);
Element rows = document.createElement("rows");
total.appendChild(rows);
for (Map<String, String> map2 : lists) {
Element corp = document.createElement("row");
rows.appendChild(corp);
Element total_code1 = document.createElement("total_code");
total_code1.setTextContent(map2.get("total_code"));
corp.appendChild(total_code1);
Element contr_serial_no = document.createElement("contr_serial_no");
contr_serial_no.setTextContent(map2.get("contr_serial_no"));
corp.appendChild(contr_serial_no);
Element corp_jgb_unique_code = document
.createElement("corp_jgb_unique_code");
corp_jgb_unique_code.setTextContent(map2
.get("corp_jgb_unique_code"));
corp.appendChild(corp_jgb_unique_code);
Element corp_name = document.createElement("corp_name");
corp_name.setTextContent(map2.get("corp_name"));
corp.appendChild(corp_name);
Element contr_balance = document.createElement("contr_balance");
contr_balance.setTextContent(map2.get("contr_balance"));
corp.appendChild(contr_balance);
Element memo1 = document.createElement("memo");
memo1.setTextContent(map2.get("memo"));
corp.appendChild(memo1);
}
return document;
}
/*
* 到账信息
*/
public Document getTotalContrRecord(Map<String, String> map,
Document document) {
Element root = document.getDocumentElement();
Element total = document.createElement("PensionInfo");
root.appendChild(total);
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssms");
Date date = new Date();
Element appseriono = document.createElement("appseriono");
appseriono.setTextContent(df.format(date) + map.get("appseriono"));
total.appendChild(appseriono);
Element trancode = document.createElement("trancode");
trancode.setTextContent(map.get("trancode"));
total.appendChild(trancode);
Element total_code = document.createElement("total_serial_no");
total_code.setTextContent(map.get("total_serial_no"));
total.appendChild(total_code);
Element areamanagecode = document.createElement("areamanagecode");
areamanagecode.setTextContent(map.get("areamanagecode"));
total.appendChild(areamanagecode);
Element areamanagename = document.createElement("areamanagename");
areamanagename.setTextContent(map.get("areamanagename"));
total.appendChild(areamanagename);
Element type = document.createElement("type");
type.setTextContent(map.get("type"));
total.appendChild(type);
Element transfer_mon_date = document.createElement("transfer_mon_date");
transfer_mon_date.setTextContent(map.get("transfer_mon_date"));
total.appendChild(transfer_mon_date);
Element total_date = document.createElement("total_date");
total_date.setTextContent(map.get("total_date"));
total.appendChild(total_date);
Element contr_state = document.createElement("contr_state");
contr_state.setTextContent(map.get("contr_state"));
total.appendChild(contr_state);
Element contr_total = document.createElement("contr_total");
contr_total.setTextContent(map.get("contr_total"));
total.appendChild(contr_total);
Element actual_cash = document.createElement("actual_cash");
actual_cash.setTextContent(map.get("actual_cash"));
total.appendChild(actual_cash);
Element memo = document.createElement("memo");
memo.setTextContent(map.get("memo"));
total.appendChild(memo);
return document;
}
/*
* 缴费汇总定长包
*/
public String analysisTotalContrXml(byte[] bytes)
throws UnsupportedEncodingException {
BaseDAO dao = new BaseDAO();
String trancode = getStr(bytes, 0, 4);
if (trancode != null && trancode.equals("2100")) {
return "0000";
}
String total_serial_no = getStr(bytes, 4, 20);
String transfer_mon_date = getStr(bytes, 174, 8);
String contr_state = getStr(bytes, 204, 2);
String actual_cash = getStr(bytes, 206, 14);
String result = dao.updateContr(total_serial_no, transfer_mon_date,
actual_cash, contr_state);
return result;
}
public static String getStr(byte[] bytes, int start, int len) {
byte[] temp = new byte[len];
for (int i = 0; i < len; i++) {
temp[i] = bytes[start + i];
}
return new String(temp);
}
/*
* 缴费汇总定长包
*/
public String getTotalContrRecordToYH(Map<String, String> map)
throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
sb.append(fillField(map.get("trancode"), "char", 4));
sb.append(fillField(map.get("total_serial_no"), "char", 20));
sb.append(fillField(map.get("areamanagecode"), "char", 20));
sb.append(fillField(map.get("areamanagename"), "char", 128));
sb.append(fillField(map.get("type"), "char", 2));
sb.append(fillField(map.get("transfer_mon_date"), "char", 8));
sb.append(fillField(map.get("total_date"), "char", 8));
sb.append(fillField(map.get("contr_total"), "decimal", 14));
sb.append(fillField(map.get("contr_state"), "char", 2));
sb.append(fillField(map.get("actual_cash"), "decimal", 14));
sb.append(fillField(map.get("memo"), "char", 128));
return sb.toString();
}
public static String fillField(String value, String dataType, int len)
throws UnsupportedEncodingException {
int fileLen = 0;
if (value != null) {
fileLen = len - value.getBytes("gbk").length;
} else {
fileLen = len;
}
StringBuilder fillValue = new StringBuilder();
if (fileLen < 0) {
value = value.substring(0, len);
}
if ("char".equalsIgnoreCase(dataType)) {
if (value != null) {
fillValue.append(value);
}
for (int i = 0; i < fileLen; i++) {
fillValue.append(" ");
}
} else if ("int".equalsIgnoreCase(dataType)
|| "decimal".equalsIgnoreCase(dataType)) {
for (int i = 0; i < fileLen; i++) {
fillValue.append(" ");
}
fillValue.append(value);
} else if ("date".equalsIgnoreCase(dataType)) {
if (value == null || value.trim().equals("")) {
value = "19000101";
}
fillValue.append(value);
}
return fillValue.toString();
}
/*
* 资金划款指令
*/
public Document getInstructRecord(Map<String, String> map, Document document) {
Element root = document.getDocumentElement();
Element total = document.createElement("PensionInfo");
root.appendChild(total);
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssms");
Date date = new Date();
Element appseriono = document.createElement("appseriono");
appseriono.setTextContent(df.format(date) + map.get("appseriono"));
total.appendChild(appseriono);
Element instruct_code = document.createElement("instruct_code");
instruct_code.setTextContent(map.get("instruct_code"));
total.appendChild(instruct_code);
Element instruct_date = document.createElement("instruct_date");
instruct_date.setTextContent(map.get("instruct_date"));
total.appendChild(instruct_date);
Element paybankaccname = document.createElement("paybankaccname");
paybankaccname.setTextContent(map.get("paybankaccname"));
total.appendChild(paybankaccname);
Element paybankaccno = document.createElement("paybankaccno");
paybankaccno.setTextContent(map.get("paybankaccno"));
total.appendChild(paybankaccno);
Element paybank = document.createElement("paybank");
paybank.setTextContent(map.get("paybank"));
total.appendChild(paybank);
Element gatheraccname = document.createElement("gatheraccname");
gatheraccname.setTextContent(map.get("gatheraccname"));
total.appendChild(gatheraccname);
Element gatherbankno = document.createElement("gatherbankno");
gatherbankno.setTextContent(map.get("gatherbankno"));
total.appendChild(gatherbankno);
Element gatherbank = document.createElement("gatherbank");
gatherbank.setTextContent(map.get("gatherbank"));
total.appendChild(gatherbank);
Element contrbalance = document.createElement("contrbalance");
contrbalance.setTextContent(map.get("contrbalance"));
total.appendChild(contrbalance);
Element memo = document.createElement("memo");
memo.setTextContent(map.get("memo"));
total.appendChild(memo);
return document;
}
/*
* 缴费汇总单
*/
public String analysisTotalContrXml(String xml) {
BaseDAO dao = new BaseDAO();
Document doc = null;
try {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(xml)));
} catch (Exception e) {
dao.insertLog(xml, "报文解析错误," + e.getMessage(), "", "", "");
}
NodeList e = doc.getElementsByTagName("total_serial_no");
String total_serial_no = e.item(0).getTextContent();
e = doc.getElementsByTagName("areamanagecode");
String areamanagecode = e.item(0).getTextContent();
e = doc.getElementsByTagName("areamanagename");
String areamanagename = e.item(0).getTextContent();
e = doc.getElementsByTagName("trancode");
String trancode = e.item(0).getTextContent();
e = doc.getElementsByTagName("type");
String type = e.item(0).getTextContent();
e = doc.getElementsByTagName("transfer_mon_date");
String transfer_mon_date = e.item(0).getTextContent();
e = doc.getElementsByTagName("total_date");
String total_date = e.item(0).getTextContent();
e = doc.getElementsByTagName("contr_state");
String contr_state = e.item(0).getTextContent();
e = doc.getElementsByTagName("contr_total");
String contr_total = e.item(0).getTextContent();
e = doc.getElementsByTagName("actual_cash");
String actual_cash = e.item(0).getTextContent();
e = doc.getElementsByTagName("memo");
String memo = e.item(0).getTextContent();
e = doc.getElementsByTagName("typecode");
String typecode = e.item(0).getTextContent();
String result = dao.insertTotalContr(total_serial_no, areamanagecode,
areamanagename, type, transfer_mon_date, total_date,
contr_state, contr_total, actual_cash, memo, trancode);
dao.insertLog(xml, result, typecode, "", total_serial_no);
return result;
}
/**
* 解析到账标识
*
* @param xml
* @return
*/
public String analysisTypeCode(String xml) {
BaseDAO dao = new BaseDAO();
Document doc = null;
String typecode = null;
try {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
NodeList e = doc.getElementsByTagName("typecode");
typecode = e.item(0).getTextContent();
} catch (Exception e) {
dao.insertLog(xml, "报文解析错误," + e.getMessage(), "", "", "");
}
return typecode;
}
public String analysisFileName(String xml) {
BaseDAO dao = new BaseDAO();
Document doc = null;
String filename = null;
try {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
NodeList e = doc.getElementsByTagName("filename");
filename = e.item(0).getTextContent();
} catch (Exception e) {
dao.insertLog(xml, "报文解析错误," + e.getMessage(), "", "", "");
}
return filename;
}
/*
* 资金划款指令
*/
public String analysisInstructXml(String xml) {
BaseDAO dao = new BaseDAO();
Document doc = null;
try {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(xml)));
} catch (Exception e) {
dao.insertLog(xml, "报文解析错误," + e.getMessage(), "", "", "");
}
NodeList e = doc.getElementsByTagName("instruct_code");
String instruct_code = e.item(0).getTextContent();
e = doc.getElementsByTagName("instruct_date");
String instruct_date = e.item(0).getTextContent();
e = doc.getElementsByTagName("paybankaccname");
String paybankaccname = e.item(0).getTextContent();
e = doc.getElementsByTagName("paybankaccno");
String paybankaccno = e.item(0).getTextContent();
e = doc.getElementsByTagName("paybank");
String paybank = e.item(0).getTextContent();
e = doc.getElementsByTagName("gatheraccname");
String gatheraccname = e.item(0).getTextContent();
e = doc.getElementsByTagName("gatherbankno");
String gatherbankno = e.item(0).getTextContent();
e = doc.getElementsByTagName("gatherbank");
String gatherbank = e.item(0).getTextContent();
e = doc.getElementsByTagName("contrbalance");
String contrbalance = e.item(0).getTextContent();
e = doc.getElementsByTagName("memo");
String memo = e.item(0).getTextContent();
e = doc.getElementsByTagName("typecode");
String typecode = e.item(0).getTextContent();
String result = dao.insertInstruct(instruct_code, instruct_date,
paybankaccname, paybankaccno, paybank, gatheraccname,
gatherbankno, gatherbank, contrbalance, memo);
dao.insertLog(xml, result, typecode, "", instruct_code);
return result;
}
public Map<String, String> analysisgetPensionData(String xml)
throws SAXException, IOException, ParserConfigurationException {
Map<String, String> map = new HashMap<String, String>();
Document doc = null;
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(xml)));
NodeList e = doc.getElementsByTagName("appcode");
String appcode = e.item(0).getTextContent();
map.put(appcode, appcode);
e = doc.getElementsByTagName("appmsg");
String appmsg = e.item(0).getTextContent();
map.put(appmsg, appmsg);
return map;
}
}
| 22,439 | 0.637376 | 0.632033 | 499 | 43.631264 | 22.16906 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.961924 | false | false | 9 |
0b8e5ca0f031e5ad6b155d9f2f4de845860c460b | 33,492,154,998,346 | 98841c1772c74555476e10890297d3539dff2ad6 | /src/test/java/utils/ReadJson.java | 0a085161899700ab00b8c15226f5df2c67404884 | [] | no_license | HectorMorales96/challengeMandA | https://github.com/HectorMorales96/challengeMandA | 1ca5e765a2a5006912c1009d81a3ebc0c4d502d1 | 90a1472ab88c43e8d7be10022b6665230cf97cca | refs/heads/main | "2023-06-05T20:16:22.258000" | "2021-06-25T12:13:53" | "2021-06-25T12:13:53" | 379,757,533 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package utils;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.JsonObject;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ReadJson {
public JSONArray getDataFromJson(String pathToJson) {
JSONParser jsonParser = new JSONParser();
JSONArray json = null;
try {
FileReader reader = new FileReader(pathToJson);
//Read JSON file
JsonObject obj = (JsonObject) jsonParser.parse(reader);
System.out.println(obj.getAsJsonArray());
//json = (JSONArray) obj;
} catch (IOException | ParseException e) {
e.printStackTrace();
}
return json;
}
}
| UTF-8 | Java | 852 | java | ReadJson.java | Java | [] | null | [] | package utils;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.JsonObject;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ReadJson {
public JSONArray getDataFromJson(String pathToJson) {
JSONParser jsonParser = new JSONParser();
JSONArray json = null;
try {
FileReader reader = new FileReader(pathToJson);
//Read JSON file
JsonObject obj = (JsonObject) jsonParser.parse(reader);
System.out.println(obj.getAsJsonArray());
//json = (JSONArray) obj;
} catch (IOException | ParseException e) {
e.printStackTrace();
}
return json;
}
}
| 852 | 0.66784 | 0.66784 | 28 | 29.428572 | 18.934904 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.642857 | false | false | 9 |
29c4bd853cee8623ec57dfd9163d23af54035019 | 11,957,188,981,181 | f5d41cd862775fafe7bcb6fb9d2e41b0c813f482 | /teste/br/com/bbml/cm/model/FieldTest.java | 47abd9b6e5cf28ce6e496099f03d5176c0d5a6fa | [] | no_license | BBML-DEV/CampoMinado | https://github.com/BBML-DEV/CampoMinado | 472b59670bef85e6f2816d3bd48db4c81dd49a15 | a920bb08bf7d06f26ad68e6763afc3a59e8d1215 | refs/heads/master | "2023-04-17T22:07:46.966000" | "2021-04-23T04:55:57" | "2021-04-23T04:55:57" | 360,766,687 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.bbml.cm.model;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import br.com.bbml.cm.excesao.ExplosaoException;
public class FieldTest {
private Field field;
@BeforeEach
void inciarCampo() { //função pra inciiar o campo
field = new Field(3,3);
}
//Funções de teste para vizinhos nas verticais e horizontais
@Test
void testeVizinhoDistancia1Esquerda() {
Field vizinho = new Field(3,2);
boolean resultado = field.adicionarVizinho(vizinho);
assertTrue(resultado);
}
@Test
void testeVizinhoDistancia1Direita() {
Field vizinho = new Field(3,4);
boolean resultado = field.adicionarVizinho(vizinho);
assertTrue(resultado);
}
@Test
void testeVizinhoDistancia1EmCima() {
Field vizinho = new Field(2,3);
boolean resultado = field.adicionarVizinho(vizinho);
assertTrue(resultado);
}
@Test
void testeVizinhoDistancia1EmBaixo() {
Field vizinho = new Field(4,3);
boolean resultado = field.adicionarVizinho(vizinho);
assertTrue(resultado);
}
//Função para teste de vizinhos nas diagonais
@Test
void testeVizinhoRealDistanciaDiagonal() {
Field vizinho = new Field(2,2);
boolean resultado = field.adicionarVizinho(vizinho);
assertTrue(resultado);
}
//Função para teste de !vizinho
@Test
void testeNaoVizinho() {
Field vizinho = new Field(1,1);
boolean resultado = field.adicionarVizinho(vizinho);
assertFalse(resultado);
}
//função testar alternar marcação
@Test
void testeValorPadraoAtributoMarcado() {
assertFalse(field.isMarcado());
}
@Test
void testeAlternarMarcacao() {
field.alternarMarcacao();
assertTrue(field.isMarcado());
}
@Test
void testeAlternarMarcacaoDuasChamadas() {
field.alternarMarcacao();
field.alternarMarcacao();
assertFalse(field.isMarcado());
}
//Função teste para abrir o campo
@Test
void testeAbrirNaoMinadoNaoMarcado() {
assertTrue(field.abrir());
}
@Test
void testeAbrirNaoMinadoMarcado() {
field.alternarMarcacao();
assertFalse(field.abrir());
}
@Test
void testeAbrirMinadoMarcado() {
field.alternarMarcacao();
field.minar();
assertFalse(field.abrir());
}
@Test
void testeAbrirMinadoNaoMarcado() {
field.minar();
assertThrows(ExplosaoException.class, () -> {
field.abrir();
});
}
@Test
void testeAbrirComVizinhos1() {
Field field11 = new Field(1, 1);
Field field22 = new Field(2, 2);
field22.adicionarVizinho(field11);
field.adicionarVizinho(field22);
field.abrir();
assertTrue(field22.isAberto() && field11.isAberto());
}
@Test
void testeAbrirComVizinhos2() {
Field field11 = new Field(1, 1);
Field field12 = new Field(1, 1);
field12.minar();
Field field22 = new Field(2, 2);
field22.adicionarVizinho(field11);
field22.adicionarVizinho(field12);
field.adicionarVizinho(field22);
field.abrir();
assertTrue(field22.isAberto() && field11.isFechado());
}
}
| ISO-8859-1 | Java | 3,087 | java | FieldTest.java | Java | [] | null | [] | package br.com.bbml.cm.model;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import br.com.bbml.cm.excesao.ExplosaoException;
public class FieldTest {
private Field field;
@BeforeEach
void inciarCampo() { //função pra inciiar o campo
field = new Field(3,3);
}
//Funções de teste para vizinhos nas verticais e horizontais
@Test
void testeVizinhoDistancia1Esquerda() {
Field vizinho = new Field(3,2);
boolean resultado = field.adicionarVizinho(vizinho);
assertTrue(resultado);
}
@Test
void testeVizinhoDistancia1Direita() {
Field vizinho = new Field(3,4);
boolean resultado = field.adicionarVizinho(vizinho);
assertTrue(resultado);
}
@Test
void testeVizinhoDistancia1EmCima() {
Field vizinho = new Field(2,3);
boolean resultado = field.adicionarVizinho(vizinho);
assertTrue(resultado);
}
@Test
void testeVizinhoDistancia1EmBaixo() {
Field vizinho = new Field(4,3);
boolean resultado = field.adicionarVizinho(vizinho);
assertTrue(resultado);
}
//Função para teste de vizinhos nas diagonais
@Test
void testeVizinhoRealDistanciaDiagonal() {
Field vizinho = new Field(2,2);
boolean resultado = field.adicionarVizinho(vizinho);
assertTrue(resultado);
}
//Função para teste de !vizinho
@Test
void testeNaoVizinho() {
Field vizinho = new Field(1,1);
boolean resultado = field.adicionarVizinho(vizinho);
assertFalse(resultado);
}
//função testar alternar marcação
@Test
void testeValorPadraoAtributoMarcado() {
assertFalse(field.isMarcado());
}
@Test
void testeAlternarMarcacao() {
field.alternarMarcacao();
assertTrue(field.isMarcado());
}
@Test
void testeAlternarMarcacaoDuasChamadas() {
field.alternarMarcacao();
field.alternarMarcacao();
assertFalse(field.isMarcado());
}
//Função teste para abrir o campo
@Test
void testeAbrirNaoMinadoNaoMarcado() {
assertTrue(field.abrir());
}
@Test
void testeAbrirNaoMinadoMarcado() {
field.alternarMarcacao();
assertFalse(field.abrir());
}
@Test
void testeAbrirMinadoMarcado() {
field.alternarMarcacao();
field.minar();
assertFalse(field.abrir());
}
@Test
void testeAbrirMinadoNaoMarcado() {
field.minar();
assertThrows(ExplosaoException.class, () -> {
field.abrir();
});
}
@Test
void testeAbrirComVizinhos1() {
Field field11 = new Field(1, 1);
Field field22 = new Field(2, 2);
field22.adicionarVizinho(field11);
field.adicionarVizinho(field22);
field.abrir();
assertTrue(field22.isAberto() && field11.isAberto());
}
@Test
void testeAbrirComVizinhos2() {
Field field11 = new Field(1, 1);
Field field12 = new Field(1, 1);
field12.minar();
Field field22 = new Field(2, 2);
field22.adicionarVizinho(field11);
field22.adicionarVizinho(field12);
field.adicionarVizinho(field22);
field.abrir();
assertTrue(field22.isAberto() && field11.isFechado());
}
}
| 3,087 | 0.721445 | 0.699967 | 144 | 20.340279 | 18.01626 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.770833 | false | false | 9 |
aeeee59e29de69ec0ae1aa613577e2f8c811241d | 3,229,815,437,935 | 9dad389e254d4fb2f1ce06229a26f1a82dd2ad48 | /Drools-Rules/DataModel/patient/VisitInfo.java | 0575a0ccfcdbe5b1c531f0be4564c04d07e4727f | [] | no_license | ZJU-BME-VICO/openEHR-COVID-19 | https://github.com/ZJU-BME-VICO/openEHR-COVID-19 | 00fa4a3a02beca4cd7847f16f4d73ca9654db011 | db10e4948feba0912d2a1f1fbc6750db3c54b8bf | refs/heads/master | "2021-02-17T08:42:45.120000" | "2020-04-20T04:09:33" | "2020-04-20T04:09:33" | 245,084,636 | 12 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cdss.kb.core.patient;
import cdss.kb.core.Core;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import java.util.ArrayList;
import java.util.Date;
@Data
public class VisitInfo extends Core {
// 入院诊断
private ArrayList<Diagnosis> diagnoses;
// 就诊ID
private String visitId;
// 保险类型: 地方医保,地方公疗,军队医改,全费
private String insuranceType;
// 入院日期: yyyy-MM-dd HH:mm:ss
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private Date enterDate;
// 科室
private String department;
// 床号
private String bedNumber;
// 病区
private String ward;
// 负责医生
private Provider staff;
// 护理等级: 特级护理,一级护理,二级护理
private String attentionLevel;
public VisitInfo(){
diagnoses = new ArrayList<>();
staff = new Provider();
}
public void AddDiagnosis(Diagnosis diagnosis){
this.diagnoses.add(diagnosis);
}
}
| UTF-8 | Java | 1,030 | java | VisitInfo.java | Java | [] | null | [] | package cdss.kb.core.patient;
import cdss.kb.core.Core;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import java.util.ArrayList;
import java.util.Date;
@Data
public class VisitInfo extends Core {
// 入院诊断
private ArrayList<Diagnosis> diagnoses;
// 就诊ID
private String visitId;
// 保险类型: 地方医保,地方公疗,军队医改,全费
private String insuranceType;
// 入院日期: yyyy-MM-dd HH:mm:ss
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private Date enterDate;
// 科室
private String department;
// 床号
private String bedNumber;
// 病区
private String ward;
// 负责医生
private Provider staff;
// 护理等级: 特级护理,一级护理,二级护理
private String attentionLevel;
public VisitInfo(){
diagnoses = new ArrayList<>();
staff = new Provider();
}
public void AddDiagnosis(Diagnosis diagnosis){
this.diagnoses.add(diagnosis);
}
}
| 1,030 | 0.662281 | 0.662281 | 39 | 22.384615 | 14.496004 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false | 9 |
af7befcc89a478b50a895f74a814846a339568b1 | 6,193,342,872,395 | e4dec25c77a05a881b8f4e6736396d51be4800f9 | /labs/11/numberOfOccurances.java | 60cb2e47b2d4e6b8f4357574a3fb05d7e8f9aec1 | [] | no_license | melissachodziutko/cmpt220chodziutko | https://github.com/melissachodziutko/cmpt220chodziutko | 34401ada4c1edef6cfea6391b4c1cb408c0ad41b | b2f749f978337a256349cac338d9e05fb0820f23 | refs/heads/master | "2021-09-13T21:37:02.202000" | "2018-05-04T14:44:45" | "2018-05-04T14:44:45" | 117,751,453 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //package pls;
//I know i have an endless loop somewhere in here but this is pretty dang close idk how to fix it
//I also commented what everything was supposed to do in case you have a solution
import java.util.Scanner;
public class numberOfOccurances {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// prompt use for string
System.out.print("Enter a string of characters: ");
String s = input.nextLine();
char[] strng = new char[s.length() - 1];
for (int i = 0; i < strng.length; i++)
strng[i] = s.charAt(i);
char ch = s.charAt(s.length() - 1);
// print # of timrs in list
System.out.println(ch + "occurs "
+ count(strng, ch) + " times in the list ");
}
//counts how many of a character are in the array
public static int count(char[] strng, char x) {
return count(strng, x, strng.length - 1);
}
//RHM
public static int count(char[] strng, char x, int high) {
if (high < 0) {
return 0;
} else if (strng[high] == x) {
return 1 + count(strng, x, high - 1);
} else {
return count(strng, x, high - 1);
}
}
} | UTF-8 | Java | 1,100 | java | numberOfOccurances.java | Java | [] | null | [] | //package pls;
//I know i have an endless loop somewhere in here but this is pretty dang close idk how to fix it
//I also commented what everything was supposed to do in case you have a solution
import java.util.Scanner;
public class numberOfOccurances {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// prompt use for string
System.out.print("Enter a string of characters: ");
String s = input.nextLine();
char[] strng = new char[s.length() - 1];
for (int i = 0; i < strng.length; i++)
strng[i] = s.charAt(i);
char ch = s.charAt(s.length() - 1);
// print # of timrs in list
System.out.println(ch + "occurs "
+ count(strng, ch) + " times in the list ");
}
//counts how many of a character are in the array
public static int count(char[] strng, char x) {
return count(strng, x, strng.length - 1);
}
//RHM
public static int count(char[] strng, char x, int high) {
if (high < 0) {
return 0;
} else if (strng[high] == x) {
return 1 + count(strng, x, high - 1);
} else {
return count(strng, x, high - 1);
}
}
} | 1,100 | 0.643636 | 0.635455 | 39 | 27.23077 | 23.284706 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.948718 | false | false | 9 |
24f793bf0ad1a28a7eb0b6b75622bc12b4bdb4b8 | 6,193,342,869,903 | 055f4a2da481ad4ca2ea26abebbdf94db53a42ab | /SemanticAnalytics/src/JenaApp/actions/UploadAction.java | 5a9dd1fcac5309b44b72b3acee8c8961626752bf | [] | no_license | RaulRC/PFC_JenaDQ | https://github.com/RaulRC/PFC_JenaDQ | 6fc807c3d4ccb63f55eaa8e489a1f4ae282dfaa1 | 7a516c5559168af0ecc7f3ae68491141ead74ca7 | refs/heads/master | "2021-01-15T20:24:26.319000" | "2015-04-15T20:05:04" | "2015-04-15T20:05:04" | 99,849,136 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package JenaApp.actions;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.Map;
import utilidades.DQModel;
import utilidades.DataPicker;
import utilidades.Operation;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private File file;
private String filename;
private String format;
private Model model;
private String uri;
private LinkedList<Property> modelProperties;
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public Model getModel() {
return model;
}
public void setModel(Model model) {
this.model = model;
}
public LinkedList<Property> getModelProperties() {
return modelProperties;
}
public void setModelProperties(LinkedList<Property> modelProperties) {
this.modelProperties = modelProperties;
}
public void setUpload(File file) {
this.file = file;
}
public void setUploadFileName(String filename) {
this.filename = filename;
}
public String execute() {
Map<String, Object> session = ActionContext.getContext().getSession(); // Get session
DataPicker dp = new DataPicker();
try{
InputStream in = new FileInputStream(this.file);
DQModel dq;
dq = new DQModel(in, dp.checkFormat(filename));
// Not neccessary output stream, just read.
setFormat(dq.getFormat());
setModel(dq.getModel());
dq.showModelWithFormat(getFormat());
Operation oper = new Operation(dq.getModel());
setModelProperties(oper.getAllProperties());
session.put("model", dq.getModel());
setUri("Local file");
in.close();
} catch (IOException e){
System.out.println(e.toString());
return ERROR;
}
return SUCCESS;
}
} | UTF-8 | Java | 2,193 | java | UploadAction.java | Java | [] | null | [] | package JenaApp.actions;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.Map;
import utilidades.DQModel;
import utilidades.DataPicker;
import utilidades.Operation;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private File file;
private String filename;
private String format;
private Model model;
private String uri;
private LinkedList<Property> modelProperties;
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public Model getModel() {
return model;
}
public void setModel(Model model) {
this.model = model;
}
public LinkedList<Property> getModelProperties() {
return modelProperties;
}
public void setModelProperties(LinkedList<Property> modelProperties) {
this.modelProperties = modelProperties;
}
public void setUpload(File file) {
this.file = file;
}
public void setUploadFileName(String filename) {
this.filename = filename;
}
public String execute() {
Map<String, Object> session = ActionContext.getContext().getSession(); // Get session
DataPicker dp = new DataPicker();
try{
InputStream in = new FileInputStream(this.file);
DQModel dq;
dq = new DQModel(in, dp.checkFormat(filename));
// Not neccessary output stream, just read.
setFormat(dq.getFormat());
setModel(dq.getModel());
dq.showModelWithFormat(getFormat());
Operation oper = new Operation(dq.getModel());
setModelProperties(oper.getAllProperties());
session.put("model", dq.getModel());
setUri("Local file");
in.close();
} catch (IOException e){
System.out.println(e.toString());
return ERROR;
}
return SUCCESS;
}
} | 2,193 | 0.723666 | 0.722298 | 99 | 21.161615 | 18.751272 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.606061 | false | false | 9 |
39b4c58ccce23a52442f6f6684bfc2c985ccb543 | 5,265,629,934,299 | 85b23692b14ef29e394f453c29e4451a40cf3903 | /library_base/src/main/java/com/example/library_base/config/SharedPreferencesKey.java | 653b0c0db216d3e0222d12db590e07ec3f556cdd | [] | no_license | ljrRookie/Mix | https://github.com/ljrRookie/Mix | a0bd48cc78e00688a47153afc7e6ff06d93d51dc | c8c1959c667f95fe316d38a8a026b11f3aa5c1fe | refs/heads/master | "2020-04-16T01:19:43.420000" | "2019-01-25T10:20:23" | "2019-01-25T10:20:23" | 165,169,149 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.library_base.config;
public class SharedPreferencesKey {
public static String TABLE_PREFS = "app_config";
public static String SP_USER = "user_config";
public static String USER_LOGIN = "user_islogin";
public static String USER_ID = "user_id";
public static String USER_NAME = "user_name";
}
| UTF-8 | Java | 336 | java | SharedPreferencesKey.java | Java | [
{
"context": "config\";\n\n\n public static String USER_LOGIN = \"user_islogin\";\n public static String USER_ID = \"user_id\";\n ",
"end": 235,
"score": 0.9932171106338501,
"start": 223,
"tag": "USERNAME",
"value": "user_islogin"
},
{
"context": "ser_islogin\";\n public static String USER_ID = \"user_id\";\n public static String USER_NAME = \"user_name",
"end": 281,
"score": 0.9884936213493347,
"start": 274,
"tag": "USERNAME",
"value": "user_id"
},
{
"context": " \"user_id\";\n public static String USER_NAME = \"user_name\";\n}\n",
"end": 331,
"score": 0.999493420124054,
"start": 322,
"tag": "USERNAME",
"value": "user_name"
}
] | null | [] | package com.example.library_base.config;
public class SharedPreferencesKey {
public static String TABLE_PREFS = "app_config";
public static String SP_USER = "user_config";
public static String USER_LOGIN = "user_islogin";
public static String USER_ID = "user_id";
public static String USER_NAME = "user_name";
}
| 336 | 0.708333 | 0.708333 | 12 | 27 | 23.126465 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
a8f244f001807e5f48d4fe232a39f1020c308bf3 | 11,149,735,141,053 | dfa9576fb9f08f5865371858e4474d8a0c4dd8a1 | /ydq_device/src/main/java/com/conagra/di/interactor/bloodsugar/BloodSugarIsExist.java | 061892716e80f3caa1d04b09e91f2d108e168293 | [] | no_license | dongqin50/IOCDemo | https://github.com/dongqin50/IOCDemo | a79a1abf3d49f130e67d0279a6fa0d6790517765 | 08689bcacdc00ec1fff6a412e2c8e0b43bc9cc17 | refs/heads/master | "2022-12-10T01:49:57.806000" | "2020-09-17T22:50:57" | "2020-09-17T22:50:57" | 296,457,960 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.conagra.di.interactor.bloodsugar;
import com.conagra.di.UseCase;
import com.conagra.di.repository.BloodSugarRepository;
import java.util.Map;
import javax.inject.Inject;
import rx.Observable;
/**
* Created by yedongqin on 2017/10/29.
*/
public class BloodSugarIsExist extends UseCase {
/**
* 患者ID
*/
public final static String CUSTOMER_ID = "CustomerID";
/**
* 时间类型
*/
public final static String TIME_SLOT = "TimeSlot";
private BloodSugarRepository repository;
@Inject
public BloodSugarIsExist(BloodSugarRepository repository) {
this.repository = repository;
}
@Override
protected Observable buildUseCaseObservable(Object params) {
return repository.isExistBloodSugar(getBody(buildJsonBody((Map) params)));
}
}
| UTF-8 | Java | 828 | java | BloodSugarIsExist.java | Java | [
{
"context": ".Inject;\n\nimport rx.Observable;\n\n/**\n * Created by yedongqin on 2017/10/29.\n */\n\npublic class BloodSugarIsExis",
"end": 236,
"score": 0.9995952844619751,
"start": 227,
"tag": "USERNAME",
"value": "yedongqin"
}
] | null | [] | package com.conagra.di.interactor.bloodsugar;
import com.conagra.di.UseCase;
import com.conagra.di.repository.BloodSugarRepository;
import java.util.Map;
import javax.inject.Inject;
import rx.Observable;
/**
* Created by yedongqin on 2017/10/29.
*/
public class BloodSugarIsExist extends UseCase {
/**
* 患者ID
*/
public final static String CUSTOMER_ID = "CustomerID";
/**
* 时间类型
*/
public final static String TIME_SLOT = "TimeSlot";
private BloodSugarRepository repository;
@Inject
public BloodSugarIsExist(BloodSugarRepository repository) {
this.repository = repository;
}
@Override
protected Observable buildUseCaseObservable(Object params) {
return repository.isExistBloodSugar(getBody(buildJsonBody((Map) params)));
}
}
| 828 | 0.702206 | 0.692402 | 39 | 19.923077 | 23.144346 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.282051 | false | false | 9 |
fd41f03a97417dc44e70f693fc28dd031467864b | 4,312,147,208,055 | e918e6c5bf32b62764653efe75df345971169efa | /eCare/src/main/java/com/t_systems/ecare/eCare/services/UserServiceImpl.java | 3ce9f8543c200e9367d43c18e60f3d821f730025 | [] | no_license | denq007/FullEcarePlusStand | https://github.com/denq007/FullEcarePlusStand | cc56534ca6f2abb45af0323810fd1f05b103ecb4 | 0d667c5263e9cc4caf18e29d5435f4fa0b9a0a96 | refs/heads/master | "2023-07-29T02:45:10.676000" | "2021-09-14T16:28:33" | "2021-09-14T16:28:33" | 373,523,846 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.t_systems.ecare.eCare.services;
import com.t_systems.ecare.eCare.DAO.ContractDao;
import com.t_systems.ecare.eCare.DAO.CustomerDAOImpl;
import com.t_systems.ecare.eCare.DAO.UserDao;
import com.t_systems.ecare.eCare.DTO.UserDTO;
import com.t_systems.ecare.eCare.entity.Contract;
import com.t_systems.ecare.eCare.entity.Customer;
import com.t_systems.ecare.eCare.entity.Role;
import com.t_systems.ecare.eCare.entity.User;
import org.apache.log4j.Logger;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Autowired
CustomerDAOImpl customerDAO;
@Autowired
private ModelMapper modelMapper;
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
ContractDao contractDao;
private static final Logger logger = org.apache.log4j.Logger.getLogger(UserServiceImpl.class);
/**
* Transforms the User to UserDTO
*
* @param user database {@code User} object
* @return userDTO (@code UserDTO)
*/
public UserDTO convertToDto(User user) {
return modelMapper.map(user, UserDTO.class);
}
/**
* Transforms the UserDTO to User
*
* @param userDto data transfer object
* @return
*/
public User convertToEntity(UserDTO userDto) {
User userEntity = modelMapper.map(userDto, User.class);
userEntity.setPassword(passwordEncoder.encode(userDto.getUserPassword()));
return userEntity;
}
/**
* Set block property of specific contract to true with role EMPLOYEE
*
* @param id id of {@code Contract} to block
* @return id of {@code Contract} to block
*/
@Override
public int blockByEmployee(int id) {
Contract contract = contractDao.findOne(id);
contract.setBlockedByAdmin(true);
contractDao.update(contract);
return contract.getCustomerId().getId();
}
/**
* Set block property of specific contract to false with role EMPLOYEE
*
* @param id id of {@code Contract} to unblock
* @return id of {@code Contract} to unblock
*/
@Override
public int unblockByEmployee(int id) {
Contract contract = contractDao.findOne(id);
contract.setBlockedByAdmin(false);
contractDao.update(contract);
return contract.getCustomerId().getId();
}
/**
* Set block property of specific contract to true with role CUSTOMER;
*
* @param id id of {@code Contract} to block
*/
@Override
public void blockByCustomer(int id) {
Contract contract = contractDao.findOne(id);
contract.setBlockedByUser(true);
contractDao.update(contract);
}
/**
* Set block property of specific contract to false with role CUSTOMER;
*
* @param id id of {@code Contract} to unblock
*/
@Override
public void unblockByCustomer(int id) {
Contract contract = contractDao.findOne(id);
contract.setBlockedByUser(false);
contractDao.update(contract);
}
/**
* Save new {@code User} based on dto properties with role CUSTOMER.User must be unique.
*
* @param user dto data transfer object contains required properties
* @return empty Optional if user is successfully created or error message if not
*/
@Transactional
public Optional<String> saveUser(UserDTO user) {
User fromDB = userDao.getUserByUsername(user.getUserLogin());
if (fromDB != null) {
return Optional.of("This user is already registered");
}
fromDB = new User();
fromDB.setRole(Role.ROLE_CUSTOMER);
fromDB.setPassword(passwordEncoder.encode(user.getUserPassword()));
fromDB.setLogin(user.getUserLogin());
user.setUserId(fromDB.getId());
user.setUserRole(Role.ROLE_CUSTOMER);
Customer customer = new Customer();
customer.setUser(fromDB);
customerDAO.save(customer);
return Optional.empty();
}
/**
* User Search based user
*
* @param user
*/
public void findUserByName(User user) {
userDao.getUserByUsername(user.getLogin());
}
/**
* User authentication using the method - HttpServletRequest.login()
*
* @param request
* @param username
* @param password
*/
public void authWithHttpServletRequest(HttpServletRequest request, String username, String password) {
try {
request.login(username, password);
} catch (ServletException e) {
logger.info("Error while login " + e.getMessage());
}
}
}
| UTF-8 | Java | 5,033 | java | UserServiceImpl.java | Java | [] | null | [] | package com.t_systems.ecare.eCare.services;
import com.t_systems.ecare.eCare.DAO.ContractDao;
import com.t_systems.ecare.eCare.DAO.CustomerDAOImpl;
import com.t_systems.ecare.eCare.DAO.UserDao;
import com.t_systems.ecare.eCare.DTO.UserDTO;
import com.t_systems.ecare.eCare.entity.Contract;
import com.t_systems.ecare.eCare.entity.Customer;
import com.t_systems.ecare.eCare.entity.Role;
import com.t_systems.ecare.eCare.entity.User;
import org.apache.log4j.Logger;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Autowired
CustomerDAOImpl customerDAO;
@Autowired
private ModelMapper modelMapper;
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
ContractDao contractDao;
private static final Logger logger = org.apache.log4j.Logger.getLogger(UserServiceImpl.class);
/**
* Transforms the User to UserDTO
*
* @param user database {@code User} object
* @return userDTO (@code UserDTO)
*/
public UserDTO convertToDto(User user) {
return modelMapper.map(user, UserDTO.class);
}
/**
* Transforms the UserDTO to User
*
* @param userDto data transfer object
* @return
*/
public User convertToEntity(UserDTO userDto) {
User userEntity = modelMapper.map(userDto, User.class);
userEntity.setPassword(passwordEncoder.encode(userDto.getUserPassword()));
return userEntity;
}
/**
* Set block property of specific contract to true with role EMPLOYEE
*
* @param id id of {@code Contract} to block
* @return id of {@code Contract} to block
*/
@Override
public int blockByEmployee(int id) {
Contract contract = contractDao.findOne(id);
contract.setBlockedByAdmin(true);
contractDao.update(contract);
return contract.getCustomerId().getId();
}
/**
* Set block property of specific contract to false with role EMPLOYEE
*
* @param id id of {@code Contract} to unblock
* @return id of {@code Contract} to unblock
*/
@Override
public int unblockByEmployee(int id) {
Contract contract = contractDao.findOne(id);
contract.setBlockedByAdmin(false);
contractDao.update(contract);
return contract.getCustomerId().getId();
}
/**
* Set block property of specific contract to true with role CUSTOMER;
*
* @param id id of {@code Contract} to block
*/
@Override
public void blockByCustomer(int id) {
Contract contract = contractDao.findOne(id);
contract.setBlockedByUser(true);
contractDao.update(contract);
}
/**
* Set block property of specific contract to false with role CUSTOMER;
*
* @param id id of {@code Contract} to unblock
*/
@Override
public void unblockByCustomer(int id) {
Contract contract = contractDao.findOne(id);
contract.setBlockedByUser(false);
contractDao.update(contract);
}
/**
* Save new {@code User} based on dto properties with role CUSTOMER.User must be unique.
*
* @param user dto data transfer object contains required properties
* @return empty Optional if user is successfully created or error message if not
*/
@Transactional
public Optional<String> saveUser(UserDTO user) {
User fromDB = userDao.getUserByUsername(user.getUserLogin());
if (fromDB != null) {
return Optional.of("This user is already registered");
}
fromDB = new User();
fromDB.setRole(Role.ROLE_CUSTOMER);
fromDB.setPassword(passwordEncoder.encode(user.getUserPassword()));
fromDB.setLogin(user.getUserLogin());
user.setUserId(fromDB.getId());
user.setUserRole(Role.ROLE_CUSTOMER);
Customer customer = new Customer();
customer.setUser(fromDB);
customerDAO.save(customer);
return Optional.empty();
}
/**
* User Search based user
*
* @param user
*/
public void findUserByName(User user) {
userDao.getUserByUsername(user.getLogin());
}
/**
* User authentication using the method - HttpServletRequest.login()
*
* @param request
* @param username
* @param password
*/
public void authWithHttpServletRequest(HttpServletRequest request, String username, String password) {
try {
request.login(username, password);
} catch (ServletException e) {
logger.info("Error while login " + e.getMessage());
}
}
}
| 5,033 | 0.671766 | 0.671369 | 158 | 30.854431 | 24.223597 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.405063 | false | false | 9 |
0363155ae9ee68f0914419f005b29255e4c41778 | 30,520,037,642,935 | e7fd210d2c6bdff87723b1363459936c1644271a | /app/src/main/java/nikhanch/com/sfbandroidchatbubbles/ApplicationService/CommunicationManager/GetMessagingInviteResponse.java | 15c231716ef919d7670f40adada5e72fe2b6235d | [] | no_license | nikhanch/SfBChatBubbles | https://github.com/nikhanch/SfBChatBubbles | 868bb3cf16f020b17de9112394158cf71332eb64 | 1236ede164d8d0f770da113781b52a02475017f5 | refs/heads/master | "2021-01-10T07:07:37.206000" | "2015-10-07T01:10:46" | "2015-10-07T01:10:46" | 43,283,068 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package nikhanch.com.sfbandroidchatbubbles.ApplicationService.CommunicationManager;
import com.google.gson.annotations.SerializedName;
/**
* Created by nikhanch on 10/1/2015.
*/
public class GetMessagingInviteResponse {
@SerializedName("direction")
public String direction;
@SerializedName("importance")
public String importance;
@SerializedName("threadId")
public String threadId;
@SerializedName("state")
public String state;
@SerializedName("operationId")
public String operationId;
@SerializedName("subject")
public String subject;
@SerializedName("_links")
public nikhanch.com.sfbandroidchatbubbles.ApplicationService.CommunicationManager.GetMessagingInviteResponse.Links Links;
@SerializedName("rel")
public String rel;
public GetMessagingInviteResponse(String direction, String importance, String threadId, String state, String operationId, String subject, nikhanch.com.sfbandroidchatbubbles.ApplicationService.CommunicationManager.GetMessagingInviteResponse.Links Links, String rel) {
this.direction = direction;
this.importance = importance;
this.threadId = threadId;
this.state = state;
this.operationId = operationId;
this.subject = subject;
this.Links = Links;
this.rel = rel;
}
public class Cancel {
@SerializedName("href")
public String href;
public Cancel(String href) {
this.href = href;
}
}
public class Conversation {
@SerializedName("href")
public String href;
public Conversation(String href) {
this.href = href;
}
}
public class From {
@SerializedName("href")
public String href;
@SerializedName("title")
public String title;
public From(String href, String title) {
this.href = href;
this.title = title;
}
}
public class Links {
@SerializedName("self")
public Self self;
@SerializedName("from")
public From from;
@SerializedName("to")
public To to;
@SerializedName("cancel")
public Cancel cancel;
@SerializedName("conversation")
public Conversation conversation;
@SerializedName("messaging")
public Messaging messaging;
public Links(Self self, From from, To to, Cancel cancel, Conversation conversation, Messaging messaging) {
this.self = self;
this.from = from;
this.to = to;
this.cancel = cancel;
this.conversation = conversation;
this.messaging = messaging;
}
}
public class Messaging {
@SerializedName("href")
public String href;
public Messaging(String href) {
this.href = href;
}
}
public class Self {
@SerializedName("href")
public String href;
public Self(String href) {
this.href = href;
}
}
public class To {
@SerializedName("href")
public String href;
public To(String href) {
this.href = href;
}
}
}
| UTF-8 | Java | 3,222 | java | GetMessagingInviteResponse.java | Java | [
{
"context": "son.annotations.SerializedName;\n\n/**\n * Created by nikhanch on 10/1/2015.\n */\npublic class GetMessagingInvite",
"end": 163,
"score": 0.9996848106384277,
"start": 155,
"tag": "USERNAME",
"value": "nikhanch"
}
] | null | [] | package nikhanch.com.sfbandroidchatbubbles.ApplicationService.CommunicationManager;
import com.google.gson.annotations.SerializedName;
/**
* Created by nikhanch on 10/1/2015.
*/
public class GetMessagingInviteResponse {
@SerializedName("direction")
public String direction;
@SerializedName("importance")
public String importance;
@SerializedName("threadId")
public String threadId;
@SerializedName("state")
public String state;
@SerializedName("operationId")
public String operationId;
@SerializedName("subject")
public String subject;
@SerializedName("_links")
public nikhanch.com.sfbandroidchatbubbles.ApplicationService.CommunicationManager.GetMessagingInviteResponse.Links Links;
@SerializedName("rel")
public String rel;
public GetMessagingInviteResponse(String direction, String importance, String threadId, String state, String operationId, String subject, nikhanch.com.sfbandroidchatbubbles.ApplicationService.CommunicationManager.GetMessagingInviteResponse.Links Links, String rel) {
this.direction = direction;
this.importance = importance;
this.threadId = threadId;
this.state = state;
this.operationId = operationId;
this.subject = subject;
this.Links = Links;
this.rel = rel;
}
public class Cancel {
@SerializedName("href")
public String href;
public Cancel(String href) {
this.href = href;
}
}
public class Conversation {
@SerializedName("href")
public String href;
public Conversation(String href) {
this.href = href;
}
}
public class From {
@SerializedName("href")
public String href;
@SerializedName("title")
public String title;
public From(String href, String title) {
this.href = href;
this.title = title;
}
}
public class Links {
@SerializedName("self")
public Self self;
@SerializedName("from")
public From from;
@SerializedName("to")
public To to;
@SerializedName("cancel")
public Cancel cancel;
@SerializedName("conversation")
public Conversation conversation;
@SerializedName("messaging")
public Messaging messaging;
public Links(Self self, From from, To to, Cancel cancel, Conversation conversation, Messaging messaging) {
this.self = self;
this.from = from;
this.to = to;
this.cancel = cancel;
this.conversation = conversation;
this.messaging = messaging;
}
}
public class Messaging {
@SerializedName("href")
public String href;
public Messaging(String href) {
this.href = href;
}
}
public class Self {
@SerializedName("href")
public String href;
public Self(String href) {
this.href = href;
}
}
public class To {
@SerializedName("href")
public String href;
public To(String href) {
this.href = href;
}
}
}
| 3,222 | 0.616698 | 0.614525 | 118 | 26.305084 | 29.703196 | 270 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.483051 | false | false | 9 |
33fdbaee01117ee9740d434233ec3071be821968 | 10,763,188,091,982 | d139d8ce3c62c982de11779f2d6723547cfb8056 | /proyectoFinal/src/JFrames/JFCuidador.java | 67a28bdf6d38a79d689883e5273d4e7278f67431 | [] | no_license | riagma5/Final-POO | https://github.com/riagma5/Final-POO | 19eb7379b941c275e00ca05e7106a17cf8a137ac | 672d1fc2cdd58e4adb033031c55685fe341b2bbe | refs/heads/master | "2022-04-19T01:44:57.526000" | "2020-04-22T00:18:06" | "2020-04-22T00:18:06" | 251,187,241 | 2 | 1 | null | false | "2020-04-20T04:38:55" | "2020-03-30T03:02:46" | "2020-04-18T00:30:23" | "2020-04-20T04:38:54" | 2,475 | 2 | 1 | 0 | Java | false | false | package JFrames;
import java.util.ArrayList;
import BackEnd.Carer;
import static JFrames.JFLogin.getConection;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Time;
import javax.swing.*;
public class JFCuidador extends javax.swing.JFrame {
PreparedStatement ps;
ResultSet sr;
protected JFMenu menu;
private String searchCarer;
private int j;
private void cleanBox() {
carerNameField.setText(null);
carerDirectionField.setText(null);
carerStartDateField.setText(null);
carerHourField.setText(null);
}
public JFCuidador() {
initComponents();
}
public JFCuidador(JFMenu menu, ArrayList<Carer> carerList) {
super();
initComponents();
setLocationRelativeTo(null);
this.menu = menu;
menu.carerList = carerList;
searchCarer = "";
j = 0;
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
carerPanel = new javax.swing.JPanel();
carerTxt = new javax.swing.JLabel();
carerGoBackButton = new javax.swing.JButton();
carerSaveButton = new javax.swing.JButton();
carerDeleteButton = new javax.swing.JButton();
carerChangeButton = new javax.swing.JButton();
carerSearchButton = new javax.swing.JButton();
carerNameTxt = new javax.swing.JLabel();
carerNameField = new javax.swing.JTextField();
carerDirectionField = new javax.swing.JTextField();
carerDirectionTxt = new javax.swing.JLabel();
carerStartDateTxt = new javax.swing.JLabel();
carerHourTxt = new javax.swing.JLabel();
carerStartDateField = new javax.swing.JFormattedTextField();
carerHourField = new javax.swing.JFormattedTextField();
txtId = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
carerPanel.setBackground(new java.awt.Color(102, 204, 255));
carerTxt.setFont(new java.awt.Font("Arial Black", 1, 24)); // NOI18N
carerTxt.setForeground(new java.awt.Color(255, 255, 255));
carerTxt.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
carerTxt.setText("Cuidador");
carerGoBackButton.setBackground(new java.awt.Color(102, 153, 255));
carerGoBackButton.setFont(new java.awt.Font("Arial Black", 1, 13)); // NOI18N
carerGoBackButton.setForeground(new java.awt.Color(255, 255, 255));
carerGoBackButton.setText("Regresar");
carerGoBackButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
carerGoBackButtonActionPerformed(evt);
}
});
carerSaveButton.setBackground(new java.awt.Color(102, 153, 255));
carerSaveButton.setFont(new java.awt.Font("Arial Black", 1, 13)); // NOI18N
carerSaveButton.setForeground(new java.awt.Color(255, 255, 255));
carerSaveButton.setText("Guardar");
carerSaveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
carerSaveButtonActionPerformed(evt);
}
});
carerDeleteButton.setBackground(new java.awt.Color(102, 153, 255));
carerDeleteButton.setFont(new java.awt.Font("Arial Black", 1, 13)); // NOI18N
carerDeleteButton.setForeground(new java.awt.Color(255, 255, 255));
carerDeleteButton.setText("Eliminar");
carerDeleteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
carerDeleteButtonActionPerformed(evt);
}
});
carerChangeButton.setBackground(new java.awt.Color(102, 153, 255));
carerChangeButton.setFont(new java.awt.Font("Arial Black", 1, 13)); // NOI18N
carerChangeButton.setForeground(new java.awt.Color(255, 255, 255));
carerChangeButton.setText("Modificar");
carerChangeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
carerChangeButtonActionPerformed(evt);
}
});
carerSearchButton.setBackground(new java.awt.Color(102, 153, 255));
carerSearchButton.setFont(new java.awt.Font("Arial Black", 1, 13)); // NOI18N
carerSearchButton.setForeground(new java.awt.Color(255, 255, 255));
carerSearchButton.setText("Buscar");
carerSearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
carerSearchButtonActionPerformed(evt);
}
});
carerNameTxt.setFont(new java.awt.Font("Arial", 0, 13)); // NOI18N
carerNameTxt.setForeground(new java.awt.Color(255, 255, 255));
carerNameTxt.setText("Nombre y Apellido");
carerNameField.setBackground(new java.awt.Color(102, 153, 255));
carerNameField.setFont(new java.awt.Font("Arial", 0, 13)); // NOI18N
carerNameField.setForeground(new java.awt.Color(255, 255, 255));
carerNameField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
carerNameFieldActionPerformed(evt);
}
});
carerDirectionField.setBackground(new java.awt.Color(102, 153, 255));
carerDirectionField.setFont(new java.awt.Font("Arial", 0, 13)); // NOI18N
carerDirectionField.setForeground(new java.awt.Color(255, 255, 255));
carerDirectionTxt.setFont(new java.awt.Font("Arial", 0, 13)); // NOI18N
carerDirectionTxt.setForeground(new java.awt.Color(255, 255, 255));
carerDirectionTxt.setText("Dirección");
carerStartDateTxt.setFont(new java.awt.Font("Arial", 0, 13)); // NOI18N
carerStartDateTxt.setForeground(new java.awt.Color(255, 255, 255));
carerStartDateTxt.setText("Fecha de Contratación");
carerHourTxt.setFont(new java.awt.Font("Arial", 0, 13)); // NOI18N
carerHourTxt.setForeground(new java.awt.Color(255, 255, 255));
carerHourTxt.setText("Hora");
carerStartDateField.setBackground(new java.awt.Color(102, 153, 255));
carerStartDateField.setForeground(new java.awt.Color(255, 255, 255));
try {
carerStartDateField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####-##-##")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
carerHourField.setBackground(new java.awt.Color(102, 153, 255));
carerHourField.setForeground(new java.awt.Color(255, 255, 255));
try {
carerHourField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##:##")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
txtId.setBackground(new java.awt.Color(102, 204, 255));
txtId.setEnabled(false);
jButton1.setText("Mostrar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout carerPanelLayout = new javax.swing.GroupLayout(carerPanel);
carerPanel.setLayout(carerPanelLayout);
carerPanelLayout.setHorizontalGroup(
carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(carerPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(carerGoBackButton)
.addContainerGap(407, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, carerPanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(carerHourField, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(carerHourTxt)
.addComponent(carerStartDateTxt)
.addGroup(carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(carerPanelLayout.createSequentialGroup()
.addGroup(carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(carerDirectionField, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(carerDirectionTxt)
.addComponent(carerNameTxt)
.addGroup(carerPanelLayout.createSequentialGroup()
.addGroup(carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton1)
.addGroup(carerPanelLayout.createSequentialGroup()
.addComponent(carerSaveButton)
.addGap(18, 18, 18)
.addComponent(carerDeleteButton, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(carerChangeButton)))
.addGap(105, 105, 105))
.addGroup(carerPanelLayout.createSequentialGroup()
.addComponent(carerNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(carerSearchButton)
.addContainerGap()))
.addComponent(carerStartDateField, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(carerPanelLayout.createSequentialGroup()
.addGap(221, 221, 221)
.addComponent(carerTxt)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(21, 21, 21))
);
carerPanelLayout.setVerticalGroup(
carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(carerPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(carerTxt)
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(40, 40, 40)
.addComponent(carerNameTxt)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(carerNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(carerSearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(carerDirectionTxt)
.addGap(16, 16, 16)
.addComponent(carerDirectionField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(carerStartDateTxt)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(carerStartDateField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(carerHourTxt)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(carerHourField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE)
.addGroup(carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(carerSaveButton)
.addComponent(carerDeleteButton, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(carerChangeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(40, 40, 40)
.addGroup(carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(carerGoBackButton)
.addComponent(jButton1))
.addGap(16, 16, 16))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(carerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(carerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void carerGoBackButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_carerGoBackButtonActionPerformed
this.dispose();
menu.setVisible(true);
}//GEN-LAST:event_carerGoBackButtonActionPerformed
private void carerSaveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_carerSaveButtonActionPerformed
Connection con = null;
try {
con = getConection();
ps = con.prepareStatement("INSERT INTO cuidador (nombre, direccionCuidador, inicioCuidador, horaCuidador) VALUES(?,?,?,?) ");
ps.setString(1, carerNameField.getText());
ps.setString(2, carerDirectionField.getText());
ps.setDate(3,Date.valueOf(carerStartDateField.getText()));
ps.setTime(4, Time.valueOf(carerHourField.getText()));
int res = ps.executeUpdate();
if(res > 0){
JOptionPane.showMessageDialog(null, "Persona Guardada");
cleanBox();
} else {
JOptionPane.showMessageDialog(null, "Error al Guardar persona");
cleanBox();
}
con.close();
} catch(Exception e){
System.out.println(e);
}
}//GEN-LAST:event_carerSaveButtonActionPerformed
private void carerDeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_carerDeleteButtonActionPerformed
Connection con = null;
try {
con = getConection();
ps = con.prepareStatement("DELETE FROM cuidador WHERE nombre=?");
ps.setString(1, carerNameField.getText());
int res = ps.executeUpdate();
if(res > 0){
JOptionPane.showMessageDialog(null, "Persona eliminada");
cleanBox();
carerSaveButton.setEnabled(true);
} else {
JOptionPane.showMessageDialog(null, "Error al eliminar persona");
cleanBox();
carerSaveButton.setEnabled(true);
}
con.close();
} catch(Exception e){
System.out.println(e);
}
}//GEN-LAST:event_carerDeleteButtonActionPerformed
private void carerChangeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_carerChangeButtonActionPerformed
Connection con = null;
try {
con = getConection();
ps = con.prepareStatement("UPDATE cuidador SET nombre=?, direccionCuidador=?, inicioCuidador=? WHERE horaCuidador =?");
ps.setString(1, carerNameField.getText());
ps.setString(2, carerDirectionField.getText());
ps.setDate(3,Date.valueOf(carerStartDateField.getText()));
ps.setTime(4, Time.valueOf(carerHourField.getText()));
int res = ps.executeUpdate();
if(res > 0){
JOptionPane.showMessageDialog(null, "Persona Modificada");
cleanBox();
carerSaveButton.setEnabled(true);
} else {
JOptionPane.showMessageDialog(null, "Error al Modificar persona");
cleanBox();
carerSaveButton.setEnabled(true);
}
con.close();
} catch(Exception e){
System.out.println(e);
}
}//GEN-LAST:event_carerChangeButtonActionPerformed
private void carerSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_carerSearchButtonActionPerformed
carerSaveButton.setEnabled(false);
com.mysql.jdbc.Connection con = null;
try{
con = (com.mysql.jdbc.Connection) getConection();
ps = con.prepareStatement("SELECT * FROM cuidador WHERE nombre = ?");
ps.setString(1, carerNameField.getText());
ResultSet rs = ps.executeQuery();
if(rs.next()){
carerNameField.setText(rs.getString("nombre"));
carerDirectionField.setText(rs.getString("direccionCuidador"));
carerStartDateField.setText(rs.getString("inicioCuidador"));
carerHourField.setText(rs.getString("horaCuidador"));
} else {
JOptionPane.showMessageDialog(null, "No existe una persona con ese nombre");
}
} catch(Exception e){
System.err.println(e);
}
}//GEN-LAST:event_carerSearchButtonActionPerformed
private void carerNameFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_carerNameFieldActionPerformed
}//GEN-LAST:event_carerNameFieldActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
JFMostrarCuidador mostrarCuidador = new JFMostrarCuidador();
setLocationRelativeTo(null);
mostrarCuidador.setVisible(true);
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(JFCuidador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JFCuidador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JFCuidador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JFCuidador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JFCuidador().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton carerChangeButton;
private javax.swing.JButton carerDeleteButton;
private javax.swing.JTextField carerDirectionField;
private javax.swing.JLabel carerDirectionTxt;
private javax.swing.JButton carerGoBackButton;
private javax.swing.JFormattedTextField carerHourField;
private javax.swing.JLabel carerHourTxt;
private javax.swing.JTextField carerNameField;
private javax.swing.JLabel carerNameTxt;
private javax.swing.JPanel carerPanel;
private javax.swing.JButton carerSaveButton;
private javax.swing.JButton carerSearchButton;
private javax.swing.JFormattedTextField carerStartDateField;
private javax.swing.JLabel carerStartDateTxt;
private javax.swing.JLabel carerTxt;
private javax.swing.JButton jButton1;
private javax.swing.JTextField txtId;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 23,087 | java | JFCuidador.java | Java | [] | null | [] | package JFrames;
import java.util.ArrayList;
import BackEnd.Carer;
import static JFrames.JFLogin.getConection;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Time;
import javax.swing.*;
public class JFCuidador extends javax.swing.JFrame {
PreparedStatement ps;
ResultSet sr;
protected JFMenu menu;
private String searchCarer;
private int j;
private void cleanBox() {
carerNameField.setText(null);
carerDirectionField.setText(null);
carerStartDateField.setText(null);
carerHourField.setText(null);
}
public JFCuidador() {
initComponents();
}
public JFCuidador(JFMenu menu, ArrayList<Carer> carerList) {
super();
initComponents();
setLocationRelativeTo(null);
this.menu = menu;
menu.carerList = carerList;
searchCarer = "";
j = 0;
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
carerPanel = new javax.swing.JPanel();
carerTxt = new javax.swing.JLabel();
carerGoBackButton = new javax.swing.JButton();
carerSaveButton = new javax.swing.JButton();
carerDeleteButton = new javax.swing.JButton();
carerChangeButton = new javax.swing.JButton();
carerSearchButton = new javax.swing.JButton();
carerNameTxt = new javax.swing.JLabel();
carerNameField = new javax.swing.JTextField();
carerDirectionField = new javax.swing.JTextField();
carerDirectionTxt = new javax.swing.JLabel();
carerStartDateTxt = new javax.swing.JLabel();
carerHourTxt = new javax.swing.JLabel();
carerStartDateField = new javax.swing.JFormattedTextField();
carerHourField = new javax.swing.JFormattedTextField();
txtId = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
carerPanel.setBackground(new java.awt.Color(102, 204, 255));
carerTxt.setFont(new java.awt.Font("Arial Black", 1, 24)); // NOI18N
carerTxt.setForeground(new java.awt.Color(255, 255, 255));
carerTxt.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
carerTxt.setText("Cuidador");
carerGoBackButton.setBackground(new java.awt.Color(102, 153, 255));
carerGoBackButton.setFont(new java.awt.Font("Arial Black", 1, 13)); // NOI18N
carerGoBackButton.setForeground(new java.awt.Color(255, 255, 255));
carerGoBackButton.setText("Regresar");
carerGoBackButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
carerGoBackButtonActionPerformed(evt);
}
});
carerSaveButton.setBackground(new java.awt.Color(102, 153, 255));
carerSaveButton.setFont(new java.awt.Font("Arial Black", 1, 13)); // NOI18N
carerSaveButton.setForeground(new java.awt.Color(255, 255, 255));
carerSaveButton.setText("Guardar");
carerSaveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
carerSaveButtonActionPerformed(evt);
}
});
carerDeleteButton.setBackground(new java.awt.Color(102, 153, 255));
carerDeleteButton.setFont(new java.awt.Font("Arial Black", 1, 13)); // NOI18N
carerDeleteButton.setForeground(new java.awt.Color(255, 255, 255));
carerDeleteButton.setText("Eliminar");
carerDeleteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
carerDeleteButtonActionPerformed(evt);
}
});
carerChangeButton.setBackground(new java.awt.Color(102, 153, 255));
carerChangeButton.setFont(new java.awt.Font("Arial Black", 1, 13)); // NOI18N
carerChangeButton.setForeground(new java.awt.Color(255, 255, 255));
carerChangeButton.setText("Modificar");
carerChangeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
carerChangeButtonActionPerformed(evt);
}
});
carerSearchButton.setBackground(new java.awt.Color(102, 153, 255));
carerSearchButton.setFont(new java.awt.Font("Arial Black", 1, 13)); // NOI18N
carerSearchButton.setForeground(new java.awt.Color(255, 255, 255));
carerSearchButton.setText("Buscar");
carerSearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
carerSearchButtonActionPerformed(evt);
}
});
carerNameTxt.setFont(new java.awt.Font("Arial", 0, 13)); // NOI18N
carerNameTxt.setForeground(new java.awt.Color(255, 255, 255));
carerNameTxt.setText("Nombre y Apellido");
carerNameField.setBackground(new java.awt.Color(102, 153, 255));
carerNameField.setFont(new java.awt.Font("Arial", 0, 13)); // NOI18N
carerNameField.setForeground(new java.awt.Color(255, 255, 255));
carerNameField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
carerNameFieldActionPerformed(evt);
}
});
carerDirectionField.setBackground(new java.awt.Color(102, 153, 255));
carerDirectionField.setFont(new java.awt.Font("Arial", 0, 13)); // NOI18N
carerDirectionField.setForeground(new java.awt.Color(255, 255, 255));
carerDirectionTxt.setFont(new java.awt.Font("Arial", 0, 13)); // NOI18N
carerDirectionTxt.setForeground(new java.awt.Color(255, 255, 255));
carerDirectionTxt.setText("Dirección");
carerStartDateTxt.setFont(new java.awt.Font("Arial", 0, 13)); // NOI18N
carerStartDateTxt.setForeground(new java.awt.Color(255, 255, 255));
carerStartDateTxt.setText("Fecha de Contratación");
carerHourTxt.setFont(new java.awt.Font("Arial", 0, 13)); // NOI18N
carerHourTxt.setForeground(new java.awt.Color(255, 255, 255));
carerHourTxt.setText("Hora");
carerStartDateField.setBackground(new java.awt.Color(102, 153, 255));
carerStartDateField.setForeground(new java.awt.Color(255, 255, 255));
try {
carerStartDateField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####-##-##")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
carerHourField.setBackground(new java.awt.Color(102, 153, 255));
carerHourField.setForeground(new java.awt.Color(255, 255, 255));
try {
carerHourField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##:##")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
txtId.setBackground(new java.awt.Color(102, 204, 255));
txtId.setEnabled(false);
jButton1.setText("Mostrar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout carerPanelLayout = new javax.swing.GroupLayout(carerPanel);
carerPanel.setLayout(carerPanelLayout);
carerPanelLayout.setHorizontalGroup(
carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(carerPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(carerGoBackButton)
.addContainerGap(407, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, carerPanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(carerHourField, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(carerHourTxt)
.addComponent(carerStartDateTxt)
.addGroup(carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(carerPanelLayout.createSequentialGroup()
.addGroup(carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(carerDirectionField, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(carerDirectionTxt)
.addComponent(carerNameTxt)
.addGroup(carerPanelLayout.createSequentialGroup()
.addGroup(carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton1)
.addGroup(carerPanelLayout.createSequentialGroup()
.addComponent(carerSaveButton)
.addGap(18, 18, 18)
.addComponent(carerDeleteButton, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(carerChangeButton)))
.addGap(105, 105, 105))
.addGroup(carerPanelLayout.createSequentialGroup()
.addComponent(carerNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(carerSearchButton)
.addContainerGap()))
.addComponent(carerStartDateField, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(carerPanelLayout.createSequentialGroup()
.addGap(221, 221, 221)
.addComponent(carerTxt)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(21, 21, 21))
);
carerPanelLayout.setVerticalGroup(
carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(carerPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(carerTxt)
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(40, 40, 40)
.addComponent(carerNameTxt)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(carerNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(carerSearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(carerDirectionTxt)
.addGap(16, 16, 16)
.addComponent(carerDirectionField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(carerStartDateTxt)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(carerStartDateField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(carerHourTxt)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(carerHourField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE)
.addGroup(carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(carerSaveButton)
.addComponent(carerDeleteButton, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(carerChangeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(40, 40, 40)
.addGroup(carerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(carerGoBackButton)
.addComponent(jButton1))
.addGap(16, 16, 16))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(carerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(carerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void carerGoBackButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_carerGoBackButtonActionPerformed
this.dispose();
menu.setVisible(true);
}//GEN-LAST:event_carerGoBackButtonActionPerformed
private void carerSaveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_carerSaveButtonActionPerformed
Connection con = null;
try {
con = getConection();
ps = con.prepareStatement("INSERT INTO cuidador (nombre, direccionCuidador, inicioCuidador, horaCuidador) VALUES(?,?,?,?) ");
ps.setString(1, carerNameField.getText());
ps.setString(2, carerDirectionField.getText());
ps.setDate(3,Date.valueOf(carerStartDateField.getText()));
ps.setTime(4, Time.valueOf(carerHourField.getText()));
int res = ps.executeUpdate();
if(res > 0){
JOptionPane.showMessageDialog(null, "Persona Guardada");
cleanBox();
} else {
JOptionPane.showMessageDialog(null, "Error al Guardar persona");
cleanBox();
}
con.close();
} catch(Exception e){
System.out.println(e);
}
}//GEN-LAST:event_carerSaveButtonActionPerformed
private void carerDeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_carerDeleteButtonActionPerformed
Connection con = null;
try {
con = getConection();
ps = con.prepareStatement("DELETE FROM cuidador WHERE nombre=?");
ps.setString(1, carerNameField.getText());
int res = ps.executeUpdate();
if(res > 0){
JOptionPane.showMessageDialog(null, "Persona eliminada");
cleanBox();
carerSaveButton.setEnabled(true);
} else {
JOptionPane.showMessageDialog(null, "Error al eliminar persona");
cleanBox();
carerSaveButton.setEnabled(true);
}
con.close();
} catch(Exception e){
System.out.println(e);
}
}//GEN-LAST:event_carerDeleteButtonActionPerformed
private void carerChangeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_carerChangeButtonActionPerformed
Connection con = null;
try {
con = getConection();
ps = con.prepareStatement("UPDATE cuidador SET nombre=?, direccionCuidador=?, inicioCuidador=? WHERE horaCuidador =?");
ps.setString(1, carerNameField.getText());
ps.setString(2, carerDirectionField.getText());
ps.setDate(3,Date.valueOf(carerStartDateField.getText()));
ps.setTime(4, Time.valueOf(carerHourField.getText()));
int res = ps.executeUpdate();
if(res > 0){
JOptionPane.showMessageDialog(null, "Persona Modificada");
cleanBox();
carerSaveButton.setEnabled(true);
} else {
JOptionPane.showMessageDialog(null, "Error al Modificar persona");
cleanBox();
carerSaveButton.setEnabled(true);
}
con.close();
} catch(Exception e){
System.out.println(e);
}
}//GEN-LAST:event_carerChangeButtonActionPerformed
private void carerSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_carerSearchButtonActionPerformed
carerSaveButton.setEnabled(false);
com.mysql.jdbc.Connection con = null;
try{
con = (com.mysql.jdbc.Connection) getConection();
ps = con.prepareStatement("SELECT * FROM cuidador WHERE nombre = ?");
ps.setString(1, carerNameField.getText());
ResultSet rs = ps.executeQuery();
if(rs.next()){
carerNameField.setText(rs.getString("nombre"));
carerDirectionField.setText(rs.getString("direccionCuidador"));
carerStartDateField.setText(rs.getString("inicioCuidador"));
carerHourField.setText(rs.getString("horaCuidador"));
} else {
JOptionPane.showMessageDialog(null, "No existe una persona con ese nombre");
}
} catch(Exception e){
System.err.println(e);
}
}//GEN-LAST:event_carerSearchButtonActionPerformed
private void carerNameFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_carerNameFieldActionPerformed
}//GEN-LAST:event_carerNameFieldActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
JFMostrarCuidador mostrarCuidador = new JFMostrarCuidador();
setLocationRelativeTo(null);
mostrarCuidador.setVisible(true);
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(JFCuidador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JFCuidador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JFCuidador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JFCuidador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JFCuidador().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton carerChangeButton;
private javax.swing.JButton carerDeleteButton;
private javax.swing.JTextField carerDirectionField;
private javax.swing.JLabel carerDirectionTxt;
private javax.swing.JButton carerGoBackButton;
private javax.swing.JFormattedTextField carerHourField;
private javax.swing.JLabel carerHourTxt;
private javax.swing.JTextField carerNameField;
private javax.swing.JLabel carerNameTxt;
private javax.swing.JPanel carerPanel;
private javax.swing.JButton carerSaveButton;
private javax.swing.JButton carerSearchButton;
private javax.swing.JFormattedTextField carerStartDateField;
private javax.swing.JLabel carerStartDateTxt;
private javax.swing.JLabel carerTxt;
private javax.swing.JButton jButton1;
private javax.swing.JTextField txtId;
// End of variables declaration//GEN-END:variables
}
| 23,087 | 0.639939 | 0.621876 | 467 | 48.432549 | 38.031788 | 168 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.860814 | false | false | 9 |
c10bb8f5b517e47c2493b94a9af3e9d6ce541d75 | 29,326,036,700,527 | fa5dac9f735c2b4516af13868d431ab3a1332071 | /src/models/StudentUtility.java | e04fa17e58848fd013c02431d4aa13326afc6918 | [] | no_license | Abdelrahman1993/ServletAndJSP_CRUD | https://github.com/Abdelrahman1993/ServletAndJSP_CRUD | 9c83247ec150c6250517c658807aab4760e7e234 | eeb75389303ef556e23c49826d3f3040462d3b16 | refs/heads/master | "2020-11-24T07:07:21.931000" | "2019-12-14T12:44:17" | "2019-12-14T12:44:17" | 228,022,279 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package models;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.sql.DataSource;
public class StudentUtility {
private DataSource dataSource;
public StudentUtility(DataSource dataSource) {
this.dataSource = dataSource;
}
public List<Student> getStudents() throws SQLException{
Connection con = null;
Statement st = null;
ResultSet rs = null;
List <Student> students= new ArrayList<>();
try {
con = dataSource.getConnection();
st = con.createStatement();
String sql = "SELECT * FROM students";
rs = st.executeQuery(sql);
while(rs.next()) {
students.add( new Student(rs.getInt("id"),rs.getString("name"), rs.getString("email") ));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
con.close();
st.close();
rs.close();
}
return students;
}
public void addStudent(Student student) throws SQLException {
Connection con = null;
PreparedStatement preStat = null;
try {
con = dataSource.getConnection();
String sql = "INSERT INTO students (name, email, password) VALUES (?, ?, ?)";
preStat = con.prepareStatement(sql);
preStat.setString(1, student.getName());
preStat.setString(2, student.getEmail());
preStat.setString(3, student.getPassword());
preStat.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
con.close();
preStat.close();
}
}
public void deleteStudent(int id) throws SQLException {
Connection con = null;
PreparedStatement preStat = null;
try {
con = dataSource.getConnection();
String sql = "DELETE FROM students where id = ?";
preStat = con.prepareStatement(sql);
preStat.setInt(1, id);
preStat.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
con.close();
preStat.close();
}
}
public void updateStudent(Student student) {
Connection con = null;
PreparedStatement preStat = null;
try {
con = dataSource.getConnection();
String sql = "UPDATE students SET name=?, email=?, password=? WHERE id=?";
preStat = con.prepareStatement(sql);
preStat.setString(1, student.getName());
preStat.setString(2, student.getEmail());
preStat.setString(3, student.getPassword());
preStat.setInt(4, student.getId());
preStat.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
con.close();
preStat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public Student getStudent(int id) throws SQLException{
Connection con = null;
Statement st = null;
ResultSet rs = null;
Student student=null;
try {
con = dataSource.getConnection();
st = con.createStatement();
String sql = "SELECT * FROM students WHERE id = "+id+"";
rs = st.executeQuery(sql);
while(rs.next()) {
student = new Student(rs.getInt("id"),rs.getString("name"), rs.getString("email"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
con.close();
st.close();
rs.close();
}
return student;
}
}
| UTF-8 | Java | 3,497 | java | StudentUtility.java | Java | [] | null | [] | package models;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.sql.DataSource;
public class StudentUtility {
private DataSource dataSource;
public StudentUtility(DataSource dataSource) {
this.dataSource = dataSource;
}
public List<Student> getStudents() throws SQLException{
Connection con = null;
Statement st = null;
ResultSet rs = null;
List <Student> students= new ArrayList<>();
try {
con = dataSource.getConnection();
st = con.createStatement();
String sql = "SELECT * FROM students";
rs = st.executeQuery(sql);
while(rs.next()) {
students.add( new Student(rs.getInt("id"),rs.getString("name"), rs.getString("email") ));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
con.close();
st.close();
rs.close();
}
return students;
}
public void addStudent(Student student) throws SQLException {
Connection con = null;
PreparedStatement preStat = null;
try {
con = dataSource.getConnection();
String sql = "INSERT INTO students (name, email, password) VALUES (?, ?, ?)";
preStat = con.prepareStatement(sql);
preStat.setString(1, student.getName());
preStat.setString(2, student.getEmail());
preStat.setString(3, student.getPassword());
preStat.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
con.close();
preStat.close();
}
}
public void deleteStudent(int id) throws SQLException {
Connection con = null;
PreparedStatement preStat = null;
try {
con = dataSource.getConnection();
String sql = "DELETE FROM students where id = ?";
preStat = con.prepareStatement(sql);
preStat.setInt(1, id);
preStat.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
con.close();
preStat.close();
}
}
public void updateStudent(Student student) {
Connection con = null;
PreparedStatement preStat = null;
try {
con = dataSource.getConnection();
String sql = "UPDATE students SET name=?, email=?, password=? WHERE id=?";
preStat = con.prepareStatement(sql);
preStat.setString(1, student.getName());
preStat.setString(2, student.getEmail());
preStat.setString(3, student.getPassword());
preStat.setInt(4, student.getId());
preStat.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
con.close();
preStat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public Student getStudent(int id) throws SQLException{
Connection con = null;
Statement st = null;
ResultSet rs = null;
Student student=null;
try {
con = dataSource.getConnection();
st = con.createStatement();
String sql = "SELECT * FROM students WHERE id = "+id+"";
rs = st.executeQuery(sql);
while(rs.next()) {
student = new Student(rs.getInt("id"),rs.getString("name"), rs.getString("email"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
con.close();
st.close();
rs.close();
}
return student;
}
}
| 3,497 | 0.66171 | 0.659422 | 153 | 21.856209 | 18.76355 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.712418 | false | false | 9 |
5d38e1f8b6e7e2c98302770f7f1b98ad2abb35a2 | 17,729,625,041,783 | 0d2a857cb276ec592c5ab1f5d51bc3c853cba808 | /GAM_Exam/src/JFX/mote/Element.java | fbccf29f6ee0327525e6382c9d522607f7ba9573 | [] | no_license | Moha-Dan/GAM_Exam | https://github.com/Moha-Dan/GAM_Exam | 6289465428b8dcc26ad029b5f46b7057e1863117 | 22bf375971ddef95e4710fdc456d00347774cac9 | refs/heads/master | "2023-02-14T20:01:32.146000" | "2020-12-31T13:43:02" | "2020-12-31T13:43:02" | 325,785,049 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package JFX.mote;
public interface Element {
public void init();
}
| UTF-8 | Java | 69 | java | Element.java | Java | [] | null | [] | package JFX.mote;
public interface Element {
public void init();
}
| 69 | 0.724638 | 0.724638 | 5 | 12.8 | 10.457533 | 26 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 9 |
d783759f61d9b7eb55cf61ddf8e3ecfb68cfb4ca | 9,242,769,621,452 | 9508b40f6914154f7511f94f55393e2e5283c8c8 | /AuthCenter/src/main/java/family/dd/DDHomeKits/AuthCenter/domain/UserAuthentication/entity/handler/PasswordHandlerFactory.java | 93c54a9ff39e92b6f280a263c96fdea67aaba4de | [] | no_license | ghostardy/DDHomeKits | https://github.com/ghostardy/DDHomeKits | c48e82edbaf13b24459d0a96c2875ec1458859ff | f254433d092de5b5424fac7eb31be79c216e53d0 | refs/heads/master | "2023-03-05T03:17:09.147000" | "2021-02-20T09:13:50" | "2021-02-20T09:13:53" | 311,490,798 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package family.dd.DDHomeKits.AuthCenter.domain.UserAuthentication.entity.handler;
public class PasswordHandlerFactory {
public static PasswordHandler getInstance(){
PasswordHandler step1 = new PasswordSimpleSaltHandler();
PasswordHandler step2 = new PasswordSHA256Handler();
PasswordHandler step3 = new PasswordSimpleSaltHandler();
PasswordHandler step4 = new PasswordSHA256Handler();
step1.next(step2).next(step3).next(step4);
return step1;
}
}
| UTF-8 | Java | 504 | java | PasswordHandlerFactory.java | Java | [] | null | [] | package family.dd.DDHomeKits.AuthCenter.domain.UserAuthentication.entity.handler;
public class PasswordHandlerFactory {
public static PasswordHandler getInstance(){
PasswordHandler step1 = new PasswordSimpleSaltHandler();
PasswordHandler step2 = new PasswordSHA256Handler();
PasswordHandler step3 = new PasswordSimpleSaltHandler();
PasswordHandler step4 = new PasswordSHA256Handler();
step1.next(step2).next(step3).next(step4);
return step1;
}
}
| 504 | 0.734127 | 0.704365 | 13 | 37.76923 | 27.80192 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false | 9 |
6e55fca67ef561e77cca6c64e47c0341788f7aaa | 37,735,582,680,457 | e9544ef559d27b6068d5721c96503214bb7e1748 | /PeppeNapo IS Progetto/Napolano N46/NAPOLANO_N46002285/N46002285Napolano/src/Control/AuthenticationManager.java | b35a5d47f40a3587eb9244a90b7ec967b7d07762 | [] | no_license | ilmissigno/Progetto_Smart_Parking_APP | https://github.com/ilmissigno/Progetto_Smart_Parking_APP | 8734d20924c7702197f78abc935e75d2cdd87e47 | 009bbb7b1335029a806845ded49119c73bce2602 | refs/heads/master | "2020-06-13T05:10:54.639000" | "2019-09-25T18:59:55" | "2019-09-25T18:59:55" | 194,544,915 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Control;
import java.sql.SQLException;
public interface AuthenticationManager {
String Login(String username, String password) throws SQLException;
}
| UTF-8 | Java | 172 | java | AuthenticationManager.java | Java | [] | null | [] | package Control;
import java.sql.SQLException;
public interface AuthenticationManager {
String Login(String username, String password) throws SQLException;
}
| 172 | 0.767442 | 0.767442 | 9 | 17.111111 | 22.820286 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 9 |
3a3ad69e64946a4c95c6413339527a4bc4a9a1bb | 32,332,513,860,656 | 001307bfea66fad1cc904ccbf8c160d5cb39083a | /myb-entity/src/main/java/com/myb/entity/pojo/mos/Role.java | 7065060f9f0a37b9e92be2ff94fdfc46e9ebfa0f | [] | no_license | yan-huan/mos | https://github.com/yan-huan/mos | 4c56f1f66aa94c2fc7042140bcaa1e132b39db9a | 6e2f3e4c769b96ea5f62222ce8abc8e13b69d044 | refs/heads/master | "2020-05-29T09:13:40.533000" | "2017-10-18T02:25:23" | "2017-10-18T02:25:23" | 68,894,559 | 0 | 0 | null | true | "2016-09-22T07:10:58" | "2016-09-22T07:10:57" | "2016-09-18T09:24:32" | "2016-09-22T06:59:11" | 8,709 | 0 | 0 | 0 | null | null | null | package com.myb.entity.pojo.mos;
import com.myb.framework.data.DataMapping;
import com.myb.framework.data.EntityBase;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.myb.framework.serialization.JsonLongDateFormatSerializer;
public class Role extends EntityBase{
@DataMapping(RoleMapping.RoleId)
private int roleId;//
@DataMapping(RoleMapping.RoleName)
private java.lang.String roleName;//
@DataMapping(RoleMapping.Status)
private int status;//
@DataMapping(RoleMapping.CreateTime)
private java.sql.Timestamp createTime;//
public Role() { }
public int getRoleId()
{
return roleId;
}
public void setRoleId(int roleId)
{
this.roleId = roleId;
}
public java.lang.String getRoleName()
{
return roleName;
}
public void setRoleName(java.lang.String roleName)
{
this.roleName = roleName;
}
public int getStatus()
{
return status;
}
public void setStatus(int status)
{
this.status = status;
}
@JsonSerialize(using = JsonLongDateFormatSerializer.class)
public java.sql.Timestamp getCreateTime()
{
return createTime;
}
public void setCreateTime(java.sql.Timestamp createTime)
{
this.createTime = createTime;
}
}
| UTF-8 | Java | 1,338 | java | Role.java | Java | [] | null | [] | package com.myb.entity.pojo.mos;
import com.myb.framework.data.DataMapping;
import com.myb.framework.data.EntityBase;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.myb.framework.serialization.JsonLongDateFormatSerializer;
public class Role extends EntityBase{
@DataMapping(RoleMapping.RoleId)
private int roleId;//
@DataMapping(RoleMapping.RoleName)
private java.lang.String roleName;//
@DataMapping(RoleMapping.Status)
private int status;//
@DataMapping(RoleMapping.CreateTime)
private java.sql.Timestamp createTime;//
public Role() { }
public int getRoleId()
{
return roleId;
}
public void setRoleId(int roleId)
{
this.roleId = roleId;
}
public java.lang.String getRoleName()
{
return roleName;
}
public void setRoleName(java.lang.String roleName)
{
this.roleName = roleName;
}
public int getStatus()
{
return status;
}
public void setStatus(int status)
{
this.status = status;
}
@JsonSerialize(using = JsonLongDateFormatSerializer.class)
public java.sql.Timestamp getCreateTime()
{
return createTime;
}
public void setCreateTime(java.sql.Timestamp createTime)
{
this.createTime = createTime;
}
}
| 1,338 | 0.672646 | 0.672646 | 59 | 21.677965 | 19.521774 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.288136 | false | false | 9 |
ac9d0cb856e10130cea6adb43be250665a2f5e77 | 33,638,183,918,857 | 613144b9f29eaa8c84c8af87399a150bfaf6e75f | /src/main/java/Errors/UsernameAlreadyExistsException.java | f435429232e491c159730b29b4091ba492358813 | [] | no_license | mguzm4n/lab4_20640869_Guzman | https://github.com/mguzm4n/lab4_20640869_Guzman | 85307882a065523a277db505c3eb59c8192824fd | ffa579832a86f292a4a873d9c39cfe50e4cff786 | refs/heads/main | "2023-03-13T06:47:52.321000" | "2021-03-05T00:30:30" | "2021-03-05T00:30:30" | 334,853,352 | 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 Errors;
/**
*
* @author Marcelo Guzmán
*/
public class UsernameAlreadyExistsException extends Exception {
public UsernameAlreadyExistsException() {
super("Este usuario ya existe.");
}
}
| WINDOWS-1250 | Java | 400 | java | UsernameAlreadyExistsException.java | Java | [
{
"context": "the editor.\n */\npackage Errors;\n\n/**\n *\n * @author Marcelo Guzmán\n */\npublic class UsernameAlreadyExistsException e",
"end": 234,
"score": 0.9998560547828674,
"start": 220,
"tag": "NAME",
"value": "Marcelo Guzmán"
}
] | 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 Errors;
/**
*
* @author <NAME>
*/
public class UsernameAlreadyExistsException extends Exception {
public UsernameAlreadyExistsException() {
super("Este usuario ya existe.");
}
}
| 391 | 0.716792 | 0.716792 | 16 | 23.9375 | 25.530542 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3125 | false | false | 9 |
f50121dfec55ebee5ce36981df337009278e3ad6 | 1,133,871,414,123 | 187712fd1765b1291e9d36aa8d13abec96a6a286 | /yuzhouwan-hacker/src/test/java/com/yuzhouwan/hacker/javaProhibited/serializable/bean/SerializableWithNoSAttribution.java | 71c48214aa91776c9e2929259f42a5f6a988bcb8 | [
"Apache-2.0"
] | permissive | asdf2014/yuzhouwan | https://github.com/asdf2014/yuzhouwan | 104e14deb289e0fb7173e845dd98b4209901d049 | 03b26f1d5d8da786a7df7e15fd4deb9335d8ba85 | refs/heads/master | "2023-08-30T01:53:01.562000" | "2023-08-29T14:32:58" | "2023-08-29T14:32:58" | 40,167,498 | 47 | 19 | Apache-2.0 | false | "2023-09-14T21:21:15" | "2015-08-04T06:32:09" | "2023-08-25T06:50:52" | "2023-09-14T21:21:15" | 45,399 | 40 | 20 | 1 | Java | false | false | package com.yuzhouwan.hacker.javaProhibited.serializable.bean;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* Copyright @ 2023 yuzhouwan.com
* All right reserved.
* Function: Serializable with No Serializable Attribution
*
* @author Benedict Jin
* @since 2015/8/4
*/
public class SerializableWithNoSAttribution implements Serializable {
private String id;
private transient String name;
private int age;
private Infos infos;
public SerializableWithNoSAttribution() {
}
public SerializableWithNoSAttribution(String id, String name, int age, Infos infos) {
this.id = id;
this.name = name;
this.age = age;
this.infos = infos;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Infos getInfos() {
return infos;
}
public void setInfos(Infos infos) {
this.infos = infos;
}
private void writeObject(final ObjectOutputStream out) throws IOException {
out.writeUTF(this.id);
out.writeUTF(this.name);
out.writeInt(this.age);
out.writeUTF(this.infos.getTel());
out.writeUTF(this.infos.getBlog());
}
private void readObject(final ObjectInputStream in) throws IOException {
this.id = in.readUTF();
this.name = in.readUTF();
this.age = in.readInt();
this.infos = new Infos(in.readUTF(), in.readUTF());
}
@Override
public String toString() {
return "SerializableWithNoSAttribution{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age=" + age +
", infos=" + infos +
'}';
}
}
| UTF-8 | Java | 2,077 | java | SerializableWithNoSAttribution.java | Java | [
{
"context": "ble with No Serializable Attribution\n *\n * @author Benedict Jin\n * @since 2015/8/4\n */\npublic class SerializableW",
"end": 337,
"score": 0.9997881054878235,
"start": 325,
"tag": "NAME",
"value": "Benedict Jin"
}
] | null | [] | package com.yuzhouwan.hacker.javaProhibited.serializable.bean;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* Copyright @ 2023 yuzhouwan.com
* All right reserved.
* Function: Serializable with No Serializable Attribution
*
* @author <NAME>
* @since 2015/8/4
*/
public class SerializableWithNoSAttribution implements Serializable {
private String id;
private transient String name;
private int age;
private Infos infos;
public SerializableWithNoSAttribution() {
}
public SerializableWithNoSAttribution(String id, String name, int age, Infos infos) {
this.id = id;
this.name = name;
this.age = age;
this.infos = infos;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Infos getInfos() {
return infos;
}
public void setInfos(Infos infos) {
this.infos = infos;
}
private void writeObject(final ObjectOutputStream out) throws IOException {
out.writeUTF(this.id);
out.writeUTF(this.name);
out.writeInt(this.age);
out.writeUTF(this.infos.getTel());
out.writeUTF(this.infos.getBlog());
}
private void readObject(final ObjectInputStream in) throws IOException {
this.id = in.readUTF();
this.name = in.readUTF();
this.age = in.readInt();
this.infos = new Infos(in.readUTF(), in.readUTF());
}
@Override
public String toString() {
return "SerializableWithNoSAttribution{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age=" + age +
", infos=" + infos +
'}';
}
}
| 2,071 | 0.589311 | 0.584497 | 91 | 21.824175 | 20.043684 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.417582 | false | false | 9 |
38b4cb995645e4b7c7db8045a7908e540cb47dfd | 19,593,640,858,366 | da08edc08445c083726b655a2e47f48733704ef2 | /PokemonArena/src/model/pokemon/kanto/Farfetchd.java | 7e3736122dbca3d94f7b14e80b32dc981b1bbf7c | [
"MIT"
] | permissive | Dantran93/PokemonArena | https://github.com/Dantran93/PokemonArena | 169e831d4d6853669cdfa64dc3c57b198b7edc03 | a224f75dcdf4eebbf3eaf2abaa5ef15bd1e6f03b | refs/heads/master | "2018-11-21T23:25:35.558000" | "2018-09-17T23:35:12" | "2018-09-17T23:35:12" | 96,361,975 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package model.pokemon.kanto;
import model.misc.Type;
import model.pokemon.Pokemon;
import model.range.DiagonalRange;
/**
* Farfetchd.java
* Author: Daniel Tranfaglia
*
* Purpose: Represents a Farfetchd in the game.
*/
public class Farfetchd extends Pokemon
{
/**
* Farfetchd Constructor (int)
*
* Purpose: Creates and initializes a Farfetchd at the given level.
*/
public Farfetchd (int level)
{
super("Farfetch'd", level);
primaryType = Type.Normal;
secondaryType = Type.Flying;
movement = new DiagonalRange(3);
} // Farfetchd Constructor (int)
} // class Farfetchd
| UTF-8 | Java | 601 | java | Farfetchd.java | Java | [
{
"context": "e.DiagonalRange;\n\n/**\n * Farfetchd.java\n * Author: Daniel Tranfaglia\n * \n * Purpose: Represents a Farfetchd in the gam",
"end": 169,
"score": 0.9998751878738403,
"start": 152,
"tag": "NAME",
"value": "Daniel Tranfaglia"
}
] | null | [] | package model.pokemon.kanto;
import model.misc.Type;
import model.pokemon.Pokemon;
import model.range.DiagonalRange;
/**
* Farfetchd.java
* Author: <NAME>
*
* Purpose: Represents a Farfetchd in the game.
*/
public class Farfetchd extends Pokemon
{
/**
* Farfetchd Constructor (int)
*
* Purpose: Creates and initializes a Farfetchd at the given level.
*/
public Farfetchd (int level)
{
super("Farfetch'd", level);
primaryType = Type.Normal;
secondaryType = Type.Flying;
movement = new DiagonalRange(3);
} // Farfetchd Constructor (int)
} // class Farfetchd
| 590 | 0.708819 | 0.707155 | 30 | 19.033333 | 17.106497 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.9 | false | false | 9 |
ce1d7316264075f8e0aea88fd8f724012e4c5126 | 2,216,203,171,350 | 7813ae656060430402b8f308cb09971a19fbe488 | /app/src/main/java/com/example/bo/nixon/presenter/MainContract.java | 5b955a00dc44a8b85c6e459d1862d9dc7a3edd7b | [] | no_license | Aa136075837/demo | https://github.com/Aa136075837/demo | 2ea10bc15e76f4543a83f426350990d37d659cf0 | d79fc15d3722f563d5b46c105fb322b637bb325a | refs/heads/master | "2021-04-05T23:42:00.517000" | "2018-03-09T03:44:01" | "2018-03-09T03:44:01" | 124,417,695 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.bo.nixon.presenter;
import android.content.ComponentName;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.example.bo.nixon.base.NixonApplication;
import com.example.bo.nixon.bean.AlarmEventBean;
import com.example.bo.nixon.bean.DbWatchBean;
import com.example.bo.nixon.bean.NetSportStepBean;
import com.example.bo.nixon.bean.UploadStepsBean;
import com.example.bo.nixon.db.DbManager;
import com.example.bo.nixon.db.DbWatchBeanCompat;
import com.example.bo.nixon.manager.ToastManager;
import com.example.bo.nixon.presenter.bleBase.BaseBlePresenter;
import com.example.bo.nixon.presenter.ota.IOtaPresenter;
import com.example.bo.nixon.ui.activity.main.IMain;
import com.example.bo.nixon.ui.fragment.alarm.AlarmCacheHelper;
import com.example.bo.nixon.utils.Constant;
import com.example.bo.nixon.utils.ConstantURL;
import com.example.bo.nixon.utils.HttpUtils;
import com.example.bo.nixon.utils.RequestCode;
import com.example.bo.nixon.utils.SPUtils;
import com.example.bo.nixon.version.DownLoaderTask;
import com.example.bo.nixon.version.FileUtil;
import com.example.bo.nixon.version.VersionControl;
import com.example.bo.nixon.version.ZIP;
import com.google.gson.Gson;
import com.smart.alarmcomponent.AlarmComponent;
import com.smart.alarmcomponent.IAlarm;
import com.smart.attributescomponent.AttributesComponent;
import com.smart.attributescomponent.listener.IPower;
import com.smart.attributescomponent.listener.IVersion;
import com.smart.connectComponent.ConnectComponent;
import com.smart.connectComponent.IAuthorization;
import com.smart.dataComponent.DataComponent;
import com.smart.dataComponent.DataStyle;
import com.smart.dataComponent.WatchBean;
import com.smart.dataComponent.listener.IRequestData;
import com.smart.dataComponent.listener.ITarget;
import com.smart.dataComponent.listener.IUpdateSumStep;
import com.smart.otacomponent.OTAComponent;
import com.smart.otacomponent.listener.IOTAListener;
import com.smart.smartble.DeviceMessage;
import com.smart.smartble.SmartManager;
import com.smart.smartble.utils.TimeZoneUtil;
import com.smart.timecomponent.ISecondTime;
import com.smart.timecomponent.TimeComponent;
import com.yanzhenjie.nohttp.rest.OnResponseListener;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author bo.
* @Date 2017/5/26.
* @desc
*/
public interface MainContract {
interface MainNixonView extends BaseNixonView {
void updateComplete(int step);
void electricity(int electricity);
void stepsDay(NetSportStepBean bean);
void stepsWeek(NetSportStepBean bean);
void stepsMonth(NetSportStepBean bean);
void onComplete(boolean isComplete);
void secondDate(Date date, int zone);
void showVersion(int main, int minor, int test);
void target(int target);
}
class MainPresenter extends BaseBlePresenter<MainNixonView> implements IUpdateSumStep, IPower, IMain, IRequestData,
VersionControl.VersionListener, DownLoaderTask.LoaderResultListener, IOtaPresenter, IOTAListener,
IVersion, ISecondTime, ITarget, IAuthorization ,IAlarm{
private static final String TAG = "MainPresenter";
private TimeComponent mTimeComponent;
private DataComponent mDataComponent;
private AttributesComponent mAttributesComponent;
private AlarmComponent mAlarmComponent;
private Handler mHandler = new Handler(Looper.getMainLooper());
private Gson gson = new Gson();
private List<DbWatchBean> dbWatchBeens;
private Map<String, String> map = new HashMap<> ();
private String deviceUUID;
private String cuntomerId = SPUtils.getString (NixonApplication.getContext (), Constant.CUSTOMER_ID);
private final int UPLOAD_WHAT = 777;
private final int GET_DAY_STEP = 12123;
private final int GET_WEEK_STEP = 12124;
private final int GET_MONTH_STEP = 12125;
private VersionControl mVersionControl;
private DownLoaderTask mDownLoaderTask;
private static final String PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/OTA/";
private OTAComponent mOtaComponent;
private ConnectComponent mConnectComponent;
private Timer mTimer;
@Override
protected void serviceConnected(SmartManager smartManager) {
mTimeComponent = new TimeComponent(smartManager);
mTimeComponent.registerComponent();
mTimeComponent.addSecondTimeListener(this);
mDataComponent = new DataComponent(smartManager);
mDataComponent.registerComponent();
mDataComponent.addSumStepListener(this);
mDataComponent.addRequestDataListener(this);
mDataComponent.addTargetListener(this);
mDataComponent.requestSumStep();
mAlarmComponent = AlarmComponent.getInstance(smartManager);
mAlarmComponent.registerComponent();
mAlarmComponent.addAlarmListener(this);
mAttributesComponent = AttributesComponent.getInstance(smartManager);
mAttributesComponent.registerComponent();
mAttributesComponent.addPowerListener(this);
mAttributesComponent.addVersionListener(this);
mAttributesComponent.getVersion();
mConnectComponent = ConnectComponent.getInstance(smartManager);
mConnectComponent.registerComponent();
mConnectComponent.addAuthorzationListener(this);
mOtaComponent = OTAComponent.getInstance(smartManager);
mOtaComponent.registerComponent();
mOtaComponent.addOTAListener(this);
startTimer();
}
private void startTimer() {
if (null != mTimer)
mTimer.cancel();
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
uploadAllData();
}
}, 0, 5 * 60 * 1000);
}
private void destroyTimer() {
if (null != mTimer)
mTimer.cancel();
}
@Override
public void attachView(MainNixonView view) {
super.attachView(view);
Log.e("DownLoaderTask", " Main attachView");
mVersionControl = new VersionControl();
mVersionControl.setVersionListener(this);
}
private void setAlarm() {
List<AlarmEventBean> eventBeen = AlarmCacheHelper.getAlarmList(NixonApplication.getContext());
for (int i = 0; i < eventBeen.size(); i++) {
AlarmEventBean alarmEventBean = eventBeen.get(i);
int open = alarmEventBean.isOpenType() ? 1 : 0;
if (0 != (alarmEventBean.getRepeatTime() & 128)) {
alarmEventBean.setRepeatTime(alarmEventBean.getRepeatTime() | 128);
}
mAlarmComponent.setAlarm(i + 1, alarmEventBean.getAlarmTime(), open, alarmEventBean.getRepeatTime());
}
}
@Override
protected void serviceDisconnected(ComponentName name) {
}
public void sendSecondTime(Date date, int arg1, int arg2) {
if (null != mTimeComponent) mTimeComponent.setSecondCity(date, arg1, arg2);
}
public void getStepValue() {
if (null != mDataComponent) mDataComponent.requestSumStep();
}
@Override
public void detachView() {
if (null != mDataComponent) {
mDataComponent.removeSumStepListener(this);
mDataComponent.removeTargetListener(this);
mDataComponent.removeSumStepListener(this);
mDataComponent.unRegisterComponent();
}
if (null != mAttributesComponent) {
mAttributesComponent.unRegisterComponent();
mAttributesComponent.removePowerListener(this);
}
if (null != mOtaComponent) {
mOtaComponent.unRegisterComponent();
}
if (null != mTimeComponent) {
mTimeComponent.removeSecondTimeListener(this);
mTimeComponent.unRegisterComponent();
}
if (null != mConnectComponent) {
mConnectComponent.unRegisterComponent();
mConnectComponent.removeAuthorzationListener(this);
}
if (null != mAlarmComponent) {
mAlarmComponent.removeAlarmListener(this);
mAlarmComponent.unRegisterComponent();
}
destroyTimer();
super.detachView();
}
@Override
public void sumStep(int step) {
if (null != getView()) getView().updateComplete(step);
}
@Override
public void electricity(int value) {
if (null != getView()) {
getView().electricity(value);
}
}
@Override
public void getElectricity() {
if (null != mAttributesComponent) {
mAttributesComponent.getElectricity();
}
}
@Override
public void onResume() {
if (null != mDataComponent) {
mDataComponent.requestSumStep();
}
if (null!= mOtaComponent){
mOtaComponent.addOTAListener (this);
}
}
@Override
public void onPause() {
if (null != mDataComponent) {
mDataComponent.pauseSumStep();
}
if (null!= mOtaComponent){
mOtaComponent.removeOTAListener (this);
}
}
@Override
public void setTargetValue(int target) {
if (null != mDataComponent) {
mDataComponent.setSportTarget(target);
}
}
@Override
public void getSecondTime() {
if (null != mTimeComponent) {
mTimeComponent.getSecondCity();
}
}
@Override
public void uploadAllData() {
if (null != mDataComponent) {
mDataComponent.requestContent(DataStyle.STEP);
}
}
@Override
public void startRequest() {
}
@Override
public void requestProgress(int max, int progress) {
}
@Override
public void requestComplete(List<WatchBean> watchBeen) {
for (int i = 0; i < watchBeen.size(); i++) {
Log.w("DataComponent", "requestComplete::" + watchBeen.size() + watchBeen.get(i).toString());
}
Log.e("UPDATELISTSTEPS", " 获取手表数据 成功");
if (watchBeen == null || watchBeen.size() == 0) {
return;
}
deviceUUID = DeviceMessage.getInstance ().getDeviceUUID ();
dbWatchBeens = DbWatchBeanCompat.watchBeenToDbWatchBean(watchBeen, cuntomerId, deviceUUID);
Log.e("UPDATELISTSTEPS", " 开始上传步数 ");
HttpUtils.getInstance().autoLogin();
updateListSteps(dbWatchBeens);
//updateSportData(10000 + "", cuntomerId, deviceUUID, 1483416000000l + "");
}
@Override
public void requestError(int errorCode, String errorMsg) {
}
private void updateListSteps (List<DbWatchBean> watchBeens) {
List<Map<String, String>> parmas = new ArrayList<> ();
Log.e ("UPDATELISTSTEPS", " watchBeens.size () = " + watchBeens.size ());
for (int i = 0; i < watchBeens.size (); i++) {
Map<String, String> element = new HashMap<> ();
DbWatchBean bean = watchBeens.get (i);
element.put ("customerId", bean.getUserId ());
element.put ("timestamp", bean.getTime () + "");
element.put ("step", bean.getValue () + "");
element.put ("deviceId", deviceUUID);
Log.d ("bigstep", " 时间 :: " + bean.getTime () + " 步数 :: " + bean.getValue ());
parmas.add (element);
}
HttpUtils.getInstance()
.requestCookieJsonArrayPost(ConstantURL.UPDATE_LIST_STEPS, 121212, parmas,
new SimpleResponseListener<JSONObject>() {
@Override
public void onSucceed(int what, Response<JSONObject> response) {
super.onSucceed(what, response);
NetSportStepBean bean = gson.fromJson(response.get().toString(), NetSportStepBean.class);
if (RequestCode.SUCCESS.equals(bean.getCode())) {
Log.e("UPDATELISTSTEPS", " 上传步数集合 成功");
} else if (RequestCode.NOT_LOGIN_STATE.equals(bean.getCode())) {
Log.e("UPDATELISTSTEPS", " 未登录状态 ");
}
}
@Override
public void onFailed(int what, Response<JSONObject> response) {
super.onFailed(what, response);
Log.e("UPDATELISTSTEPS", " 上传步数集合 失败 " + what);
if (null != dbWatchBeens) {
DbManager.insertDbWatchBean(dbWatchBeens);
}
}
});
}
private void updateSportData(String step, String customerID, String deviceID, String time) {
map.put("customerId", customerID);
map.put("timestamp", time);
map.put("step", step);
map.put("deviceId", deviceID);
HttpUtils.getInstance().requestJsonObjectPost(ConstantURL.UPDATE_STEPS, UPLOAD_WHAT, map, mListener);
}
public void getStepsByDay () {
deviceUUID = DeviceMessage.getInstance ().getDeviceUUID ();
Map<String, String> map = new HashMap<> ();
Date date = new Date ();
map.put ("year", date.getYear () + 1900 + "");
map.put ("month", date.getMonth () + 1 + "");
map.put ("day", date.getDate () + "");
map.put ("count", 30 + "");
map.put ("queryTimeOffSet", TimeZoneUtil.getCurrentTimeZone (Calendar.getInstance ().getTimeZone ()));
map.put ("deviceId", deviceUUID);
map.put ("customerId", cuntomerId);
HttpUtils.getInstance ()
.requestCookieJsonObjectPost (ConstantURL.GET_STEP_BY_DAY, GET_DAY_STEP, map, mSimpleResponseListener);
}
public void getStepsByWeek() {
Map<String, String> map = new HashMap<>();
Date date = new Date();
int weekYear = Calendar.getInstance().get(Calendar.WEEK_OF_YEAR);
Log.e("NIXONLOGIN", "...weekYear.." + weekYear);
map.put("year", date.getYear() + 1900 + "");
map.put("week", weekYear + "");
map.put("count", 16 + "");
map.put("queryTimeOffSet", TimeZoneUtil.getCurrentTimeZone(Calendar.getInstance().getTimeZone()));
map.put("deviceId", deviceUUID);
map.put("customerId", cuntomerId);
HttpUtils.getInstance()
.requestCookieJsonObjectPost(ConstantURL.GET_STEP_BY_WEEK, GET_WEEK_STEP, map,
mSimpleResponseListener);
}
public void getStepsByMonth () {
Map<String, String> map = new HashMap<> ();
Date date = new Date ();
map.put ("year", date.getYear () + 1900 + "");
map.put ("month", date.getMonth () + 1 + "");
map.put ("count", 28 + "");
map.put ("queryTimeOffSet", TimeZoneUtil.getCurrentTimeZone (Calendar.getInstance ().getTimeZone ()));
map.put ("deviceId", deviceUUID);
map.put ("customerId", cuntomerId);
HttpUtils.getInstance ()
.requestCookieJsonObjectPost (ConstantURL.GET_STEP_BY_MONTHS, GET_MONTH_STEP, map,
mSimpleResponseListener);
}
SimpleResponseListener mSimpleResponseListener = new SimpleResponseListener<JSONObject> () {
@Override public void onSucceed (int what, Response<JSONObject> response) {
super.onSucceed (what, response);
NetSportStepBean bean = gson.fromJson (response.get ().toString (), NetSportStepBean.class);
//Log.e ("NIXONLOGIN", " " + bean.getInfo () + " value = " + bean.getObject ().toString ());
switch (what) {
case GET_DAY_STEP:
switch (bean.getCode()) {
case RequestCode.SUCCESS:
if (getView() != null) {
getView().stepsDay(bean);
}
getStepsByWeek();
break;
default:
break;
}
break;
case GET_WEEK_STEP:
switch (bean.getCode()) {
case RequestCode.SUCCESS:
if (getView() != null) {
getView().stepsWeek(bean);
}
getStepsByMonth();
break;
default:
break;
}
break;
case GET_MONTH_STEP:
switch (bean.getCode()) {
case RequestCode.SUCCESS:
if (getView() != null) {
getView().stepsMonth(bean);
}
break;
default:
break;
}
break;
}
}
@Override
public void onFailed(int what, Response<JSONObject> response) {
super.onFailed(what, response);
Log.e("NIXONLOGIN", " 获取步数 失败 ");
if (response != null){
Log.e ("NIXONLOGIN"," response = " + response.getException ());
}
}
};
OnResponseListener mListener = new OnResponseListener<JSONObject>() {
@Override
public void onStart(int what) {
}
@Override
public void onSucceed(int what, Response<JSONObject> response) {
Log.e("NIXONLOGIN", " 成功" + response.get().toString());
UploadStepsBean bean = gson.fromJson(response.get().toString(), UploadStepsBean.class);
switch (bean.getCode()) {
case RequestCode.SUCCESS:
Log.e("NIXONLOGIN", "运动数据上传成功");
break;
case RequestCode.NOT_LOGIN_STATE:
HttpUtils.getInstance().autoLogin(ConstantURL.UPDATE_STEPS, UPLOAD_WHAT, map, mListener);
break;
case RequestCode.LACK_USERINFO:
break;
}
}
@Override
public void onFailed(int what, Response<JSONObject> response) {
Log.e("NIXONLOGIN", " 运动数据上传失败 " + response.get().toString());
if (null != dbWatchBeens) {
DbManager.insertDbWatchBean(dbWatchBeens);
}
}
@Override
public void onFinish(int what) {
}
};
public void downLoad(String url) {
Log.w("DownLoaderTask", "run--------->1" + url);
if (TextUtils.isEmpty(url))
return;
Log.w("DownLoaderTask", "run--------->2" + url);
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/OTA/");
FileUtil.DeleteFile(file);
mDownLoaderTask = new DownLoaderTask(url, PATH);
mDownLoaderTask.setLoaderResultListener(this);
mDownLoaderTask.execute();
}
public void checkoutVersion(String version) {
if (null != mVersionControl) {
Log.e("DownLoaderTask", " 检测版本");
mVersionControl.checkVersion(version, "P7003");
}
}
@Override
public void onSuccessful(String url, String message) {
Log.w("DownLoaderTask", "开始下载新版本 ");
downLoad(url);
}
@Override
public void onNoVersion() {
}
@Override
public void onVersionProgress(long max, long progress) {
}
@Override
public void onVersionResult(boolean complete, String path) {
Log.w("DownLoaderTask", "下载成功");
File file = new File(path);
if (null != file)
if (file.getName().endsWith("zip")) {
try {
ZIP.UnZipFolder(file.getAbsolutePath(), file.getParent(), new ZIP.ZipResult() {
@Override
public void complete(String path) {
startOTA(path);
Log.w("DownLoaderTask", "complete::" + path);
}
});
} catch (Exception e) {
e.printStackTrace();
Log.w("DownLoaderTask", "Exception" + e.toString());
}
}
}
public void confirmUpdateOta() {
mOtaComponent.delayToSendMcu();
}
@Override
public void startOTA(String path) {
if (!TextUtils.isEmpty(path))
mOtaComponent.startPath(path);
}
@Override
public void dealFile() {
Log.w(TAG, "dealFile::");
}
@Override
public void otaStart() {
Log.w(TAG, "otaStart::");
//if (null != getView())
// getView().onBegin();
}
@Override
public void onProgress(int max, int progress) {
Log.w("OTAComponent", "onProgress::" + max + " or " + progress);
//if (null != getView())
// getView().onProgress(max, progress);
}
@Override
public void onComplete(int complete) {
Log.w(TAG, "onComplete::");
if (0 == complete) {
ToastManager.show(NixonApplication.getContext(), "升级成功", Toast.LENGTH_SHORT);
} else if (5 == complete) {
ToastManager.show(NixonApplication.getContext(), "升级版本与当前版本一致请更新", Toast.LENGTH_SHORT);
} else {
ToastManager.show(NixonApplication.getContext(), "升级中断", Toast.LENGTH_SHORT);
}
if (null != getView())
getView().onComplete(0 == complete);
}
@Override
public void onFail() {
Log.w(TAG, "onFail::");
}
@Override
public void secondTime(Date date, int high, int low) {
if (null != getView()) {
getView().secondDate(date, high);
}
}
@Override
public void version(int main, int minor, int test) {
Log.e("DownLoaderTask", " xinbanben ");
if (null != getView()) {
getView().showVersion(main, minor, test);
}
}
@Override
public void target(int target) {
SPUtils.putString(NixonApplication.getContext(), Constant.GOAL_KEY, String.valueOf(target));
if (null != getView()) {
getView().target(target);
}
}
@Override
public void authorization(boolean author) {
if (author) {
uploadAllData();
}
}
@Override
public void AuthorizationTimeOut() {
}
@Override
public void alarm(int index, int time, int open, int repeat) {
if (repeat == 0)
return;
AlarmEventBean alarmEventBean =
AlarmCacheHelper.getAlarmEventBean(NixonApplication.getContext(), index - 1);
alarmEventBean.setAlarmTime(time);
alarmEventBean.setOpenType(open == 1);
if ((repeat & 128) != 128) {
alarmEventBean.setRepeatTime(repeat & 128);
alarmEventBean.setRepeat(false);
} else {
alarmEventBean.setRepeatTime(repeat);
alarmEventBean.setRepeat(true);
}
AlarmCacheHelper.setAlarm(NixonApplication.getContext(), index - 1, alarmEventBean);
}
public void sendCurrentZoneTime() {
boolean autoTime = SPUtils.getBoolean(NixonApplication.getContext(), Constant.IS_AUTO_TIME_KEY);
if (autoTime) {
if(null != mTimeComponent){
mTimeComponent.setMcuTime(1, new Date());
}
}
}
}
}
| UTF-8 | Java | 26,290 | java | MainContract.java | Java | [
{
"context": "Timer;\nimport java.util.TimerTask;\n\n/**\n * @author bo.\n * @Date 2017/5/26.\n * @desc\n */\n\npublic interfa",
"end": 2708,
"score": 0.5348079204559326,
"start": 2706,
"tag": "USERNAME",
"value": "bo"
},
{
"context": "().get(Calendar.WEEK_OF_YEAR);\n Log.e(\"NIXONLOGIN\", \"...weekYear..\" + weekYear);\n map.pu",
"end": 15532,
"score": 0.7512219548225403,
"start": 15522,
"tag": "USERNAME",
"value": "NIXONLOGIN"
},
{
"context": "etSportStepBean.class);\n //Log.e (\"NIXONLOGIN\", \" \" + bean.getInfo () + \" value = \" + bean.g",
"end": 17184,
"score": 0.7830613851547241,
"start": 17174,
"tag": "USERNAME",
"value": "NIXONLOGIN"
}
] | null | [] | package com.example.bo.nixon.presenter;
import android.content.ComponentName;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.example.bo.nixon.base.NixonApplication;
import com.example.bo.nixon.bean.AlarmEventBean;
import com.example.bo.nixon.bean.DbWatchBean;
import com.example.bo.nixon.bean.NetSportStepBean;
import com.example.bo.nixon.bean.UploadStepsBean;
import com.example.bo.nixon.db.DbManager;
import com.example.bo.nixon.db.DbWatchBeanCompat;
import com.example.bo.nixon.manager.ToastManager;
import com.example.bo.nixon.presenter.bleBase.BaseBlePresenter;
import com.example.bo.nixon.presenter.ota.IOtaPresenter;
import com.example.bo.nixon.ui.activity.main.IMain;
import com.example.bo.nixon.ui.fragment.alarm.AlarmCacheHelper;
import com.example.bo.nixon.utils.Constant;
import com.example.bo.nixon.utils.ConstantURL;
import com.example.bo.nixon.utils.HttpUtils;
import com.example.bo.nixon.utils.RequestCode;
import com.example.bo.nixon.utils.SPUtils;
import com.example.bo.nixon.version.DownLoaderTask;
import com.example.bo.nixon.version.FileUtil;
import com.example.bo.nixon.version.VersionControl;
import com.example.bo.nixon.version.ZIP;
import com.google.gson.Gson;
import com.smart.alarmcomponent.AlarmComponent;
import com.smart.alarmcomponent.IAlarm;
import com.smart.attributescomponent.AttributesComponent;
import com.smart.attributescomponent.listener.IPower;
import com.smart.attributescomponent.listener.IVersion;
import com.smart.connectComponent.ConnectComponent;
import com.smart.connectComponent.IAuthorization;
import com.smart.dataComponent.DataComponent;
import com.smart.dataComponent.DataStyle;
import com.smart.dataComponent.WatchBean;
import com.smart.dataComponent.listener.IRequestData;
import com.smart.dataComponent.listener.ITarget;
import com.smart.dataComponent.listener.IUpdateSumStep;
import com.smart.otacomponent.OTAComponent;
import com.smart.otacomponent.listener.IOTAListener;
import com.smart.smartble.DeviceMessage;
import com.smart.smartble.SmartManager;
import com.smart.smartble.utils.TimeZoneUtil;
import com.smart.timecomponent.ISecondTime;
import com.smart.timecomponent.TimeComponent;
import com.yanzhenjie.nohttp.rest.OnResponseListener;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author bo.
* @Date 2017/5/26.
* @desc
*/
public interface MainContract {
interface MainNixonView extends BaseNixonView {
void updateComplete(int step);
void electricity(int electricity);
void stepsDay(NetSportStepBean bean);
void stepsWeek(NetSportStepBean bean);
void stepsMonth(NetSportStepBean bean);
void onComplete(boolean isComplete);
void secondDate(Date date, int zone);
void showVersion(int main, int minor, int test);
void target(int target);
}
class MainPresenter extends BaseBlePresenter<MainNixonView> implements IUpdateSumStep, IPower, IMain, IRequestData,
VersionControl.VersionListener, DownLoaderTask.LoaderResultListener, IOtaPresenter, IOTAListener,
IVersion, ISecondTime, ITarget, IAuthorization ,IAlarm{
private static final String TAG = "MainPresenter";
private TimeComponent mTimeComponent;
private DataComponent mDataComponent;
private AttributesComponent mAttributesComponent;
private AlarmComponent mAlarmComponent;
private Handler mHandler = new Handler(Looper.getMainLooper());
private Gson gson = new Gson();
private List<DbWatchBean> dbWatchBeens;
private Map<String, String> map = new HashMap<> ();
private String deviceUUID;
private String cuntomerId = SPUtils.getString (NixonApplication.getContext (), Constant.CUSTOMER_ID);
private final int UPLOAD_WHAT = 777;
private final int GET_DAY_STEP = 12123;
private final int GET_WEEK_STEP = 12124;
private final int GET_MONTH_STEP = 12125;
private VersionControl mVersionControl;
private DownLoaderTask mDownLoaderTask;
private static final String PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/OTA/";
private OTAComponent mOtaComponent;
private ConnectComponent mConnectComponent;
private Timer mTimer;
@Override
protected void serviceConnected(SmartManager smartManager) {
mTimeComponent = new TimeComponent(smartManager);
mTimeComponent.registerComponent();
mTimeComponent.addSecondTimeListener(this);
mDataComponent = new DataComponent(smartManager);
mDataComponent.registerComponent();
mDataComponent.addSumStepListener(this);
mDataComponent.addRequestDataListener(this);
mDataComponent.addTargetListener(this);
mDataComponent.requestSumStep();
mAlarmComponent = AlarmComponent.getInstance(smartManager);
mAlarmComponent.registerComponent();
mAlarmComponent.addAlarmListener(this);
mAttributesComponent = AttributesComponent.getInstance(smartManager);
mAttributesComponent.registerComponent();
mAttributesComponent.addPowerListener(this);
mAttributesComponent.addVersionListener(this);
mAttributesComponent.getVersion();
mConnectComponent = ConnectComponent.getInstance(smartManager);
mConnectComponent.registerComponent();
mConnectComponent.addAuthorzationListener(this);
mOtaComponent = OTAComponent.getInstance(smartManager);
mOtaComponent.registerComponent();
mOtaComponent.addOTAListener(this);
startTimer();
}
private void startTimer() {
if (null != mTimer)
mTimer.cancel();
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
uploadAllData();
}
}, 0, 5 * 60 * 1000);
}
private void destroyTimer() {
if (null != mTimer)
mTimer.cancel();
}
@Override
public void attachView(MainNixonView view) {
super.attachView(view);
Log.e("DownLoaderTask", " Main attachView");
mVersionControl = new VersionControl();
mVersionControl.setVersionListener(this);
}
private void setAlarm() {
List<AlarmEventBean> eventBeen = AlarmCacheHelper.getAlarmList(NixonApplication.getContext());
for (int i = 0; i < eventBeen.size(); i++) {
AlarmEventBean alarmEventBean = eventBeen.get(i);
int open = alarmEventBean.isOpenType() ? 1 : 0;
if (0 != (alarmEventBean.getRepeatTime() & 128)) {
alarmEventBean.setRepeatTime(alarmEventBean.getRepeatTime() | 128);
}
mAlarmComponent.setAlarm(i + 1, alarmEventBean.getAlarmTime(), open, alarmEventBean.getRepeatTime());
}
}
@Override
protected void serviceDisconnected(ComponentName name) {
}
public void sendSecondTime(Date date, int arg1, int arg2) {
if (null != mTimeComponent) mTimeComponent.setSecondCity(date, arg1, arg2);
}
public void getStepValue() {
if (null != mDataComponent) mDataComponent.requestSumStep();
}
@Override
public void detachView() {
if (null != mDataComponent) {
mDataComponent.removeSumStepListener(this);
mDataComponent.removeTargetListener(this);
mDataComponent.removeSumStepListener(this);
mDataComponent.unRegisterComponent();
}
if (null != mAttributesComponent) {
mAttributesComponent.unRegisterComponent();
mAttributesComponent.removePowerListener(this);
}
if (null != mOtaComponent) {
mOtaComponent.unRegisterComponent();
}
if (null != mTimeComponent) {
mTimeComponent.removeSecondTimeListener(this);
mTimeComponent.unRegisterComponent();
}
if (null != mConnectComponent) {
mConnectComponent.unRegisterComponent();
mConnectComponent.removeAuthorzationListener(this);
}
if (null != mAlarmComponent) {
mAlarmComponent.removeAlarmListener(this);
mAlarmComponent.unRegisterComponent();
}
destroyTimer();
super.detachView();
}
@Override
public void sumStep(int step) {
if (null != getView()) getView().updateComplete(step);
}
@Override
public void electricity(int value) {
if (null != getView()) {
getView().electricity(value);
}
}
@Override
public void getElectricity() {
if (null != mAttributesComponent) {
mAttributesComponent.getElectricity();
}
}
@Override
public void onResume() {
if (null != mDataComponent) {
mDataComponent.requestSumStep();
}
if (null!= mOtaComponent){
mOtaComponent.addOTAListener (this);
}
}
@Override
public void onPause() {
if (null != mDataComponent) {
mDataComponent.pauseSumStep();
}
if (null!= mOtaComponent){
mOtaComponent.removeOTAListener (this);
}
}
@Override
public void setTargetValue(int target) {
if (null != mDataComponent) {
mDataComponent.setSportTarget(target);
}
}
@Override
public void getSecondTime() {
if (null != mTimeComponent) {
mTimeComponent.getSecondCity();
}
}
@Override
public void uploadAllData() {
if (null != mDataComponent) {
mDataComponent.requestContent(DataStyle.STEP);
}
}
@Override
public void startRequest() {
}
@Override
public void requestProgress(int max, int progress) {
}
@Override
public void requestComplete(List<WatchBean> watchBeen) {
for (int i = 0; i < watchBeen.size(); i++) {
Log.w("DataComponent", "requestComplete::" + watchBeen.size() + watchBeen.get(i).toString());
}
Log.e("UPDATELISTSTEPS", " 获取手表数据 成功");
if (watchBeen == null || watchBeen.size() == 0) {
return;
}
deviceUUID = DeviceMessage.getInstance ().getDeviceUUID ();
dbWatchBeens = DbWatchBeanCompat.watchBeenToDbWatchBean(watchBeen, cuntomerId, deviceUUID);
Log.e("UPDATELISTSTEPS", " 开始上传步数 ");
HttpUtils.getInstance().autoLogin();
updateListSteps(dbWatchBeens);
//updateSportData(10000 + "", cuntomerId, deviceUUID, 1483416000000l + "");
}
@Override
public void requestError(int errorCode, String errorMsg) {
}
private void updateListSteps (List<DbWatchBean> watchBeens) {
List<Map<String, String>> parmas = new ArrayList<> ();
Log.e ("UPDATELISTSTEPS", " watchBeens.size () = " + watchBeens.size ());
for (int i = 0; i < watchBeens.size (); i++) {
Map<String, String> element = new HashMap<> ();
DbWatchBean bean = watchBeens.get (i);
element.put ("customerId", bean.getUserId ());
element.put ("timestamp", bean.getTime () + "");
element.put ("step", bean.getValue () + "");
element.put ("deviceId", deviceUUID);
Log.d ("bigstep", " 时间 :: " + bean.getTime () + " 步数 :: " + bean.getValue ());
parmas.add (element);
}
HttpUtils.getInstance()
.requestCookieJsonArrayPost(ConstantURL.UPDATE_LIST_STEPS, 121212, parmas,
new SimpleResponseListener<JSONObject>() {
@Override
public void onSucceed(int what, Response<JSONObject> response) {
super.onSucceed(what, response);
NetSportStepBean bean = gson.fromJson(response.get().toString(), NetSportStepBean.class);
if (RequestCode.SUCCESS.equals(bean.getCode())) {
Log.e("UPDATELISTSTEPS", " 上传步数集合 成功");
} else if (RequestCode.NOT_LOGIN_STATE.equals(bean.getCode())) {
Log.e("UPDATELISTSTEPS", " 未登录状态 ");
}
}
@Override
public void onFailed(int what, Response<JSONObject> response) {
super.onFailed(what, response);
Log.e("UPDATELISTSTEPS", " 上传步数集合 失败 " + what);
if (null != dbWatchBeens) {
DbManager.insertDbWatchBean(dbWatchBeens);
}
}
});
}
private void updateSportData(String step, String customerID, String deviceID, String time) {
map.put("customerId", customerID);
map.put("timestamp", time);
map.put("step", step);
map.put("deviceId", deviceID);
HttpUtils.getInstance().requestJsonObjectPost(ConstantURL.UPDATE_STEPS, UPLOAD_WHAT, map, mListener);
}
public void getStepsByDay () {
deviceUUID = DeviceMessage.getInstance ().getDeviceUUID ();
Map<String, String> map = new HashMap<> ();
Date date = new Date ();
map.put ("year", date.getYear () + 1900 + "");
map.put ("month", date.getMonth () + 1 + "");
map.put ("day", date.getDate () + "");
map.put ("count", 30 + "");
map.put ("queryTimeOffSet", TimeZoneUtil.getCurrentTimeZone (Calendar.getInstance ().getTimeZone ()));
map.put ("deviceId", deviceUUID);
map.put ("customerId", cuntomerId);
HttpUtils.getInstance ()
.requestCookieJsonObjectPost (ConstantURL.GET_STEP_BY_DAY, GET_DAY_STEP, map, mSimpleResponseListener);
}
public void getStepsByWeek() {
Map<String, String> map = new HashMap<>();
Date date = new Date();
int weekYear = Calendar.getInstance().get(Calendar.WEEK_OF_YEAR);
Log.e("NIXONLOGIN", "...weekYear.." + weekYear);
map.put("year", date.getYear() + 1900 + "");
map.put("week", weekYear + "");
map.put("count", 16 + "");
map.put("queryTimeOffSet", TimeZoneUtil.getCurrentTimeZone(Calendar.getInstance().getTimeZone()));
map.put("deviceId", deviceUUID);
map.put("customerId", cuntomerId);
HttpUtils.getInstance()
.requestCookieJsonObjectPost(ConstantURL.GET_STEP_BY_WEEK, GET_WEEK_STEP, map,
mSimpleResponseListener);
}
public void getStepsByMonth () {
Map<String, String> map = new HashMap<> ();
Date date = new Date ();
map.put ("year", date.getYear () + 1900 + "");
map.put ("month", date.getMonth () + 1 + "");
map.put ("count", 28 + "");
map.put ("queryTimeOffSet", TimeZoneUtil.getCurrentTimeZone (Calendar.getInstance ().getTimeZone ()));
map.put ("deviceId", deviceUUID);
map.put ("customerId", cuntomerId);
HttpUtils.getInstance ()
.requestCookieJsonObjectPost (ConstantURL.GET_STEP_BY_MONTHS, GET_MONTH_STEP, map,
mSimpleResponseListener);
}
SimpleResponseListener mSimpleResponseListener = new SimpleResponseListener<JSONObject> () {
@Override public void onSucceed (int what, Response<JSONObject> response) {
super.onSucceed (what, response);
NetSportStepBean bean = gson.fromJson (response.get ().toString (), NetSportStepBean.class);
//Log.e ("NIXONLOGIN", " " + bean.getInfo () + " value = " + bean.getObject ().toString ());
switch (what) {
case GET_DAY_STEP:
switch (bean.getCode()) {
case RequestCode.SUCCESS:
if (getView() != null) {
getView().stepsDay(bean);
}
getStepsByWeek();
break;
default:
break;
}
break;
case GET_WEEK_STEP:
switch (bean.getCode()) {
case RequestCode.SUCCESS:
if (getView() != null) {
getView().stepsWeek(bean);
}
getStepsByMonth();
break;
default:
break;
}
break;
case GET_MONTH_STEP:
switch (bean.getCode()) {
case RequestCode.SUCCESS:
if (getView() != null) {
getView().stepsMonth(bean);
}
break;
default:
break;
}
break;
}
}
@Override
public void onFailed(int what, Response<JSONObject> response) {
super.onFailed(what, response);
Log.e("NIXONLOGIN", " 获取步数 失败 ");
if (response != null){
Log.e ("NIXONLOGIN"," response = " + response.getException ());
}
}
};
OnResponseListener mListener = new OnResponseListener<JSONObject>() {
@Override
public void onStart(int what) {
}
@Override
public void onSucceed(int what, Response<JSONObject> response) {
Log.e("NIXONLOGIN", " 成功" + response.get().toString());
UploadStepsBean bean = gson.fromJson(response.get().toString(), UploadStepsBean.class);
switch (bean.getCode()) {
case RequestCode.SUCCESS:
Log.e("NIXONLOGIN", "运动数据上传成功");
break;
case RequestCode.NOT_LOGIN_STATE:
HttpUtils.getInstance().autoLogin(ConstantURL.UPDATE_STEPS, UPLOAD_WHAT, map, mListener);
break;
case RequestCode.LACK_USERINFO:
break;
}
}
@Override
public void onFailed(int what, Response<JSONObject> response) {
Log.e("NIXONLOGIN", " 运动数据上传失败 " + response.get().toString());
if (null != dbWatchBeens) {
DbManager.insertDbWatchBean(dbWatchBeens);
}
}
@Override
public void onFinish(int what) {
}
};
public void downLoad(String url) {
Log.w("DownLoaderTask", "run--------->1" + url);
if (TextUtils.isEmpty(url))
return;
Log.w("DownLoaderTask", "run--------->2" + url);
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/OTA/");
FileUtil.DeleteFile(file);
mDownLoaderTask = new DownLoaderTask(url, PATH);
mDownLoaderTask.setLoaderResultListener(this);
mDownLoaderTask.execute();
}
public void checkoutVersion(String version) {
if (null != mVersionControl) {
Log.e("DownLoaderTask", " 检测版本");
mVersionControl.checkVersion(version, "P7003");
}
}
@Override
public void onSuccessful(String url, String message) {
Log.w("DownLoaderTask", "开始下载新版本 ");
downLoad(url);
}
@Override
public void onNoVersion() {
}
@Override
public void onVersionProgress(long max, long progress) {
}
@Override
public void onVersionResult(boolean complete, String path) {
Log.w("DownLoaderTask", "下载成功");
File file = new File(path);
if (null != file)
if (file.getName().endsWith("zip")) {
try {
ZIP.UnZipFolder(file.getAbsolutePath(), file.getParent(), new ZIP.ZipResult() {
@Override
public void complete(String path) {
startOTA(path);
Log.w("DownLoaderTask", "complete::" + path);
}
});
} catch (Exception e) {
e.printStackTrace();
Log.w("DownLoaderTask", "Exception" + e.toString());
}
}
}
public void confirmUpdateOta() {
mOtaComponent.delayToSendMcu();
}
@Override
public void startOTA(String path) {
if (!TextUtils.isEmpty(path))
mOtaComponent.startPath(path);
}
@Override
public void dealFile() {
Log.w(TAG, "dealFile::");
}
@Override
public void otaStart() {
Log.w(TAG, "otaStart::");
//if (null != getView())
// getView().onBegin();
}
@Override
public void onProgress(int max, int progress) {
Log.w("OTAComponent", "onProgress::" + max + " or " + progress);
//if (null != getView())
// getView().onProgress(max, progress);
}
@Override
public void onComplete(int complete) {
Log.w(TAG, "onComplete::");
if (0 == complete) {
ToastManager.show(NixonApplication.getContext(), "升级成功", Toast.LENGTH_SHORT);
} else if (5 == complete) {
ToastManager.show(NixonApplication.getContext(), "升级版本与当前版本一致请更新", Toast.LENGTH_SHORT);
} else {
ToastManager.show(NixonApplication.getContext(), "升级中断", Toast.LENGTH_SHORT);
}
if (null != getView())
getView().onComplete(0 == complete);
}
@Override
public void onFail() {
Log.w(TAG, "onFail::");
}
@Override
public void secondTime(Date date, int high, int low) {
if (null != getView()) {
getView().secondDate(date, high);
}
}
@Override
public void version(int main, int minor, int test) {
Log.e("DownLoaderTask", " xinbanben ");
if (null != getView()) {
getView().showVersion(main, minor, test);
}
}
@Override
public void target(int target) {
SPUtils.putString(NixonApplication.getContext(), Constant.GOAL_KEY, String.valueOf(target));
if (null != getView()) {
getView().target(target);
}
}
@Override
public void authorization(boolean author) {
if (author) {
uploadAllData();
}
}
@Override
public void AuthorizationTimeOut() {
}
@Override
public void alarm(int index, int time, int open, int repeat) {
if (repeat == 0)
return;
AlarmEventBean alarmEventBean =
AlarmCacheHelper.getAlarmEventBean(NixonApplication.getContext(), index - 1);
alarmEventBean.setAlarmTime(time);
alarmEventBean.setOpenType(open == 1);
if ((repeat & 128) != 128) {
alarmEventBean.setRepeatTime(repeat & 128);
alarmEventBean.setRepeat(false);
} else {
alarmEventBean.setRepeatTime(repeat);
alarmEventBean.setRepeat(true);
}
AlarmCacheHelper.setAlarm(NixonApplication.getContext(), index - 1, alarmEventBean);
}
public void sendCurrentZoneTime() {
boolean autoTime = SPUtils.getBoolean(NixonApplication.getContext(), Constant.IS_AUTO_TIME_KEY);
if (autoTime) {
if(null != mTimeComponent){
mTimeComponent.setMcuTime(1, new Date());
}
}
}
}
}
| 26,290 | 0.546162 | 0.541638 | 678 | 37.469025 | 27.026941 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.693215 | false | false | 9 |
954233d5879846879a610f0f2fbdab03f1af332e | 14,791,867,435,471 | 68327a264a1d53f3ca7169de00777c8dadcf9776 | /spring-boot-3-integrationtests/src/test/java/org/axonframework/springboot/autoconfig/AggregateStereotypeAutoConfigurationTest.java | 6e9496a95adc53ecaacc16936fabf2bd4eb4827d | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-unknown"
] | permissive | nagyist/AxonFramework | https://github.com/nagyist/AxonFramework | 03c0f9d4f059b3f7cd50323bfe85fbd33765f46b | d92f72af86e6a6304a46b229bb83cc67225ca32d | refs/heads/master | "2023-09-01T02:22:50.326000" | "2023-08-28T03:02:07" | "2023-08-28T03:02:07" | 21,167,278 | 0 | 0 | Apache-2.0 | true | "2023-09-11T19:36:58" | "2014-06-24T14:14:25" | "2022-12-17T05:48:02" | "2023-09-11T19:36:57" | 41,002 | 0 | 0 | 1 | Java | false | false | /*
* Copyright (c) 2010-2022. Axon Framework
*
* 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 org.axonframework.springboot.autoconfig;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.commandhandling.gateway.DefaultCommandGateway;
import org.axonframework.common.Registration;
import org.axonframework.common.caching.Cache;
import org.axonframework.common.lock.Lock;
import org.axonframework.common.lock.LockFactory;
import org.axonframework.eventsourcing.EventCountSnapshotTriggerDefinition;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.eventsourcing.EventSourcingRepository;
import org.axonframework.eventsourcing.SnapshotTriggerDefinition;
import org.axonframework.eventsourcing.Snapshotter;
import org.axonframework.eventsourcing.eventstore.EventStore;
import org.axonframework.eventsourcing.snapshotting.SnapshotFilter;
import org.axonframework.modelling.command.AggregateIdentifier;
import org.axonframework.modelling.command.CommandTargetResolver;
import org.axonframework.modelling.command.GenericJpaRepository;
import org.axonframework.modelling.command.Repository;
import org.axonframework.modelling.command.TargetAggregateIdentifier;
import org.axonframework.modelling.command.VersionedAggregateIdentifier;
import org.axonframework.spring.stereotype.Aggregate;
import org.junit.jupiter.api.*;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import static org.axonframework.common.StringUtils.lowerCaseFirstCharacterOf;
import static org.axonframework.modelling.command.AggregateLifecycle.apply;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
/**
* Test class validating whether the {@link Aggregate} stereotype annotation with the configurable bean names sets an
* Aggregate correctly.
*
* @author Steven van Beelen
*/
class AggregateStereotypeAutoConfigurationTest {
private static final Object AGGREGATE_IDENTIFIER = "aggregateIdentifier";
private static AtomicBoolean snapshotFilterInvoked;
private static AtomicBoolean commandTargetResolverInvoked;
private static AtomicBoolean cacheInvoked;
private static AtomicBoolean lockFactoryInvoked;
private ApplicationContextRunner testApplicationContext;
@BeforeEach
void setUp() {
snapshotFilterInvoked = new AtomicBoolean(false);
commandTargetResolverInvoked = new AtomicBoolean(false);
cacheInvoked = new AtomicBoolean(false);
lockFactoryInvoked = new AtomicBoolean(false);
testApplicationContext = new ApplicationContextRunner().withUserConfiguration(TestContext.class)
.withPropertyValues("axon.axonserver.enabled:false");
}
@Test
void aggregateStereotypeConfiguration() {
testApplicationContext.run(context -> {
// Publish the first command to create the TestAggregate
CommandGateway commandGateway = context.getBean(DefaultCommandGateway.class);
String aggregateId = commandGateway.sendAndWait(new CreateTestAggregate());
SnapshotTriggerDefinition snapshotTriggerDefinition =
context.getBean("testSnapshotTriggerDefinition", SnapshotTriggerDefinition.class);
verify(snapshotTriggerDefinition).prepareTrigger(TestContext.TestAggregate.class);
assertTrue(cacheInvoked.get());
assertTrue(lockFactoryInvoked.get());
// Publish the second command to trigger the SnapshotFilter and CommandTargetResolver
commandGateway.sendAndWait(new UpdateTestAggregate(aggregateId));
assertTrue(snapshotFilterInvoked.get());
assertTrue(commandTargetResolverInvoked.get());
EventStore eventStore = context.getBean("eventBus", EventStore.class);
assertTrue(eventStore.readEvents(aggregateId)
.asStream()
.allMatch(event -> Objects.equals(event.getType(), "testType")));
});
}
/**
* By configuring a custom {@link Repository} through the {@link Aggregate} stereotype, you remove the bean
* definitions of the {@link SnapshotTriggerDefinition}, {@link Cache}, and the {@link LockFactory}. This holds as
* the framework directly configures these components on the {@code Repository}. This test also asserts that the
* {@link SnapshotFilter} is <b>not</b> invoked, since the {@code SnapshotTriggerDefinition} is no longer defined on
* the {@code Repository}.
*/
@Test
void aggregateStereotypeWithCustomizedRepository() {
testApplicationContext.run(context -> {
// Publish the first command to create the TestAggregate
CommandGateway commandGateway = context.getBean(DefaultCommandGateway.class);
String aggregateId = commandGateway.sendAndWait(new CreateCustomRepoTestAggregate());
//noinspection unchecked
Repository<TestContext.CustomRepoTestAggregate> testRepository =
context.getBean("testRepository", Repository.class);
verify(testRepository).newInstance(any());
SnapshotTriggerDefinition snapshotTriggerDefinition =
context.getBean("testSnapshotTriggerDefinition", SnapshotTriggerDefinition.class);
verifyNoInteractions(snapshotTriggerDefinition);
assertFalse(cacheInvoked.get());
assertFalse(lockFactoryInvoked.get());
// Publish the second command to trigger the SnapshotFilter and CommandTargetResolver
commandGateway.sendAndWait(new UpdateCustomRepoTestAggregate(aggregateId));
verify(testRepository).load(aggregateId, null);
assertTrue(commandTargetResolverInvoked.get());
verifyNoInteractions(snapshotTriggerDefinition);
assertFalse(snapshotFilterInvoked.get());
assertFalse(cacheInvoked.get());
assertFalse(lockFactoryInvoked.get());
EventStore eventStore = context.getBean("eventBus", EventStore.class);
assertTrue(eventStore.readEvents(aggregateId)
.asStream()
.allMatch(event -> Objects.equals(event.getType(), "testTypeWithCustomRepository")));
});
}
@Test
void aggregateWithEntityManagerAnnotationIsAutoconfiguredWitDefaultJpaRepository() {
String expectedRepositoryBeanName = repositoryBeanName(TestContext.SimpleStateStoredAggregate.class);
testApplicationContext.run(context -> {
assertTrue(context.containsBean(expectedRepositoryBeanName));
Object actual = context.getBean(expectedRepositoryBeanName);
assertTrue(actual instanceof GenericJpaRepository, "Expected Jpa repository to have been configured");
});
}
private static String repositoryBeanName(@SuppressWarnings("SameParameterValue") Class<?> aggregateClass) {
return lowerCaseFirstCharacterOf(aggregateClass.getSimpleName()) + "Repository";
}
@Test
void aggregateWithEntityManagerAnnotationIsAutoconfiguredWitExistingJpaRepository() {
String beanName = "org.axonframework.springboot.autoconfig.AggregateStereotypeAutoConfigurationTest$TestContext$SimpleStateStoredAggregate";
Repository<?> mockRepo = mock(Repository.class);
testApplicationContext.withBean(beanName + "Repository", Repository.class, () -> mockRepo)
.run(context -> {
assertTrue(context.containsBean(beanName + "Repository"));
Object actual = context.getBean(beanName + "Repository");
assertSame(mockRepo, actual, "Expected defined repository to have been configured");
});
}
@Configuration
@EnableAutoConfiguration
static class TestContext {
@SuppressWarnings({"FieldCanBeLocal", "unused"})
@Aggregate(
snapshotTriggerDefinition = "testSnapshotTriggerDefinition",
snapshotFilter = "testSnapshotFilter",
type = "testType",
commandTargetResolver = "testCommandTargetResolver",
cache = "testCache",
lockFactory = "testLockFactory"
)
public static class TestAggregate {
@AggregateIdentifier
private String aggregateId;
@CommandHandler
public TestAggregate(CreateTestAggregate cmd) {
apply(new TestAggregateCreated(cmd.getAggregateId()));
// Publish multiple events to hit the snapshot event count when configured.
apply(new TestAggregateUpdated(cmd.getAggregateId()));
apply(new TestAggregateUpdated(cmd.getAggregateId()));
apply(new TestAggregateUpdated(cmd.getAggregateId()));
}
@CommandHandler
public void handle(UpdateTestAggregate command) {
// Do nothing
}
@EventSourcingHandler
public void on(TestAggregateCreated event) {
aggregateId = event.getAggregateId();
}
private TestAggregate() {
// Required by AggregateFactory
}
}
@SuppressWarnings({"FieldCanBeLocal", "unused"})
@Aggregate(
repository = "testRepository",
snapshotTriggerDefinition = "testSnapshotTriggerDefinition",
snapshotFilter = "testSnapshotFilter",
type = "testTypeWithCustomRepository",
commandTargetResolver = "testCommandTargetResolver",
cache = "testCache",
lockFactory = "testLockFactory"
)
private static class CustomRepoTestAggregate {
@AggregateIdentifier
private String aggregateId;
@CommandHandler
public CustomRepoTestAggregate(CreateCustomRepoTestAggregate cmd) {
apply(new CustomRepoTestAggregateCreated(cmd.getAggregateId()));
// Publish multiple events to hit the snapshot event count when configured.
apply(new CustomRepoTestAggregateUpdated(cmd.getAggregateId()));
apply(new CustomRepoTestAggregateUpdated(cmd.getAggregateId()));
apply(new CustomRepoTestAggregateUpdated(cmd.getAggregateId()));
}
@CommandHandler
public void handle(UpdateCustomRepoTestAggregate command) {
// Do nothing
}
@EventSourcingHandler
public void on(CustomRepoTestAggregateCreated event) {
aggregateId = event.getAggregateId();
}
private CustomRepoTestAggregate() {
// Required by AggregateFactory
}
}
@SuppressWarnings("unused")
@Entity(name = "simpleAggregate")
@Aggregate
private static class SimpleStateStoredAggregate {
@Id
private String aggregateId;
public SimpleStateStoredAggregate() {
// required for JPA
}
@CommandHandler
public SimpleStateStoredAggregate(CreateStateStoredAggregateCommand command) {
this.aggregateId = command.getAggregateId();
}
}
@Bean
public SnapshotTriggerDefinition testSnapshotTriggerDefinition(Snapshotter snapshotter) {
return spy(new EventCountSnapshotTriggerDefinition(snapshotter, 3));
}
@Bean
public SnapshotFilter testSnapshotFilter() {
return domainEventData -> {
snapshotFilterInvoked.set(true);
return false;
};
}
@Bean
public CommandTargetResolver testCommandTargetResolver() {
return command -> {
commandTargetResolverInvoked.set(true);
return new VersionedAggregateIdentifier(AGGREGATE_IDENTIFIER, null);
};
}
@Bean
public Cache testCache() {
return new Cache() {
@Override
public <K, V> V get(K key) {
return null;
}
@Override
public void put(Object key, Object value) {
cacheInvoked.set(true);
}
@Override
public boolean putIfAbsent(Object key, Object value) {
return false;
}
@Override
public <T> T computeIfAbsent(Object key, Supplier<T> valueSupplier) {
return valueSupplier.get();
}
@Override
public boolean remove(Object key) {
return false;
}
@Override
public void removeAll() {
// Do nothing.
}
@Override
public boolean containsKey(Object key) {
return false;
}
@Override
public Registration registerCacheEntryListener(EntryListener cacheEntryListener) {
return null;
}
@Override
public <V> void computeIfPresent(Object key, UnaryOperator<V> update) {
// Do nothing.
}
};
}
@Bean
public LockFactory testLockFactory() {
return identifier -> {
lockFactoryInvoked.set(true);
return new Lock() {
@Override
public void release() {
// Do nothing
}
@Override
public boolean isHeld() {
return true;
}
};
};
}
@Bean
public Repository<CustomRepoTestAggregate> testRepository(EventStore eventStore) {
return spy(EventSourcingRepository.builder(CustomRepoTestAggregate.class)
.eventStore(eventStore)
.build());
}
}
static class CreateStateStoredAggregateCommand {
final String aggregateId;
CreateStateStoredAggregateCommand(String aggregateId) {
this.aggregateId = aggregateId;
}
public String getAggregateId() {
return aggregateId;
}
}
static class CreateTestAggregate {
private final String aggregateId;
CreateTestAggregate() {
this(AGGREGATE_IDENTIFIER.toString());
}
CreateTestAggregate(String aggregateId) {
this.aggregateId = aggregateId;
}
public String getAggregateId() {
return aggregateId;
}
}
static class TestAggregateCreated {
private final String aggregateId;
TestAggregateCreated(String aggregateId) {
this.aggregateId = aggregateId;
}
public String getAggregateId() {
return aggregateId;
}
}
@SuppressWarnings("unused")
static class UpdateTestAggregate {
@TargetAggregateIdentifier
private final String aggregateId;
UpdateTestAggregate() {
this(AGGREGATE_IDENTIFIER.toString());
}
UpdateTestAggregate(String aggregateId) {
this.aggregateId = aggregateId;
}
public String getAggregateId() {
return aggregateId;
}
}
@SuppressWarnings("unused")
static class TestAggregateUpdated {
private final String aggregateId;
TestAggregateUpdated(String aggregateId) {
this.aggregateId = aggregateId;
}
public String getAggregateId() {
return aggregateId;
}
}
static class CreateCustomRepoTestAggregate {
private final String aggregateId;
CreateCustomRepoTestAggregate() {
this(AGGREGATE_IDENTIFIER.toString());
}
CreateCustomRepoTestAggregate(String aggregateId) {
this.aggregateId = aggregateId;
}
public String getAggregateId() {
return aggregateId;
}
}
static class CustomRepoTestAggregateCreated {
private final String aggregateId;
CustomRepoTestAggregateCreated(String aggregateId) {
this.aggregateId = aggregateId;
}
public String getAggregateId() {
return aggregateId;
}
}
@SuppressWarnings("unused")
static class UpdateCustomRepoTestAggregate {
@TargetAggregateIdentifier
private final String aggregateId;
UpdateCustomRepoTestAggregate() {
this(AGGREGATE_IDENTIFIER.toString());
}
UpdateCustomRepoTestAggregate(String aggregateId) {
this.aggregateId = aggregateId;
}
public String getAggregateId() {
return aggregateId;
}
}
@SuppressWarnings("unused")
static class CustomRepoTestAggregateUpdated {
private final String aggregateId;
CustomRepoTestAggregateUpdated(String aggregateId) {
this.aggregateId = aggregateId;
}
public String getAggregateId() {
return aggregateId;
}
}
}
| UTF-8 | Java | 18,691 | java | AggregateStereotypeAutoConfigurationTest.java | Java | [
{
"context": "ames sets an\n * Aggregate correctly.\n *\n * @author Steven van Beelen\n */\nclass AggregateStereotypeAutoConfigurationTes",
"end": 2868,
"score": 0.9992577433586121,
"start": 2851,
"tag": "NAME",
"value": "Steven van Beelen"
}
] | null | [] | /*
* Copyright (c) 2010-2022. Axon Framework
*
* 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 org.axonframework.springboot.autoconfig;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.commandhandling.gateway.DefaultCommandGateway;
import org.axonframework.common.Registration;
import org.axonframework.common.caching.Cache;
import org.axonframework.common.lock.Lock;
import org.axonframework.common.lock.LockFactory;
import org.axonframework.eventsourcing.EventCountSnapshotTriggerDefinition;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.eventsourcing.EventSourcingRepository;
import org.axonframework.eventsourcing.SnapshotTriggerDefinition;
import org.axonframework.eventsourcing.Snapshotter;
import org.axonframework.eventsourcing.eventstore.EventStore;
import org.axonframework.eventsourcing.snapshotting.SnapshotFilter;
import org.axonframework.modelling.command.AggregateIdentifier;
import org.axonframework.modelling.command.CommandTargetResolver;
import org.axonframework.modelling.command.GenericJpaRepository;
import org.axonframework.modelling.command.Repository;
import org.axonframework.modelling.command.TargetAggregateIdentifier;
import org.axonframework.modelling.command.VersionedAggregateIdentifier;
import org.axonframework.spring.stereotype.Aggregate;
import org.junit.jupiter.api.*;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import static org.axonframework.common.StringUtils.lowerCaseFirstCharacterOf;
import static org.axonframework.modelling.command.AggregateLifecycle.apply;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
/**
* Test class validating whether the {@link Aggregate} stereotype annotation with the configurable bean names sets an
* Aggregate correctly.
*
* @author <NAME>
*/
class AggregateStereotypeAutoConfigurationTest {
private static final Object AGGREGATE_IDENTIFIER = "aggregateIdentifier";
private static AtomicBoolean snapshotFilterInvoked;
private static AtomicBoolean commandTargetResolverInvoked;
private static AtomicBoolean cacheInvoked;
private static AtomicBoolean lockFactoryInvoked;
private ApplicationContextRunner testApplicationContext;
@BeforeEach
void setUp() {
snapshotFilterInvoked = new AtomicBoolean(false);
commandTargetResolverInvoked = new AtomicBoolean(false);
cacheInvoked = new AtomicBoolean(false);
lockFactoryInvoked = new AtomicBoolean(false);
testApplicationContext = new ApplicationContextRunner().withUserConfiguration(TestContext.class)
.withPropertyValues("axon.axonserver.enabled:false");
}
@Test
void aggregateStereotypeConfiguration() {
testApplicationContext.run(context -> {
// Publish the first command to create the TestAggregate
CommandGateway commandGateway = context.getBean(DefaultCommandGateway.class);
String aggregateId = commandGateway.sendAndWait(new CreateTestAggregate());
SnapshotTriggerDefinition snapshotTriggerDefinition =
context.getBean("testSnapshotTriggerDefinition", SnapshotTriggerDefinition.class);
verify(snapshotTriggerDefinition).prepareTrigger(TestContext.TestAggregate.class);
assertTrue(cacheInvoked.get());
assertTrue(lockFactoryInvoked.get());
// Publish the second command to trigger the SnapshotFilter and CommandTargetResolver
commandGateway.sendAndWait(new UpdateTestAggregate(aggregateId));
assertTrue(snapshotFilterInvoked.get());
assertTrue(commandTargetResolverInvoked.get());
EventStore eventStore = context.getBean("eventBus", EventStore.class);
assertTrue(eventStore.readEvents(aggregateId)
.asStream()
.allMatch(event -> Objects.equals(event.getType(), "testType")));
});
}
/**
* By configuring a custom {@link Repository} through the {@link Aggregate} stereotype, you remove the bean
* definitions of the {@link SnapshotTriggerDefinition}, {@link Cache}, and the {@link LockFactory}. This holds as
* the framework directly configures these components on the {@code Repository}. This test also asserts that the
* {@link SnapshotFilter} is <b>not</b> invoked, since the {@code SnapshotTriggerDefinition} is no longer defined on
* the {@code Repository}.
*/
@Test
void aggregateStereotypeWithCustomizedRepository() {
testApplicationContext.run(context -> {
// Publish the first command to create the TestAggregate
CommandGateway commandGateway = context.getBean(DefaultCommandGateway.class);
String aggregateId = commandGateway.sendAndWait(new CreateCustomRepoTestAggregate());
//noinspection unchecked
Repository<TestContext.CustomRepoTestAggregate> testRepository =
context.getBean("testRepository", Repository.class);
verify(testRepository).newInstance(any());
SnapshotTriggerDefinition snapshotTriggerDefinition =
context.getBean("testSnapshotTriggerDefinition", SnapshotTriggerDefinition.class);
verifyNoInteractions(snapshotTriggerDefinition);
assertFalse(cacheInvoked.get());
assertFalse(lockFactoryInvoked.get());
// Publish the second command to trigger the SnapshotFilter and CommandTargetResolver
commandGateway.sendAndWait(new UpdateCustomRepoTestAggregate(aggregateId));
verify(testRepository).load(aggregateId, null);
assertTrue(commandTargetResolverInvoked.get());
verifyNoInteractions(snapshotTriggerDefinition);
assertFalse(snapshotFilterInvoked.get());
assertFalse(cacheInvoked.get());
assertFalse(lockFactoryInvoked.get());
EventStore eventStore = context.getBean("eventBus", EventStore.class);
assertTrue(eventStore.readEvents(aggregateId)
.asStream()
.allMatch(event -> Objects.equals(event.getType(), "testTypeWithCustomRepository")));
});
}
@Test
void aggregateWithEntityManagerAnnotationIsAutoconfiguredWitDefaultJpaRepository() {
String expectedRepositoryBeanName = repositoryBeanName(TestContext.SimpleStateStoredAggregate.class);
testApplicationContext.run(context -> {
assertTrue(context.containsBean(expectedRepositoryBeanName));
Object actual = context.getBean(expectedRepositoryBeanName);
assertTrue(actual instanceof GenericJpaRepository, "Expected Jpa repository to have been configured");
});
}
private static String repositoryBeanName(@SuppressWarnings("SameParameterValue") Class<?> aggregateClass) {
return lowerCaseFirstCharacterOf(aggregateClass.getSimpleName()) + "Repository";
}
@Test
void aggregateWithEntityManagerAnnotationIsAutoconfiguredWitExistingJpaRepository() {
String beanName = "org.axonframework.springboot.autoconfig.AggregateStereotypeAutoConfigurationTest$TestContext$SimpleStateStoredAggregate";
Repository<?> mockRepo = mock(Repository.class);
testApplicationContext.withBean(beanName + "Repository", Repository.class, () -> mockRepo)
.run(context -> {
assertTrue(context.containsBean(beanName + "Repository"));
Object actual = context.getBean(beanName + "Repository");
assertSame(mockRepo, actual, "Expected defined repository to have been configured");
});
}
@Configuration
@EnableAutoConfiguration
static class TestContext {
@SuppressWarnings({"FieldCanBeLocal", "unused"})
@Aggregate(
snapshotTriggerDefinition = "testSnapshotTriggerDefinition",
snapshotFilter = "testSnapshotFilter",
type = "testType",
commandTargetResolver = "testCommandTargetResolver",
cache = "testCache",
lockFactory = "testLockFactory"
)
public static class TestAggregate {
@AggregateIdentifier
private String aggregateId;
@CommandHandler
public TestAggregate(CreateTestAggregate cmd) {
apply(new TestAggregateCreated(cmd.getAggregateId()));
// Publish multiple events to hit the snapshot event count when configured.
apply(new TestAggregateUpdated(cmd.getAggregateId()));
apply(new TestAggregateUpdated(cmd.getAggregateId()));
apply(new TestAggregateUpdated(cmd.getAggregateId()));
}
@CommandHandler
public void handle(UpdateTestAggregate command) {
// Do nothing
}
@EventSourcingHandler
public void on(TestAggregateCreated event) {
aggregateId = event.getAggregateId();
}
private TestAggregate() {
// Required by AggregateFactory
}
}
@SuppressWarnings({"FieldCanBeLocal", "unused"})
@Aggregate(
repository = "testRepository",
snapshotTriggerDefinition = "testSnapshotTriggerDefinition",
snapshotFilter = "testSnapshotFilter",
type = "testTypeWithCustomRepository",
commandTargetResolver = "testCommandTargetResolver",
cache = "testCache",
lockFactory = "testLockFactory"
)
private static class CustomRepoTestAggregate {
@AggregateIdentifier
private String aggregateId;
@CommandHandler
public CustomRepoTestAggregate(CreateCustomRepoTestAggregate cmd) {
apply(new CustomRepoTestAggregateCreated(cmd.getAggregateId()));
// Publish multiple events to hit the snapshot event count when configured.
apply(new CustomRepoTestAggregateUpdated(cmd.getAggregateId()));
apply(new CustomRepoTestAggregateUpdated(cmd.getAggregateId()));
apply(new CustomRepoTestAggregateUpdated(cmd.getAggregateId()));
}
@CommandHandler
public void handle(UpdateCustomRepoTestAggregate command) {
// Do nothing
}
@EventSourcingHandler
public void on(CustomRepoTestAggregateCreated event) {
aggregateId = event.getAggregateId();
}
private CustomRepoTestAggregate() {
// Required by AggregateFactory
}
}
@SuppressWarnings("unused")
@Entity(name = "simpleAggregate")
@Aggregate
private static class SimpleStateStoredAggregate {
@Id
private String aggregateId;
public SimpleStateStoredAggregate() {
// required for JPA
}
@CommandHandler
public SimpleStateStoredAggregate(CreateStateStoredAggregateCommand command) {
this.aggregateId = command.getAggregateId();
}
}
@Bean
public SnapshotTriggerDefinition testSnapshotTriggerDefinition(Snapshotter snapshotter) {
return spy(new EventCountSnapshotTriggerDefinition(snapshotter, 3));
}
@Bean
public SnapshotFilter testSnapshotFilter() {
return domainEventData -> {
snapshotFilterInvoked.set(true);
return false;
};
}
@Bean
public CommandTargetResolver testCommandTargetResolver() {
return command -> {
commandTargetResolverInvoked.set(true);
return new VersionedAggregateIdentifier(AGGREGATE_IDENTIFIER, null);
};
}
@Bean
public Cache testCache() {
return new Cache() {
@Override
public <K, V> V get(K key) {
return null;
}
@Override
public void put(Object key, Object value) {
cacheInvoked.set(true);
}
@Override
public boolean putIfAbsent(Object key, Object value) {
return false;
}
@Override
public <T> T computeIfAbsent(Object key, Supplier<T> valueSupplier) {
return valueSupplier.get();
}
@Override
public boolean remove(Object key) {
return false;
}
@Override
public void removeAll() {
// Do nothing.
}
@Override
public boolean containsKey(Object key) {
return false;
}
@Override
public Registration registerCacheEntryListener(EntryListener cacheEntryListener) {
return null;
}
@Override
public <V> void computeIfPresent(Object key, UnaryOperator<V> update) {
// Do nothing.
}
};
}
@Bean
public LockFactory testLockFactory() {
return identifier -> {
lockFactoryInvoked.set(true);
return new Lock() {
@Override
public void release() {
// Do nothing
}
@Override
public boolean isHeld() {
return true;
}
};
};
}
@Bean
public Repository<CustomRepoTestAggregate> testRepository(EventStore eventStore) {
return spy(EventSourcingRepository.builder(CustomRepoTestAggregate.class)
.eventStore(eventStore)
.build());
}
}
static class CreateStateStoredAggregateCommand {
final String aggregateId;
CreateStateStoredAggregateCommand(String aggregateId) {
this.aggregateId = aggregateId;
}
public String getAggregateId() {
return aggregateId;
}
}
static class CreateTestAggregate {
private final String aggregateId;
CreateTestAggregate() {
this(AGGREGATE_IDENTIFIER.toString());
}
CreateTestAggregate(String aggregateId) {
this.aggregateId = aggregateId;
}
public String getAggregateId() {
return aggregateId;
}
}
static class TestAggregateCreated {
private final String aggregateId;
TestAggregateCreated(String aggregateId) {
this.aggregateId = aggregateId;
}
public String getAggregateId() {
return aggregateId;
}
}
@SuppressWarnings("unused")
static class UpdateTestAggregate {
@TargetAggregateIdentifier
private final String aggregateId;
UpdateTestAggregate() {
this(AGGREGATE_IDENTIFIER.toString());
}
UpdateTestAggregate(String aggregateId) {
this.aggregateId = aggregateId;
}
public String getAggregateId() {
return aggregateId;
}
}
@SuppressWarnings("unused")
static class TestAggregateUpdated {
private final String aggregateId;
TestAggregateUpdated(String aggregateId) {
this.aggregateId = aggregateId;
}
public String getAggregateId() {
return aggregateId;
}
}
static class CreateCustomRepoTestAggregate {
private final String aggregateId;
CreateCustomRepoTestAggregate() {
this(AGGREGATE_IDENTIFIER.toString());
}
CreateCustomRepoTestAggregate(String aggregateId) {
this.aggregateId = aggregateId;
}
public String getAggregateId() {
return aggregateId;
}
}
static class CustomRepoTestAggregateCreated {
private final String aggregateId;
CustomRepoTestAggregateCreated(String aggregateId) {
this.aggregateId = aggregateId;
}
public String getAggregateId() {
return aggregateId;
}
}
@SuppressWarnings("unused")
static class UpdateCustomRepoTestAggregate {
@TargetAggregateIdentifier
private final String aggregateId;
UpdateCustomRepoTestAggregate() {
this(AGGREGATE_IDENTIFIER.toString());
}
UpdateCustomRepoTestAggregate(String aggregateId) {
this.aggregateId = aggregateId;
}
public String getAggregateId() {
return aggregateId;
}
}
@SuppressWarnings("unused")
static class CustomRepoTestAggregateUpdated {
private final String aggregateId;
CustomRepoTestAggregateUpdated(String aggregateId) {
this.aggregateId = aggregateId;
}
public String getAggregateId() {
return aggregateId;
}
}
}
| 18,680 | 0.635333 | 0.634637 | 515 | 35.293205 | 30.221087 | 148 | false | false | 0 | 0 | 0 | 0 | 76 | 0.008079 | 0.382524 | false | false | 9 |
a78cca68338973ccbf196413fddf33f92bfd318a | 6,751,688,644,895 | 5d37b26ec4377e90d8584f9e96bb693ed2e96495 | /Moveon/src/main/java/com/mphasis/moveon/entities/Vehicle.java | 131b726d0aae2120beae5aa01ccf7bfa0cb31db3 | [] | no_license | trainingprojects-159/MoveOn | https://github.com/trainingprojects-159/MoveOn | 4957ac2979012d82ece88834a4761562fcd6bfc8 | e7e453570cf5b388ba11abf5f17c1d689a138f54 | refs/heads/master | "2020-05-20T02:18:41.412000" | "2019-05-14T13:13:16" | "2019-05-14T13:13:16" | 185,328,963 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mphasis.moveon.entities;
import javax.persistence.Entity;
import org.hibernate.annotations.*;
import com.mphasis.moveon.util.StringPrefixedSequenceIdGenerator;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class Vehicle
{
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="vehicle_seq")
@GenericGenerator(
name = "vehicle_seq",
strategy = "com.mphasis.moveon.util.StringPrefixedSequenceIdGenerator",
parameters = {
@Parameter(name = StringPrefixedSequenceIdGenerator.INCREMENT_PARAM, value = "4"),
@Parameter(name = StringPrefixedSequenceIdGenerator.VALUE_PREFIX_PARAMETER, value = "VI"),
@Parameter(name = StringPrefixedSequenceIdGenerator.NUMBER_FORMAT_PARAMETER, value = "%03d") })
private String vehicle_Id;
private String vehicle_Name;
private String vehicle_Type;
private int seat_Capacity;
private String vehicle_Num;
private double fare;
@ManyToOne
private Admin admin;
@ManyToOne
private Route route;
public void setRoute(Route route) {
this.route = route;
}
public void setAdmin(Admin admin) {
this.admin = admin;
}
public String getVehicle_Id() {
return vehicle_Id;
}
public void setVehicle_Id(String vehicle_Id) {
this.vehicle_Id = vehicle_Id;
}
public String getVehicle_Name() {
return vehicle_Name;
}
public void setVehicle_Name(String vehicle_Name) {
this.vehicle_Name = vehicle_Name;
}
public String getVehicle_Type() {
return vehicle_Type;
}
public void setVehicle_Type(String vehicle_Type) {
this.vehicle_Type = vehicle_Type;
}
public int getSeat_Capacity() {
return seat_Capacity;
}
public void setSeat_Capacity(int seat_Capacity) {
this.seat_Capacity = seat_Capacity;
}
public String getVehicle_Num() {
return vehicle_Num;
}
public void setVehicle_Num(String vehicle_Num) {
this.vehicle_Num = vehicle_Num;
}
public double getFare() {
return fare;
}
public void setFare(double fare) {
this.fare = fare;
}
}
| UTF-8 | Java | 2,210 | java | Vehicle.java | Java | [] | null | [] | package com.mphasis.moveon.entities;
import javax.persistence.Entity;
import org.hibernate.annotations.*;
import com.mphasis.moveon.util.StringPrefixedSequenceIdGenerator;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class Vehicle
{
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="vehicle_seq")
@GenericGenerator(
name = "vehicle_seq",
strategy = "com.mphasis.moveon.util.StringPrefixedSequenceIdGenerator",
parameters = {
@Parameter(name = StringPrefixedSequenceIdGenerator.INCREMENT_PARAM, value = "4"),
@Parameter(name = StringPrefixedSequenceIdGenerator.VALUE_PREFIX_PARAMETER, value = "VI"),
@Parameter(name = StringPrefixedSequenceIdGenerator.NUMBER_FORMAT_PARAMETER, value = "%03d") })
private String vehicle_Id;
private String vehicle_Name;
private String vehicle_Type;
private int seat_Capacity;
private String vehicle_Num;
private double fare;
@ManyToOne
private Admin admin;
@ManyToOne
private Route route;
public void setRoute(Route route) {
this.route = route;
}
public void setAdmin(Admin admin) {
this.admin = admin;
}
public String getVehicle_Id() {
return vehicle_Id;
}
public void setVehicle_Id(String vehicle_Id) {
this.vehicle_Id = vehicle_Id;
}
public String getVehicle_Name() {
return vehicle_Name;
}
public void setVehicle_Name(String vehicle_Name) {
this.vehicle_Name = vehicle_Name;
}
public String getVehicle_Type() {
return vehicle_Type;
}
public void setVehicle_Type(String vehicle_Type) {
this.vehicle_Type = vehicle_Type;
}
public int getSeat_Capacity() {
return seat_Capacity;
}
public void setSeat_Capacity(int seat_Capacity) {
this.seat_Capacity = seat_Capacity;
}
public String getVehicle_Num() {
return vehicle_Num;
}
public void setVehicle_Num(String vehicle_Num) {
this.vehicle_Num = vehicle_Num;
}
public double getFare() {
return fare;
}
public void setFare(double fare) {
this.fare = fare;
}
}
| 2,210 | 0.699548 | 0.69819 | 84 | 24.309525 | 23.756691 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.452381 | false | false | 9 |
1f84d6867bf7d0c2b82f00d413b72d10622f9df5 | 36,129,264,902,644 | f8cd162c849f5bf67a9ea3fc24dfab8ee1c3f43f | /umi-boot-service/src/main/java/org/umi/boot/web/rest/manage/ResourceAttribute.java | efa1a9b7e2b1b46994ce651c1c28f6c5fdc295a5 | [
"MIT"
] | permissive | huang6349/umi-boot-admin | https://github.com/huang6349/umi-boot-admin | fd135feb8a67eb20cfd4b0cf0bbc743c6c3cc8aa | c76fb04ea4e4fe2d309d19a4e1061113a8ce4220 | refs/heads/master | "2023-02-26T08:14:05.700000" | "2023-01-10T00:37:32" | "2023-01-10T00:37:32" | 282,758,132 | 0 | 0 | MIT | false | "2023-02-04T20:14:20" | "2020-07-27T00:34:15" | "2022-12-07T08:06:13" | "2023-02-04T20:14:20" | 2,218 | 0 | 0 | 2 | Java | false | false | package org.umi.boot.web.rest.manage;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.umi.boot.domain.Resource;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@ApiModel(description = "菜单资源管理(新增属性)", value = "ResourceAttribute")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResourceAttribute {
@ApiModelProperty(value = "所属菜单", required = true)
@NotNull(message = "所属菜单不能为空")
private Long permissionId;
@ApiModelProperty(value = "资源地址", required = true)
@NotBlank(message = "资源地址不能为空")
private String pattern;
@ApiModelProperty(value = "资源类型", required = true)
@NotNull(message = "资源类型不能为空")
private Long methodId;
@ApiModelProperty(value = "资源描述")
private String desc;
public static Resource adapt(ResourceAttribute attribute) {
if (attribute == null) return null;
Resource resource = new Resource();
BeanUtils.copyProperties(attribute, resource);
return resource;
}
}
| UTF-8 | Java | 1,304 | java | ResourceAttribute.java | Java | [] | null | [] | package org.umi.boot.web.rest.manage;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.umi.boot.domain.Resource;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@ApiModel(description = "菜单资源管理(新增属性)", value = "ResourceAttribute")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResourceAttribute {
@ApiModelProperty(value = "所属菜单", required = true)
@NotNull(message = "所属菜单不能为空")
private Long permissionId;
@ApiModelProperty(value = "资源地址", required = true)
@NotBlank(message = "资源地址不能为空")
private String pattern;
@ApiModelProperty(value = "资源类型", required = true)
@NotNull(message = "资源类型不能为空")
private Long methodId;
@ApiModelProperty(value = "资源描述")
private String desc;
public static Resource adapt(ResourceAttribute attribute) {
if (attribute == null) return null;
Resource resource = new Resource();
BeanUtils.copyProperties(attribute, resource);
return resource;
}
}
| 1,304 | 0.7375 | 0.7375 | 41 | 28.268293 | 19.750917 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.560976 | false | false | 9 |
dbc5005272368168d97a0646e21387fcbaa2ab97 | 266,288,020,772 | e977a7210e645dcd42e8b58cd8dfef88c9180bd4 | /src/main/java/com/cg/aps/serviceimpl/VisitorServiceImpl.java | c47abf4d44fc3d7e384237a22b4a5549912c73a9 | [] | no_license | Paneeshbs77/Sprint1 | https://github.com/Paneeshbs77/Sprint1 | b6fbf3f30a1cdd86cb99a4b85bfc721ab2ed8d6c | bd603a2858866bb64a28bc400eda2c53cecaa8ee | refs/heads/main | "2023-07-02T20:21:24.655000" | "2021-08-10T08:11:19" | "2021-08-10T08:11:19" | 392,666,669 | 0 | 0 | null | true | "2021-08-04T11:42:23" | "2021-08-04T11:42:23" | "2021-08-02T08:47:39" | "2021-08-02T08:47:36" | 63 | 0 | 0 | 0 | null | false | false | package com.cg.aps.serviceimpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cg.aps.dao.VisitorDAOInt;
import com.cg.aps.entities.VisitorEntity;
import com.cg.aps.service.VisitorServiceInt;
@Service
public class VisitorServiceImpl implements VisitorServiceInt {
@Autowired
VisitorDAOInt dao;
public VisitorServiceImpl() {
}
public VisitorServiceImpl(VisitorDAOInt dao) {
this.dao=dao;
}
@Override
public void add(VisitorEntity bean) {
dao.add(bean);
}
@Override
public void update(VisitorEntity bean) {
dao.update(bean);
}
@Override
public void delete(int visId) {
dao.delete(visId);
}
@Override
public VisitorEntity findByName(String name) {
return dao.findByName(name);
}
@Override
public VisitorEntity findByPk(int id) {
return dao.findByPk(id);
}
@Override
public List<VisitorEntity> getAllVisitors() {
return dao.getAllVisitors();
}
@Override
public VisitorEntity getVisitor(int id) {
return dao.getVisitor(id);
}
}
| UTF-8 | Java | 1,092 | java | VisitorServiceImpl.java | Java | [] | null | [] | package com.cg.aps.serviceimpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cg.aps.dao.VisitorDAOInt;
import com.cg.aps.entities.VisitorEntity;
import com.cg.aps.service.VisitorServiceInt;
@Service
public class VisitorServiceImpl implements VisitorServiceInt {
@Autowired
VisitorDAOInt dao;
public VisitorServiceImpl() {
}
public VisitorServiceImpl(VisitorDAOInt dao) {
this.dao=dao;
}
@Override
public void add(VisitorEntity bean) {
dao.add(bean);
}
@Override
public void update(VisitorEntity bean) {
dao.update(bean);
}
@Override
public void delete(int visId) {
dao.delete(visId);
}
@Override
public VisitorEntity findByName(String name) {
return dao.findByName(name);
}
@Override
public VisitorEntity findByPk(int id) {
return dao.findByPk(id);
}
@Override
public List<VisitorEntity> getAllVisitors() {
return dao.getAllVisitors();
}
@Override
public VisitorEntity getVisitor(int id) {
return dao.getVisitor(id);
}
}
| 1,092 | 0.744505 | 0.744505 | 70 | 14.6 | 17.721979 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.885714 | false | false | 9 |
2d26e51f1f59e0121816d0c132b4a57a98e70ff3 | 13,889,924,289,729 | 29ce2041b0da18051c76f8bd969bd16fecefda07 | /ChatClient/src/chatClient/view/ChatClientGUI.java | 84fb8e84ac546d935887ce5f5e5c236433bfe4ed | [] | no_license | hacker119/HET715-Network-Computing-Java-Chat-Program | https://github.com/hacker119/HET715-Network-Computing-Java-Chat-Program | 5505115cabb8590d1a1c77ae413108ea11b42729 | 7eed38e75e7b27f65cb123906094dfb45667551a | refs/heads/master | "2016-09-10T17:14:19.341000" | "2012-10-01T23:19:34" | "2012-10-01T23:19:34" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package chatClient.view;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
//import user created packages
import chat.model.*;
/**
* @author CTB
*
*/
/**
* @author CTB
*
*/
public class ChatClientGUI extends JFrame implements ActionListener, ObserverChat, ObserverableChat{
Container container;
JButton sendButton, clearButton, quitButton;
private JTextArea messageArea; // for the email message body
private JTextArea responseArea; // for the server response etc.
private ArrayList <ObserverChat> observerList;
private String message;
//constructor
public ChatClientGUI(){
}
//@init the UI
public void init()
{
//init the observerList
observerList = new ArrayList<ObserverChat>();
initUI();
}
/**
* testing
*/
public void clearAll()
{
messageArea.setText("");
responseArea.setText("");
}
public void initUI()
{
setSize(600, 600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
InetAddress localHost = null;
try
{
localHost = InetAddress.getLocalHost();
}
catch(Exception ex)
{
ex.printStackTrace();
}
this.setTitle("HET715 GROUP N3 - Chat Client Version 1.0 - " + localHost.getHostAddress() );
//set up the elements in the GUI
sendButton = new JButton(" Send Text ");
clearButton = new JButton("Clear Screen");
//quitButton = new JButton("Quit");
messageArea = new JTextArea(10,30);
responseArea = new JTextArea(15,30);
responseArea.setEditable(false);
//create the layout of the client GUI
container = getContentPane();
container.setLayout( new FlowLayout() );
Box hBox_Response = Box.createHorizontalBox();
Box hBox_Message = Box.createHorizontalBox();
JLabel response_Label = new JLabel("Response area");
JLabel message_Label = new JLabel("Message area");
Box vBox = Box.createVerticalBox();
//response area
hBox_Response.add(new JScrollPane(responseArea) );
hBox_Response.add(clearButton);
//hBox_Response.add(quitButton);
//message area
hBox_Message.add( new JScrollPane(messageArea) );
hBox_Message.add(sendButton);
//body
vBox.add(response_Label);
vBox.add(hBox_Response);
vBox.add(Box.createVerticalStrut(10));
vBox.add(message_Label);
vBox.add(hBox_Message);
container.add(vBox);
//action listeners
clearButton.addActionListener(this);
sendButton.addActionListener(this);
//quitButton.addActionListener(this);
this.setVisible( true );
}
/**
* This method is invoked when the send button is pressed
* @param e button pressed event
*/
public void actionPerformed(ActionEvent e)
{
System.out.println("button clicked");
if (e.getSource() == sendButton )
{
System.out.println("send button");
message = messageArea.getText();
notifyObserverChat_SendingMessage();
}
else if (e.getSource() == clearButton)
{
// System.out.println("clear button");
clearAll();
}
/* else
if (e.getSource() == quitButton)
{
message = ApplicationConstant.QUIT_STRING;
notifyObserverChat_SendingMessage();
}
*//*
else if (e.getSource() == helpButton)
{
System.out.println("helpEmail button");
JFrame help = new displayHelp();
help.setVisible(true);
}
*/
}
//update the response area
//this method is called by the receiving thread.
public void updateResponse(String message)
{
System.out.println("Textarea receives a message: " + message);
responseArea.append("\n" + message);
}
public void updateMessage(String message)
{
}
public void addObserverChat(ObserverChat observer)
{
observerList.add(observer);
}
//the GUI only need to notify observers when it wants to send messages.
// it doesn't need to tell observers when it receives message
public void notifyObserverChat_SendingMessage()
{
for (ObserverChat observer:observerList)
{
observer.updateMessage(message);
}
}
//don't need to implement
//the GUI only need to notify observers when it wants to send messages.
// it doesn't need to tell observers when it receives message
public void notifyObserverChat_ReceivingMessage()
{
}
}
| UTF-8 | Java | 4,507 | java | ChatClientGUI.java | Java | [
{
"context": "ated packages\nimport chat.model.*;\n\n/**\n * @author CTB\n *\n */\n/**\n * @author CTB\n *\n */\npublic class Cha",
"end": 211,
"score": 0.9994045495986938,
"start": 208,
"tag": "USERNAME",
"value": "CTB"
},
{
"context": "model.*;\n\n/**\n * @author CTB\n *\n */\n/**\n * @author CTB\n *\n */\npublic class ChatClientGUI extends JFrame ",
"end": 237,
"score": 0.9993558526039124,
"start": 234,
"tag": "USERNAME",
"value": "CTB"
}
] | null | [] | package chatClient.view;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
//import user created packages
import chat.model.*;
/**
* @author CTB
*
*/
/**
* @author CTB
*
*/
public class ChatClientGUI extends JFrame implements ActionListener, ObserverChat, ObserverableChat{
Container container;
JButton sendButton, clearButton, quitButton;
private JTextArea messageArea; // for the email message body
private JTextArea responseArea; // for the server response etc.
private ArrayList <ObserverChat> observerList;
private String message;
//constructor
public ChatClientGUI(){
}
//@init the UI
public void init()
{
//init the observerList
observerList = new ArrayList<ObserverChat>();
initUI();
}
/**
* testing
*/
public void clearAll()
{
messageArea.setText("");
responseArea.setText("");
}
public void initUI()
{
setSize(600, 600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
InetAddress localHost = null;
try
{
localHost = InetAddress.getLocalHost();
}
catch(Exception ex)
{
ex.printStackTrace();
}
this.setTitle("HET715 GROUP N3 - Chat Client Version 1.0 - " + localHost.getHostAddress() );
//set up the elements in the GUI
sendButton = new JButton(" Send Text ");
clearButton = new JButton("Clear Screen");
//quitButton = new JButton("Quit");
messageArea = new JTextArea(10,30);
responseArea = new JTextArea(15,30);
responseArea.setEditable(false);
//create the layout of the client GUI
container = getContentPane();
container.setLayout( new FlowLayout() );
Box hBox_Response = Box.createHorizontalBox();
Box hBox_Message = Box.createHorizontalBox();
JLabel response_Label = new JLabel("Response area");
JLabel message_Label = new JLabel("Message area");
Box vBox = Box.createVerticalBox();
//response area
hBox_Response.add(new JScrollPane(responseArea) );
hBox_Response.add(clearButton);
//hBox_Response.add(quitButton);
//message area
hBox_Message.add( new JScrollPane(messageArea) );
hBox_Message.add(sendButton);
//body
vBox.add(response_Label);
vBox.add(hBox_Response);
vBox.add(Box.createVerticalStrut(10));
vBox.add(message_Label);
vBox.add(hBox_Message);
container.add(vBox);
//action listeners
clearButton.addActionListener(this);
sendButton.addActionListener(this);
//quitButton.addActionListener(this);
this.setVisible( true );
}
/**
* This method is invoked when the send button is pressed
* @param e button pressed event
*/
public void actionPerformed(ActionEvent e)
{
System.out.println("button clicked");
if (e.getSource() == sendButton )
{
System.out.println("send button");
message = messageArea.getText();
notifyObserverChat_SendingMessage();
}
else if (e.getSource() == clearButton)
{
// System.out.println("clear button");
clearAll();
}
/* else
if (e.getSource() == quitButton)
{
message = ApplicationConstant.QUIT_STRING;
notifyObserverChat_SendingMessage();
}
*//*
else if (e.getSource() == helpButton)
{
System.out.println("helpEmail button");
JFrame help = new displayHelp();
help.setVisible(true);
}
*/
}
//update the response area
//this method is called by the receiving thread.
public void updateResponse(String message)
{
System.out.println("Textarea receives a message: " + message);
responseArea.append("\n" + message);
}
public void updateMessage(String message)
{
}
public void addObserverChat(ObserverChat observer)
{
observerList.add(observer);
}
//the GUI only need to notify observers when it wants to send messages.
// it doesn't need to tell observers when it receives message
public void notifyObserverChat_SendingMessage()
{
for (ObserverChat observer:observerList)
{
observer.updateMessage(message);
}
}
//don't need to implement
//the GUI only need to notify observers when it wants to send messages.
// it doesn't need to tell observers when it receives message
public void notifyObserverChat_ReceivingMessage()
{
}
}
| 4,507 | 0.644331 | 0.63945 | 179 | 24.17877 | 21.32461 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.312849 | false | false | 9 |
b1d6d2a5841e1cc13d37b8ef414cbb2d9628a938 | 14,156,212,264,537 | 406757a1fd3624bdc64c97a905bfa6d31f48293f | /externals/src/main/java/llnl/gnem/core/polygon/CartesianPolygon.java | b93723af0bd56830ae85c8c34989b30fec20e622 | [
"Apache-2.0"
] | permissive | LLNL/coda-calibration-tool | https://github.com/LLNL/coda-calibration-tool | 67e349f9c0653b5ab0804cc8a90e77c1817394a1 | f86cdc694ca7cc6a34b965321d5c87684afb9cf4 | refs/heads/master | "2023-08-30T05:03:58.686000" | "2023-08-23T20:44:10" | "2023-08-23T20:44:10" | 114,670,393 | 18 | 1 | Apache-2.0 | false | "2023-02-20T10:09:05" | "2017-12-18T17:42:33" | "2022-10-21T00:24:51" | "2023-02-20T10:09:02" | 38,395 | 17 | 1 | 1 | Java | false | false | /*
* Copyright (c) 2018, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory
* CODE-743439.
* All rights reserved.
* This file is part of CCT. For details, see https://github.com/LLNL/coda-calibration-tool.
*
* Licensed under the Apache License, Version 2.0 (the “Licensee”); 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.
*
* This work was performed under the auspices of the U.S. Department of Energy
* by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344.
*/
package llnl.gnem.core.polygon;
import java.util.ArrayList;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import llnl.gnem.core.util.Geometry.NEZCoordinate;
public class CartesianPolygon {
private final ArrayList<Vector3D> vertices;
public CartesianPolygon(ArrayList<NEZCoordinate> v) {
vertices = new ArrayList<>();
for (NEZCoordinate coord : v) {
vertices.add(coord.toVector3D());
}
}
public void scale(double factor) {
for (Vector3D v3d : vertices) {
v3d.scalarMultiply(factor);
}
}
public boolean contains(Vector3D tLocal) {
// build the test line ...
line testline = new line(tLocal, new Vector3D(Double.MAX_VALUE, tLocal.getY(), tLocal.getZ()));
int N = vertices.size();
int i = 0;
int count = 0;
double yval = tLocal.getY();
line edge;
while (i < N) {
int next = i < N - 1 ? i + 1 : 0;
Vector3D vi = vertices.get(i);
Vector3D vNext = vertices.get(next);
if (vi.equals(tLocal)) {
return true;
}
if (vi.getX() < vNext.getX()) {
edge = new line(vi, vNext);
} else {
edge = new line(vNext, vi);
}
if (intersect(edge, testline)) {
++count;
if (edge.p2.getY() == yval || edge.p1.getY() == yval) // If the intersection is on a vertex don't
{
++i;
}
// process next edge or intersection gets counted twice.
}
++i;
}
return (count % 2 == 1);
}
// ---------------------------------------------------------------------------
public boolean contains(double x, double y) {
return contains(new Vector3D(x, y, 0));
}
/*
* Given 3 Vertices p0, p1, p2 traveling from the 1st to the 2nd to the 3rd, are
* we going counter clockwise or clockwise?
* 1 => ccw
* -1 => cw
* 0 => Vertices colinear and p2 between p0 and p1
*/
private int ccw(Vector3D p0, Vector3D p1, Vector3D p2) {
double dx1;
double dx2;
double dy1;
double dy2;
dx1 = p1.getX() - p0.getX();
dy1 = p1.getY() - p0.getY();
dx2 = p2.getX() - p0.getX();
dy2 = p2.getY() - p0.getY();
if (dx1 * dy2 > dy1 * dx2) {
return 1;
}
if (dx1 * dy2 < dy1 * dx2) {
return -1;
}
if ((dx1 * dy2 < 0) || (dy1 * dy2 < 0)) {
return -1;
}
if ((dx1 * dx1 + dy1 * dy1) < (dx2 * dx2 + dy2 * dy2)) {
return 1;
}
return 0;
}
private boolean intersect(line l1, line l2) {
double ccw11 = ccw(l1.p1, l1.p2, l2.p1);
double ccw12 = ccw(l1.p1, l1.p2, l2.p2);
double ccw21 = ccw(l2.p1, l2.p2, l1.p1);
double ccw22 = ccw(l2.p1, l2.p2, l1.p2);
return (ccw11 * ccw12 <= 0 && ccw21 * ccw22 <= 0);
}
public ArrayList<Vector3D> getVertices() {
return new ArrayList<Vector3D>(vertices);
}
}
| UTF-8 | Java | 4,160 | java | CartesianPolygon.java | Java | [
{
"context": " part of CCT. For details, see https://github.com/LLNL/coda-calibration-tool. \n* \n* Licensed under the A",
"end": 229,
"score": 0.9994974136352539,
"start": 225,
"tag": "USERNAME",
"value": "LLNL"
}
] | null | [] | /*
* Copyright (c) 2018, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory
* CODE-743439.
* All rights reserved.
* This file is part of CCT. For details, see https://github.com/LLNL/coda-calibration-tool.
*
* Licensed under the Apache License, Version 2.0 (the “Licensee”); 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.
*
* This work was performed under the auspices of the U.S. Department of Energy
* by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344.
*/
package llnl.gnem.core.polygon;
import java.util.ArrayList;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import llnl.gnem.core.util.Geometry.NEZCoordinate;
public class CartesianPolygon {
private final ArrayList<Vector3D> vertices;
public CartesianPolygon(ArrayList<NEZCoordinate> v) {
vertices = new ArrayList<>();
for (NEZCoordinate coord : v) {
vertices.add(coord.toVector3D());
}
}
public void scale(double factor) {
for (Vector3D v3d : vertices) {
v3d.scalarMultiply(factor);
}
}
public boolean contains(Vector3D tLocal) {
// build the test line ...
line testline = new line(tLocal, new Vector3D(Double.MAX_VALUE, tLocal.getY(), tLocal.getZ()));
int N = vertices.size();
int i = 0;
int count = 0;
double yval = tLocal.getY();
line edge;
while (i < N) {
int next = i < N - 1 ? i + 1 : 0;
Vector3D vi = vertices.get(i);
Vector3D vNext = vertices.get(next);
if (vi.equals(tLocal)) {
return true;
}
if (vi.getX() < vNext.getX()) {
edge = new line(vi, vNext);
} else {
edge = new line(vNext, vi);
}
if (intersect(edge, testline)) {
++count;
if (edge.p2.getY() == yval || edge.p1.getY() == yval) // If the intersection is on a vertex don't
{
++i;
}
// process next edge or intersection gets counted twice.
}
++i;
}
return (count % 2 == 1);
}
// ---------------------------------------------------------------------------
public boolean contains(double x, double y) {
return contains(new Vector3D(x, y, 0));
}
/*
* Given 3 Vertices p0, p1, p2 traveling from the 1st to the 2nd to the 3rd, are
* we going counter clockwise or clockwise?
* 1 => ccw
* -1 => cw
* 0 => Vertices colinear and p2 between p0 and p1
*/
private int ccw(Vector3D p0, Vector3D p1, Vector3D p2) {
double dx1;
double dx2;
double dy1;
double dy2;
dx1 = p1.getX() - p0.getX();
dy1 = p1.getY() - p0.getY();
dx2 = p2.getX() - p0.getX();
dy2 = p2.getY() - p0.getY();
if (dx1 * dy2 > dy1 * dx2) {
return 1;
}
if (dx1 * dy2 < dy1 * dx2) {
return -1;
}
if ((dx1 * dy2 < 0) || (dy1 * dy2 < 0)) {
return -1;
}
if ((dx1 * dx1 + dy1 * dy1) < (dx2 * dx2 + dy2 * dy2)) {
return 1;
}
return 0;
}
private boolean intersect(line l1, line l2) {
double ccw11 = ccw(l1.p1, l1.p2, l2.p1);
double ccw12 = ccw(l1.p1, l1.p2, l2.p2);
double ccw21 = ccw(l2.p1, l2.p2, l1.p1);
double ccw22 = ccw(l2.p1, l2.p2, l1.p2);
return (ccw11 * ccw12 <= 0 && ccw21 * ccw22 <= 0);
}
public ArrayList<Vector3D> getVertices() {
return new ArrayList<Vector3D>(vertices);
}
}
| 4,160 | 0.552746 | 0.515896 | 119 | 33.890755 | 33.084255 | 209 | true | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.663866 | false | false | 9 |
3136638dae33c4dd36b966b692df940c4b562ca8 | 38,070,590,112,230 | dbd1be6d467c6e8df751092f1e41fbd6fcdef333 | /user-service/src/main/java/com/yf/sysuser/dao/SysUserTokenMapper.java | 5c5c22521ae73cc6c4665dbe342e3fb396f4bfb0 | [] | no_license | jinghan99/girl-springcloud | https://github.com/jinghan99/girl-springcloud | 1c8c39bc0794e5c8f510831b0420b989aea700f8 | 057aed796a22230226a6ca06571d3bc8d5f69e6e | refs/heads/master | "2020-03-31T12:29:09.358000" | "2019-05-15T04:21:34" | "2019-05-15T04:21:34" | 152,217,664 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yf.sysuser.dao;
import com.yf.sysuser.entity.SysUserTokenEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* 用户token
* @author zcl<yczclcn@163.com>
*/
@Mapper
public interface SysUserTokenMapper extends BaseMapper<SysUserTokenEntity> {
/**
* 根据token查询
* @param token
* @return
*/
SysUserTokenEntity getByToken(String token);
/**
* 根据用户id查询
* @param userId
* @return
*/
SysUserTokenEntity getByUserId(Long userId);
}
| UTF-8 | Java | 489 | java | SysUserTokenMapper.java | Java | [
{
"context": "is.annotations.Mapper;\n\n\n/**\n * 用户token\n * @author zcl<yczclcn@163.com>\n */\n@Mapper\npublic interface Sys",
"end": 154,
"score": 0.999596893787384,
"start": 151,
"tag": "USERNAME",
"value": "zcl"
},
{
"context": "notations.Mapper;\n\n\n/**\n * 用户token\n * @author zcl<yczclcn@163.com>\n */\n@Mapper\npublic interface SysUserTokenMapper ",
"end": 170,
"score": 0.9999281167984009,
"start": 155,
"tag": "EMAIL",
"value": "yczclcn@163.com"
}
] | null | [] | package com.yf.sysuser.dao;
import com.yf.sysuser.entity.SysUserTokenEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* 用户token
* @author zcl<<EMAIL>>
*/
@Mapper
public interface SysUserTokenMapper extends BaseMapper<SysUserTokenEntity> {
/**
* 根据token查询
* @param token
* @return
*/
SysUserTokenEntity getByToken(String token);
/**
* 根据用户id查询
* @param userId
* @return
*/
SysUserTokenEntity getByUserId(Long userId);
}
| 481 | 0.716129 | 0.709677 | 28 | 15.607142 | 19.150419 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.642857 | false | false | 9 |
549134742291d326950ffe4f6eebcef240422bb6 | 5,076,651,389,246 | 02e54bab62a146bd05867eecc73a184b7ffa1243 | /0csy/TestDevToolProject/app/src/main/java/com/csy/demo/netlib/net/retrofit/module/request/BasicRequest.java | fbee18b93f36535987adc072f359e58ebd09bc43 | [] | no_license | y979416339/DevNote | https://github.com/y979416339/DevNote | 7656f5fbc04814b024d27736b7755aa2da69c296 | 011afb0510784bf9e4eb8cfaec91e7f915ead0dd | refs/heads/master | "2023-04-09T02:22:09.074000" | "2023-03-31T06:14:54" | "2023-03-31T06:14:54" | 562,080,644 | 0 | 0 | null | true | "2022-11-05T08:45:44" | "2022-11-05T08:45:43" | "2022-03-03T08:28:21" | "2019-07-26T04:37:04" | 177,585 | 0 | 0 | 0 | null | false | false | package com.csy.demo.netlib.net.retrofit.module.request;
import com.csy.net.utils.SharedPreferencesHelper;
import com.csy.net.utils.Utils;
/**
* Created by csy on 2017/10/25.
* Description:
*/
public class BasicRequest {
public String token = (String) SharedPreferencesHelper.get(Utils.getContext(), "token", "");
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
| UTF-8 | Java | 463 | java | BasicRequest.java | Java | [
{
"context": "import com.csy.net.utils.Utils;\n\n/**\n * Created by csy on 2017/10/25.\n * Description:\n */\n\npublic class ",
"end": 163,
"score": 0.9993441104888916,
"start": 160,
"tag": "USERNAME",
"value": "csy"
}
] | null | [] | package com.csy.demo.netlib.net.retrofit.module.request;
import com.csy.net.utils.SharedPreferencesHelper;
import com.csy.net.utils.Utils;
/**
* Created by csy on 2017/10/25.
* Description:
*/
public class BasicRequest {
public String token = (String) SharedPreferencesHelper.get(Utils.getContext(), "token", "");
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
| 463 | 0.678186 | 0.660907 | 22 | 20.045454 | 23.92313 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 9 |
44fcae85f3b275b5319db17a60c87d718ea79486 | 35,966,056,161,277 | c7c351d1980f31d93c9986c8f23a023f0fd38c53 | /app/src/main/java/cat/ycatapp/xandone/ui/joke/JokeCommentActivity.java | 4edf7bc8be145228fe0a162e6a93b241aaa4d7bd | [] | no_license | xandone/yCatApp | https://github.com/xandone/yCatApp | 36ba6d7a354451cc68f515b51f645da562e67cb0 | c45fab2abe6934adaeba5785da80fefce54c4b5d | refs/heads/master | "2021-04-26T22:06:41.350000" | "2018-12-03T13:59:10" | "2018-12-03T13:59:10" | 124,021,780 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cat.ycatapp.xandone.ui.joke;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import cat.ycatapp.xandone.App;
import cat.ycatapp.xandone.R;
import cat.ycatapp.xandone.base.RxBaseActivity;
import cat.ycatapp.xandone.cache.UserInfoCache;
import cat.ycatapp.xandone.config.Constants;
import cat.ycatapp.xandone.model.base.BaseResponse;
import cat.ycatapp.xandone.model.bean.CommentBean;
import cat.ycatapp.xandone.model.bean.JokeBean;
import cat.ycatapp.xandone.model.bean.JokeListBean;
import cat.ycatapp.xandone.uitils.SimpleUtils;
import cat.ycatapp.xandone.uitils.ToastUtils;
import cat.ycatapp.xandone.uitils.XString;
import cat.ycatapp.xandone.widget.LoadingLayout;
/**
* author: xandone
* created on: 2018/3/15 22:04
*/
public class JokeCommentActivity extends RxBaseActivity<JokeCommentPresenter> implements JokeCommentContact.MyView {
@BindView(R.id.act_joke_comment_list)
RecyclerView act_joke_comment_list;
@BindView(R.id.refreshLayout)
SmartRefreshLayout mRefreshLayout;
@BindView(R.id.loadingLayout)
LoadingLayout loadingLayout;
@BindView(R.id.toolBar)
Toolbar toolBar;
@BindView(R.id.act_joke_comment_et)
EditText act_joke_comment_et;
private JokeCommentAdapter jokeCommentAdapter;
private List<CommentBean.RowsBean> comments;
private int mPage = 1;
private int mCount = 10;
private LoadingLayout.OnReloadListener onReloadListener;
private JokeBean jokeBean;
@Override
public void initInject() {
getActivityComponent().inject(this);
}
@Override
public int setLayout() {
return R.layout.act_joke_comment_layout;
}
@Override
public void initData() {
super.initData();
setToolBar(toolBar, getString(R.string.x_joke_comment_title));
jokeBean = (JokeBean) getIntent().getSerializableExtra(Constants.KEY_JOKEBEAN);
if (jokeBean == null) {
return;
}
comments = new ArrayList<>();
jokeCommentAdapter = new JokeCommentAdapter(this, comments);
act_joke_comment_list.setAdapter(jokeCommentAdapter);
act_joke_comment_list.setLayoutManager(new LinearLayoutManager(App.sContext));
mPresenter.getContentList(mPage, mCount, jokeBean.getJoke_id(), JokeCommentContact.MODE_ONE);
loadingLayout.setLoadingTips(LoadingLayout.loading);
onReloadListener = new LoadingLayout.OnReloadListener() {
@Override
public void reLoad() {
mPage = 1;
mPresenter.getContentList(mPage, mCount, jokeBean.getJoke_id(), JokeContact.MODE_ONE);
loadingLayout.setLoadingTips(LoadingLayout.loading);
}
};
loadingLayout.setOnReloadListener(onReloadListener);
mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(RefreshLayout refreshlayout) {
mPage = 1;
mPresenter.getContentList(mPage, mCount, jokeBean.getJoke_id(), JokeContact.MODE_ONE);
}
});
mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void onLoadMore(RefreshLayout refreshlayout) {
mPage++;
mPresenter.getContentList(mPage, mCount, jokeBean.getJoke_id(), JokeContact.MODE_MORE);
}
});
act_joke_comment_et.post(new Runnable() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(act_joke_comment_et, 0);
}
});
}
@Override
public void showContent(CommentBean commentBean) {
mRefreshLayout.finishRefresh();
if (commentBean == null || commentBean.getRows() == null || commentBean.getRows().isEmpty()) {
showMsg("无数据", LoadingLayout.empty);
return;
}
showMsg("加载完毕", LoadingLayout.finish);
comments.clear();
comments.addAll(commentBean.getRows());
jokeCommentAdapter.notifyDataSetChanged();
}
@Override
public void showContentMore(CommentBean commentBean) {
mRefreshLayout.finishLoadMore();
if (commentBean == null || commentBean.getRows() == null || commentBean.getRows().isEmpty()) {
return;
}
comments.addAll(commentBean.getRows());
jokeCommentAdapter.notifyDataSetChanged();
}
@Override
public void showMsg(String msg, int loadStatus) {
mRefreshLayout.finishRefresh();
mRefreshLayout.finishLoadMore();
loadingLayout.setLoadingTips(loadStatus);
}
@Override
public void showCommentResult(BaseResponse<List<CommentBean.RowsBean>> response) {
dismissLoadingDialog();
if (response == null || response.getDataList() == null || response.getDataList().isEmpty()) {
return;
}
if ("1".equals(response.getCode())) {
if (loadingLayout.getVisibility() == View.VISIBLE) {
loadingLayout.setVisibility(View.GONE);
}
ToastUtils.showShort("评论成功");
act_joke_comment_et.setText("");
CommentBean.RowsBean commentBean = response.getDataList().get(0);
comments.add(0, commentBean);
jokeCommentAdapter.notifyItemChanged(0);
} else {
ToastUtils.showShort("评论失败");
}
}
@Override
public void showCommentError() {
dismissLoadingDialog();
}
@OnClick({R.id.act_joke_comment_commit})
public void click(View view) {
switch (view.getId()) {
case R.id.act_joke_comment_commit:
if (!UserInfoCache.isLogin()) {
ToastUtils.showShort("你还未登录");
break;
}
String jokeId = jokeBean.getJoke_id();
String userId = UserInfoCache.getUserBean().getUserId();
String details = act_joke_comment_et.getText().toString();
if (XString.isEmpty(details)) {
ToastUtils.showShort("请输入内容");
break;
}
SimpleUtils.hideSoftInput(this);
showLoadingDialog(false);
mPresenter.addComment(jokeId, userId, details);
break;
}
}
}
| UTF-8 | Java | 7,100 | java | JokeCommentActivity.java | Java | [
{
"context": "tapp.xandone.widget.LoadingLayout;\n\n/**\n * author: xandone\n * created on: 2018/3/15 22:04\n */\n\npublic class ",
"end": 1296,
"score": 0.9996471405029297,
"start": 1289,
"tag": "USERNAME",
"value": "xandone"
}
] | null | [] | package cat.ycatapp.xandone.ui.joke;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import cat.ycatapp.xandone.App;
import cat.ycatapp.xandone.R;
import cat.ycatapp.xandone.base.RxBaseActivity;
import cat.ycatapp.xandone.cache.UserInfoCache;
import cat.ycatapp.xandone.config.Constants;
import cat.ycatapp.xandone.model.base.BaseResponse;
import cat.ycatapp.xandone.model.bean.CommentBean;
import cat.ycatapp.xandone.model.bean.JokeBean;
import cat.ycatapp.xandone.model.bean.JokeListBean;
import cat.ycatapp.xandone.uitils.SimpleUtils;
import cat.ycatapp.xandone.uitils.ToastUtils;
import cat.ycatapp.xandone.uitils.XString;
import cat.ycatapp.xandone.widget.LoadingLayout;
/**
* author: xandone
* created on: 2018/3/15 22:04
*/
public class JokeCommentActivity extends RxBaseActivity<JokeCommentPresenter> implements JokeCommentContact.MyView {
@BindView(R.id.act_joke_comment_list)
RecyclerView act_joke_comment_list;
@BindView(R.id.refreshLayout)
SmartRefreshLayout mRefreshLayout;
@BindView(R.id.loadingLayout)
LoadingLayout loadingLayout;
@BindView(R.id.toolBar)
Toolbar toolBar;
@BindView(R.id.act_joke_comment_et)
EditText act_joke_comment_et;
private JokeCommentAdapter jokeCommentAdapter;
private List<CommentBean.RowsBean> comments;
private int mPage = 1;
private int mCount = 10;
private LoadingLayout.OnReloadListener onReloadListener;
private JokeBean jokeBean;
@Override
public void initInject() {
getActivityComponent().inject(this);
}
@Override
public int setLayout() {
return R.layout.act_joke_comment_layout;
}
@Override
public void initData() {
super.initData();
setToolBar(toolBar, getString(R.string.x_joke_comment_title));
jokeBean = (JokeBean) getIntent().getSerializableExtra(Constants.KEY_JOKEBEAN);
if (jokeBean == null) {
return;
}
comments = new ArrayList<>();
jokeCommentAdapter = new JokeCommentAdapter(this, comments);
act_joke_comment_list.setAdapter(jokeCommentAdapter);
act_joke_comment_list.setLayoutManager(new LinearLayoutManager(App.sContext));
mPresenter.getContentList(mPage, mCount, jokeBean.getJoke_id(), JokeCommentContact.MODE_ONE);
loadingLayout.setLoadingTips(LoadingLayout.loading);
onReloadListener = new LoadingLayout.OnReloadListener() {
@Override
public void reLoad() {
mPage = 1;
mPresenter.getContentList(mPage, mCount, jokeBean.getJoke_id(), JokeContact.MODE_ONE);
loadingLayout.setLoadingTips(LoadingLayout.loading);
}
};
loadingLayout.setOnReloadListener(onReloadListener);
mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(RefreshLayout refreshlayout) {
mPage = 1;
mPresenter.getContentList(mPage, mCount, jokeBean.getJoke_id(), JokeContact.MODE_ONE);
}
});
mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void onLoadMore(RefreshLayout refreshlayout) {
mPage++;
mPresenter.getContentList(mPage, mCount, jokeBean.getJoke_id(), JokeContact.MODE_MORE);
}
});
act_joke_comment_et.post(new Runnable() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(act_joke_comment_et, 0);
}
});
}
@Override
public void showContent(CommentBean commentBean) {
mRefreshLayout.finishRefresh();
if (commentBean == null || commentBean.getRows() == null || commentBean.getRows().isEmpty()) {
showMsg("无数据", LoadingLayout.empty);
return;
}
showMsg("加载完毕", LoadingLayout.finish);
comments.clear();
comments.addAll(commentBean.getRows());
jokeCommentAdapter.notifyDataSetChanged();
}
@Override
public void showContentMore(CommentBean commentBean) {
mRefreshLayout.finishLoadMore();
if (commentBean == null || commentBean.getRows() == null || commentBean.getRows().isEmpty()) {
return;
}
comments.addAll(commentBean.getRows());
jokeCommentAdapter.notifyDataSetChanged();
}
@Override
public void showMsg(String msg, int loadStatus) {
mRefreshLayout.finishRefresh();
mRefreshLayout.finishLoadMore();
loadingLayout.setLoadingTips(loadStatus);
}
@Override
public void showCommentResult(BaseResponse<List<CommentBean.RowsBean>> response) {
dismissLoadingDialog();
if (response == null || response.getDataList() == null || response.getDataList().isEmpty()) {
return;
}
if ("1".equals(response.getCode())) {
if (loadingLayout.getVisibility() == View.VISIBLE) {
loadingLayout.setVisibility(View.GONE);
}
ToastUtils.showShort("评论成功");
act_joke_comment_et.setText("");
CommentBean.RowsBean commentBean = response.getDataList().get(0);
comments.add(0, commentBean);
jokeCommentAdapter.notifyItemChanged(0);
} else {
ToastUtils.showShort("评论失败");
}
}
@Override
public void showCommentError() {
dismissLoadingDialog();
}
@OnClick({R.id.act_joke_comment_commit})
public void click(View view) {
switch (view.getId()) {
case R.id.act_joke_comment_commit:
if (!UserInfoCache.isLogin()) {
ToastUtils.showShort("你还未登录");
break;
}
String jokeId = jokeBean.getJoke_id();
String userId = UserInfoCache.getUserBean().getUserId();
String details = act_joke_comment_et.getText().toString();
if (XString.isEmpty(details)) {
ToastUtils.showShort("请输入内容");
break;
}
SimpleUtils.hideSoftInput(this);
showLoadingDialog(false);
mPresenter.addComment(jokeId, userId, details);
break;
}
}
}
| 7,100 | 0.651631 | 0.648227 | 202 | 33.90099 | 26.533186 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.663366 | false | false | 9 |
0e4f14f2b45ec6112de064eaf7448857d8a62d50 | 35,966,056,160,330 | dbe6baa4fdf11ec51ccf3bb05fc0cd244639e265 | /hsd-account/hsd-account-actor/hsd-account-actor-api/src/main/java/com/hsd/account/actor/api/user/IUserService.java | 577cadf9252b883205b93cadf73248ed132c3dd6 | [] | no_license | xuxiaowei007/sc-framework | https://github.com/xuxiaowei007/sc-framework | f25aa310929c06132a944fdc142d2b9d91955fed | d09382749150e108975c4f53d8e8f721fabea800 | refs/heads/master | "2020-03-21T20:10:57.671000" | "2018-01-29T02:36:09" | "2018-01-29T02:36:09" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hsd.account.actor.api.user;
import com.github.pagehelper.PageInfo;
import com.hsd.account.actor.dto.identity.IdentityDto;
import com.hsd.account.actor.dto.user.UserDto;
import com.hsd.framework.Response;
import com.hsd.framework.config.FeignConfiguration;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
/**
* <p>客户表 业务处理接口类。
*/
@FeignClient(value = "${feign.name.account.actor}",configuration = FeignConfiguration.class)//, fallback = TestServiceHystrix.class)
public interface IUserService {
String acPrefix = "/feign/account/actor/IUserService";
/**
* <p>信息列表 分页。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/findDataIsPage")
public PageInfo findDataIsPage(UserDto dto) throws Exception;
/**
* <p>信息列表。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/findDataIsList")
public List<UserDto> findDataIsList(UserDto dto) throws Exception;
/**
* <p>信息编辑。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/saveOrUpdateData")
public Response saveOrUpdateData(UserDto dto) throws Exception;
/**
* <p>信息详情。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/findDataById")
public UserDto findDataById(UserDto dto) throws Exception;
/**
* <p>物理删除。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/deleteData")
public String deleteData(UserDto dto) throws Exception;
/**
* <p>设置标签。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/setTags")
public Response setTags(UserDto dto) throws Exception;
/**
* <p>设置黑名单。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/setBlacklist")
public Response setBlacklist(UserDto dto) throws Exception;
/**
* <p>移除黑名单。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/delBlacklist")
public Response delBlacklist(UserDto dto) throws Exception;
/**
* <p>用户信息。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/findUserByAccount")
public UserDto findUserByAccount(@RequestParam("account") String account, @RequestParam("userType") Integer userType);
/**
* <p>更新客户登陆信息
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/lastLogin")
public Integer lastLogin(UserDto dto);
/**
* <p>客户注册。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/register")
public Response register(UserDto dto) throws Exception;
/**
* <p>获取账号信息。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/getAccount")
public UserDto getAccount(UserDto dto) throws Exception;
/**
* <p>客户密码找回。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/restPwd")
public Response restPwd(UserDto dto) throws Exception;
/**
* <p>绑定手机修改。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/phoneBind")
public Response phoneBind(UserDto dto) throws Exception;
/**
* <p>绑定邮箱修改。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/emailBind")
public Response emailBind(UserDto dto) throws Exception;
/**
* <p>客户密码修改。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/updatePwd")
public Response updatePwd(UserDto dto) throws Exception;
/**
* <p>实名认证。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/identity")
public Response identity(IdentityDto dto) throws Exception;
/** <p>交易密码-设置 or 密码重置。 */
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/pwd/trade/setting")
public Response pwdTradeSetting(UserDto dto) throws Exception;
/** <p>交易密码-修改。 */
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/pwd/trade/update")
public Response pwdTradeUpdate(UserDto dto) throws Exception;
/** <p>找回交易密码-密码重置。 */
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/pwd/trade/reset/setting")
public Response pwdTradeResetSetting(UserDto dto) throws Exception;
} | UTF-8 | Java | 4,756 | java | IUserService.java | Java | [] | null | [] | package com.hsd.account.actor.api.user;
import com.github.pagehelper.PageInfo;
import com.hsd.account.actor.dto.identity.IdentityDto;
import com.hsd.account.actor.dto.user.UserDto;
import com.hsd.framework.Response;
import com.hsd.framework.config.FeignConfiguration;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
/**
* <p>客户表 业务处理接口类。
*/
@FeignClient(value = "${feign.name.account.actor}",configuration = FeignConfiguration.class)//, fallback = TestServiceHystrix.class)
public interface IUserService {
String acPrefix = "/feign/account/actor/IUserService";
/**
* <p>信息列表 分页。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/findDataIsPage")
public PageInfo findDataIsPage(UserDto dto) throws Exception;
/**
* <p>信息列表。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/findDataIsList")
public List<UserDto> findDataIsList(UserDto dto) throws Exception;
/**
* <p>信息编辑。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/saveOrUpdateData")
public Response saveOrUpdateData(UserDto dto) throws Exception;
/**
* <p>信息详情。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/findDataById")
public UserDto findDataById(UserDto dto) throws Exception;
/**
* <p>物理删除。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/deleteData")
public String deleteData(UserDto dto) throws Exception;
/**
* <p>设置标签。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/setTags")
public Response setTags(UserDto dto) throws Exception;
/**
* <p>设置黑名单。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/setBlacklist")
public Response setBlacklist(UserDto dto) throws Exception;
/**
* <p>移除黑名单。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/delBlacklist")
public Response delBlacklist(UserDto dto) throws Exception;
/**
* <p>用户信息。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/findUserByAccount")
public UserDto findUserByAccount(@RequestParam("account") String account, @RequestParam("userType") Integer userType);
/**
* <p>更新客户登陆信息
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/lastLogin")
public Integer lastLogin(UserDto dto);
/**
* <p>客户注册。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/register")
public Response register(UserDto dto) throws Exception;
/**
* <p>获取账号信息。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/getAccount")
public UserDto getAccount(UserDto dto) throws Exception;
/**
* <p>客户密码找回。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/restPwd")
public Response restPwd(UserDto dto) throws Exception;
/**
* <p>绑定手机修改。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/phoneBind")
public Response phoneBind(UserDto dto) throws Exception;
/**
* <p>绑定邮箱修改。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/emailBind")
public Response emailBind(UserDto dto) throws Exception;
/**
* <p>客户密码修改。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/updatePwd")
public Response updatePwd(UserDto dto) throws Exception;
/**
* <p>实名认证。
*/
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/identity")
public Response identity(IdentityDto dto) throws Exception;
/** <p>交易密码-设置 or 密码重置。 */
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/pwd/trade/setting")
public Response pwdTradeSetting(UserDto dto) throws Exception;
/** <p>交易密码-修改。 */
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/pwd/trade/update")
public Response pwdTradeUpdate(UserDto dto) throws Exception;
/** <p>找回交易密码-密码重置。 */
@RequestMapping(method = {RequestMethod.POST},value = acPrefix + "/pwd/trade/reset/setting")
public Response pwdTradeResetSetting(UserDto dto) throws Exception;
} | 4,756 | 0.681127 | 0.681127 | 119 | 36.588234 | 33.107773 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.462185 | false | false | 9 |
a06f287339ffbe286532eee364874a36f90d5ed8 | 34,222,299,458,340 | e248d26c9950d4242ee0951069519b6e5b1f0fe1 | /ibeeditor/base/src/main/java/com/github/franckyi/ibeeditor/base/client/mvc/controller/entry/BooleanEntryController.java | 9d66b64f4f4aec03f2f42a376fb971184938f932 | [
"MIT"
] | permissive | BernardoGrigiastro/IBE-Editor | https://github.com/BernardoGrigiastro/IBE-Editor | 9d7068a03f71580f606e01e7af7f4100cc756ed3 | 74c15936877d176a9770b2ee1d8ca062ff5eb492 | refs/heads/master | "2023-07-15T09:04:01.814000" | "2021-08-27T21:12:31" | "2021-08-27T21:22:53" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.franckyi.ibeeditor.base.client.mvc.controller.entry;
import com.github.franckyi.ibeeditor.base.client.mvc.model.entry.BooleanEntryModel;
import com.github.franckyi.ibeeditor.base.client.mvc.view.entry.BooleanEntryView;
public class BooleanEntryController<M extends BooleanEntryModel, V extends BooleanEntryView> extends ValueEntryController<M, V> {
public BooleanEntryController(M model, V view) {
super(model, view);
}
@Override
public void bind() {
super.bind();
view.getCheckBox().checkedProperty().addListener(model::setValue);
model.valueProperty().addListener(view.getCheckBox()::setChecked);
view.getCheckBox().setChecked(model.getValue());
}
}
| UTF-8 | Java | 734 | java | BooleanEntryController.java | Java | [
{
"context": "package com.github.franckyi.ibeeditor.base.client.mvc.controller.entry;\n\nimpo",
"end": 27,
"score": 0.9845661520957947,
"start": 19,
"tag": "USERNAME",
"value": "franckyi"
},
{
"context": "e.client.mvc.controller.entry;\n\nimport com.github.franckyi.ibeeditor.base.client.mvc.model.entry.BooleanEntr",
"end": 99,
"score": 0.9805794358253479,
"start": 91,
"tag": "USERNAME",
"value": "franckyi"
},
{
"context": ".model.entry.BooleanEntryModel;\nimport com.github.franckyi.ibeeditor.base.client.mvc.view.entry.BooleanEntry",
"end": 183,
"score": 0.9528306722640991,
"start": 175,
"tag": "USERNAME",
"value": "franckyi"
}
] | null | [] | package com.github.franckyi.ibeeditor.base.client.mvc.controller.entry;
import com.github.franckyi.ibeeditor.base.client.mvc.model.entry.BooleanEntryModel;
import com.github.franckyi.ibeeditor.base.client.mvc.view.entry.BooleanEntryView;
public class BooleanEntryController<M extends BooleanEntryModel, V extends BooleanEntryView> extends ValueEntryController<M, V> {
public BooleanEntryController(M model, V view) {
super(model, view);
}
@Override
public void bind() {
super.bind();
view.getCheckBox().checkedProperty().addListener(model::setValue);
model.valueProperty().addListener(view.getCheckBox()::setChecked);
view.getCheckBox().setChecked(model.getValue());
}
}
| 734 | 0.741144 | 0.741144 | 18 | 39.777779 | 37.571495 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 9 |
9a434a4111d2fe1dd8bbffe72b8890ea256e0d1d | 28,982,439,331,236 | 39b6f83641d1a80a48937c42beb6a73311aebc55 | /extensions/liquibase/runtime/src/main/java/io/quarkus/liquibase/runtime/LiquibaseDataSourceBuildTimeConfig.java | 02be6092e80cc9a50c89119df1ca23dadb7046e1 | [
"Apache-2.0"
] | permissive | quarkusio/quarkus | https://github.com/quarkusio/quarkus | 112ecda7236bc061920978ac49289da6259360f4 | 68af440f3081de7a26bbee655f74bb8b2c57c2d5 | refs/heads/main | "2023-09-04T06:39:33.043000" | "2023-09-04T05:44:43" | "2023-09-04T05:44:43" | 139,914,932 | 13,109 | 2,940 | Apache-2.0 | false | "2023-09-14T21:31:23" | "2018-07-06T00:44:20" | "2023-09-14T21:29:58" | "2023-09-14T21:31:22" | 264,839 | 12,241 | 2,328 | 2,315 | Java | false | false | package io.quarkus.liquibase.runtime;
import io.quarkus.runtime.annotations.ConfigGroup;
import io.quarkus.runtime.annotations.ConfigItem;
/**
* The liquibase data source build time configuration
*/
@ConfigGroup
public final class LiquibaseDataSourceBuildTimeConfig {
static final String DEFAULT_CHANGE_LOG = "db/changeLog.xml";
/**
* Creates a {@link LiquibaseDataSourceBuildTimeConfig} with default settings.
*
* @return {@link LiquibaseDataSourceBuildTimeConfig}
*/
public static final LiquibaseDataSourceBuildTimeConfig defaultConfig() {
LiquibaseDataSourceBuildTimeConfig defaultConfig = new LiquibaseDataSourceBuildTimeConfig();
defaultConfig.changeLog = DEFAULT_CHANGE_LOG;
return defaultConfig;
}
/**
* The liquibase change log file. All included change log files in this file are scanned and add to the projects.
*/
@ConfigItem(defaultValue = DEFAULT_CHANGE_LOG)
public String changeLog;
}
| UTF-8 | Java | 989 | java | LiquibaseDataSourceBuildTimeConfig.java | Java | [] | null | [] | package io.quarkus.liquibase.runtime;
import io.quarkus.runtime.annotations.ConfigGroup;
import io.quarkus.runtime.annotations.ConfigItem;
/**
* The liquibase data source build time configuration
*/
@ConfigGroup
public final class LiquibaseDataSourceBuildTimeConfig {
static final String DEFAULT_CHANGE_LOG = "db/changeLog.xml";
/**
* Creates a {@link LiquibaseDataSourceBuildTimeConfig} with default settings.
*
* @return {@link LiquibaseDataSourceBuildTimeConfig}
*/
public static final LiquibaseDataSourceBuildTimeConfig defaultConfig() {
LiquibaseDataSourceBuildTimeConfig defaultConfig = new LiquibaseDataSourceBuildTimeConfig();
defaultConfig.changeLog = DEFAULT_CHANGE_LOG;
return defaultConfig;
}
/**
* The liquibase change log file. All included change log files in this file are scanned and add to the projects.
*/
@ConfigItem(defaultValue = DEFAULT_CHANGE_LOG)
public String changeLog;
}
| 989 | 0.741153 | 0.741153 | 31 | 30.903225 | 32.817535 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.258065 | false | false | 9 |
46aed91c816562f54aeee56fc60302128398cb0e | 5,428,838,678,357 | a30e780d029806d41b713b0f33932d59b0a424b4 | /src/main/java/com/cmazxiaoma/wx/service/SysUserService.java | 018917607294cdaa186635f410116289a2931cb6 | [] | no_license | cmazxiaoma/wechat_punch | https://github.com/cmazxiaoma/wechat_punch | 71639b27cc7ff27ad9b5909839ba7257c8831ef2 | 421effec06e4960f9c874d7f7e47555bc508df79 | refs/heads/master | "2021-05-12T05:26:12.406000" | "2018-06-08T06:47:57" | "2018-06-08T06:47:57" | 117,193,532 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cmazxiaoma.wx.service;
import com.cmazxiaoma.wx.model.SysUser;
import com.cmazxiaoma.wx.core.Service;
import org.springframework.security.core.userdetails.UserDetailsService;
/**
* Created by cmazxiaoma on 2018/01/13.
*/
public interface SysUserService extends Service<SysUser>, UserDetailsService {
}
| UTF-8 | Java | 319 | java | SysUserService.java | Java | [
{
"context": "serdetails.UserDetailsService;\n\n\n/**\n * Created by cmazxiaoma on 2018/01/13.\n */\npublic interface SysUserServic",
"end": 217,
"score": 0.9996843934059143,
"start": 207,
"tag": "USERNAME",
"value": "cmazxiaoma"
}
] | null | [] | package com.cmazxiaoma.wx.service;
import com.cmazxiaoma.wx.model.SysUser;
import com.cmazxiaoma.wx.core.Service;
import org.springframework.security.core.userdetails.UserDetailsService;
/**
* Created by cmazxiaoma on 2018/01/13.
*/
public interface SysUserService extends Service<SysUser>, UserDetailsService {
}
| 319 | 0.802508 | 0.777429 | 12 | 25.583334 | 27.499874 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 9 |
2bec9c7c3c512573f8b240cbd49c35f209274368 | 206,158,481,421 | cfbbcf9a54fb657663fe30c447a4b9036d9a2ca5 | /src/main/java/com/github/sokyranthedragon/mia/integrations/industrialforegoing/IIndustrialForegoingIntegration.java | b6ec3ad5b2148d2761bc8dbe1c50d9c0597ef928 | [
"MIT"
] | permissive | SokyranTheDragon/Minor-Integrations-and-Additions-MIA- | https://github.com/SokyranTheDragon/Minor-Integrations-and-Additions-MIA- | e4d64f1c095cf62e242d646a63be8274781d7542 | 25e6836f200b9b6002a3dec2c6a163d88721d23a | refs/heads/master | "2022-08-09T06:10:23.901000" | "2022-05-20T18:32:50" | "2022-05-20T18:32:50" | 186,796,147 | 7 | 3 | MIT | false | "2022-05-18T22:38:56" | "2019-05-15T09:40:19" | "2022-05-15T03:06:22" | "2022-05-18T22:38:55" | 1,184 | 7 | 4 | 9 | Java | false | false | package com.github.sokyranthedragon.mia.integrations.industrialforegoing;
import com.buuz135.industrial.api.extractor.ExtractorEntry;
import com.github.sokyranthedragon.mia.integrations.base.IModIntegration;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.item.ItemStack;
import org.apache.logging.log4j.util.TriConsumer;
import javax.annotation.ParametersAreNonnullByDefault;
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
public interface IIndustrialForegoingIntegration extends IModIntegration
{
default void addGenericIntegrations()
{
}
default void addPostInitRecipes()
{
}
default void addFrosterRecipe(TriConsumer<String, ItemStack, Integer> frosterEntry)
{
}
default ItemStack[] getBasicProteinGeneratorEntries()
{
return new ItemStack[0];
}
default ExtractorEntry[] getLatexEntries()
{
return new ExtractorEntry[0];
}
default boolean loadLaserDrillEntries()
{
return false;
}
}
| UTF-8 | Java | 1,041 | java | IIndustrialForegoingIntegration.java | Java | [
{
"context": "package com.github.sokyranthedragon.mia.integrations.industrialforegoing;\n\nimport com",
"end": 35,
"score": 0.9994434118270874,
"start": 19,
"tag": "USERNAME",
"value": "sokyranthedragon"
},
{
"context": "mia.integrations.industrialforegoing;\n\nimport com.buuz135.industrial.api.extractor.ExtractorEntry;\nimport c",
"end": 93,
"score": 0.9894107580184937,
"start": 86,
"tag": "USERNAME",
"value": "buuz135"
},
{
"context": "l.api.extractor.ExtractorEntry;\nimport com.github.sokyranthedragon.mia.integrations.base.IModIntegration;\nimport mcp",
"end": 169,
"score": 0.9993902444839478,
"start": 153,
"tag": "USERNAME",
"value": "sokyranthedragon"
}
] | null | [] | package com.github.sokyranthedragon.mia.integrations.industrialforegoing;
import com.buuz135.industrial.api.extractor.ExtractorEntry;
import com.github.sokyranthedragon.mia.integrations.base.IModIntegration;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.item.ItemStack;
import org.apache.logging.log4j.util.TriConsumer;
import javax.annotation.ParametersAreNonnullByDefault;
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
public interface IIndustrialForegoingIntegration extends IModIntegration
{
default void addGenericIntegrations()
{
}
default void addPostInitRecipes()
{
}
default void addFrosterRecipe(TriConsumer<String, ItemStack, Integer> frosterEntry)
{
}
default ItemStack[] getBasicProteinGeneratorEntries()
{
return new ItemStack[0];
}
default ExtractorEntry[] getLatexEntries()
{
return new ExtractorEntry[0];
}
default boolean loadLaserDrillEntries()
{
return false;
}
}
| 1,041 | 0.745437 | 0.739673 | 41 | 24.390244 | 25.218922 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.292683 | false | false | 9 |
ad5a22f79cf9e6c6e5ccb06c9530f910931fe0e6 | 206,158,483,796 | a32ef51c4cc8655c39a7978f07009318fe1bd30d | /app/src/main/java/com/camachoyury/andreddit/interactor/PostExecutionThread.java | 41ed96eb7a4a66e9853618bd1c5bcc7df461327b | [] | no_license | camachoyury/AndReddit | https://github.com/camachoyury/AndReddit | 6946a95dfcb9a8908936afe5c11260a710029a4c | 68ea47b25cc2215ba84b341fe775d09c1b72afc5 | refs/heads/master | "2021-01-19T20:02:58.358000" | "2017-08-23T19:27:09" | "2017-08-23T19:27:09" | 101,217,299 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.camachoyury.andreddit.interactor;
import io.reactivex.Scheduler;
/**
* Created by yury on 8/22/17.
*/
public interface PostExecutionThread {
Scheduler getScheduler();
}
| UTF-8 | Java | 191 | java | PostExecutionThread.java | Java | [
{
"context": "\nimport io.reactivex.Scheduler;\n\n/**\n * Created by yury on 8/22/17.\n */\n\npublic interface PostExecutio",
"end": 98,
"score": 0.6126862168312073,
"start": 97,
"tag": "NAME",
"value": "y"
},
{
"context": "mport io.reactivex.Scheduler;\n\n/**\n * Created by yury on 8/22/17.\n */\n\npublic interface PostExecutionTh",
"end": 101,
"score": 0.5056393146514893,
"start": 98,
"tag": "USERNAME",
"value": "ury"
}
] | null | [] | package com.camachoyury.andreddit.interactor;
import io.reactivex.Scheduler;
/**
* Created by yury on 8/22/17.
*/
public interface PostExecutionThread {
Scheduler getScheduler();
}
| 191 | 0.73822 | 0.712042 | 12 | 14.916667 | 16.977722 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 9 |
eb64e1195545e15df0c8aa8ef9032bc887b36577 | 28,733,331,258,280 | 191a4f31a245b42ba1b06f3ff18c9ed0e3aabfbd | /src/main/java/com/shengchanshixi/gongxiangyigui/dao/BrandDao.java | 5fb237df04839e484985eafbd668ee17b7639b7e | [] | no_license | likeholmes/gongxiangyigui | https://github.com/likeholmes/gongxiangyigui | 906542e28eae3f591a3bd38004eeb9c678693183 | 323610c83396c9c68d8f7172c20cef7ae85ca876 | refs/heads/master | "2022-12-22T11:10:05.051000" | "2019-09-19T02:11:16" | "2019-09-19T02:11:16" | 207,685,995 | 0 | 0 | null | false | "2022-12-10T05:44:55" | "2019-09-11T00:11:35" | "2019-09-19T02:11:35" | "2022-12-10T05:44:54" | 1,675 | 0 | 0 | 2 | Java | false | false | package com.shengchanshixi.gongxiangyigui.dao;
import com.shengchanshixi.gongxiangyigui.entity.Brand;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public interface BrandDao extends JpaRepository<Brand,Long> {
@Transactional
@Query(value = "delete from brand_list where id=?1 ", nativeQuery = true)
@Modifying
void deleteById(int id);
List<Brand> findByName(String name);
Brand findById(int id);
}
| UTF-8 | Java | 645 | java | BrandDao.java | Java | [] | null | [] | package com.shengchanshixi.gongxiangyigui.dao;
import com.shengchanshixi.gongxiangyigui.entity.Brand;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public interface BrandDao extends JpaRepository<Brand,Long> {
@Transactional
@Query(value = "delete from brand_list where id=?1 ", nativeQuery = true)
@Modifying
void deleteById(int id);
List<Brand> findByName(String name);
Brand findById(int id);
}
| 645 | 0.786047 | 0.784496 | 22 | 28.318182 | 26.140158 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 9 |
ce3fb68782468c574a785eceb052b6ecd6234114 | 3,728,031,630,309 | 8f7e6127a1ef6ce9b094b076878b64198298907b | /GpStudy-design-module/src/main/java/com/ghk/study/bridge/simple/SamsungMonitor.java | b4d6f2440c6e410d99cdd48dcbab0d08c22e66e0 | [] | no_license | guohuike/GpStudy | https://github.com/guohuike/GpStudy | 771e12f14f7041dbaa7809f600d6c847c04eaf3c | 830a2f111ffe2b78c04610e795178aa19773713e | refs/heads/master | "2023-05-22T19:40:44.316000" | "2021-06-10T15:10:34" | "2021-06-10T15:10:34" | 328,701,757 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ghk.study.bridge.simple;
/**
* @Title: SamsungMonitor
* @Package: com.ghk.study.bridge.simple
* @Description: TODO(用一句话描述该文件做什么)
* @author: huike.guo
* @date: 2021/4/28 17:55
* @version: V1.0
* <p>Company: Leyou(China) Chain Store Co.,Ltd</p >
* <p>版权所有: Copyright1999-2021 leyou.com. All Rights Reserved</p >
*/
public class SamsungMonitor implements Monitor{
@Override
public String display() {
return "Samsung Monitor display";
}
} | UTF-8 | Java | 508 | java | SamsungMonitor.java | Java | [
{
"context": "le\n * @Description: TODO(用一句话描述该文件做什么)\n * @author: huike.guo\n * @date: 2021/4/28 17:55\n * @version: V1.0\n * <p",
"end": 166,
"score": 0.9851014614105225,
"start": 157,
"tag": "NAME",
"value": "huike.guo"
}
] | null | [] | package com.ghk.study.bridge.simple;
/**
* @Title: SamsungMonitor
* @Package: com.ghk.study.bridge.simple
* @Description: TODO(用一句话描述该文件做什么)
* @author: huike.guo
* @date: 2021/4/28 17:55
* @version: V1.0
* <p>Company: Leyou(China) Chain Store Co.,Ltd</p >
* <p>版权所有: Copyright1999-2021 leyou.com. All Rights Reserved</p >
*/
public class SamsungMonitor implements Monitor{
@Override
public String display() {
return "Samsung Monitor display";
}
} | 508 | 0.678571 | 0.634454 | 18 | 25.5 | 18.856918 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 9 |
de187ff1cd12a342de8a83cbae89ea27e8584d81 | 19,207,093,766,789 | cf46600f1d9e85c4c4ccf7836f32d141ca75b532 | /MovieBookingSystem/src/main/java/com/raghu/mbs/MovieBookingSystemApplication.java | 7a5ccf30aa2c58551222db7881866dcf11f76046 | [] | no_license | Raghuraam/INTERVIEW | https://github.com/Raghuraam/INTERVIEW | b82f92acb3a48128a89bf01ae793d17ccb43782c | 2bb8d512b66f903b449fc843f3137789e355abe8 | refs/heads/main | "2023-03-18T07:35:58.873000" | "2021-03-14T13:43:45" | "2021-03-14T13:43:45" | 319,813,545 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.raghu.mbs;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.raghu.mbs.repository.SeatRepository;
import com.raghu.mbs.service.SeatReleaseHook;
import com.raghu.mbs.util.StaticData;
@SpringBootApplication
public class MovieBookingSystemApplication {
@Autowired
StaticData staticData;
@Autowired
SeatReleaseHook seatReleaseHook;
@PostConstruct
private void init() {
System.out.println("MovieBookingSystemApplication initialization logic starts...");
staticData.PersistStaticData();
System.out.println("InitDemoApplication initialization logic ends...");
Thread t1 = new Thread(seatReleaseHook);
t1.start();
System.out.println("Seat release thread started");
}
public static void main(String[] args) {
SpringApplication.run(MovieBookingSystemApplication.class, args);
}
}
| UTF-8 | Java | 1,000 | java | MovieBookingSystemApplication.java | Java | [] | null | [] | package com.raghu.mbs;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.raghu.mbs.repository.SeatRepository;
import com.raghu.mbs.service.SeatReleaseHook;
import com.raghu.mbs.util.StaticData;
@SpringBootApplication
public class MovieBookingSystemApplication {
@Autowired
StaticData staticData;
@Autowired
SeatReleaseHook seatReleaseHook;
@PostConstruct
private void init() {
System.out.println("MovieBookingSystemApplication initialization logic starts...");
staticData.PersistStaticData();
System.out.println("InitDemoApplication initialization logic ends...");
Thread t1 = new Thread(seatReleaseHook);
t1.start();
System.out.println("Seat release thread started");
}
public static void main(String[] args) {
SpringApplication.run(MovieBookingSystemApplication.class, args);
}
}
| 1,000 | 0.804 | 0.802 | 37 | 26.027027 | 24.869917 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.162162 | false | false | 9 |
ad86e84209fcc5943e820f9a31f07b4f184b3af6 | 14,525,579,398,445 | a246fe566924d11f9589e0e844439987aee86099 | /src/IPLonginLogs.java | 3d0ad2ffe24c59a83a217d330663d1fd1095bda2 | [] | no_license | asia105022002/Swing_Login-master | https://github.com/asia105022002/Swing_Login-master | 76d56bc9ac443ddd432cc4129069cbc5a76747d2 | 8d3971ee103fa10da489379bb9a12f564baa92f1 | refs/heads/master | "2020-03-30T18:49:23.340000" | "2018-10-27T13:03:52" | "2018-10-27T13:03:52" | 151,508,602 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
public class IPLonginLogs extends JFrame{
private File path =new File(System.getProperty("user.home") + "/Desktop");
private JTextField textField1;
private JButton button1;
private JButton runButton;
private JPanel mainPanel;
private JTextField TextField;
private File file=null;
public static void main(String[] args) {
IPLonginLogs ipLonginLogs=new IPLonginLogs();
ipLonginLogs.setVisible(true);
}
public IPLonginLogs() {
init();
}
private void initListener() {
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser=new JFileChooser(path);
//fileChooser.setCurrentDirectory(InputPath);
if(fileChooser.showOpenDialog(IPLonginLogs.this)==JFileChooser.APPROVE_OPTION) {
try {
path = fileChooser.getSelectedFile();
File file = fileChooser.getSelectedFile();
FileInputStream fileInputStream = new FileInputStream(file);
String path=file.toString();
textField1.setText(path);
} catch (FileNotFoundException e1) {
JOptionPane.showMessageDialog(IPLonginLogs.this, "檔案不存在");
path = fileChooser.getSelectedFile().getParentFile();
}
}
}
});
runButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(textField1.getText().equals(""))
JOptionPane.showMessageDialog(IPLonginLogs.this, "請選擇檔案");
else {
file=new File(textField1.getText());
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
StringBuilder sb=new StringBuilder();
StringBuilder sb2=new StringBuilder();
String line;
boolean read=false;
Map<String, ArrayList<String>> map = new HashMap<>();
while((line=br.readLine())!=null) {
if(line.contains("LOGIN_REQUEST"))
read=true;
if(line.contains("receiveObject end")&&read) {
read = false;
sb.append("\r\n");
}
if(read) {
sb.append(line);
sb.append("\r\n");
if(line.contains("LOGIN logged")) {
sb2.append(line + "\r\n");
String team=line.substring(line.indexOf("logged in")+10,line.indexOf("@")-1);
String ip=line.substring(line.indexOf("addr")+6,line.indexOf(","));
if(map.containsKey(ip)){
if(map.get(ip).size()>0) {
if(!map.get(ip).contains(team)) {
map.get(ip).add(team);
}
}
}
else{
ArrayList a=new ArrayList();
a.add(team);
map.put(ip,a);
}
}
}
}
fr.close();
StringBuilder sb3=new StringBuilder();
Set keySet = map.keySet();
Iterator it = keySet.iterator();
while(it.hasNext()){
String key = (String)it.next();
ArrayList value = map.get(key);
sb3.append("IP:" + key + "\t Login team:" + value+"\r\n");
}
FileWriter fw= new FileWriter(file.getParent()+"\\all.txt");
fw.write(sb.toString());
fw.flush();
fw.close();
fw= new FileWriter(file.getParent()+"\\ip_time.txt");
fw.write(sb2.toString());
fw.flush();
fw.close();
fw= new FileWriter(file.getParent()+"\\ip.txt");
fw.write(sb3.toString());
fw.flush();
fw.close();
JOptionPane.showMessageDialog(IPLonginLogs.this, "Done!");
Desktop desktop = Desktop.getDesktop();
desktop.open(new File(file.getParent()+"\\ip.txt"));
} catch (FileNotFoundException e1) {
JOptionPane.showMessageDialog(IPLonginLogs.this, "檔案不存在");
} catch (IOException e1) {
JOptionPane.showMessageDialog(IPLonginLogs.this, "IO例外"+e1);
}
}
}
});
}
private void init() {
setTitle("PC2登入IP查詢");
setSize(600,134);
setContentPane(mainPanel);
setLocationRelativeTo(null);
setResizable(false);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
initListener();
}
}
| UTF-8 | Java | 6,058 | java | IPLonginLogs.java | Java | [] | null | [] | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
public class IPLonginLogs extends JFrame{
private File path =new File(System.getProperty("user.home") + "/Desktop");
private JTextField textField1;
private JButton button1;
private JButton runButton;
private JPanel mainPanel;
private JTextField TextField;
private File file=null;
public static void main(String[] args) {
IPLonginLogs ipLonginLogs=new IPLonginLogs();
ipLonginLogs.setVisible(true);
}
public IPLonginLogs() {
init();
}
private void initListener() {
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser=new JFileChooser(path);
//fileChooser.setCurrentDirectory(InputPath);
if(fileChooser.showOpenDialog(IPLonginLogs.this)==JFileChooser.APPROVE_OPTION) {
try {
path = fileChooser.getSelectedFile();
File file = fileChooser.getSelectedFile();
FileInputStream fileInputStream = new FileInputStream(file);
String path=file.toString();
textField1.setText(path);
} catch (FileNotFoundException e1) {
JOptionPane.showMessageDialog(IPLonginLogs.this, "檔案不存在");
path = fileChooser.getSelectedFile().getParentFile();
}
}
}
});
runButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(textField1.getText().equals(""))
JOptionPane.showMessageDialog(IPLonginLogs.this, "請選擇檔案");
else {
file=new File(textField1.getText());
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
StringBuilder sb=new StringBuilder();
StringBuilder sb2=new StringBuilder();
String line;
boolean read=false;
Map<String, ArrayList<String>> map = new HashMap<>();
while((line=br.readLine())!=null) {
if(line.contains("LOGIN_REQUEST"))
read=true;
if(line.contains("receiveObject end")&&read) {
read = false;
sb.append("\r\n");
}
if(read) {
sb.append(line);
sb.append("\r\n");
if(line.contains("LOGIN logged")) {
sb2.append(line + "\r\n");
String team=line.substring(line.indexOf("logged in")+10,line.indexOf("@")-1);
String ip=line.substring(line.indexOf("addr")+6,line.indexOf(","));
if(map.containsKey(ip)){
if(map.get(ip).size()>0) {
if(!map.get(ip).contains(team)) {
map.get(ip).add(team);
}
}
}
else{
ArrayList a=new ArrayList();
a.add(team);
map.put(ip,a);
}
}
}
}
fr.close();
StringBuilder sb3=new StringBuilder();
Set keySet = map.keySet();
Iterator it = keySet.iterator();
while(it.hasNext()){
String key = (String)it.next();
ArrayList value = map.get(key);
sb3.append("IP:" + key + "\t Login team:" + value+"\r\n");
}
FileWriter fw= new FileWriter(file.getParent()+"\\all.txt");
fw.write(sb.toString());
fw.flush();
fw.close();
fw= new FileWriter(file.getParent()+"\\ip_time.txt");
fw.write(sb2.toString());
fw.flush();
fw.close();
fw= new FileWriter(file.getParent()+"\\ip.txt");
fw.write(sb3.toString());
fw.flush();
fw.close();
JOptionPane.showMessageDialog(IPLonginLogs.this, "Done!");
Desktop desktop = Desktop.getDesktop();
desktop.open(new File(file.getParent()+"\\ip.txt"));
} catch (FileNotFoundException e1) {
JOptionPane.showMessageDialog(IPLonginLogs.this, "檔案不存在");
} catch (IOException e1) {
JOptionPane.showMessageDialog(IPLonginLogs.this, "IO例外"+e1);
}
}
}
});
}
private void init() {
setTitle("PC2登入IP查詢");
setSize(600,134);
setContentPane(mainPanel);
setLocationRelativeTo(null);
setResizable(false);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
initListener();
}
}
| 6,058 | 0.431848 | 0.427194 | 134 | 43.895523 | 24.207829 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.671642 | false | false | 9 |
ca7c77a3ba75bc94662861294ee6d9517b871403 | 27,547,920,257,348 | f57cfe30019188df380e79d2aa118d33dfcff27f | /app/src/main/java/com/example/corodinatelayout/GridLayout_Selected.java | f7a09e0d015cb393a36661b0185961402acc0f49 | [] | no_license | diorw/Material_design_learning | https://github.com/diorw/Material_design_learning | c4f95ee5165c1c38cb66ab293ebaca7083b3b3b2 | d059411819e4f65bb96680a01bd216066bdd513f | refs/heads/master | "2021-01-21T18:28:04.187000" | "2017-07-03T14:45:59" | "2017-07-03T14:45:59" | 92,048,724 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.corodinatelayout;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import java.util.HashMap;
import java.util.Map;
public class GridLayout_Selected extends Activity implements MultiChoiceModeListener {
private GridView mGridView;
private GridAdapter mGridAdapter;
private TextView mActionText;
private static final int MENU_SELECT_ALL = 0;
private static final int MENU_UNSELECT_ALL = MENU_SELECT_ALL + 1;
private Map<Integer, Boolean> mSelectMap = new HashMap<Integer, Boolean>();
private int[] glist = new int[15];
private int[] mImgIds = new int[] { R.drawable.animal_select, R.drawable.car_select,
R.drawable.city_select, R.drawable.iphone7_select, R.drawable.movie_select,
R.drawable.save_select };
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_selected_main);
mGridView = (GridView) findViewById(R.id.gridview);
mGridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
mGridAdapter = new GridAdapter(this);
mGridView.setAdapter(mGridAdapter);
mGridView.setMultiChoiceModeListener(this);
}
/** Override MultiChoiceModeListener start **/
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
View v = LayoutInflater.from(this).inflate(R.layout.actionbar_layout_selected,
null);
mActionText = (TextView) v.findViewById(R.id.action_text);
mActionText.setText(formatString(mGridView.getCheckedItemCount()));
mode.setCustomView(v);
getMenuInflater().inflate(R.menu.action_menu_selected, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
menu.getItem(MENU_SELECT_ALL).setEnabled(
mGridView.getCheckedItemCount() != mGridView.getCount());
return true;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Intent intent = new Intent();
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.menu_select:
for (int i = 0; i < mGridView.getCount(); i++) {
mGridView.setItemChecked(i, true);
mSelectMap.put(i, true);
}
break;
case R.id.menu_unselect:
for (int i = 0; i < mGridView.getCount(); i++) {
mGridView.setItemChecked(i, false);
mSelectMap.clear();
}
break;
case R.id.select_update:
int j = 1;
for (int i = 0; i < mGridView.getCount(); i++) {
if(mSelectMap.get(i) != null) {
if (mSelectMap.get(i)) {
glist[j] = i+1;
System.out.println(glist[j]);
}
j++;
}
System.out.println("选择结束1");
}
for (int a = 0;a< j;a++ ){
System.out.println(glist[a]);
}
System.out.println("选择结束");
intent.putExtra("getlist",glist);
intent.setClass(GridLayout_Selected.this, SelectPictureShowActivity.class);
startActivity(intent);
break;
}
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
mGridAdapter.notifyDataSetChanged();
}
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// TODO Auto-generated method stub
mActionText.setText(formatString(mGridView.getCheckedItemCount()));
mSelectMap.put(position, checked);
mode.invalidate();
}
/** Override MultiChoiceModeListener end **/
private String formatString(int count) {
return String.format(getString(R.string.selection), count);
}
private class GridAdapter extends BaseAdapter {
private Context mContext;
public GridAdapter(Context ctx) {
mContext = ctx;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mImgIds.length;
}
@Override
public Integer getItem(int position) {
// TODO Auto-generated method stub
return Integer.valueOf(mImgIds[position]);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
GridItem_Selected item;
if (convertView == null) {
item = new GridItem_Selected(mContext);
item.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
} else {
item = (GridItem_Selected) convertView;
}
item.setImgResId(getItem(position));
item.setChecked(mSelectMap.get(position) == null ? false
: mSelectMap.get(position));
return item;
}
}
} | UTF-8 | Java | 6,193 | java | GridLayout_Selected.java | Java | [] | null | [] | package com.example.corodinatelayout;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import java.util.HashMap;
import java.util.Map;
public class GridLayout_Selected extends Activity implements MultiChoiceModeListener {
private GridView mGridView;
private GridAdapter mGridAdapter;
private TextView mActionText;
private static final int MENU_SELECT_ALL = 0;
private static final int MENU_UNSELECT_ALL = MENU_SELECT_ALL + 1;
private Map<Integer, Boolean> mSelectMap = new HashMap<Integer, Boolean>();
private int[] glist = new int[15];
private int[] mImgIds = new int[] { R.drawable.animal_select, R.drawable.car_select,
R.drawable.city_select, R.drawable.iphone7_select, R.drawable.movie_select,
R.drawable.save_select };
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_selected_main);
mGridView = (GridView) findViewById(R.id.gridview);
mGridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
mGridAdapter = new GridAdapter(this);
mGridView.setAdapter(mGridAdapter);
mGridView.setMultiChoiceModeListener(this);
}
/** Override MultiChoiceModeListener start **/
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
View v = LayoutInflater.from(this).inflate(R.layout.actionbar_layout_selected,
null);
mActionText = (TextView) v.findViewById(R.id.action_text);
mActionText.setText(formatString(mGridView.getCheckedItemCount()));
mode.setCustomView(v);
getMenuInflater().inflate(R.menu.action_menu_selected, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
menu.getItem(MENU_SELECT_ALL).setEnabled(
mGridView.getCheckedItemCount() != mGridView.getCount());
return true;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Intent intent = new Intent();
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.menu_select:
for (int i = 0; i < mGridView.getCount(); i++) {
mGridView.setItemChecked(i, true);
mSelectMap.put(i, true);
}
break;
case R.id.menu_unselect:
for (int i = 0; i < mGridView.getCount(); i++) {
mGridView.setItemChecked(i, false);
mSelectMap.clear();
}
break;
case R.id.select_update:
int j = 1;
for (int i = 0; i < mGridView.getCount(); i++) {
if(mSelectMap.get(i) != null) {
if (mSelectMap.get(i)) {
glist[j] = i+1;
System.out.println(glist[j]);
}
j++;
}
System.out.println("选择结束1");
}
for (int a = 0;a< j;a++ ){
System.out.println(glist[a]);
}
System.out.println("选择结束");
intent.putExtra("getlist",glist);
intent.setClass(GridLayout_Selected.this, SelectPictureShowActivity.class);
startActivity(intent);
break;
}
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
mGridAdapter.notifyDataSetChanged();
}
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// TODO Auto-generated method stub
mActionText.setText(formatString(mGridView.getCheckedItemCount()));
mSelectMap.put(position, checked);
mode.invalidate();
}
/** Override MultiChoiceModeListener end **/
private String formatString(int count) {
return String.format(getString(R.string.selection), count);
}
private class GridAdapter extends BaseAdapter {
private Context mContext;
public GridAdapter(Context ctx) {
mContext = ctx;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mImgIds.length;
}
@Override
public Integer getItem(int position) {
// TODO Auto-generated method stub
return Integer.valueOf(mImgIds[position]);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
GridItem_Selected item;
if (convertView == null) {
item = new GridItem_Selected(mContext);
item.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
} else {
item = (GridItem_Selected) convertView;
}
item.setImgResId(getItem(position));
item.setChecked(mSelectMap.get(position) == null ? false
: mSelectMap.get(position));
return item;
}
}
} | 6,193 | 0.594463 | 0.592521 | 182 | 32.945053 | 23.910715 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.604396 | false | false | 9 |
a6c8f3f02aaf956a94761c2b49d5f2acdbb67ec4 | 33,243,046,929,667 | 367a0cd4a48d9218e2d18e539724b208694041b7 | /CollectionExample/src/collectionexample/comparetox/Simple.java | 8e555ae4658b95774164532a87ca5d3b570d8635 | [] | no_license | amin110230/javaSE6 | https://github.com/amin110230/javaSE6 | 2ec91f0e93b1f0e0701eb1b31db2795750f759c8 | 0d4794d15bcefd782f7ae5c77c64202bb1517fa0 | refs/heads/master | "2021-01-13T12:17:17.132000" | "2017-01-07T08:50:01" | "2017-01-07T08:50:01" | 78,219,497 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package collectionexample.comparetox;
import java.util.*;
public class Simple {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(new Student(101, "Uzzal", 23));
al.add(new Student(106, "Amlan", 27));
al.add(new Student(105, "Jia", 21));
System.out.println("Sorting by Name...");
Collections.sort(al, new NameComparator());
Iterator itr = al.iterator();
while (itr.hasNext()) {
Student s = (Student) itr.next();
System.out.println(s.rollno+ " " + s.name + " " + s.age);
}
System.out.println("sorting by age...");
Collections.sort(al, new AgeComparator());
Iterator itr2 = al.iterator();
while (itr2.hasNext()) {
Student s = (Student) itr2.next();
System.out.println(s.rollno+ " " + s.name + " " + s.age);
}
}
}
| UTF-8 | Java | 981 | java | Simple.java | Java | [
{
"context": "new ArrayList();\n al.add(new Student(101, \"Uzzal\", 23));\n al.add(new Student(106, \"Amlan\", ",
"end": 214,
"score": 0.9995388984680176,
"start": 209,
"tag": "NAME",
"value": "Uzzal"
},
{
"context": ", \"Uzzal\", 23));\n al.add(new Student(106, \"Amlan\", 27));\n al.add(new Student(105, \"Jia\", 21",
"end": 261,
"score": 0.9996588826179504,
"start": 256,
"tag": "NAME",
"value": "Amlan"
},
{
"context": ", \"Amlan\", 27));\n al.add(new Student(105, \"Jia\", 21));\n \n System.out.println(\"Sort",
"end": 306,
"score": 0.9993776679039001,
"start": 303,
"tag": "NAME",
"value": "Jia"
}
] | null | [] | package collectionexample.comparetox;
import java.util.*;
public class Simple {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(new Student(101, "Uzzal", 23));
al.add(new Student(106, "Amlan", 27));
al.add(new Student(105, "Jia", 21));
System.out.println("Sorting by Name...");
Collections.sort(al, new NameComparator());
Iterator itr = al.iterator();
while (itr.hasNext()) {
Student s = (Student) itr.next();
System.out.println(s.rollno+ " " + s.name + " " + s.age);
}
System.out.println("sorting by age...");
Collections.sort(al, new AgeComparator());
Iterator itr2 = al.iterator();
while (itr2.hasNext()) {
Student s = (Student) itr2.next();
System.out.println(s.rollno+ " " + s.name + " " + s.age);
}
}
}
| 981 | 0.507645 | 0.489297 | 32 | 29.65625 | 22.379692 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 9 |
a124268539e3b201eab5baba7312225c1c9e6aa3 | 9,122,510,570,099 | 7c85272e5dfba8bb2b1c2375d1b8fff8facbf191 | /src/main/java/com/hwk/leetCode/ThirdMax.java | 070a446f3d6e89e9fa46ef0a07fd266dcc78af66 | [] | no_license | SmallAntBrother/blood-Ant | https://github.com/SmallAntBrother/blood-Ant | b8220ddead9d9358b7187e8b42a257fefdbafe9b | f8fedb9a9380f3497c1545fd2912ffa900ea6711 | refs/heads/master | "2022-07-09T22:09:07.689000" | "2019-09-17T05:59:08" | "2019-09-17T05:59:08" | 93,131,585 | 0 | 0 | null | false | "2022-06-30T20:19:48" | "2017-06-02T05:50:52" | "2019-09-17T06:00:07" | "2022-06-30T20:19:46" | 53,928 | 0 | 0 | 2 | Java | false | false | package com.hwk.leetCode;
import java.util.Arrays;
public class ThirdMax {
public static void main(String[] args) {
// System.out.println(findMedianSortedArrays(new int[] {1 , 2},new int[] {3} ));
// System.out.println(findMedianSortedArrays(new int[] {1 , 2},new int[] {3,4} ));
//
//
// System.out.println(findMedianSortedArrays(new int[] {1 , 2},new int[] {3,4,6} ));
// System.out.println(findMedianSortedArrays(new int[] {1 , 2},new int[] {3,4,6,7} ));
System.out.println(myAtoi("42"));
System.out.println(myAtoi(" -42"));
System.out.println(myAtoi("-42"));
System.out.println(myAtoi("4193 with words"));
System.out.println(myAtoi("words and 987"));
System.out.println(myAtoi("-91283472332"));
System.out.println(myAtoi("91283472332"));
System.out.println(myAtoi(" 0000000000012345678"));
System.out.println(myAtoi(" -0000000000012345678"));
}
public static int myAtoi(String str) {
Long num = 0L;
Boolean zhengshu = true;
int index = 0 ;
boolean flag = true;
while(index < str.length()) {
if(' ' == str.charAt(index)) {
index ++;
continue;
}
if(flag && ('-' == str.charAt(index) || '+' == str.charAt(index))) {
zhengshu = '+' == str.charAt(index);
flag = !flag;
}else if("0123456789".indexOf(String.valueOf(str.charAt(index))) > -1) {
if(!flag && num == 0 && str.charAt(index) - '0' == 0) {
return 0;
}
num = num * 10 + (zhengshu ? (str.charAt(index) - '0') : -(str.charAt(index) - '0'));
}else{
break;
}
index ++;
}
num = num < Integer.MIN_VALUE ? Integer.MIN_VALUE : num > Integer.MAX_VALUE ? Integer.MAX_VALUE : num;
return num.intValue() ;
}
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] nums = new int[nums1.length + nums2.length] ;
for(int i = 0 ; i < nums1.length ; i ++) {
nums[i] = nums1[i];
}
for(int i = 0 ; i < nums2.length ; i ++) {
nums[nums1.length + i] = nums2[i];
}
Arrays.sort(nums);
return (nums.length & 1) == 1 ? nums[nums.length / 2] : (nums[nums.length / 2 ] + nums[nums.length / 2 - 1]) / 2.0;
}
public static int thirdMax(int[] nums) {
if (nums.length == 1) {
return nums[0];
} else if (nums.length == 2) {
return Math.max(nums[0], nums[1]);
}
int[] smax = new int[3];
int index = 0;
for (int i = 0; i < nums.length; i++) {
if (index == 0) {
smax[index++] = nums[i];
}
}
return smax[2] == 0 ? smax[0] : smax[2];
}
}
| UTF-8 | Java | 2,519 | java | ThirdMax.java | Java | [] | null | [] | package com.hwk.leetCode;
import java.util.Arrays;
public class ThirdMax {
public static void main(String[] args) {
// System.out.println(findMedianSortedArrays(new int[] {1 , 2},new int[] {3} ));
// System.out.println(findMedianSortedArrays(new int[] {1 , 2},new int[] {3,4} ));
//
//
// System.out.println(findMedianSortedArrays(new int[] {1 , 2},new int[] {3,4,6} ));
// System.out.println(findMedianSortedArrays(new int[] {1 , 2},new int[] {3,4,6,7} ));
System.out.println(myAtoi("42"));
System.out.println(myAtoi(" -42"));
System.out.println(myAtoi("-42"));
System.out.println(myAtoi("4193 with words"));
System.out.println(myAtoi("words and 987"));
System.out.println(myAtoi("-91283472332"));
System.out.println(myAtoi("91283472332"));
System.out.println(myAtoi(" 0000000000012345678"));
System.out.println(myAtoi(" -0000000000012345678"));
}
public static int myAtoi(String str) {
Long num = 0L;
Boolean zhengshu = true;
int index = 0 ;
boolean flag = true;
while(index < str.length()) {
if(' ' == str.charAt(index)) {
index ++;
continue;
}
if(flag && ('-' == str.charAt(index) || '+' == str.charAt(index))) {
zhengshu = '+' == str.charAt(index);
flag = !flag;
}else if("0123456789".indexOf(String.valueOf(str.charAt(index))) > -1) {
if(!flag && num == 0 && str.charAt(index) - '0' == 0) {
return 0;
}
num = num * 10 + (zhengshu ? (str.charAt(index) - '0') : -(str.charAt(index) - '0'));
}else{
break;
}
index ++;
}
num = num < Integer.MIN_VALUE ? Integer.MIN_VALUE : num > Integer.MAX_VALUE ? Integer.MAX_VALUE : num;
return num.intValue() ;
}
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] nums = new int[nums1.length + nums2.length] ;
for(int i = 0 ; i < nums1.length ; i ++) {
nums[i] = nums1[i];
}
for(int i = 0 ; i < nums2.length ; i ++) {
nums[nums1.length + i] = nums2[i];
}
Arrays.sort(nums);
return (nums.length & 1) == 1 ? nums[nums.length / 2] : (nums[nums.length / 2 ] + nums[nums.length / 2 - 1]) / 2.0;
}
public static int thirdMax(int[] nums) {
if (nums.length == 1) {
return nums[0];
} else if (nums.length == 2) {
return Math.max(nums[0], nums[1]);
}
int[] smax = new int[3];
int index = 0;
for (int i = 0; i < nums.length; i++) {
if (index == 0) {
smax[index++] = nums[i];
}
}
return smax[2] == 0 ? smax[0] : smax[2];
}
}
| 2,519 | 0.575625 | 0.51846 | 93 | 26.086021 | 27.182638 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.677419 | false | false | 9 |
b7909151039711b235848eecb63ddd8106ece5eb | 33,681,133,552,986 | 9bc2c94206ffd7b3b292277aee22f091d9356da9 | /app/src/main/java/com/scientechperu/pideloya/Clases/Vehiculos.java | 6b0f291a26f4068324c9256fce0bb007fefd348f | [] | no_license | HansCordovaGoicochea/TiendasSC | https://github.com/HansCordovaGoicochea/TiendasSC | b41af6ccb249f6a4acb0ac58a9d8f300b3f98339 | f49995636c62c5d641e72824060b3f1200adb93d | refs/heads/master | "2020-03-27T09:46:10.214000" | "2018-10-13T02:07:26" | "2018-10-13T02:07:26" | 146,370,656 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.scientechperu.pideloya.Clases;
import com.orm.SugarRecord;
public class Vehiculos extends SugarRecord {
private String idcustomer;
private String placa;
private String modelo;
private String marca;
private String tipo_vehiculo;
private String fecha_adquisicion;
private String color;
private String tipo_combustible;
private String id_shop;
private boolean estado;
public Vehiculos() {
}
public Vehiculos(String idcustomer, String placa, String modelo, String marca, String tipo_vehiculo, String fecha_adquisicion, String color, String tipo_combustible, String id_shop, boolean estado) {
this.idcustomer = idcustomer;
this.placa = placa;
this.modelo = modelo;
this.marca = marca;
this.tipo_vehiculo = tipo_vehiculo;
this.fecha_adquisicion = fecha_adquisicion;
this.color = color;
this.tipo_combustible = tipo_combustible;
this.id_shop = id_shop;
this.estado = estado;
}
public String getIdcustomer() {
return idcustomer;
}
public void setIdcustomer(String idcustomer) {
this.idcustomer = idcustomer;
}
public String getPlaca() {
return placa;
}
public void setPlaca(String placa) {
this.placa = placa;
}
public String getModelo() {
return modelo;
}
public void setModelo(String modelo) {
this.modelo = modelo;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getTipo_vehiculo() {
return tipo_vehiculo;
}
public void setTipo_vehiculo(String tipo_vehiculo) {
this.tipo_vehiculo = tipo_vehiculo;
}
public String getFecha_adquisicion() {
return fecha_adquisicion;
}
public void setFecha_adquisicion(String fecha_adquisicion) {
this.fecha_adquisicion = fecha_adquisicion;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getTipo_combustible() {
return tipo_combustible;
}
public void setTipo_combustible(String tipo_combustible) {
this.tipo_combustible = tipo_combustible;
}
public String getId_shop() {
return id_shop;
}
public void setId_shop(String id_shop) {
this.id_shop = id_shop;
}
public boolean isEstado() {
return estado;
}
public void setEstado(boolean estado) {
this.estado = estado;
}
}
| UTF-8 | Java | 2,626 | java | Vehiculos.java | Java | [] | null | [] | package com.scientechperu.pideloya.Clases;
import com.orm.SugarRecord;
public class Vehiculos extends SugarRecord {
private String idcustomer;
private String placa;
private String modelo;
private String marca;
private String tipo_vehiculo;
private String fecha_adquisicion;
private String color;
private String tipo_combustible;
private String id_shop;
private boolean estado;
public Vehiculos() {
}
public Vehiculos(String idcustomer, String placa, String modelo, String marca, String tipo_vehiculo, String fecha_adquisicion, String color, String tipo_combustible, String id_shop, boolean estado) {
this.idcustomer = idcustomer;
this.placa = placa;
this.modelo = modelo;
this.marca = marca;
this.tipo_vehiculo = tipo_vehiculo;
this.fecha_adquisicion = fecha_adquisicion;
this.color = color;
this.tipo_combustible = tipo_combustible;
this.id_shop = id_shop;
this.estado = estado;
}
public String getIdcustomer() {
return idcustomer;
}
public void setIdcustomer(String idcustomer) {
this.idcustomer = idcustomer;
}
public String getPlaca() {
return placa;
}
public void setPlaca(String placa) {
this.placa = placa;
}
public String getModelo() {
return modelo;
}
public void setModelo(String modelo) {
this.modelo = modelo;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getTipo_vehiculo() {
return tipo_vehiculo;
}
public void setTipo_vehiculo(String tipo_vehiculo) {
this.tipo_vehiculo = tipo_vehiculo;
}
public String getFecha_adquisicion() {
return fecha_adquisicion;
}
public void setFecha_adquisicion(String fecha_adquisicion) {
this.fecha_adquisicion = fecha_adquisicion;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getTipo_combustible() {
return tipo_combustible;
}
public void setTipo_combustible(String tipo_combustible) {
this.tipo_combustible = tipo_combustible;
}
public String getId_shop() {
return id_shop;
}
public void setId_shop(String id_shop) {
this.id_shop = id_shop;
}
public boolean isEstado() {
return estado;
}
public void setEstado(boolean estado) {
this.estado = estado;
}
}
| 2,626 | 0.632521 | 0.632521 | 113 | 22.238937 | 24.490662 | 203 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.451327 | false | false | 9 |
c443248bd6d7558720976dd528dd79e45082b7cb | 25,331,717,115,964 | c0adc0a75902d2cfff12f38f25590b6eabad7281 | /FireGallery/app/src/main/java/com/example/firegallery/UploadImage.java | 19a0c6c0ddd4917eb5cf51324ebe371c6f5c2a14 | [] | no_license | Bala-MK/Android | https://github.com/Bala-MK/Android | ddefe2e7603a6253ced640d0eccec4c2b2f677ba | 5afe72344e7c9c56970dfdc4e93558ceaa27f437 | refs/heads/master | "2022-12-26T15:19:04.151000" | "2020-10-09T05:50:53" | "2020-10-09T05:50:53" | 290,744,965 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.firegallery;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class UploadImage extends AppCompatActivity {
EditText editText;
Button imgbtn;
private static final int IMAGE_UPLOAD=1;
FirebaseStorage storage;
StorageReference storageRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_image);
editText=findViewById(R.id.imgname);
imgbtn=findViewById(R.id.img);
storage=FirebaseStorage.getInstance();
storageRef=storage.getReference();
}
public void chooseImage(View view) {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT) ;
startActivityForResult(Intent.createChooser(intent,"Image"),IMAGE_UPLOAD);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if(requestCode==IMAGE_UPLOAD && resultCode==RESULT_OK){
if(data.getData()!=null){
uploadtoFire(data.getData());
}
else Toast.makeText(this, "No Image selected", Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadtoFire(Uri file) {
StorageReference image=storageRef.child("images/"+editText.getText().toString());
final UploadTask task = image.putFile(file);
task.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(UploadImage.this, "Successfully Uploaded!!", Toast.LENGTH_SHORT).show();
finish();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(UploadImage.this, "Uploading",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(UploadImage.this, "Upload Failed! Try Again.", Toast.LENGTH_SHORT).show();
}
});
}
} | UTF-8 | Java | 3,003 | java | UploadImage.java | Java | [] | null | [] | package com.example.firegallery;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class UploadImage extends AppCompatActivity {
EditText editText;
Button imgbtn;
private static final int IMAGE_UPLOAD=1;
FirebaseStorage storage;
StorageReference storageRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_image);
editText=findViewById(R.id.imgname);
imgbtn=findViewById(R.id.img);
storage=FirebaseStorage.getInstance();
storageRef=storage.getReference();
}
public void chooseImage(View view) {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT) ;
startActivityForResult(Intent.createChooser(intent,"Image"),IMAGE_UPLOAD);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if(requestCode==IMAGE_UPLOAD && resultCode==RESULT_OK){
if(data.getData()!=null){
uploadtoFire(data.getData());
}
else Toast.makeText(this, "No Image selected", Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadtoFire(Uri file) {
StorageReference image=storageRef.child("images/"+editText.getText().toString());
final UploadTask task = image.putFile(file);
task.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(UploadImage.this, "Successfully Uploaded!!", Toast.LENGTH_SHORT).show();
finish();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(UploadImage.this, "Uploading",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(UploadImage.this, "Upload Failed! Try Again.", Toast.LENGTH_SHORT).show();
}
});
}
} | 3,003 | 0.689644 | 0.689311 | 78 | 37.512821 | 27.391157 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.717949 | false | false | 9 |
0e9c9e55d3bfd2cbdf0eb3cff1ea4da8a0f59642 | 22,497,038,728,322 | 95b9126ac95a10d13fc263957972fcd555f7df05 | /Core/src/main/java/br/com/primum/modelo/viasoft/NOTAMEDIDAS/Notamedidas.java | 31501149a9394cbac03c9fbe7803adf6bfe2f1c7 | [] | no_license | jeffersonbraga/PrimeMachine | https://github.com/jeffersonbraga/PrimeMachine | 78598066ebe2057d320d9f24ad359fcf278d5598 | 97ee5ef02de75aaa7aea46cc0d39a14ed9adc645 | refs/heads/master | "2020-03-18T12:37:53.388000" | "2018-05-24T16:07:59" | "2018-05-24T16:07:59" | 72,764,484 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.primum.modelo.viasoft.NOTAMEDIDAS;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
@Entity
@Table(name="NOTAMEDIDAS")
public class Notamedidas implements Serializable {
@Transient
private static final long serialVersionUID = 1L;
@Id
@Column
private Integer ESTAB;
@Column
private Integer IDNOTA;
@Column
private Integer SEQITEM;
@Column
private Integer ALTURA;
@Column
private Integer LARGURA;
@Column
private Integer COMPRIMENTO;
@Column
private Integer ESPESSURA;
@Column
private String STATUS;
@Column
private String OBSERVACAO;
@Column
private Integer IDVENDEDOR;
@Column
private Integer QTDE;
@Column
private Integer SEQ;
@Column
private Integer QTDEDEV;
public Integer getEstab(){
return ESTAB;
}
public void setEstab(Integer ESTAB){
this.ESTAB = ESTAB;
}
public Integer getIdnota(){
return IDNOTA;
}
public void setIdnota(Integer IDNOTA){
this.IDNOTA = IDNOTA;
}
public Integer getSeqitem(){
return SEQITEM;
}
public void setSeqitem(Integer SEQITEM){
this.SEQITEM = SEQITEM;
}
public Integer getAltura(){
return ALTURA;
}
public void setAltura(Integer ALTURA){
this.ALTURA = ALTURA;
}
public Integer getLargura(){
return LARGURA;
}
public void setLargura(Integer LARGURA){
this.LARGURA = LARGURA;
}
public Integer getComprimento(){
return COMPRIMENTO;
}
public void setComprimento(Integer COMPRIMENTO){
this.COMPRIMENTO = COMPRIMENTO;
}
public Integer getEspessura(){
return ESPESSURA;
}
public void setEspessura(Integer ESPESSURA){
this.ESPESSURA = ESPESSURA;
}
public String getStatus(){
return STATUS;
}
public void setStatus(String STATUS){
this.STATUS = STATUS;
}
public String getObservacao(){
return OBSERVACAO;
}
public void setObservacao(String OBSERVACAO){
this.OBSERVACAO = OBSERVACAO;
}
public Integer getIdvendedor(){
return IDVENDEDOR;
}
public void setIdvendedor(Integer IDVENDEDOR){
this.IDVENDEDOR = IDVENDEDOR;
}
public Integer getQtde(){
return QTDE;
}
public void setQtde(Integer QTDE){
this.QTDE = QTDE;
}
public Integer getSeq(){
return SEQ;
}
public void setSeq(Integer SEQ){
this.SEQ = SEQ;
}
public Integer getQtdedev(){
return QTDEDEV;
}
public void setQtdedev(Integer QTDEDEV){
this.QTDEDEV = QTDEDEV;
}
} | UTF-8 | Java | 2,524 | java | Notamedidas.java | Java | [] | null | [] | package br.com.primum.modelo.viasoft.NOTAMEDIDAS;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
@Entity
@Table(name="NOTAMEDIDAS")
public class Notamedidas implements Serializable {
@Transient
private static final long serialVersionUID = 1L;
@Id
@Column
private Integer ESTAB;
@Column
private Integer IDNOTA;
@Column
private Integer SEQITEM;
@Column
private Integer ALTURA;
@Column
private Integer LARGURA;
@Column
private Integer COMPRIMENTO;
@Column
private Integer ESPESSURA;
@Column
private String STATUS;
@Column
private String OBSERVACAO;
@Column
private Integer IDVENDEDOR;
@Column
private Integer QTDE;
@Column
private Integer SEQ;
@Column
private Integer QTDEDEV;
public Integer getEstab(){
return ESTAB;
}
public void setEstab(Integer ESTAB){
this.ESTAB = ESTAB;
}
public Integer getIdnota(){
return IDNOTA;
}
public void setIdnota(Integer IDNOTA){
this.IDNOTA = IDNOTA;
}
public Integer getSeqitem(){
return SEQITEM;
}
public void setSeqitem(Integer SEQITEM){
this.SEQITEM = SEQITEM;
}
public Integer getAltura(){
return ALTURA;
}
public void setAltura(Integer ALTURA){
this.ALTURA = ALTURA;
}
public Integer getLargura(){
return LARGURA;
}
public void setLargura(Integer LARGURA){
this.LARGURA = LARGURA;
}
public Integer getComprimento(){
return COMPRIMENTO;
}
public void setComprimento(Integer COMPRIMENTO){
this.COMPRIMENTO = COMPRIMENTO;
}
public Integer getEspessura(){
return ESPESSURA;
}
public void setEspessura(Integer ESPESSURA){
this.ESPESSURA = ESPESSURA;
}
public String getStatus(){
return STATUS;
}
public void setStatus(String STATUS){
this.STATUS = STATUS;
}
public String getObservacao(){
return OBSERVACAO;
}
public void setObservacao(String OBSERVACAO){
this.OBSERVACAO = OBSERVACAO;
}
public Integer getIdvendedor(){
return IDVENDEDOR;
}
public void setIdvendedor(Integer IDVENDEDOR){
this.IDVENDEDOR = IDVENDEDOR;
}
public Integer getQtde(){
return QTDE;
}
public void setQtde(Integer QTDE){
this.QTDE = QTDE;
}
public Integer getSeq(){
return SEQ;
}
public void setSeq(Integer SEQ){
this.SEQ = SEQ;
}
public Integer getQtdedev(){
return QTDEDEV;
}
public void setQtdedev(Integer QTDEDEV){
this.QTDEDEV = QTDEDEV;
}
} | 2,524 | 0.725832 | 0.725436 | 188 | 12.430851 | 14.515234 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.962766 | false | false | 9 |
aa399105c8866e8ea7a015867abf23c0a4d00aa6 | 25,443,386,286,637 | 460c38ea068971a461c9289d5613cbdd02cb5ca7 | /src/main/java/com/epam/big_task/model/BusinessLogic.java | 0ce2d5bea4733ca639ad3700f68ed1ee438b7671 | [] | no_license | xxxandriyxxx/task09_string | https://github.com/xxxandriyxxx/task09_string | b14760eb09f263388ecfd10ae2166f62e396c06c | 36b02c360fc05046a99d96e156a3c619070d83a0 | refs/heads/master | "2020-09-24T11:04:54.813000" | "2019-12-04T00:16:31" | "2019-12-04T00:16:31" | 225,745,826 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.epam.big_task.model;
import java.util.*;
import java.util.stream.Collectors;
public class BusinessLogic implements Model {
@Override
public List<Sentence> getSortedSentenceList(List<Sentence> sentences) {
List<Sentence> sortedList = new ArrayList<>(sentences);
Collections.sort(sortedList);
return sortedList;
}
@Override
public List<Word> getUniqueWords(Sentence sentence, List<Sentence> otherSentences) {
List<Word> uniqueWords = new ArrayList<>();
boolean found = false;
for (Word wu : sentence.getWords()) {
for (Sentence s : otherSentences) {
if (!found) {
for (Word w : s.getWords()) {
if (w.equals(wu)) {
found = true;
break;
}
}
}
}
if (!found) {
uniqueWords.add(wu);
} else {
found = false;
}
}
return uniqueWords;
}
@Override
public Map<Sentence, Integer> getSortedByRepeating(List<Sentence> sentences) {
List<Map<Word, Long>> numberOfWords = new ArrayList<>();
for (Sentence s : sentences) {
Map<Word, Long> map = s.getWords().stream()
.collect(Collectors.groupingBy(value -> value, Collectors.counting()));
numberOfWords.add(map);
}
Map<Sentence, Integer> sortedByRepeating = new HashMap<>();
int counter = 0;
int sentenceCounter = -1;
for (Map m : numberOfWords) {
// System.out.println("----");
counter = 0;
sentenceCounter++;
Iterator<Map.Entry<Word, Long>> iterator = m.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Word, Long> entry = iterator.next();
if (entry.getValue() > 1) {
// System.out.println("Key: " + entry.getKey() + " Value: " + entry.getValue());
counter += entry.getValue();
}
}
sortedByRepeating.put(sentences.get(sentenceCounter), counter);
// System.out.println("couter = " + counter);
}
sortedByRepeating = sortedByRepeating.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(
Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
return sortedByRepeating;
}
@Override
public Map<Sentence, List<Word>> getWordsOfQuestion(List<Sentence> sentences, int length) {
Map<Sentence, List<Word>> wordMap = new HashMap<>();
List<Word> words = new ArrayList<>();
for (Sentence s : sentences) {
if (s.getValue().matches(".+\\?")) {
words.clear();
for (Word w : s.getWords()) {
if (w.getValue().length() == length) {
words.add(w);
}
}
words = words.stream()
.distinct()
.collect(Collectors.toList());
wordMap.put(s, words);
}
}
return wordMap;
}
@Override
public void replaceLongestVowel(List<Sentence> sentences) {
String longestWord;
String vowel;
int indexV;
int indexL;
for (Sentence s : sentences) {
longestWord = "";
vowel = "";
indexV = -1;
indexL = -1;
for (Word w : s.getWords()) {
if (w.getValue().matches("[aeiouyAEIOUY].*")) {
System.out.println("+++ wovel " + w);
vowel = w.getValue();
indexV = s.getWords().indexOf(w);
for (Word w2 : s.getWords()) {
if (w2.getValue().length() > longestWord.length()) {
longestWord = w2.getValue();
indexL = s.getWords().indexOf(w2);
System.out.println("+++ longest " + w2);
}
}
break;
}
}
if (indexV >= 0 && indexL >= 0) {
s.getWords().set(indexV, new Word(longestWord));
s.getWords().set(indexL, new Word(vowel));
StringBuilder sb = new StringBuilder();
for (Word w : s.getWords()) {
sb.append(" ").append(w.getValue());
}
s.setValue(sb.toString().trim());
}
}
}
@Override
public void printWordsByAlphabet(List<Sentence> sentences) {
List<Word> allWords = new ArrayList<>();
char lastChar = 'a';
for (Sentence s : sentences) {
allWords.addAll(s.getWords());
}
allWords = allWords.stream()
.distinct()
.collect(Collectors.toList());
Collections.sort(allWords);
for (Word w : allWords) {
if (w.getValue().charAt(0) != lastChar) {
System.out.print("\n");
}
System.out.print(w.getValue() + " ");
lastChar = w.getValue().charAt(0);
}
}
@Override
public void deleteWordsStartConsonant(List<Sentence> sentences, int length) {
for (Sentence s : sentences) {
for (Word w : new ArrayList<>(s.getWords())) {
if ((w.getValue().length() == length) && (w.getValue().matches("^[^aeiouyAEIOUY].*"))) {
s.getWords().remove(w);
}
}
StringBuilder sb = new StringBuilder();
for (Word w : s.getWords()) {
sb.append(" ").append(w.getValue());
}
s.setValue(sb.toString().trim());
}
}
}
| UTF-8 | Java | 6,066 | java | BusinessLogic.java | Java | [] | null | [] | package com.epam.big_task.model;
import java.util.*;
import java.util.stream.Collectors;
public class BusinessLogic implements Model {
@Override
public List<Sentence> getSortedSentenceList(List<Sentence> sentences) {
List<Sentence> sortedList = new ArrayList<>(sentences);
Collections.sort(sortedList);
return sortedList;
}
@Override
public List<Word> getUniqueWords(Sentence sentence, List<Sentence> otherSentences) {
List<Word> uniqueWords = new ArrayList<>();
boolean found = false;
for (Word wu : sentence.getWords()) {
for (Sentence s : otherSentences) {
if (!found) {
for (Word w : s.getWords()) {
if (w.equals(wu)) {
found = true;
break;
}
}
}
}
if (!found) {
uniqueWords.add(wu);
} else {
found = false;
}
}
return uniqueWords;
}
@Override
public Map<Sentence, Integer> getSortedByRepeating(List<Sentence> sentences) {
List<Map<Word, Long>> numberOfWords = new ArrayList<>();
for (Sentence s : sentences) {
Map<Word, Long> map = s.getWords().stream()
.collect(Collectors.groupingBy(value -> value, Collectors.counting()));
numberOfWords.add(map);
}
Map<Sentence, Integer> sortedByRepeating = new HashMap<>();
int counter = 0;
int sentenceCounter = -1;
for (Map m : numberOfWords) {
// System.out.println("----");
counter = 0;
sentenceCounter++;
Iterator<Map.Entry<Word, Long>> iterator = m.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Word, Long> entry = iterator.next();
if (entry.getValue() > 1) {
// System.out.println("Key: " + entry.getKey() + " Value: " + entry.getValue());
counter += entry.getValue();
}
}
sortedByRepeating.put(sentences.get(sentenceCounter), counter);
// System.out.println("couter = " + counter);
}
sortedByRepeating = sortedByRepeating.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(
Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
return sortedByRepeating;
}
@Override
public Map<Sentence, List<Word>> getWordsOfQuestion(List<Sentence> sentences, int length) {
Map<Sentence, List<Word>> wordMap = new HashMap<>();
List<Word> words = new ArrayList<>();
for (Sentence s : sentences) {
if (s.getValue().matches(".+\\?")) {
words.clear();
for (Word w : s.getWords()) {
if (w.getValue().length() == length) {
words.add(w);
}
}
words = words.stream()
.distinct()
.collect(Collectors.toList());
wordMap.put(s, words);
}
}
return wordMap;
}
@Override
public void replaceLongestVowel(List<Sentence> sentences) {
String longestWord;
String vowel;
int indexV;
int indexL;
for (Sentence s : sentences) {
longestWord = "";
vowel = "";
indexV = -1;
indexL = -1;
for (Word w : s.getWords()) {
if (w.getValue().matches("[aeiouyAEIOUY].*")) {
System.out.println("+++ wovel " + w);
vowel = w.getValue();
indexV = s.getWords().indexOf(w);
for (Word w2 : s.getWords()) {
if (w2.getValue().length() > longestWord.length()) {
longestWord = w2.getValue();
indexL = s.getWords().indexOf(w2);
System.out.println("+++ longest " + w2);
}
}
break;
}
}
if (indexV >= 0 && indexL >= 0) {
s.getWords().set(indexV, new Word(longestWord));
s.getWords().set(indexL, new Word(vowel));
StringBuilder sb = new StringBuilder();
for (Word w : s.getWords()) {
sb.append(" ").append(w.getValue());
}
s.setValue(sb.toString().trim());
}
}
}
@Override
public void printWordsByAlphabet(List<Sentence> sentences) {
List<Word> allWords = new ArrayList<>();
char lastChar = 'a';
for (Sentence s : sentences) {
allWords.addAll(s.getWords());
}
allWords = allWords.stream()
.distinct()
.collect(Collectors.toList());
Collections.sort(allWords);
for (Word w : allWords) {
if (w.getValue().charAt(0) != lastChar) {
System.out.print("\n");
}
System.out.print(w.getValue() + " ");
lastChar = w.getValue().charAt(0);
}
}
@Override
public void deleteWordsStartConsonant(List<Sentence> sentences, int length) {
for (Sentence s : sentences) {
for (Word w : new ArrayList<>(s.getWords())) {
if ((w.getValue().length() == length) && (w.getValue().matches("^[^aeiouyAEIOUY].*"))) {
s.getWords().remove(w);
}
}
StringBuilder sb = new StringBuilder();
for (Word w : s.getWords()) {
sb.append(" ").append(w.getValue());
}
s.setValue(sb.toString().trim());
}
}
}
| 6,066 | 0.472634 | 0.469667 | 169 | 34.869823 | 23.760782 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526627 | false | false | 9 |
b430ec2c2f18bb191f31099a63d8badf77da2a3b | 27,264,452,420,728 | e5224618c59081af1062825d92d7fb1b87967151 | /src/main/java/io/mycat/net/SocketAcceptor.java | f35664897797205556bd0703775c60953dd31e65 | [
"GPL-2.0-only"
] | permissive | lizhanke/Mycat-Server | https://github.com/lizhanke/Mycat-Server | 5836c51089925ef92d69fde50b0f17f0846700cb | ea2e1469c9f84c42ecf1f916a7ad537cbfe2f012 | refs/heads/master | "2021-01-11T19:48:52.761000" | "2018-03-12T08:44:25" | "2018-09-06T14:03:20" | 49,316,066 | 0 | 0 | Apache-2.0 | true | "2018-09-06T14:03:22" | "2016-01-09T07:57:01" | "2016-01-09T07:57:05" | "2018-09-06T14:03:22" | 10,933 | 0 | 0 | 0 | Java | false | null | package io.mycat.net;
public interface SocketAcceptor {
void start();
String getName();
int getPort();
}
| UTF-8 | Java | 113 | java | SocketAcceptor.java | Java | [] | null | [] | package io.mycat.net;
public interface SocketAcceptor {
void start();
String getName();
int getPort();
}
| 113 | 0.690265 | 0.690265 | 11 | 9.272727 | 10.996618 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false | 9 |
6e302893645bb52b567aabe55781d4fbe9904676 | 635,655,223,162 | 736d267f0c73db085675a6879aee492f7039b396 | /j2se/xuxin/j2se/data/CharStack.java | abe063dee8a15d001bc2881eb4d29058e349504f | [] | no_license | xuxin23/xuxin | https://github.com/xuxin23/xuxin | 50537ce219f27284f7a70dc803ca337100190c3e | 484fd9de32efce2a19b80b95b831a7cc3b0c54e8 | refs/heads/master | "2021-01-21T01:46:22.255000" | "2016-03-22T02:28:36" | "2016-03-22T02:28:36" | 11,066,371 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package xuxin.j2se.data;
/*
* 单词逆序---用数组实现栈
* 原理:数组为私有,只能通过public方法操作数组。
* top指向数组的位置随着方法的调用而移动。
* 一句话就是,让你不能直接访问数组,而只能调用
* public方法移动top指向数组的位置来获取值。
* */
public class CharStack {
private int maxSize;
private char[] arr;
//top是关键,好好体会。
private int top;
public CharStack(int maxSize) {
this.maxSize = maxSize;
arr = new char[maxSize];
top = -1;
}
//压栈
public void push(char c) {
arr[++top] = c;
}
//出栈
public char pop() {
return arr[top--];
}
//查看栈顶元素
public char peek() {
return arr[top];
}
//判断栈是否为空
public boolean isEmpty() {
return top == -1;
}
//判断栈是否已满
public boolean isFull() {
return top == maxSize-1;
}
//测试,将字符数组反向输出
public static void main(String[] args) {
CharStack stack = new CharStack(20);
String str = "aBcdeFGHiJkLmNopqrst";
char[] c = str.toCharArray();
for (int i=0; i<c.length; i++) {
if (!stack.isFull()) {
stack.push(c[i]);
}else {
break;
}
}
while (!stack.isEmpty()) {
System.out.print(stack.pop());
}
}
}
| UTF-8 | Java | 1,359 | java | CharStack.java | Java | [] | null | [] | package xuxin.j2se.data;
/*
* 单词逆序---用数组实现栈
* 原理:数组为私有,只能通过public方法操作数组。
* top指向数组的位置随着方法的调用而移动。
* 一句话就是,让你不能直接访问数组,而只能调用
* public方法移动top指向数组的位置来获取值。
* */
public class CharStack {
private int maxSize;
private char[] arr;
//top是关键,好好体会。
private int top;
public CharStack(int maxSize) {
this.maxSize = maxSize;
arr = new char[maxSize];
top = -1;
}
//压栈
public void push(char c) {
arr[++top] = c;
}
//出栈
public char pop() {
return arr[top--];
}
//查看栈顶元素
public char peek() {
return arr[top];
}
//判断栈是否为空
public boolean isEmpty() {
return top == -1;
}
//判断栈是否已满
public boolean isFull() {
return top == maxSize-1;
}
//测试,将字符数组反向输出
public static void main(String[] args) {
CharStack stack = new CharStack(20);
String str = "aBcdeFGHiJkLmNopqrst";
char[] c = str.toCharArray();
for (int i=0; i<c.length; i++) {
if (!stack.isFull()) {
stack.push(c[i]);
}else {
break;
}
}
while (!stack.isEmpty()) {
System.out.print(stack.pop());
}
}
}
| 1,359 | 0.57247 | 0.566089 | 66 | 14.621212 | 11.95923 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.606061 | false | false | 4 |
728ee720f73270f40610db0b6044119f68c271df | 13,778,255,144,297 | cc35df09224df5fd2bb4a1820f3f998b9b5d9571 | /project-engine-web/src/test/java/com/bt/rsqe/projectengine/web/quoteoption/priceupdater/ProductInfoSheetUpdaterTest.java | e2dc2d235a2aecec44adafa2c67716628dc581eb | [] | no_license | LokeshCT/Junit | https://github.com/LokeshCT/Junit | 87c7f32bd7205f67206dad6b2659a5d713aed515 | 7f140f0fb1fdce552417c3128432d874eaab1f54 | refs/heads/master | "2020-03-22T16:37:41.186000" | "2018-07-09T21:01:50" | "2018-07-09T21:01:50" | 140,340,405 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bt.rsqe.projectengine.web.quoteoption.priceupdater;
import com.bt.rsqe.customerinventory.parameter.LineItemId;
import com.bt.rsqe.projectengine.web.facades.LineItemFacade;
import com.bt.rsqe.projectengine.web.model.LineItemModel;
import com.bt.rsqe.projectengine.web.model.bcmspreadsheet.InvalidExportDataException;
import com.bt.rsqe.projectengine.web.model.bcmspreadsheet.ProductInfoSheet;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.junit.Before;
import org.junit.Test;
import static com.bt.rsqe.projectengine.web.fixtures.LineItemModelFixture.*;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.*;
public class ProductInfoSheetUpdaterTest {
ProductInfoSheetUpdater updater;
@Mock
private LineItemFacade lineItemFacade;
@Before
public void setUp() throws Exception {
initMocks(this);
}
public void setUpWithValidValues() throws Exception {
ProductInfoSheet productInfoSheet = createProductInfoSheet();
updater = new ProductInfoSheetUpdater(productInfoSheet, lineItemFacade);
}
private ProductInfoSheet createProductInfoSheet() {
HSSFSheet sheet = new HSSFWorkbook().createSheet();
sheet.createRow(0);
final HSSFRow row = sheet.createRow(1);
HSSFCell firstCell = row.createCell(0);
firstCell.setCellValue("Connect Acceleration");
HSSFCell secondCell = row.createCell(1);
secondCell.setCellValue(10000);
return new ProductInfoSheet(sheet);
}
@Test
public void shouldUpdateNumericValue() throws Exception {
setUpWithValidValues();
final String customerId = "customerId";
LineItemModel lineItem = aLineItemModel().withCustomerId(customerId).withQuoteOptionItemDTOId("lineItemId").forProductCategory("Connect Acceleration").build();
updater.update(lineItem);
verify(lineItemFacade).persistMinimumRevenueCommitment("projectId", "quoteOptionId", new LineItemId("lineItemId"), "10000.0", null);
}
@Test
public void shouldNotUpdateValueForDifferentProductNames() throws Exception {
setUpWithValidValues();
final String customerId = "customerId";
LineItemModel lineItem = aLineItemModel().withCustomerId(customerId).withQuoteOptionItemDTOId("lineItemId").forProductCategory("Connect Optimisation").build();
updater.update(lineItem);
verify(lineItemFacade, never()).persistMinimumRevenueCommitment("projectId", "quoteOptionId", new LineItemId("lineItemId"), "10000.0", null);
}
@Test(expected = InvalidExportDataException.class)
public void shouldThrowExceptionForNonNumeric() {
setUpWithInvalidValues();
final String customerId = "customerId";
LineItemModel lineItem = aLineItemModel().withCustomerId(customerId).withQuoteOptionItemDTOId("lineItemId").forProductCategory("Connect Acceleration").build();
updater.update(lineItem);
}
private void setUpWithInvalidValues() {
HSSFSheet sheet = new HSSFWorkbook().createSheet();
final HSSFRow row = sheet.createRow(1);
HSSFCell firstCell = row.createCell(0);
firstCell.setCellValue("Connect Acceleration");
HSSFCell secondCell = row.createCell(1);
secondCell.setCellValue("100A0");
ProductInfoSheet productInfoSheet = new ProductInfoSheet(sheet);
updater = new ProductInfoSheetUpdater(productInfoSheet, lineItemFacade);
}
}
| UTF-8 | Java | 3,626 | java | ProductInfoSheetUpdaterTest.java | Java | [] | null | [] | package com.bt.rsqe.projectengine.web.quoteoption.priceupdater;
import com.bt.rsqe.customerinventory.parameter.LineItemId;
import com.bt.rsqe.projectengine.web.facades.LineItemFacade;
import com.bt.rsqe.projectengine.web.model.LineItemModel;
import com.bt.rsqe.projectengine.web.model.bcmspreadsheet.InvalidExportDataException;
import com.bt.rsqe.projectengine.web.model.bcmspreadsheet.ProductInfoSheet;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.junit.Before;
import org.junit.Test;
import static com.bt.rsqe.projectengine.web.fixtures.LineItemModelFixture.*;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.*;
public class ProductInfoSheetUpdaterTest {
ProductInfoSheetUpdater updater;
@Mock
private LineItemFacade lineItemFacade;
@Before
public void setUp() throws Exception {
initMocks(this);
}
public void setUpWithValidValues() throws Exception {
ProductInfoSheet productInfoSheet = createProductInfoSheet();
updater = new ProductInfoSheetUpdater(productInfoSheet, lineItemFacade);
}
private ProductInfoSheet createProductInfoSheet() {
HSSFSheet sheet = new HSSFWorkbook().createSheet();
sheet.createRow(0);
final HSSFRow row = sheet.createRow(1);
HSSFCell firstCell = row.createCell(0);
firstCell.setCellValue("Connect Acceleration");
HSSFCell secondCell = row.createCell(1);
secondCell.setCellValue(10000);
return new ProductInfoSheet(sheet);
}
@Test
public void shouldUpdateNumericValue() throws Exception {
setUpWithValidValues();
final String customerId = "customerId";
LineItemModel lineItem = aLineItemModel().withCustomerId(customerId).withQuoteOptionItemDTOId("lineItemId").forProductCategory("Connect Acceleration").build();
updater.update(lineItem);
verify(lineItemFacade).persistMinimumRevenueCommitment("projectId", "quoteOptionId", new LineItemId("lineItemId"), "10000.0", null);
}
@Test
public void shouldNotUpdateValueForDifferentProductNames() throws Exception {
setUpWithValidValues();
final String customerId = "customerId";
LineItemModel lineItem = aLineItemModel().withCustomerId(customerId).withQuoteOptionItemDTOId("lineItemId").forProductCategory("Connect Optimisation").build();
updater.update(lineItem);
verify(lineItemFacade, never()).persistMinimumRevenueCommitment("projectId", "quoteOptionId", new LineItemId("lineItemId"), "10000.0", null);
}
@Test(expected = InvalidExportDataException.class)
public void shouldThrowExceptionForNonNumeric() {
setUpWithInvalidValues();
final String customerId = "customerId";
LineItemModel lineItem = aLineItemModel().withCustomerId(customerId).withQuoteOptionItemDTOId("lineItemId").forProductCategory("Connect Acceleration").build();
updater.update(lineItem);
}
private void setUpWithInvalidValues() {
HSSFSheet sheet = new HSSFWorkbook().createSheet();
final HSSFRow row = sheet.createRow(1);
HSSFCell firstCell = row.createCell(0);
firstCell.setCellValue("Connect Acceleration");
HSSFCell secondCell = row.createCell(1);
secondCell.setCellValue("100A0");
ProductInfoSheet productInfoSheet = new ProductInfoSheet(sheet);
updater = new ProductInfoSheetUpdater(productInfoSheet, lineItemFacade);
}
}
| 3,626 | 0.742692 | 0.73497 | 83 | 42.686749 | 38.050671 | 167 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.73494 | false | false | 4 |
bfc7588449ef789bab855e403716375479c62a45 | 7,327,214,229,012 | 5cb568e151410e77dbf9c4adfa0b3acc04ada3a4 | /sport-en/src/main/java/com/appscomm/sport/action/DeviceSetAction.java | 3e9b6bdff7771d2dc99acab3dabb1f88171fe716 | [] | no_license | gitfancc/mywebsite | https://github.com/gitfancc/mywebsite | 533592f6546edf5b0e6cde6933ccd02bd516f559 | 50979ea8fae3ab6232eb605d08c504150d2526f1 | refs/heads/master | "2021-01-17T20:07:54.072000" | "2016-10-24T07:02:44" | "2016-10-24T07:02:44" | 71,745,791 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.appscomm.sport.action;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.appscomm.sport.common.SportApiCode;
import com.appscomm.sport.model.PersonWatchVO;
import com.appscomm.sport.model.UserVO;
import com.appscomm.sport.model.WatchVO;
import com.appscomm.sport.service.DeviceSetService;
import com.appscomm.sport.service.UserService;
import com.opensymphony.xwork2.Action;
public class DeviceSetAction extends BaseAction {
private static final long serialVersionUID = -6748925554476869953L;
private static Log logger = LogFactory.getLog(DeviceSetAction.class);
@Autowired
private DeviceSetService deviceSetService;
@Autowired
private UserService userService;
private WatchVO watch;
private String result;
private UserVO user;
private Long personId;
private Integer defaultDevice;
private List<Integer> timeIntervalList = new ArrayList<Integer>();
private List<Integer> timeHourList = new ArrayList<Integer>();
private List<PersonWatchVO> personWatchList;
/**
* 初始化页面
*
* @return
* @throws Exception
*/
public String initDevice() throws Exception {
logger.debug("<<< device setting init >>>");
user = super.getUsers();
if (user == null){
return Action.LOGIN;
}
// 加载页面列表默认项
for (int i = 1; i <= 12; i++) {
timeIntervalList.add(i * 5);
}
for (int i = 0; i < 24; i++) {
timeHourList.add(i);
}
watch = deviceSetService.getDeviceInfo(watch, user.getUserId());
logger.debug(watch.toString());
return Action.INPUT;
}
public String listDevice() throws Exception {
logger.info("device list");
String logined = super.getLogin();
// String logined = (String) session.get("isLogined");
request.setAttribute("logined", logined);
// user = super.getUsers();
// if (user == null){
// return Action.LOGIN;
// }
// personId = user.getUserId();
// logger.debug("List Device >>> personId=" + personId);
// personWatchList = deviceSetService.getDeviceList(personId);
// if(personWatchList.size()==0){
// personWatchList = null;
// }
return Action.SUCCESS;
}
/**
* 保存设备设置信息
*
* @return
* @throws Exception
*/
public String saveDevice() throws Exception {
user = super.getUsers();
if (user == null){
return Action.LOGIN;
}
logger.debug("Device Info <<< " + watch.toString() + " >>>");
personId = user.getUserId();
if (null == personId) {
// 用户不存在
result = SportApiCode.ERROR_3001.getDesc();
return Action.SUCCESS;
}
Integer code = deviceSetService.saveDeviceInfo(watch, user.getUserId());
if (code < 0) {
result = SportApiCode.ERROR_7787.getDesc();
} else {
result = SportApiCode.SUCCESS.getDesc();
// 发送短信,告知设备同步配置参数
deviceSetService.sendSms(watch);
}
return Action.SUCCESS;
}
/**
* 保存新增的设备绑定信息
*
* @return
* @throws Exception
*/
public String saveBind() throws Exception {
user = super.getUsers();
if (user == null){
return Action.LOGIN;
}
personId = user.getUserId();
logger.debug("Device WatchId <<<" + watch.getWatchId() + ", PersonId:" + personId + ", WatchSim:" + watch.getWatchSim() + " >>>");
Integer code = deviceSetService.bindDevice(personId, watch, defaultDevice);
if (code == -1) {
result = SportApiCode.ERROR_7782.getDesc() ;
result = result + "<" + getBindPersonAccount(watch.getWatchId()) + ">";
} else if(code == -2) {
result = SportApiCode.ERROR_7795.getDesc();
} else {
result = SportApiCode.SUCCESS.getDesc();
}
return Action.SUCCESS;
}
/**
* 绑定腕表
*
* @return
* @throws Exception
*/
public String bindWatchId() throws Exception {
user = super.getUsers();
if (user == null){
return Action.LOGIN;
}
personId = user.getUserId();
logger.debug("Device WatchId <<<" + watch.getWatchId() + ", PersonId:" + personId + " >>>");
if (null == personId) {
// 用户不存在
result = SportApiCode.ERROR_3001.getDesc();
return Action.SUCCESS;
}
Integer code = deviceSetService.bindDeviceId(personId, watch.getWatchId(), defaultDevice, watch.getType());
if (code == -1) {
result = SportApiCode.ERROR_7782.getDesc();
result = result + "<" + getBindPersonAccount(watch.getWatchId()) + ">";
} else if(code == -2) {
result = SportApiCode.ERROR_7795.getDesc();
}else {
result = SportApiCode.SUCCESS.getDesc();
}
//保存watchId到session中
user.setWatchId(watch.getWatchId());
super.session.remove(IndexAction.LOGIN_SESSION_USER);
super.session.put(IndexAction.LOGIN_SESSION_USER, user);
return Action.SUCCESS;
}
/**
* 解绑腕表
*
* @return
* @throws Exception
*/
public String unBindWatchId() throws Exception {
user = super.getUsers();
if (user == null){
return Action.LOGIN;
}
personId = user.getUserId();
logger.debug("Device WatchId <<<" + watch.getWatchId() + " >>>");
if (null == personId) {
// 用户不存在
result = SportApiCode.ERROR_3001.getDesc();
return Action.SUCCESS;
}
Integer code = deviceSetService.unBindDeviceId(personId, watch.getWatchId());
if (code == -1) {
result = SportApiCode.ERROR_7789.getDesc();
} else {
result = SportApiCode.SUCCESS.getDesc();
}
// 从session中清除watchId
user.setWatchId("");
super.session.remove(IndexAction.LOGIN_SESSION_USER);
super.session.put(IndexAction.LOGIN_SESSION_USER, user);
return Action.SUCCESS;
}
/**
* 绑定电话号码
*
* @return
* @throws Exception
*/
public String bindWatchSim() throws Exception {
user = super.getUsers();
if (user == null){
return Action.LOGIN;
}
personId = user.getUserId();
logger.debug("Device WatchSim <<< " + watch.getWatchSim() + ",watchId " + watch.getWatchId() + " >>>");
if (null == personId) {
// 用户不存在
result = SportApiCode.ERROR_3001.getDesc();
return Action.SUCCESS;
}
Integer code = deviceSetService.bindDeviceSim(watch.getWatchId(),watch.getWatchSim());
if (code < 0) {
result = SportApiCode.ERROR_7785.getDesc();
} else {
result = SportApiCode.SUCCESS.getDesc();
}
return Action.SUCCESS;
}
/**
* 解绑电话号码
*
* @return
* @throws Exception
*/
public String unBindWatchSim() throws Exception {
user = super.getUsers();
if (user == null){
return Action.LOGIN;
}
personId = user.getUserId();
logger.debug("Device WatchSim <<< " + watch.getWatchSim() + " >>>");
if (null == personId) {
// 用户不存在
result = SportApiCode.ERROR_3001.getDesc();
return Action.SUCCESS;
}
Integer code = deviceSetService.unBindDeviceSim(personId, watch.getWatchId());
if (code < 0) {
result = SportApiCode.ERROR_7786.getDesc();
} else {
result = SportApiCode.SUCCESS.getDesc();
}
return Action.SUCCESS;
}
/**
* 根据绑定的设备号获取其绑定的人的信息
*
* @param watchId
* @return
*/
private String getBindPersonAccount(String watchId){
String account = "";
if (StringUtils.isEmpty(watchId)) return account;
List<UserVO> list = userService.getBindUserInfo(watchId);
if(list != null && list.size() > 0){
UserVO u = list.get(0);
String mail = u.getMail();
String tel = u.getTelphone();
if (StringUtils.isNotEmpty(mail)){
account = mail;
} else {
account = tel;
}
}
return account;
}
/**
* 设置系统默认设备(腕表)
*
* @return
*/
public void setDefaultWatch(){
UserVO user = super.getUsers();
if (user == null) {
super.writeJson("ERROR");
}
//if (StringUtils.isNotEmpty(super.getDefaultWatchType())){
// 更新数据库中缺省的设备
//deviceSetService.setDefaultWatch(personId, defaultType);
// }
super.writeJson("OK");
}
public WatchVO getWatch() {
return watch;
}
public void setWatch(WatchVO watch) {
this.watch = watch;
}
public DeviceSetService getDeviceSetService() {
return deviceSetService;
}
public void setDeviceSetService(DeviceSetService deviceSetService) {
this.deviceSetService = deviceSetService;
}
public List<Integer> getTimeIntervalList() {
return timeIntervalList;
}
public void setTimeIntervalList(List<Integer> timeIntervalList) {
this.timeIntervalList = timeIntervalList;
}
public List<Integer> getTimeHourList() {
return timeHourList;
}
public void setTimeHourList(List<Integer> timeHourList) {
this.timeHourList = timeHourList;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public UserVO getUser() {
return user;
}
public void setUser(UserVO user) {
this.user = user;
}
public Long getPersonId() {
return personId;
}
public void setPersonId(Long personId) {
this.personId = personId;
}
public List<PersonWatchVO> getPersonWatchList() {
return personWatchList;
}
public void setPersonWatchList(List<PersonWatchVO> personWatchList) {
this.personWatchList = personWatchList;
}
public Integer getDefaultDevice() {
return defaultDevice;
}
public void setDefaultDevice(Integer defaultDevice) {
this.defaultDevice = defaultDevice;
}
}
| UTF-8 | Java | 9,339 | java | DeviceSetAction.java | Java | [] | null | [] | package com.appscomm.sport.action;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.appscomm.sport.common.SportApiCode;
import com.appscomm.sport.model.PersonWatchVO;
import com.appscomm.sport.model.UserVO;
import com.appscomm.sport.model.WatchVO;
import com.appscomm.sport.service.DeviceSetService;
import com.appscomm.sport.service.UserService;
import com.opensymphony.xwork2.Action;
public class DeviceSetAction extends BaseAction {
private static final long serialVersionUID = -6748925554476869953L;
private static Log logger = LogFactory.getLog(DeviceSetAction.class);
@Autowired
private DeviceSetService deviceSetService;
@Autowired
private UserService userService;
private WatchVO watch;
private String result;
private UserVO user;
private Long personId;
private Integer defaultDevice;
private List<Integer> timeIntervalList = new ArrayList<Integer>();
private List<Integer> timeHourList = new ArrayList<Integer>();
private List<PersonWatchVO> personWatchList;
/**
* 初始化页面
*
* @return
* @throws Exception
*/
public String initDevice() throws Exception {
logger.debug("<<< device setting init >>>");
user = super.getUsers();
if (user == null){
return Action.LOGIN;
}
// 加载页面列表默认项
for (int i = 1; i <= 12; i++) {
timeIntervalList.add(i * 5);
}
for (int i = 0; i < 24; i++) {
timeHourList.add(i);
}
watch = deviceSetService.getDeviceInfo(watch, user.getUserId());
logger.debug(watch.toString());
return Action.INPUT;
}
public String listDevice() throws Exception {
logger.info("device list");
String logined = super.getLogin();
// String logined = (String) session.get("isLogined");
request.setAttribute("logined", logined);
// user = super.getUsers();
// if (user == null){
// return Action.LOGIN;
// }
// personId = user.getUserId();
// logger.debug("List Device >>> personId=" + personId);
// personWatchList = deviceSetService.getDeviceList(personId);
// if(personWatchList.size()==0){
// personWatchList = null;
// }
return Action.SUCCESS;
}
/**
* 保存设备设置信息
*
* @return
* @throws Exception
*/
public String saveDevice() throws Exception {
user = super.getUsers();
if (user == null){
return Action.LOGIN;
}
logger.debug("Device Info <<< " + watch.toString() + " >>>");
personId = user.getUserId();
if (null == personId) {
// 用户不存在
result = SportApiCode.ERROR_3001.getDesc();
return Action.SUCCESS;
}
Integer code = deviceSetService.saveDeviceInfo(watch, user.getUserId());
if (code < 0) {
result = SportApiCode.ERROR_7787.getDesc();
} else {
result = SportApiCode.SUCCESS.getDesc();
// 发送短信,告知设备同步配置参数
deviceSetService.sendSms(watch);
}
return Action.SUCCESS;
}
/**
* 保存新增的设备绑定信息
*
* @return
* @throws Exception
*/
public String saveBind() throws Exception {
user = super.getUsers();
if (user == null){
return Action.LOGIN;
}
personId = user.getUserId();
logger.debug("Device WatchId <<<" + watch.getWatchId() + ", PersonId:" + personId + ", WatchSim:" + watch.getWatchSim() + " >>>");
Integer code = deviceSetService.bindDevice(personId, watch, defaultDevice);
if (code == -1) {
result = SportApiCode.ERROR_7782.getDesc() ;
result = result + "<" + getBindPersonAccount(watch.getWatchId()) + ">";
} else if(code == -2) {
result = SportApiCode.ERROR_7795.getDesc();
} else {
result = SportApiCode.SUCCESS.getDesc();
}
return Action.SUCCESS;
}
/**
* 绑定腕表
*
* @return
* @throws Exception
*/
public String bindWatchId() throws Exception {
user = super.getUsers();
if (user == null){
return Action.LOGIN;
}
personId = user.getUserId();
logger.debug("Device WatchId <<<" + watch.getWatchId() + ", PersonId:" + personId + " >>>");
if (null == personId) {
// 用户不存在
result = SportApiCode.ERROR_3001.getDesc();
return Action.SUCCESS;
}
Integer code = deviceSetService.bindDeviceId(personId, watch.getWatchId(), defaultDevice, watch.getType());
if (code == -1) {
result = SportApiCode.ERROR_7782.getDesc();
result = result + "<" + getBindPersonAccount(watch.getWatchId()) + ">";
} else if(code == -2) {
result = SportApiCode.ERROR_7795.getDesc();
}else {
result = SportApiCode.SUCCESS.getDesc();
}
//保存watchId到session中
user.setWatchId(watch.getWatchId());
super.session.remove(IndexAction.LOGIN_SESSION_USER);
super.session.put(IndexAction.LOGIN_SESSION_USER, user);
return Action.SUCCESS;
}
/**
* 解绑腕表
*
* @return
* @throws Exception
*/
public String unBindWatchId() throws Exception {
user = super.getUsers();
if (user == null){
return Action.LOGIN;
}
personId = user.getUserId();
logger.debug("Device WatchId <<<" + watch.getWatchId() + " >>>");
if (null == personId) {
// 用户不存在
result = SportApiCode.ERROR_3001.getDesc();
return Action.SUCCESS;
}
Integer code = deviceSetService.unBindDeviceId(personId, watch.getWatchId());
if (code == -1) {
result = SportApiCode.ERROR_7789.getDesc();
} else {
result = SportApiCode.SUCCESS.getDesc();
}
// 从session中清除watchId
user.setWatchId("");
super.session.remove(IndexAction.LOGIN_SESSION_USER);
super.session.put(IndexAction.LOGIN_SESSION_USER, user);
return Action.SUCCESS;
}
/**
* 绑定电话号码
*
* @return
* @throws Exception
*/
public String bindWatchSim() throws Exception {
user = super.getUsers();
if (user == null){
return Action.LOGIN;
}
personId = user.getUserId();
logger.debug("Device WatchSim <<< " + watch.getWatchSim() + ",watchId " + watch.getWatchId() + " >>>");
if (null == personId) {
// 用户不存在
result = SportApiCode.ERROR_3001.getDesc();
return Action.SUCCESS;
}
Integer code = deviceSetService.bindDeviceSim(watch.getWatchId(),watch.getWatchSim());
if (code < 0) {
result = SportApiCode.ERROR_7785.getDesc();
} else {
result = SportApiCode.SUCCESS.getDesc();
}
return Action.SUCCESS;
}
/**
* 解绑电话号码
*
* @return
* @throws Exception
*/
public String unBindWatchSim() throws Exception {
user = super.getUsers();
if (user == null){
return Action.LOGIN;
}
personId = user.getUserId();
logger.debug("Device WatchSim <<< " + watch.getWatchSim() + " >>>");
if (null == personId) {
// 用户不存在
result = SportApiCode.ERROR_3001.getDesc();
return Action.SUCCESS;
}
Integer code = deviceSetService.unBindDeviceSim(personId, watch.getWatchId());
if (code < 0) {
result = SportApiCode.ERROR_7786.getDesc();
} else {
result = SportApiCode.SUCCESS.getDesc();
}
return Action.SUCCESS;
}
/**
* 根据绑定的设备号获取其绑定的人的信息
*
* @param watchId
* @return
*/
private String getBindPersonAccount(String watchId){
String account = "";
if (StringUtils.isEmpty(watchId)) return account;
List<UserVO> list = userService.getBindUserInfo(watchId);
if(list != null && list.size() > 0){
UserVO u = list.get(0);
String mail = u.getMail();
String tel = u.getTelphone();
if (StringUtils.isNotEmpty(mail)){
account = mail;
} else {
account = tel;
}
}
return account;
}
/**
* 设置系统默认设备(腕表)
*
* @return
*/
public void setDefaultWatch(){
UserVO user = super.getUsers();
if (user == null) {
super.writeJson("ERROR");
}
//if (StringUtils.isNotEmpty(super.getDefaultWatchType())){
// 更新数据库中缺省的设备
//deviceSetService.setDefaultWatch(personId, defaultType);
// }
super.writeJson("OK");
}
public WatchVO getWatch() {
return watch;
}
public void setWatch(WatchVO watch) {
this.watch = watch;
}
public DeviceSetService getDeviceSetService() {
return deviceSetService;
}
public void setDeviceSetService(DeviceSetService deviceSetService) {
this.deviceSetService = deviceSetService;
}
public List<Integer> getTimeIntervalList() {
return timeIntervalList;
}
public void setTimeIntervalList(List<Integer> timeIntervalList) {
this.timeIntervalList = timeIntervalList;
}
public List<Integer> getTimeHourList() {
return timeHourList;
}
public void setTimeHourList(List<Integer> timeHourList) {
this.timeHourList = timeHourList;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public UserVO getUser() {
return user;
}
public void setUser(UserVO user) {
this.user = user;
}
public Long getPersonId() {
return personId;
}
public void setPersonId(Long personId) {
this.personId = personId;
}
public List<PersonWatchVO> getPersonWatchList() {
return personWatchList;
}
public void setPersonWatchList(List<PersonWatchVO> personWatchList) {
this.personWatchList = personWatchList;
}
public Integer getDefaultDevice() {
return defaultDevice;
}
public void setDefaultDevice(Integer defaultDevice) {
this.defaultDevice = defaultDevice;
}
}
| 9,339 | 0.678181 | 0.668138 | 380 | 22.844736 | 22.021391 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.994737 | false | false | 4 |
cbb44aed5fd1894d3ecff6187db375b4832ad557 | 14,439,680,057,941 | e6846f21025a4f802ae30aabe40d5e9f6626575e | /src/main/java/com/pgis/bus/net/request/FindPathsRequest.java | df0f7fdd87b14b7a5c4df4b891fbb05f461c01ca | [] | no_license | rshafeev/busweb-net | https://github.com/rshafeev/busweb-net | 90b4d08a3449d94289ae8c153e4520806d41a5bf | 874fd829cdf56a18f49f86acac9ecdc788b80222 | refs/heads/master | "2022-11-21T04:02:48.841000" | "2015-01-16T09:39:56" | "2015-01-16T09:39:56" | 194,873,000 | 0 | 0 | null | false | "2022-11-16T03:18:30" | "2019-07-02T13:53:22" | "2019-07-02T14:05:55" | "2022-11-16T03:18:29" | 65 | 0 | 0 | 4 | Java | false | false | package com.pgis.bus.net.request;
import java.io.Serializable;
import java.util.Collection;
import com.pgis.bus.net.models.AlgStrategyEnumModel;
import com.pgis.bus.net.models.LangEnumModel;
import com.pgis.bus.net.models.geom.PointModel;
import com.pgis.bus.net.request.data.OutTimeModel;
import com.pgis.bus.net.request.data.RouteTypeDiscount;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Класс хранит параметры поиска мршрутов м/у точками назначения
*
* @author romario
*/
@XmlRootElement
public class FindPathsRequest implements Serializable{
private int cityID;
private PointModel p1;
private PointModel p2;
private Collection<RouteTypeDiscount> routeTypes;
private boolean transitions;
private AlgStrategyEnumModel algStrategy;
private LangEnumModel langID;
private double maxDistance;
private OutTimeModel outTime;
public FindPathsRequest() {
}
public int getCityID() {
return cityID;
}
public void setCityID(int cityID) {
this.cityID = cityID;
}
public PointModel getP1() {
return p1;
}
public void setP1(PointModel p1) {
this.p1 = p1;
}
public PointModel getP2() {
return p2;
}
public void setP2(PointModel p2) {
this.p2 = p2;
}
public Collection<RouteTypeDiscount> getRouteTypes() {
return routeTypes;
}
public void setRouteTypes(Collection<RouteTypeDiscount> routeTypes) {
this.routeTypes = routeTypes;
}
public AlgStrategyEnumModel getAlgStrategy() {
return algStrategy;
}
public void setAlgStrategy(AlgStrategyEnumModel algStrategy) {
this.algStrategy = algStrategy;
}
/**
* Возвращает язык
*
* @return идентификатор языка. Возможные значения: ru, en, uk
*/
public LangEnumModel getLangID() {
return langID;
}
public void setLangID(LangEnumModel langID) {
this.langID = langID;
}
public double getMaxDistance() {
return maxDistance;
}
public void setMaxDistance(double maxDistance) {
this.maxDistance = maxDistance;
}
public OutTimeModel getOutTime() {
return outTime;
}
public void setOutTime(OutTimeModel outTime) {
this.outTime = outTime;
}
public boolean isTransitions() {
return transitions;
}
public void setTransitions(boolean isTransitions) {
this.transitions = isTransitions;
}
@Override
public String toString() {
return "FindPathsOptions [cityID=" + cityID + ", p1=" + p1 + ", p2=" + p2 + ", routeTypes=" + routeTypes
+ ", transitions=" + transitions + ", algStrategy=" + algStrategy + ", langID=" + langID
+ ", maxDistance=" + maxDistance + ", outTime=" + outTime + "]";
}
}
| UTF-8 | Java | 2,650 | java | FindPathsRequest.java | Java | [
{
"context": "ска мршрутов м/у точками назначения\n * \n * @author romario\n */\n@XmlRootElement\npublic class FindPathsRequest",
"end": 490,
"score": 0.9954023957252502,
"start": 483,
"tag": "USERNAME",
"value": "romario"
}
] | null | [] | package com.pgis.bus.net.request;
import java.io.Serializable;
import java.util.Collection;
import com.pgis.bus.net.models.AlgStrategyEnumModel;
import com.pgis.bus.net.models.LangEnumModel;
import com.pgis.bus.net.models.geom.PointModel;
import com.pgis.bus.net.request.data.OutTimeModel;
import com.pgis.bus.net.request.data.RouteTypeDiscount;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Класс хранит параметры поиска мршрутов м/у точками назначения
*
* @author romario
*/
@XmlRootElement
public class FindPathsRequest implements Serializable{
private int cityID;
private PointModel p1;
private PointModel p2;
private Collection<RouteTypeDiscount> routeTypes;
private boolean transitions;
private AlgStrategyEnumModel algStrategy;
private LangEnumModel langID;
private double maxDistance;
private OutTimeModel outTime;
public FindPathsRequest() {
}
public int getCityID() {
return cityID;
}
public void setCityID(int cityID) {
this.cityID = cityID;
}
public PointModel getP1() {
return p1;
}
public void setP1(PointModel p1) {
this.p1 = p1;
}
public PointModel getP2() {
return p2;
}
public void setP2(PointModel p2) {
this.p2 = p2;
}
public Collection<RouteTypeDiscount> getRouteTypes() {
return routeTypes;
}
public void setRouteTypes(Collection<RouteTypeDiscount> routeTypes) {
this.routeTypes = routeTypes;
}
public AlgStrategyEnumModel getAlgStrategy() {
return algStrategy;
}
public void setAlgStrategy(AlgStrategyEnumModel algStrategy) {
this.algStrategy = algStrategy;
}
/**
* Возвращает язык
*
* @return идентификатор языка. Возможные значения: ru, en, uk
*/
public LangEnumModel getLangID() {
return langID;
}
public void setLangID(LangEnumModel langID) {
this.langID = langID;
}
public double getMaxDistance() {
return maxDistance;
}
public void setMaxDistance(double maxDistance) {
this.maxDistance = maxDistance;
}
public OutTimeModel getOutTime() {
return outTime;
}
public void setOutTime(OutTimeModel outTime) {
this.outTime = outTime;
}
public boolean isTransitions() {
return transitions;
}
public void setTransitions(boolean isTransitions) {
this.transitions = isTransitions;
}
@Override
public String toString() {
return "FindPathsOptions [cityID=" + cityID + ", p1=" + p1 + ", p2=" + p2 + ", routeTypes=" + routeTypes
+ ", transitions=" + transitions + ", algStrategy=" + algStrategy + ", langID=" + langID
+ ", maxDistance=" + maxDistance + ", outTime=" + outTime + "]";
}
}
| 2,650 | 0.730769 | 0.723705 | 120 | 20.233334 | 22.142994 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.233333 | false | false | 4 |
b3094976452e0a27e879e64031ead9862ed9eb2c | 17,652,315,598,848 | a4f30efa871cf1bb4f254c3901db728548102184 | /src/test/java/UAT/Clinicians_Filter.java | 191c701a68e3488c834f154614776d574aeaaeee | [] | no_license | DocmanQA/Hub | https://github.com/DocmanQA/Hub | 71cbd69adc05aa511fb5fc273edfa61e3c8155de | 251429a47678fef22d6d2bf390fe5ede7b4e9ce9 | refs/heads/master | "2021-01-10T18:05:53.269000" | "2016-03-24T10:08:47" | "2016-03-24T10:08:47" | 49,638,770 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package UAT;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
public class Clinicians_Filter {
private WebDriver driver;
private boolean NextBtn_isEnable = true;
private WebElement table;
private List<WebElement> table_row;
private List<WebElement> table_data;
private int Clinician_count = 0;
private WebElement NextBtn;
private boolean Is_Hide_Inactive;
private List<String> EndPoint = new ArrayList<String>();
@Test
public void main() {
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
//Click End Points under Configuration
driver.findElement(By.xpath("//*[contains(text(), 'Clinician')]")).click();
//Verify the Title
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
String Clinician_List_title = driver.getTitle();
Assert.assertTrue(Clinician_List_title.contains("Clinician List"));
System.out.println(Clinician_List_title);
//Filter type Practice
Select select_type = new Select(driver.findElement(By.id("ctl00_cp1_cboFPrac")));
select_type.selectByVisibleText("Pioneers Way 2");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
if (driver.findElement(By.id("ctl00_cp1_tbl")).findElements(By.tagName("tr")).size() > 1){
NextBtn_isEnable = true;
} else {
NextBtn_isEnable = false;
System.out.println("No clinician on the list after filter");
}
do{
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
table = driver.findElement(By.id("ctl00_cp1_tbl"));
table_row = table.findElements(By.tagName("tr"));
for (int x = 1; x < table_row.size(); x++){
table_data = table_row.get(x).findElements(By.tagName("td"));
Assert.assertTrue(table_data.get(2).getText().equals("Pioneers Way 2"));
Clinician_count ++;
}
//driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
NextBtn = driver.findElement(By.id("ctl00_cp1_cmdNext"));
if (NextBtn.isEnabled()){
NextBtn_isEnable = true;
//Click the next button to next page.
NextBtn.click();
} else {
NextBtn_isEnable = false;
}
} while (NextBtn_isEnable == true);
System.out.println("There are " + Clinician_count + " clinicians. After filter out.");
Assert.assertTrue(driver.findElement(By.id("ctl00_cp1_lblItemCount")).getText().contains(Integer.toString(Clinician_count)));
System.out.println("Correct Clinician Count Title.");
//System.out.println(Name);
//System.out.println(NACS);
}
@BeforeTest
public void beforeTest() {
driver = Set_Web_Browser.Set_Web_Browser();
}
@AfterTest
public void afterTest() {
driver.quit();
}
}
| UTF-8 | Java | 3,144 | java | Clinicians_Filter.java | Java | [] | null | [] | package UAT;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
public class Clinicians_Filter {
private WebDriver driver;
private boolean NextBtn_isEnable = true;
private WebElement table;
private List<WebElement> table_row;
private List<WebElement> table_data;
private int Clinician_count = 0;
private WebElement NextBtn;
private boolean Is_Hide_Inactive;
private List<String> EndPoint = new ArrayList<String>();
@Test
public void main() {
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
//Click End Points under Configuration
driver.findElement(By.xpath("//*[contains(text(), 'Clinician')]")).click();
//Verify the Title
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
String Clinician_List_title = driver.getTitle();
Assert.assertTrue(Clinician_List_title.contains("Clinician List"));
System.out.println(Clinician_List_title);
//Filter type Practice
Select select_type = new Select(driver.findElement(By.id("ctl00_cp1_cboFPrac")));
select_type.selectByVisibleText("Pioneers Way 2");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
if (driver.findElement(By.id("ctl00_cp1_tbl")).findElements(By.tagName("tr")).size() > 1){
NextBtn_isEnable = true;
} else {
NextBtn_isEnable = false;
System.out.println("No clinician on the list after filter");
}
do{
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
table = driver.findElement(By.id("ctl00_cp1_tbl"));
table_row = table.findElements(By.tagName("tr"));
for (int x = 1; x < table_row.size(); x++){
table_data = table_row.get(x).findElements(By.tagName("td"));
Assert.assertTrue(table_data.get(2).getText().equals("Pioneers Way 2"));
Clinician_count ++;
}
//driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
NextBtn = driver.findElement(By.id("ctl00_cp1_cmdNext"));
if (NextBtn.isEnabled()){
NextBtn_isEnable = true;
//Click the next button to next page.
NextBtn.click();
} else {
NextBtn_isEnable = false;
}
} while (NextBtn_isEnable == true);
System.out.println("There are " + Clinician_count + " clinicians. After filter out.");
Assert.assertTrue(driver.findElement(By.id("ctl00_cp1_lblItemCount")).getText().contains(Integer.toString(Clinician_count)));
System.out.println("Correct Clinician Count Title.");
//System.out.println(Name);
//System.out.println(NACS);
}
@BeforeTest
public void beforeTest() {
driver = Set_Web_Browser.Set_Web_Browser();
}
@AfterTest
public void afterTest() {
driver.quit();
}
}
| 3,144 | 0.711832 | 0.701972 | 97 | 31.412371 | 26.005056 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.835052 | false | false | 4 |
29fe673a30ef09049e741d21d7d051a27b1cdcd9 | 16,913,581,214,282 | 59b0000b26739775d838b20af73daa10905f2cd9 | /src/com/ogc/action/Change.java | f02a86776ff5078682be5ae138ef4f90bed64b8b | [] | no_license | lorenzoviva/QRWebServer | https://github.com/lorenzoviva/QRWebServer | 35e88ba1fe01d805367c474cffbaabcd948ef3f5 | 80be6e669f3c212982cbbcefce818f6b419bfcc1 | refs/heads/master | "2021-01-21T11:44:56.773000" | "2015-12-09T23:28:15" | "2015-12-09T23:28:15" | 42,775,256 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ogc.action;
import org.codehaus.jettison.json.JSONObject;
import com.google.gson.JsonObject;
public class Change extends Action{
public Change() {
super(null);
}
@Override
public boolean canPerform(JsonObject parameters) {
// TODO Auto-generated method stub
return true;
}
@Override
public JsonObject perform(JSONObject parameters) {
// TODO Auto-generated method stub
return null;
}
}
| UTF-8 | Java | 423 | java | Change.java | Java | [] | null | [] | package com.ogc.action;
import org.codehaus.jettison.json.JSONObject;
import com.google.gson.JsonObject;
public class Change extends Action{
public Change() {
super(null);
}
@Override
public boolean canPerform(JsonObject parameters) {
// TODO Auto-generated method stub
return true;
}
@Override
public JsonObject perform(JSONObject parameters) {
// TODO Auto-generated method stub
return null;
}
}
| 423 | 0.742317 | 0.742317 | 25 | 15.92 | 17.341095 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.96 | false | false | 4 |
8a10c8f0baa4962683690ad3df03d8f27b49b2d5 | 2,070,174,254,690 | c427dff9a47dbea0e9f64a14c7d611d97dc00e15 | /javaStmt/src/ifelse/TimeCalc.java | daf769ee5e4efb43815e368f951f674f01326b0b | [] | no_license | pakjkwan/jse_160310 | https://github.com/pakjkwan/jse_160310 | 8fb800250c0045dfb842d23f20d3d51b4d77d4b8 | ed586119879ed795c55554480c3d41ddab1c5e78 | refs/heads/master | "2020-03-05T01:53:10.391000" | "2016-05-09T05:18:53" | "2016-05-09T05:18:53" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ifelse;
public class TimeCalc {
private int inputSec, hour, min, sec, remain;
public void getTimeCalc(int inputSec) {
this.inputSec = inputSec;
this.hour = inputSec / 3600;
this.remain = inputSec % 3600;
this.min = remain / 60;
this.sec = remain % 60;
}
@Override
public String toString() {
return inputSec + "초는 " + hour + "시간 " + min + "분 " + sec + "초 입니다.";
}
}
| UTF-8 | Java | 412 | java | TimeCalc.java | Java | [] | null | [] | package ifelse;
public class TimeCalc {
private int inputSec, hour, min, sec, remain;
public void getTimeCalc(int inputSec) {
this.inputSec = inputSec;
this.hour = inputSec / 3600;
this.remain = inputSec % 3600;
this.min = remain / 60;
this.sec = remain % 60;
}
@Override
public String toString() {
return inputSec + "초는 " + hour + "시간 " + min + "분 " + sec + "초 입니다.";
}
}
| 412 | 0.637056 | 0.606599 | 18 | 20.888889 | 18.852907 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.666667 | false | false | 4 |
9f8f2a2ee3483de71c96e4935a838226c860d377 | 1,013,612,350,895 | ca8752deea6520e64fa5b52aff13267c329b8811 | /src/Details/DetailsMethods.java | 55ecc19f7df0b01495c623902c013c1a09d556f0 | [] | no_license | YoussefKafa/Project | https://github.com/YoussefKafa/Project | 816e3fd9e3ae982fc63a3148cde862e133daf0b6 | eeaf681cbf8ce91e8ac9fa5f50ea529896c2ed1b | refs/heads/master | "2023-02-19T01:39:16.032000" | "2022-01-31T21:33:47" | "2022-01-31T21:33:47" | 185,861,620 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Details;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class DetailsMethods {
public static String stringToBinary(String s) {
byte[] bytes = s.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
return "'" + s + "' to binary: " + binary;
}
public static String stringToASCII(String t) throws UnsupportedEncodingException {
String text = t;
// translating text String to 7 bit ASCII encoding
byte[] bytes = text.getBytes("US-ASCII");
return "ASCII value of " +"\""+text +"\""+ " is following:\n "+Arrays.toString(bytes);
}
public static String calculateBits (String text) {
return "bits in "+ "\""+ text + "\""+": "+ text.length()*8+" bits";
}
public static String calculateBytes (String text) {
return "bytes in "+ "\""+ text + "\""+": "+ text.length()+" bytes";
}
public static String calculateWords (String text) {
return "words in "+ "\""+ text + "\""+": "+ text.length()*2+" words";
}
public static void main (String args[]) throws UnsupportedEncodingException {
System.out.println( stringToASCII("hello world"));
System.out.println(calculateBits("he"));
System.out.println(calculateBytes("he"));
System.out.println(calculateWords("he"));
}
}
| UTF-8 | Java | 1,463 | java | DetailsMethods.java | Java | [] | null | [] | package Details;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class DetailsMethods {
public static String stringToBinary(String s) {
byte[] bytes = s.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
return "'" + s + "' to binary: " + binary;
}
public static String stringToASCII(String t) throws UnsupportedEncodingException {
String text = t;
// translating text String to 7 bit ASCII encoding
byte[] bytes = text.getBytes("US-ASCII");
return "ASCII value of " +"\""+text +"\""+ " is following:\n "+Arrays.toString(bytes);
}
public static String calculateBits (String text) {
return "bits in "+ "\""+ text + "\""+": "+ text.length()*8+" bits";
}
public static String calculateBytes (String text) {
return "bytes in "+ "\""+ text + "\""+": "+ text.length()+" bytes";
}
public static String calculateWords (String text) {
return "words in "+ "\""+ text + "\""+": "+ text.length()*2+" words";
}
public static void main (String args[]) throws UnsupportedEncodingException {
System.out.println( stringToASCII("hello world"));
System.out.println(calculateBits("he"));
System.out.println(calculateBytes("he"));
System.out.println(calculateWords("he"));
}
}
| 1,463 | 0.617225 | 0.609023 | 42 | 33.833332 | 25.724657 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.357143 | false | false | 4 |
bb46fb4bc6d6bdbadd7c9de50ffdc722179d5620 | 2,250,562,904,275 | ee22101d8af54d66b7e845fd6b42eb872c8acdca | /src/main/java/com/modelagem/software/jogo/mario/world/jogo/retorno/DtoRetornoConsultarPalavraAleatoria.java | 25ed9d69282c09929ac26b505b871830f7b0a65a | [] | no_license | Ale-Rabbit/jogo-forca | https://github.com/Ale-Rabbit/jogo-forca | fbc6a333581f3f8ac31688396b4e291de8fd2d5a | 98170ab3fd63c27a6a3586a9a6427fb7f7ea0f84 | refs/heads/master | "2023-04-25T08:34:09.853000" | "2021-05-10T00:56:43" | "2021-05-10T00:56:43" | 356,956,775 | 0 | 1 | null | false | "2021-04-29T23:12:20" | "2021-04-11T19:10:45" | "2021-04-25T20:15:00" | "2021-04-29T23:12:19" | 89 | 0 | 1 | 0 | Java | false | false | package com.modelagem.software.jogo.mario.world.jogo.retorno;
import lombok.*;
@Data
@EqualsAndHashCode(callSuper = false)
public class DtoRetornoConsultarPalavraAleatoria extends DtoRetorno {
private String palavra;
public DtoRetornoConsultarPalavraAleatoria(boolean sucesso, String mensagem) {
super(sucesso, mensagem);
}
@Builder(builderMethodName = "builderDefault")
public DtoRetornoConsultarPalavraAleatoria(String palavra) {
this.palavra = palavra;
this.setSucesso(true);
}
}
| UTF-8 | Java | 538 | java | DtoRetornoConsultarPalavraAleatoria.java | Java | [] | null | [] | package com.modelagem.software.jogo.mario.world.jogo.retorno;
import lombok.*;
@Data
@EqualsAndHashCode(callSuper = false)
public class DtoRetornoConsultarPalavraAleatoria extends DtoRetorno {
private String palavra;
public DtoRetornoConsultarPalavraAleatoria(boolean sucesso, String mensagem) {
super(sucesso, mensagem);
}
@Builder(builderMethodName = "builderDefault")
public DtoRetornoConsultarPalavraAleatoria(String palavra) {
this.palavra = palavra;
this.setSucesso(true);
}
}
| 538 | 0.741636 | 0.741636 | 22 | 23.454546 | 26.180714 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 4 |
0a3a8bbf2823dc88210521b4264e35e1f160df2e | 1,915,555,434,388 | b6ddc1cc72511786aa6990aa9fc428cc7877cc4b | /src/Solution.java | 19cf35b2213a23f0c7b78657fbd70b19bf2884ed | [] | no_license | Dawid24/Codility5.2_CountDiv | https://github.com/Dawid24/Codility5.2_CountDiv | 5d46b33f738ffa9546878bfc39e43cbd5eeac5b9 | 1dcfc6195533310e00083b480a86e66452688a3c | refs/heads/master | "2020-03-28T04:03:46.157000" | "2018-09-06T15:10:07" | "2018-09-06T15:10:07" | 147,692,198 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Solution {
public static int divK(int A, int B, int K) {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
scheduledExecutorService.schedule(new CountDivThread(A, (B - A) / 2 + A, K), 0, TimeUnit.SECONDS);
scheduledExecutorService.schedule(new CountDivThread((B - A) / 2 + A, B + 1, K), 0, TimeUnit.SECONDS);
scheduledExecutorService.shutdown();
if (scheduledExecutorService.isShutdown()) {
return CountDivUtils.CountDiv;
} else return - 1;
}
}
| UTF-8 | Java | 699 | java | Solution.java | Java | [] | null | [] | import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Solution {
public static int divK(int A, int B, int K) {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
scheduledExecutorService.schedule(new CountDivThread(A, (B - A) / 2 + A, K), 0, TimeUnit.SECONDS);
scheduledExecutorService.schedule(new CountDivThread((B - A) / 2 + A, B + 1, K), 0, TimeUnit.SECONDS);
scheduledExecutorService.shutdown();
if (scheduledExecutorService.isShutdown()) {
return CountDivUtils.CountDiv;
} else return - 1;
}
}
| 699 | 0.703863 | 0.693848 | 17 | 40.117645 | 35.020805 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.117647 | false | false | 4 |
94f2d86c79c7efdf718d6b16a6e4b794dd3c83f5 | 4,320,737,166,003 | d37cc474f1ab80e13d2febb2a2cc48fa61ab600b | /aboutme/src/test/java/com/example/aboutme/AboutmeApplicationTests.java | cb3027cc3ab52dd6f67e8f3e0e10e561f84cb200 | [] | no_license | heatherdoone/samples | https://github.com/heatherdoone/samples | 16ef401d887c8d882a3c04eede491aa137cf5867 | f6f8d75345dd2d5d943f0306e35d4e998130a9ca | refs/heads/master | "2021-07-18T22:36:33.572000" | "2017-10-26T12:19:58" | "2017-10-26T12:19:58" | 105,323,752 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.aboutme;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javax.inject.Inject;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import com.example.aboutme.albums.Album;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
@RunWith ( SpringRunner.class )
@SpringBootTest ( classes = AboutmeApplication.class )
@ConfigurationProperties ( prefix = "heather.samples" )
@ActiveProfiles ( "junit" )
public class AboutmeApplicationTests {
final static private Logger logger = LoggerFactory.getLogger( AboutmeApplicationTests.class );
public void setTest1 ( String test1 ) {
this.test1 = test1;
}
public void setTest2 ( int test2 ) {
this.test2 = test2;
}
private String test1 = null;
private int test2 = -1;
@BeforeClass
public static void setUpBeforeClass ()
throws Exception {
// InitializeLogging.printTestHeader( logger.getName() );
logger.info( "Getting started" );
}
// @Autowired
@Inject
private ApplicationContext applicationContext;
@Inject
private Environment springEnv;
@Test
public void validate_spring_context_loaded () {
assertThat(
applicationContext.getBeanDefinitionCount() )
.as( "Spring Bean count" )
.isGreaterThan( 15 );
List<String> beanList = Arrays.asList( applicationContext.getBeanDefinitionNames() );
StringBuilder beanInfo = new StringBuilder( "Spring Beans" );
beanList.stream()
.sorted()
.forEach( bean -> {
beanInfo.append( "\n\t" + bean );
} );
logger.info( "\n\n Bean graph for heather: \n\n{}\n\n\n", beanInfo.toString() );
}
@Test
public void validate_spring_environment_available () {
logger.info( "heather.test {}",
springEnv.getProperty( "heather.test" ) );
assertThat(
springEnv.getProperty( "heather.test" ) )
.as( "HD Test" )
.isEqualTo( "16" );
}
@Test
public void validate_spring_configuration_properties_available () {
logger.info( " test1: {}, test2: {}", test1, test2 );
assertThat(
springEnv.getProperty( "heather.test" ) )
.as( "HD Test" )
.isEqualTo( "16" );
}
@Inject
ObjectMapper jsonMapper;
static class SimplePerson {
@Override
public String toString () {
return "TestJson [title=" + name + ", age=" + age + "]";
}
public String name;
public String age;
}
@Test
public void test_simple_json ()
throws Exception {
ObjectNode testJsonObject = jsonMapper.createObjectNode();
testJsonObject.put( "title", "tay" );
testJsonObject.put( "age", 5 );
SimplePerson simplePerson = jsonMapper.readValue(
testJsonObject.toString(),
SimplePerson.class );
logger.info( "testJsonObject: {}\n simplePerson: {}",
testJsonObject,
simplePerson );
}
@Test
public void test_album ()
throws Exception {
ObjectNode albumObject = jsonMapper.createObjectNode();
albumObject.put( "title", "taylor" );
albumObject.put( "description", "Age 5" );
Album tayAlbum = jsonMapper.readValue(
albumObject.toString(),
Album.class );
logger.info( "albumObject: {}\n Album: {}",
albumObject,
tayAlbum );
assertThat(
tayAlbum.getTitle() )
.as( "Album Title" )
.isEqualTo( "taylor" );
}
@Test
public void verify_album_with_extra_field_is_ignored ()
throws Exception {
ObjectNode albumObject = jsonMapper.createObjectNode();
albumObject.put( "title", "invalidTitle" );
albumObject.put( "description", "Age 5" );
albumObject.put( "invalid", "Age 6" );
Album tayAlbum = jsonMapper.readValue(
albumObject.toString(),
Album.class );
logger.info( "albumObject: {}\n Album: {}",
albumObject,
tayAlbum );
assertThat(
tayAlbum.getTitle() )
.as( "Album Title" )
.isEqualTo( "invalidTitle" );
}
@Test
public void verify_album_with_missing_field_is_ignored ()
throws Exception {
ObjectNode albumObject = jsonMapper.createObjectNode();
albumObject.put( "title", "invalidTitle" );
Album tayAlbum = jsonMapper.readValue(
albumObject.toString(),
Album.class );
logger.info( "albumObject: {}\n Album: {}",
albumObject,
tayAlbum );
assertThat(
tayAlbum.getTitle() )
.as( "Album Title" )
.isEqualTo( "invalidTitle" );
}
}
| UTF-8 | Java | 4,778 | java | AboutmeApplicationTests.java | Java | [
{
"context": "ateObjectNode();\n\n\t\ttestJsonObject.put( \"title\", \"tay\" );\n\t\ttestJsonObject.put( \"age\", 5 );\n\n\t\tSimple",
"end": 3053,
"score": 0.5761716365814209,
"start": 3052,
"tag": "NAME",
"value": "t"
},
{
"context": "createObjectNode();\n\n\t\talbumObject.put( \"title\", \"taylor\" );\n\t\talbumObject.put( \"description\", \"Age 5",
"end": 3448,
"score": 0.8761568069458008,
"start": 3447,
"tag": "NAME",
"value": "t"
},
{
"context": "reateObjectNode();\n\n\t\talbumObject.put( \"title\", \"taylor\" );\n\t\talbumObject.put( \"description\", \"Age 5\" );\n",
"end": 3453,
"score": 0.5191957354545593,
"start": 3448,
"tag": "NAME",
"value": "aylor"
},
{
"context": "tle() )\n\t\t\t\t.as( \"Album Title\" )\n\t\t\t\t.isEqualTo( \"taylor\" );\n\t}\n\n\t@Test\n\tpublic void verify_album_wit",
"end": 3751,
"score": 0.8865734338760376,
"start": 3750,
"tag": "NAME",
"value": "t"
},
{
"context": "le() )\n\t\t\t\t.as( \"Album Title\" )\n\t\t\t\t.isEqualTo( \"taylor\" );\n\t}\n\n\t@Test\n\tpublic void verify_album_with_ext",
"end": 3756,
"score": 0.4943671226501465,
"start": 3751,
"tag": "NAME",
"value": "aylor"
}
] | null | [] | package com.example.aboutme;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javax.inject.Inject;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import com.example.aboutme.albums.Album;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
@RunWith ( SpringRunner.class )
@SpringBootTest ( classes = AboutmeApplication.class )
@ConfigurationProperties ( prefix = "heather.samples" )
@ActiveProfiles ( "junit" )
public class AboutmeApplicationTests {
final static private Logger logger = LoggerFactory.getLogger( AboutmeApplicationTests.class );
public void setTest1 ( String test1 ) {
this.test1 = test1;
}
public void setTest2 ( int test2 ) {
this.test2 = test2;
}
private String test1 = null;
private int test2 = -1;
@BeforeClass
public static void setUpBeforeClass ()
throws Exception {
// InitializeLogging.printTestHeader( logger.getName() );
logger.info( "Getting started" );
}
// @Autowired
@Inject
private ApplicationContext applicationContext;
@Inject
private Environment springEnv;
@Test
public void validate_spring_context_loaded () {
assertThat(
applicationContext.getBeanDefinitionCount() )
.as( "Spring Bean count" )
.isGreaterThan( 15 );
List<String> beanList = Arrays.asList( applicationContext.getBeanDefinitionNames() );
StringBuilder beanInfo = new StringBuilder( "Spring Beans" );
beanList.stream()
.sorted()
.forEach( bean -> {
beanInfo.append( "\n\t" + bean );
} );
logger.info( "\n\n Bean graph for heather: \n\n{}\n\n\n", beanInfo.toString() );
}
@Test
public void validate_spring_environment_available () {
logger.info( "heather.test {}",
springEnv.getProperty( "heather.test" ) );
assertThat(
springEnv.getProperty( "heather.test" ) )
.as( "HD Test" )
.isEqualTo( "16" );
}
@Test
public void validate_spring_configuration_properties_available () {
logger.info( " test1: {}, test2: {}", test1, test2 );
assertThat(
springEnv.getProperty( "heather.test" ) )
.as( "HD Test" )
.isEqualTo( "16" );
}
@Inject
ObjectMapper jsonMapper;
static class SimplePerson {
@Override
public String toString () {
return "TestJson [title=" + name + ", age=" + age + "]";
}
public String name;
public String age;
}
@Test
public void test_simple_json ()
throws Exception {
ObjectNode testJsonObject = jsonMapper.createObjectNode();
testJsonObject.put( "title", "tay" );
testJsonObject.put( "age", 5 );
SimplePerson simplePerson = jsonMapper.readValue(
testJsonObject.toString(),
SimplePerson.class );
logger.info( "testJsonObject: {}\n simplePerson: {}",
testJsonObject,
simplePerson );
}
@Test
public void test_album ()
throws Exception {
ObjectNode albumObject = jsonMapper.createObjectNode();
albumObject.put( "title", "taylor" );
albumObject.put( "description", "Age 5" );
Album tayAlbum = jsonMapper.readValue(
albumObject.toString(),
Album.class );
logger.info( "albumObject: {}\n Album: {}",
albumObject,
tayAlbum );
assertThat(
tayAlbum.getTitle() )
.as( "Album Title" )
.isEqualTo( "taylor" );
}
@Test
public void verify_album_with_extra_field_is_ignored ()
throws Exception {
ObjectNode albumObject = jsonMapper.createObjectNode();
albumObject.put( "title", "invalidTitle" );
albumObject.put( "description", "Age 5" );
albumObject.put( "invalid", "Age 6" );
Album tayAlbum = jsonMapper.readValue(
albumObject.toString(),
Album.class );
logger.info( "albumObject: {}\n Album: {}",
albumObject,
tayAlbum );
assertThat(
tayAlbum.getTitle() )
.as( "Album Title" )
.isEqualTo( "invalidTitle" );
}
@Test
public void verify_album_with_missing_field_is_ignored ()
throws Exception {
ObjectNode albumObject = jsonMapper.createObjectNode();
albumObject.put( "title", "invalidTitle" );
Album tayAlbum = jsonMapper.readValue(
albumObject.toString(),
Album.class );
logger.info( "albumObject: {}\n Album: {}",
albumObject,
tayAlbum );
assertThat(
tayAlbum.getTitle() )
.as( "Album Title" )
.isEqualTo( "invalidTitle" );
}
}
| 4,778 | 0.703851 | 0.697991 | 207 | 22.082125 | 21.302696 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.753623 | false | false | 4 |
46fe158dad1abae742a83dc251423133b01413cf | 24,000,277,284,947 | ef28c4d27fc912b27830c6a60a9064ae76bf88ce | /development/desktop-applications-development/src/main/java/com/hard/views/EditorView.java | e77c747f79bf856f07c494d8480f773d75733d10 | [] | no_license | DmitryBelkevich/dev-library-java | https://github.com/DmitryBelkevich/dev-library-java | 4fff75d0014e08715c80dfdf04c8ecd0cb288108 | f72b290188128899f63215ceec9f67cdea738f32 | refs/heads/master | "2018-09-28T10:27:05.153000" | "2018-06-23T18:24:25" | "2018-06-23T18:24:25" | 123,944,292 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hard.views;
import com.hard.controllers.Editor;
import com.hard.models.Circle;
import com.hard.models.Rectangle;
import com.hard.models.Shape;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.Collection;
public class EditorView {
/**
* Gui
*/
private JFrame frame;
private JPanel panel;
private Graphics2D panelGraphics;
private BufferedImage canvas;
private Graphics2D canvasGraphics;
static class Canvas {
static int x = 0;
static int y = 0;
static int w = 640;
static int h = 480;
}
static class Camera {
static int x = 0;
static int y = 0;
static int w = 640;
static int h = 480;
}
/**
* Controller
*/
private Editor editor;
/**
* Model
*/
private Collection<Shape> shapes;
public EditorView(Editor editor, Collection<Shape> shapes) {
this.editor = editor;
this.shapes = shapes;
}
public void run() {
createGui();
initGraphic();
initListeners();
new Thread(() -> {
while (true) {
draw();
}
}).start();
}
public void createGui() {
frame = new JFrame();
frame.setSize(640, 480);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setPreferredSize(new Dimension(640, 480));
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public void initGraphic() {
panelGraphics = (Graphics2D) panel.getGraphics();
panelGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
panelGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
// init canvas
canvas = new BufferedImage(EditorView.Canvas.w, EditorView.Canvas.h, BufferedImage.TYPE_INT_RGB);
canvasGraphics = (Graphics2D) canvas.getGraphics();
canvasGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
canvasGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
}
public void initListeners() {
panel.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
editor.mousePressed(e);
}
@Override
public void mouseReleased(MouseEvent e) {
editor.mouseReleased(e);
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
panel.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {
editor.mouseMoved(e);
}
@Override
public void mouseDragged(MouseEvent e) {
editor.mouseDragged(e);
}
});
frame.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
editor.keyPressed(e);
}
@Override
public void keyReleased(KeyEvent e) {
editor.keyReleased(e);
}
});
}
public void draw() {
clearCanvas();
drawCanvas();
drawCanvasToPanel();
}
public void clearCanvas() {
canvasGraphics.setColor(new Color(0, 0, 0, 255));
canvasGraphics.fillRect(EditorView.Canvas.x, EditorView.Canvas.y, EditorView.Canvas.w, EditorView.Canvas.h);
}
public void drawCanvas() {
for (Shape shape : shapes) {
shape.draw(canvasGraphics);
}
}
public void drawCanvasToPanel() {
panelGraphics.drawImage(canvas, EditorView.Camera.x, EditorView.Camera.y, EditorView.Camera.w, EditorView.Camera.h, null);
}
}
| UTF-8 | Java | 4,375 | java | EditorView.java | Java | [] | null | [] | package com.hard.views;
import com.hard.controllers.Editor;
import com.hard.models.Circle;
import com.hard.models.Rectangle;
import com.hard.models.Shape;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.Collection;
public class EditorView {
/**
* Gui
*/
private JFrame frame;
private JPanel panel;
private Graphics2D panelGraphics;
private BufferedImage canvas;
private Graphics2D canvasGraphics;
static class Canvas {
static int x = 0;
static int y = 0;
static int w = 640;
static int h = 480;
}
static class Camera {
static int x = 0;
static int y = 0;
static int w = 640;
static int h = 480;
}
/**
* Controller
*/
private Editor editor;
/**
* Model
*/
private Collection<Shape> shapes;
public EditorView(Editor editor, Collection<Shape> shapes) {
this.editor = editor;
this.shapes = shapes;
}
public void run() {
createGui();
initGraphic();
initListeners();
new Thread(() -> {
while (true) {
draw();
}
}).start();
}
public void createGui() {
frame = new JFrame();
frame.setSize(640, 480);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setPreferredSize(new Dimension(640, 480));
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public void initGraphic() {
panelGraphics = (Graphics2D) panel.getGraphics();
panelGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
panelGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
// init canvas
canvas = new BufferedImage(EditorView.Canvas.w, EditorView.Canvas.h, BufferedImage.TYPE_INT_RGB);
canvasGraphics = (Graphics2D) canvas.getGraphics();
canvasGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
canvasGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
}
public void initListeners() {
panel.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
editor.mousePressed(e);
}
@Override
public void mouseReleased(MouseEvent e) {
editor.mouseReleased(e);
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
panel.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {
editor.mouseMoved(e);
}
@Override
public void mouseDragged(MouseEvent e) {
editor.mouseDragged(e);
}
});
frame.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
editor.keyPressed(e);
}
@Override
public void keyReleased(KeyEvent e) {
editor.keyReleased(e);
}
});
}
public void draw() {
clearCanvas();
drawCanvas();
drawCanvasToPanel();
}
public void clearCanvas() {
canvasGraphics.setColor(new Color(0, 0, 0, 255));
canvasGraphics.fillRect(EditorView.Canvas.x, EditorView.Canvas.y, EditorView.Canvas.w, EditorView.Canvas.h);
}
public void drawCanvas() {
for (Shape shape : shapes) {
shape.draw(canvasGraphics);
}
}
public void drawCanvasToPanel() {
panelGraphics.drawImage(canvas, EditorView.Camera.x, EditorView.Camera.y, EditorView.Camera.w, EditorView.Camera.h, null);
}
}
| 4,375 | 0.579886 | 0.5712 | 175 | 24 | 25.087276 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.48 | false | false | 4 |
118909c3402cf0d92e013008525f0e4a4d331954 | 29,678,224,029,656 | 94f91fae532f86ef33b442bce9363cfe3973f2c4 | /coffee-se/coffee-se-logging/src/main/java/hu/icellmobilsoft/coffee/se/logging/mdc/CoffeeMDCAdapter.java | 0919af56c7ce71126c43845abe461637bc1270dd | [
"Apache-2.0"
] | permissive | speter555/coffee | https://github.com/speter555/coffee | 296e2d8ebedfdb4e83614f64ed1bbd540a0d6f5a | 910c1bd69b7e05b50a3a3790eccebb5b0c54f2da | refs/heads/master | "2022-12-18T15:58:25.178000" | "2020-09-16T15:53:51" | "2020-09-16T15:53:51" | 290,177,747 | 0 | 0 | null | true | "2020-08-25T09:53:55" | "2020-08-25T09:53:54" | "2020-08-17T07:34:02" | "2020-08-17T07:34:58" | 935 | 0 | 0 | 0 | null | false | false | /*-
* #%L
* Coffee
* %%
* Copyright (C) 2020 i-Cell Mobilsoft Zrt.
* %%
* 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.
* #L%
*/
package hu.icellmobilsoft.coffee.se.logging.mdc;
import java.util.HashMap;
import java.util.Map;
/**
* Fallback MDC adapter for coffee; if no other adapter is available
*
* @author mark.petrenyi
* @since 1.1.0
*/
public class CoffeeMDCAdapter implements MDCAdapter {
private final ThreadLocal<Map<String, String>> mdcMap = new ThreadLocal<>();
/** {@inheritDoc} */
@Override
public void put(String key, String val) {
mdcMap().put(key, val);
}
/** {@inheritDoc} */
@Override
public String get(String key) {
return mdcMap().get(key);
}
/** {@inheritDoc} */
@Override
public void remove(String key) {
mdcMap().remove(key);
}
/** {@inheritDoc} */
@Override
public Map<String, String> getMap() {
return Map.copyOf(mdcMap());
}
/** {@inheritDoc} */
@Override
public void clear() {
mdcMap().clear();
}
private Map<String, String> mdcMap() {
Map<String, String> map = mdcMap.get();
if (map == null) {
map = new HashMap<>();
mdcMap.set(map);
}
return map;
}
}
| UTF-8 | Java | 1,801 | java | CoffeeMDCAdapter.java | Java | [
{
"context": "e; if no other adapter is available\n * \n * @author mark.petrenyi\n * @since 1.1.0\n */\npublic class CoffeeMDCAdapter",
"end": 846,
"score": 0.9993504285812378,
"start": 833,
"tag": "NAME",
"value": "mark.petrenyi"
}
] | null | [] | /*-
* #%L
* Coffee
* %%
* Copyright (C) 2020 i-Cell Mobilsoft Zrt.
* %%
* 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.
* #L%
*/
package hu.icellmobilsoft.coffee.se.logging.mdc;
import java.util.HashMap;
import java.util.Map;
/**
* Fallback MDC adapter for coffee; if no other adapter is available
*
* @author mark.petrenyi
* @since 1.1.0
*/
public class CoffeeMDCAdapter implements MDCAdapter {
private final ThreadLocal<Map<String, String>> mdcMap = new ThreadLocal<>();
/** {@inheritDoc} */
@Override
public void put(String key, String val) {
mdcMap().put(key, val);
}
/** {@inheritDoc} */
@Override
public String get(String key) {
return mdcMap().get(key);
}
/** {@inheritDoc} */
@Override
public void remove(String key) {
mdcMap().remove(key);
}
/** {@inheritDoc} */
@Override
public Map<String, String> getMap() {
return Map.copyOf(mdcMap());
}
/** {@inheritDoc} */
@Override
public void clear() {
mdcMap().clear();
}
private Map<String, String> mdcMap() {
Map<String, String> map = mdcMap.get();
if (map == null) {
map = new HashMap<>();
mdcMap.set(map);
}
return map;
}
}
| 1,801 | 0.615769 | 0.609661 | 74 | 23.337837 | 22.249371 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.337838 | false | false | 4 |
a0ce52c9a89172ee33eb873604f7c418c3eb0e01 | 19,756,849,588,065 | 1a0e33023b03f56f732ae60af29f40493822e48d | /extensions/dataseed/dataseed-policy/src/main/java/com/microsoft/dagx/dataseed/policy/PolicyDataSeederExtension.java | 076ef7e091e2e79e60ee3ede7c65e195e7040672 | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | jcvanderwal/Data-Appliance-GX | https://github.com/jcvanderwal/Data-Appliance-GX | 6b068ad07af83f4a4c4bc26afa24586f8616a5da | 655747cffe7df6595972e4f4d03f6e43247b4168 | refs/heads/main | "2023-06-26T16:09:46.220000" | "2021-07-21T08:06:32" | "2021-07-21T08:06:32" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) Microsoft Corporation.
* All rights reserved.
*
*/
package com.microsoft.dagx.dataseed.policy;
import com.microsoft.dagx.policy.model.*;
import com.microsoft.dagx.spi.monitor.Monitor;
import com.microsoft.dagx.spi.policy.PolicyRegistry;
import com.microsoft.dagx.spi.system.ServiceExtension;
import com.microsoft.dagx.spi.system.ServiceExtensionContext;
import java.util.List;
import static com.microsoft.dagx.policy.model.Operator.IN;
public class PolicyDataSeederExtension implements ServiceExtension {
public static final String USE_EU_POLICY = "use-eu";
public static final String USE_US_OR_EU_POLICY = "use-us-eu";
private Monitor monitor;
private ServiceExtensionContext context;
@Override
public void initialize(ServiceExtensionContext context) {
monitor = context.getMonitor();
this.context = context;
monitor.info("Initialized Policy DataSeeder extension");
}
@Override
public void start() {
savePolicies();
monitor.info("Started Policy DataSeeder extension");
}
@Override
public void shutdown() {
monitor.info("Shutdown Policy DataSeeder extension");
}
private void savePolicies() {
PolicyRegistry policyRegistry = context.getService(PolicyRegistry.class);
LiteralExpression spatialExpression = new LiteralExpression("ids:absoluteSpatialPosition");
var euConstraint = AtomicConstraint.Builder.newInstance().leftExpression(spatialExpression).operator(IN).rightExpression(new LiteralExpression("eu")).build();
var euUsePermission = Permission.Builder.newInstance().action(Action.Builder.newInstance().type("idsc:USE").build()).constraint(euConstraint).build();
var euPolicy = Policy.Builder.newInstance().id(USE_EU_POLICY).permission(euUsePermission).build();
policyRegistry.registerPolicy(euPolicy);
var usConstraint = AtomicConstraint.Builder.newInstance().leftExpression(spatialExpression).operator(IN).rightExpression(new LiteralExpression("us")).build();
var usOrEuConstrain = OrConstraint.Builder.newInstance().constraints(List.of(euConstraint, usConstraint)).build();
var usOrEuPermission = Permission.Builder.newInstance().action(Action.Builder.newInstance().type("idsc:USE").build()).constraint(usOrEuConstrain).build();
var usOrEuPolicy = Policy.Builder.newInstance().id(USE_US_OR_EU_POLICY).permission(usOrEuPermission).build();
policyRegistry.registerPolicy(usOrEuPolicy);
}
}
| UTF-8 | Java | 2,533 | java | PolicyDataSeederExtension.java | Java | [] | null | [] | /*
* Copyright (c) Microsoft Corporation.
* All rights reserved.
*
*/
package com.microsoft.dagx.dataseed.policy;
import com.microsoft.dagx.policy.model.*;
import com.microsoft.dagx.spi.monitor.Monitor;
import com.microsoft.dagx.spi.policy.PolicyRegistry;
import com.microsoft.dagx.spi.system.ServiceExtension;
import com.microsoft.dagx.spi.system.ServiceExtensionContext;
import java.util.List;
import static com.microsoft.dagx.policy.model.Operator.IN;
public class PolicyDataSeederExtension implements ServiceExtension {
public static final String USE_EU_POLICY = "use-eu";
public static final String USE_US_OR_EU_POLICY = "use-us-eu";
private Monitor monitor;
private ServiceExtensionContext context;
@Override
public void initialize(ServiceExtensionContext context) {
monitor = context.getMonitor();
this.context = context;
monitor.info("Initialized Policy DataSeeder extension");
}
@Override
public void start() {
savePolicies();
monitor.info("Started Policy DataSeeder extension");
}
@Override
public void shutdown() {
monitor.info("Shutdown Policy DataSeeder extension");
}
private void savePolicies() {
PolicyRegistry policyRegistry = context.getService(PolicyRegistry.class);
LiteralExpression spatialExpression = new LiteralExpression("ids:absoluteSpatialPosition");
var euConstraint = AtomicConstraint.Builder.newInstance().leftExpression(spatialExpression).operator(IN).rightExpression(new LiteralExpression("eu")).build();
var euUsePermission = Permission.Builder.newInstance().action(Action.Builder.newInstance().type("idsc:USE").build()).constraint(euConstraint).build();
var euPolicy = Policy.Builder.newInstance().id(USE_EU_POLICY).permission(euUsePermission).build();
policyRegistry.registerPolicy(euPolicy);
var usConstraint = AtomicConstraint.Builder.newInstance().leftExpression(spatialExpression).operator(IN).rightExpression(new LiteralExpression("us")).build();
var usOrEuConstrain = OrConstraint.Builder.newInstance().constraints(List.of(euConstraint, usConstraint)).build();
var usOrEuPermission = Permission.Builder.newInstance().action(Action.Builder.newInstance().type("idsc:USE").build()).constraint(usOrEuConstrain).build();
var usOrEuPolicy = Policy.Builder.newInstance().id(USE_US_OR_EU_POLICY).permission(usOrEuPermission).build();
policyRegistry.registerPolicy(usOrEuPolicy);
}
}
| 2,533 | 0.740624 | 0.740624 | 63 | 39.206348 | 44.998821 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.47619 | false | false | 4 |
315f5e6524164ca279d6764f04f2fe41a830b02f | 21,371,757,284,618 | 824a30bf234c02d71643aa52e60d6d2eeb833353 | /OMF-search-service/src/main/java/com/mindtree/search/SearchServiceApplication.java | b86320164d0c11f3d13e0a1a8e5c7369ad58bd67 | [] | no_license | santhu97/RestaurantMicroserviceBackend | https://github.com/santhu97/RestaurantMicroserviceBackend | 824af8dc4ee7f5106a96beed5d4fabebee34e688 | 48b1ee30626295888f3df2f2637381491dbac35e | refs/heads/master | "2023-01-05T22:30:51.698000" | "2020-09-30T15:23:04" | "2020-09-30T15:23:04" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mindtree.search;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import com.mindtree.search.controller.SearchController;
@SpringBootApplication
@EnableDiscoveryClient
@RefreshScope
@EnableCaching
public class SearchServiceApplication {
private static final Logger logger = LoggerFactory.getLogger(SearchServiceApplication.class);
public static void main(String[] args) {
logger.info("Seach service Started Successfully...!");
SpringApplication.run(SearchServiceApplication.class, args);
}
}
| UTF-8 | Java | 852 | java | SearchServiceApplication.java | Java | [] | null | [] | package com.mindtree.search;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import com.mindtree.search.controller.SearchController;
@SpringBootApplication
@EnableDiscoveryClient
@RefreshScope
@EnableCaching
public class SearchServiceApplication {
private static final Logger logger = LoggerFactory.getLogger(SearchServiceApplication.class);
public static void main(String[] args) {
logger.info("Seach service Started Successfully...!");
SpringApplication.run(SearchServiceApplication.class, args);
}
}
| 852 | 0.839202 | 0.836854 | 27 | 30.555555 | 28.120552 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false | 4 |
b4cbfc0a2dcd8b4cbd78cf43fa055d05aabff9a1 | 20,186,346,318,282 | ad7bebba2f5f12d2dbe874f02a9cd44393ebab3f | /maven_webapp/src/main/java/com/bemach/jersey/FriendsDaoImpl.java | 7c5214417e3c9ad86d8e551c8c14272adeeb8c12 | [] | no_license | drtran/training | https://github.com/drtran/training | cae665a78f95307233fc308463f8250060ef452c | ed89db9b9e078b43c9a6dd32d981e6ab775da4cb | refs/heads/master | "2018-12-28T07:00:55.259000" | "2014-08-10T12:59:52" | "2014-08-10T12:59:52" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bemach.jersey;
import java.util.ArrayList;
// friend
public class FriendsDaoImpl implements IFriendsDao{
static ArrayList<Friend> friends;
static String friendNames[] = {"lisa", "linda", "melissa", "larry", "barry", "crazy-horse"};
static{
friends = new ArrayList<Friend>();
for (int idx = 0; idx < friendNames.length; idx++) {
Friend friend = new Friend();
friend.setName(friendNames[idx]);
friends.add(friend);
}
}
public static IFriendsDao getInstance() {
return new FriendsDaoImpl();
}
public Friend[] getFriends() {
return friends.toArray(new Friend[friends.size()]);
}
public void removeFriend(String name) {
for (int idx = 0; idx < friends.size(); idx++) {
Friend friend = friends.get(idx);
if (friend.getName().equalsIgnoreCase(name)) {
friends.remove(idx);
break;
}
}
}
public void addFriend(String name) {
Friend friend = new Friend();
friend.setName(name);
friends.add(friend);
}
}
| UTF-8 | Java | 973 | java | FriendsDaoImpl.java | Java | [
{
"context": "Friend> friends;\n\tstatic String friendNames[] = {\"lisa\", \"linda\", \"melissa\", \"larry\", \"barry\", \"crazy-ho",
"end": 193,
"score": 0.9983929991722107,
"start": 189,
"tag": "NAME",
"value": "lisa"
},
{
"context": "friends;\n\tstatic String friendNames[] = {\"lisa\", \"linda\", \"melissa\", \"larry\", \"barry\", \"crazy-horse\"};\n\ts",
"end": 202,
"score": 0.9983867406845093,
"start": 197,
"tag": "NAME",
"value": "linda"
},
{
"context": "\tstatic String friendNames[] = {\"lisa\", \"linda\", \"melissa\", \"larry\", \"barry\", \"crazy-horse\"};\n\tstatic{\n\t\tfr",
"end": 213,
"score": 0.999189019203186,
"start": 206,
"tag": "NAME",
"value": "melissa"
},
{
"context": "ing friendNames[] = {\"lisa\", \"linda\", \"melissa\", \"larry\", \"barry\", \"crazy-horse\"};\n\tstatic{\n\t\tfriends = n",
"end": 222,
"score": 0.9992355704307556,
"start": 217,
"tag": "NAME",
"value": "larry"
},
{
"context": "dNames[] = {\"lisa\", \"linda\", \"melissa\", \"larry\", \"barry\", \"crazy-horse\"};\n\tstatic{\n\t\tfriends = new ArrayL",
"end": 231,
"score": 0.9990973472595215,
"start": 226,
"tag": "NAME",
"value": "barry"
},
{
"context": "= {\"lisa\", \"linda\", \"melissa\", \"larry\", \"barry\", \"crazy-horse\"};\n\tstatic{\n\t\tfriends = new ArrayList<Friend>();\n",
"end": 246,
"score": 0.8547361493110657,
"start": 235,
"tag": "USERNAME",
"value": "crazy-horse"
}
] | null | [] | package com.bemach.jersey;
import java.util.ArrayList;
// friend
public class FriendsDaoImpl implements IFriendsDao{
static ArrayList<Friend> friends;
static String friendNames[] = {"lisa", "linda", "melissa", "larry", "barry", "crazy-horse"};
static{
friends = new ArrayList<Friend>();
for (int idx = 0; idx < friendNames.length; idx++) {
Friend friend = new Friend();
friend.setName(friendNames[idx]);
friends.add(friend);
}
}
public static IFriendsDao getInstance() {
return new FriendsDaoImpl();
}
public Friend[] getFriends() {
return friends.toArray(new Friend[friends.size()]);
}
public void removeFriend(String name) {
for (int idx = 0; idx < friends.size(); idx++) {
Friend friend = friends.get(idx);
if (friend.getName().equalsIgnoreCase(name)) {
friends.remove(idx);
break;
}
}
}
public void addFriend(String name) {
Friend friend = new Friend();
friend.setName(name);
friends.add(friend);
}
}
| 973 | 0.672148 | 0.670093 | 41 | 22.731707 | 21.044697 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.097561 | false | false | 4 |
5e5d0cd77ae27f653e3fa23066f7257666fb31f1 | 28,647,431,879,321 | 7498a75458df71a0d8e4b51f4577f4b5ac73baf5 | /Projet/Plateau.java | 4ee2ce66ae64c111b6ce749ca9f57e9b4382d5af | [] | no_license | maxxx06/java | https://github.com/maxxx06/java | 442790541a35903400608951008dd458a3acc8bb | 6a96c5cbb87abb5d4cc20ff181ea4dc04c855413 | refs/heads/master | "2020-04-18T08:11:36.264000" | "2019-02-18T14:38:41" | "2019-02-18T14:38:41" | 167,387,897 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.*;
import java.util.*;
import java.lang.*;
import java.util.regex.*;
public class Plateau {
public static String[] directions={"q","w","s","d","a","z"}; // configuration possible à l'utilisateur pour se deplacer
public static Individu[][] grille=generation_plateau();
public static Individu[][] generation_plateau() { // creation de la grille
Individu plateau [][] = new Individu[20][20];
for (int i = 0; i<20; i++ ) {
for (int j = 0; j<20; j++ ) {
Empty item=new Empty(i,j); // remplir par des cases vides
plateau[i][j]=item;
}
}
return plateau;
}
public static void affiche_plateau() { // methode d'affiche de la grille
for (int i = 0; i<20; i++ ) {
for (int j = 0; j<20; j++ ) {
System.out.print("|"+grille[i][j].get_id()+"|");
}
System.out.println();
}
}
public static void aleatoire(String mode, int[] mode_de_jeu) { // placer aléatoirement les individus sur la grille
CVVector vct= new CVVector();
Vector<Integer> tab = new Vector<>();
for ( int i=0;i<400;i++) {
tab.add(i); // ce vecteur nous serbviration pour recuperer les indices de chaque iondividu
}
if(mode.equals("personnalise")) {
vct.add_idv_personnalise();
}
else {
vct.add_idv_fixe(mode_de_jeu);
}
for (Enumeration e = vct.elements(); e.hasMoreElements();) { // parcours du vecteur
Random rand = new Random(); // creation d'un objet Random
int indice= rand.nextInt(tab.size()); // choix aleatoire d'un indice du vecteur tab
int new_indice_line=tab.elementAt(indice)%20; // attribution d'un coordonne x
int new_indice_column=tab.elementAt(indice)/20; // attribution d'une coordonnée Y
Individu item = (Individu)e.nextElement();
item.set_x(new_indice_line); // definir les coordonee de l'individu
item.set_y(new_indice_column);
grille[new_indice_line][new_indice_column]=item; // placer l'individu sur le plateau
tab.remove(indice); // retire l'indice trouve pour evide de tomber plusieurs fois sur les meme coordonnees
}
}
public static void deplacement_plateau(int cpt, String type) {
while(true){
Individu item=find_plateau(choix_individu());
if((item instanceof Cell && type=="Virus") || (item instanceof Virus && type=="Cell")) { // quand c'est au tour des virus mais qu'il selectionne une cellule
// ou lorsqu'il joue les cellules mais qu'il a selectionne un virus
System.out.println("Vous avez selectionne une entite appartenant a l'adversaire");
deplacement_plateau(cpt,type);
return;
}
item.affiche();
if(cpt==0 && !(item instanceof Y_Cell)){
item.reset_move();
}
if(!(item.did_moved())) { // si l'individu ne s'est pas encore deplacé
String move_choice=choix_deplacement();
if (item instanceof Cell) { // si il a selectionné une cellule
Cell cellule=(Cell)item;
cellule.deplacement(move_choice); // deplacement cellule
break;
}
else{
Virus vrs=(Virus)item;
vrs.deplacement(move_choice); // deplacement des virus
break;
}
}
else{
System.out.println("Cet individu est infecte ou a deja ete deplace.");
}
}
}
public static Individu find_plateau(String id) { // fonction de recherche d'un id sur la grille
for (int i = 0; i<20; i++ ) {
for (int j = 0; j<20; j++ ) {
Individu item = grille[i][j];
if (item.get_id().equals(id)) {
return item;
}
}
}
System.out.println("Objet introuvable");
Individu item=find_plateau(choix_individu());
return item;
}
public static void gestion_infectes() { // cas des cellules infectees
for (int i = 0; i<20; i++ ) {
for (int j = 0; j<20; j++ ) {
Individu item = grille[i][j];
if(item instanceof Y_Cell) {
((Y_Cell) item).y_turn(); // cas pour la cellule y
}
}
}
}
public static String choix_individu() {
System.out.println("Donnez l'id de l'individu que vous voulez deplacer");
String choix=utile.saisie_chaine();
return choix;
}
public static String choix_deplacement() {
System.out.println("Dans quelle direction ? q/a : gauche s : bas d : droite z/w : haut");
String move_choice=utile.saisie_chaine();
if(utile.includes(directions, move_choice)){
return move_choice;
}
System.out.println("Erreur de saisie. Reessayez en utilisant les touches zqsd ou wasd.");
String second_move_choice=choix_deplacement();
return second_move_choice;
}
}
| UTF-8 | Java | 5,331 | java | Plateau.java | Java | [] | null | [] | import java.io.*;
import java.util.*;
import java.lang.*;
import java.util.regex.*;
public class Plateau {
public static String[] directions={"q","w","s","d","a","z"}; // configuration possible à l'utilisateur pour se deplacer
public static Individu[][] grille=generation_plateau();
public static Individu[][] generation_plateau() { // creation de la grille
Individu plateau [][] = new Individu[20][20];
for (int i = 0; i<20; i++ ) {
for (int j = 0; j<20; j++ ) {
Empty item=new Empty(i,j); // remplir par des cases vides
plateau[i][j]=item;
}
}
return plateau;
}
public static void affiche_plateau() { // methode d'affiche de la grille
for (int i = 0; i<20; i++ ) {
for (int j = 0; j<20; j++ ) {
System.out.print("|"+grille[i][j].get_id()+"|");
}
System.out.println();
}
}
public static void aleatoire(String mode, int[] mode_de_jeu) { // placer aléatoirement les individus sur la grille
CVVector vct= new CVVector();
Vector<Integer> tab = new Vector<>();
for ( int i=0;i<400;i++) {
tab.add(i); // ce vecteur nous serbviration pour recuperer les indices de chaque iondividu
}
if(mode.equals("personnalise")) {
vct.add_idv_personnalise();
}
else {
vct.add_idv_fixe(mode_de_jeu);
}
for (Enumeration e = vct.elements(); e.hasMoreElements();) { // parcours du vecteur
Random rand = new Random(); // creation d'un objet Random
int indice= rand.nextInt(tab.size()); // choix aleatoire d'un indice du vecteur tab
int new_indice_line=tab.elementAt(indice)%20; // attribution d'un coordonne x
int new_indice_column=tab.elementAt(indice)/20; // attribution d'une coordonnée Y
Individu item = (Individu)e.nextElement();
item.set_x(new_indice_line); // definir les coordonee de l'individu
item.set_y(new_indice_column);
grille[new_indice_line][new_indice_column]=item; // placer l'individu sur le plateau
tab.remove(indice); // retire l'indice trouve pour evide de tomber plusieurs fois sur les meme coordonnees
}
}
public static void deplacement_plateau(int cpt, String type) {
while(true){
Individu item=find_plateau(choix_individu());
if((item instanceof Cell && type=="Virus") || (item instanceof Virus && type=="Cell")) { // quand c'est au tour des virus mais qu'il selectionne une cellule
// ou lorsqu'il joue les cellules mais qu'il a selectionne un virus
System.out.println("Vous avez selectionne une entite appartenant a l'adversaire");
deplacement_plateau(cpt,type);
return;
}
item.affiche();
if(cpt==0 && !(item instanceof Y_Cell)){
item.reset_move();
}
if(!(item.did_moved())) { // si l'individu ne s'est pas encore deplacé
String move_choice=choix_deplacement();
if (item instanceof Cell) { // si il a selectionné une cellule
Cell cellule=(Cell)item;
cellule.deplacement(move_choice); // deplacement cellule
break;
}
else{
Virus vrs=(Virus)item;
vrs.deplacement(move_choice); // deplacement des virus
break;
}
}
else{
System.out.println("Cet individu est infecte ou a deja ete deplace.");
}
}
}
public static Individu find_plateau(String id) { // fonction de recherche d'un id sur la grille
for (int i = 0; i<20; i++ ) {
for (int j = 0; j<20; j++ ) {
Individu item = grille[i][j];
if (item.get_id().equals(id)) {
return item;
}
}
}
System.out.println("Objet introuvable");
Individu item=find_plateau(choix_individu());
return item;
}
public static void gestion_infectes() { // cas des cellules infectees
for (int i = 0; i<20; i++ ) {
for (int j = 0; j<20; j++ ) {
Individu item = grille[i][j];
if(item instanceof Y_Cell) {
((Y_Cell) item).y_turn(); // cas pour la cellule y
}
}
}
}
public static String choix_individu() {
System.out.println("Donnez l'id de l'individu que vous voulez deplacer");
String choix=utile.saisie_chaine();
return choix;
}
public static String choix_deplacement() {
System.out.println("Dans quelle direction ? q/a : gauche s : bas d : droite z/w : haut");
String move_choice=utile.saisie_chaine();
if(utile.includes(directions, move_choice)){
return move_choice;
}
System.out.println("Erreur de saisie. Reessayez en utilisant les touches zqsd ou wasd.");
String second_move_choice=choix_deplacement();
return second_move_choice;
}
}
| 5,331 | 0.538678 | 0.531731 | 141 | 36.773048 | 36.301216 | 171 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.092199 | false | false | 4 |
ff708d070ef0ab1654e4d3379740d9f855e02e65 | 15,126,874,882,087 | 1708e936bd2bd33e5d5dd96889342b0a1bca99f4 | /src/test/java/com/hackmongo/SocialReferral/service/SocialServiceTest.java | 6d9cbe2c0ba1fd20db80bb828f1125ee15ac04a3 | [] | no_license | manishbisht2210/Social-refral | https://github.com/manishbisht2210/Social-refral | 9526766216051d411dc8681ec7ed7399df9aebe8 | ee17a4b333e0986670025f3f49e18e343a965889 | refs/heads/master | "2020-07-15T09:53:06.018000" | "2019-08-31T11:42:00" | "2019-08-31T11:42:00" | 205,536,712 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hackmongo.SocialReferral.service;
import com.hackmongo.SocialReferral.repository.SocialRepository;
import com.hackmongo.SocialReferral.domain.Referral;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Created by manish.bisht on 5/2/2018.
*/
@RunWith(MockitoJUnitRunner.class)
public class SocialServiceTest {
private SocialService socialService;
@Mock
private SocialRepository socialRepository;
private Referral referral;
@Before
public void setUp() {
referral = new Referral("Aditya", "Praveen");
socialService = new SocialServiceimpl(socialRepository);
}
@Test
public void getreferrals_returnsReferrals() {
Mockito.when(socialRepository.findByReferredBy("Aditya")).thenReturn(Flux.just(referral));
StepVerifier.create(this.socialService.getReferrals("Aditya"))
.consumeNextWith(referral -> {
assertThat(referral.getReferredBy()).isEqualToIgnoringCase("aditya");
assertThat(referral.getReferredTo()).isEqualToIgnoringCase("praveen");
})
.verifyComplete();
}
}
| UTF-8 | Java | 1,530 | java | SocialServiceTest.java | Java | [
{
"context": "core.api.Assertions.assertThat;\n\n/**\n * Created by manish.bisht on 5/2/2018.\n */\n@RunWith(MockitoJUnitRunner.clas",
"end": 627,
"score": 0.9942755699157715,
"start": 615,
"tag": "USERNAME",
"value": "manish.bisht"
},
{
"context": "c void setUp() {\n referral = new Referral(\"Aditya\", \"Praveen\");\n socialService = new SocialS",
"end": 922,
"score": 0.9949172139167786,
"start": 916,
"tag": "NAME",
"value": "Aditya"
},
{
"context": "Up() {\n referral = new Referral(\"Aditya\", \"Praveen\");\n socialService = new SocialServiceimpl(",
"end": 933,
"score": 0.9990124702453613,
"start": 926,
"tag": "NAME",
"value": "Praveen"
},
{
"context": " Mockito.when(socialRepository.findByReferredBy(\"Aditya\")).thenReturn(Flux.just(referral));\n\n Step",
"end": 1131,
"score": 0.97776859998703,
"start": 1125,
"tag": "NAME",
"value": "Aditya"
},
{
"context": "pVerifier.create(this.socialService.getReferrals(\"Aditya\"))\n .consumeNextWith(referral -> {",
"end": 1236,
"score": 0.9650953412055969,
"start": 1230,
"tag": "NAME",
"value": "Aditya"
},
{
"context": "(referral.getReferredBy()).isEqualToIgnoringCase(\"aditya\");\n assertThat(referral.getRef",
"end": 1373,
"score": 0.7064463496208191,
"start": 1367,
"tag": "NAME",
"value": "aditya"
}
] | null | [] | package com.hackmongo.SocialReferral.service;
import com.hackmongo.SocialReferral.repository.SocialRepository;
import com.hackmongo.SocialReferral.domain.Referral;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Created by manish.bisht on 5/2/2018.
*/
@RunWith(MockitoJUnitRunner.class)
public class SocialServiceTest {
private SocialService socialService;
@Mock
private SocialRepository socialRepository;
private Referral referral;
@Before
public void setUp() {
referral = new Referral("Aditya", "Praveen");
socialService = new SocialServiceimpl(socialRepository);
}
@Test
public void getreferrals_returnsReferrals() {
Mockito.when(socialRepository.findByReferredBy("Aditya")).thenReturn(Flux.just(referral));
StepVerifier.create(this.socialService.getReferrals("Aditya"))
.consumeNextWith(referral -> {
assertThat(referral.getReferredBy()).isEqualToIgnoringCase("aditya");
assertThat(referral.getReferredTo()).isEqualToIgnoringCase("praveen");
})
.verifyComplete();
}
}
| 1,530 | 0.729412 | 0.72549 | 47 | 31.553192 | 26.483885 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.510638 | false | false | 4 |
3f7f0e28393a18ed084efd94d894c55421632028 | 22,806,276,387,819 | f1d8ef7acca89e9bde70ac54a893e74e91c8ac45 | /server/src/it/quickorder/domain/Notifica.java | 3615967c9ed15ec739b21462353e07d4b858a6ac | [] | no_license | mciarcia-nav/quickorder | https://github.com/mciarcia-nav/quickorder | 4d8fa28cc960eab3c90f0ff4829ea81674f79b67 | 1308ae791e540e15ae4da85db92c324fa84ad551 | refs/heads/master | "2016-09-14T09:03:23.025000" | "2011-07-15T08:24:18" | "2011-07-15T08:24:18" | 56,710,909 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.quickorder.domain;
import java.util.Date;
public class Notifica
{
private Cliente cliente;
private Date arrivo;
private Runnable threadPartenza;
public Cliente getCliente()
{
return cliente;
}
public void setCliente(Cliente cliente)
{
this.cliente = cliente;
}
public Date getArrivo()
{
return arrivo;
}
public void setArrivo(Date arrivo)
{
this.arrivo = arrivo;
}
public Runnable getThreadPartenza()
{
return threadPartenza;
}
public void setThreadPartenza(Runnable threadPartenza)
{
this.threadPartenza = threadPartenza;
}
}
| UTF-8 | Java | 633 | java | Notifica.java | Java | [] | null | [] | package it.quickorder.domain;
import java.util.Date;
public class Notifica
{
private Cliente cliente;
private Date arrivo;
private Runnable threadPartenza;
public Cliente getCliente()
{
return cliente;
}
public void setCliente(Cliente cliente)
{
this.cliente = cliente;
}
public Date getArrivo()
{
return arrivo;
}
public void setArrivo(Date arrivo)
{
this.arrivo = arrivo;
}
public Runnable getThreadPartenza()
{
return threadPartenza;
}
public void setThreadPartenza(Runnable threadPartenza)
{
this.threadPartenza = threadPartenza;
}
}
| 633 | 0.671406 | 0.671406 | 41 | 13.439024 | 14.960189 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.243902 | false | false | 4 |
9ba0749f41961b603eec442a1963207477761398 | 22,806,276,389,504 | e9d8d49cc24b1c2b101a3e777408ba8616ec7302 | /.svn/pristine/6c/6c7e3d699c700263219a3fb3dc7536a2e0019ce3.svn-base | 04f720f72edd2f4ea16d3cdb677d107f3039500d | [] | no_license | lijiangrui/cbzcts | https://github.com/lijiangrui/cbzcts | e8869d8053ab11d780226c2552bba1b76782c37d | 80d713b3c6b837b687c8b2f8cded74f6c19d5d6c | refs/heads/master | "2020-10-02T04:48:12.614000" | "2017-06-15T10:25:59" | "2017-06-15T10:25:59" | 67,474,428 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jbl.service;
public interface RepairService {
public void repair() throws Exception;
}
| UTF-8 | Java | 102 | 6c7e3d699c700263219a3fb3dc7536a2e0019ce3.svn-base | Java | [] | null | [] | package com.jbl.service;
public interface RepairService {
public void repair() throws Exception;
}
| 102 | 0.77451 | 0.77451 | 6 | 16 | 16.258331 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
|
0ca2f7c4c65cee985e7f75efca09fc8a1328a3b7 | 23,862,838,314,795 | 2fcd8ce3a122b6732d2ba2670321a8579de63225 | /src/com/Box/Obstacle.java | 2bc591d8b5be353527eacdb36a4a5c8685c0416c | [] | no_license | JasonD0/JBox | https://github.com/JasonD0/JBox | f02c7ea30fce0b4e7e212b728a369d14c1cce34f | 032546d89c42318d3f7f56efdf7dd05a0931033d | refs/heads/master | "2020-03-27T06:03:12.105000" | "2018-11-25T04:21:19" | "2018-11-25T04:21:19" | 146,074,278 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.Box;
import java.awt.Rectangle;
public class Obstacle {
private int length, height, x, y, y2, topHeight, botHeight;
private boolean inFrame;
private int obstacleVel;
public Obstacle(int x, int y, int obstacleVel, int length, int height) {
this.x = x;
this.y = y;
this.obstacleVel = obstacleVel;
this.length = length;
this.height = height;
inFrame = true;
}
public Obstacle(int x, int y1, int y2, int obstacleVel, int length, int topHeight, int botHeight) {
this.x = x;
this.y = y1;
this.y2 = y2;
this.obstacleVel = obstacleVel;
this.length = length;
this.topHeight = topHeight;
this.botHeight = botHeight;
inFrame = true;
}
public void move() {
if (x + length < 0) {
inFrame = false;
}
x -= obstacleVel;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getY2() { return this.y2; }
public int getLength() {
return this.length;
}
public int getHeight() {
return this.height;
}
public boolean inFrame() {
return this.inFrame;
}
public void setVel(int speed) {
obstacleVel = speed;
}
public int getTopH() { return this.topHeight; }
public int getBotH() { return this.botHeight; }
public Rectangle getBoundary() {
return new Rectangle(x, y, length, height);
}
}
| UTF-8 | Java | 1,531 | java | Obstacle.java | Java | [] | null | [] | package com.Box;
import java.awt.Rectangle;
public class Obstacle {
private int length, height, x, y, y2, topHeight, botHeight;
private boolean inFrame;
private int obstacleVel;
public Obstacle(int x, int y, int obstacleVel, int length, int height) {
this.x = x;
this.y = y;
this.obstacleVel = obstacleVel;
this.length = length;
this.height = height;
inFrame = true;
}
public Obstacle(int x, int y1, int y2, int obstacleVel, int length, int topHeight, int botHeight) {
this.x = x;
this.y = y1;
this.y2 = y2;
this.obstacleVel = obstacleVel;
this.length = length;
this.topHeight = topHeight;
this.botHeight = botHeight;
inFrame = true;
}
public void move() {
if (x + length < 0) {
inFrame = false;
}
x -= obstacleVel;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getY2() { return this.y2; }
public int getLength() {
return this.length;
}
public int getHeight() {
return this.height;
}
public boolean inFrame() {
return this.inFrame;
}
public void setVel(int speed) {
obstacleVel = speed;
}
public int getTopH() { return this.topHeight; }
public int getBotH() { return this.botHeight; }
public Rectangle getBoundary() {
return new Rectangle(x, y, length, height);
}
}
| 1,531 | 0.563684 | 0.557805 | 71 | 20.563381 | 19.545347 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.704225 | false | false | 4 |
0999784ed6c1ef925a6b6540d15ff24615bcb367 | 24,756,191,502,834 | d114de28f116d1a2b53fb66064a81cd9ddac4701 | /mobile/src/main/java/com/mobvoi/knowledgegraph/wearcontroltetris/pieces/ZPiece.java | 0d88687a576a2092a9c9ae1073efdbab21193b8d | [] | no_license | leaderliang/wear_control_tetris | https://github.com/leaderliang/wear_control_tetris | 1cc5648198124a14d5a14897cff6dbdfd4e27277 | e8166231ab3b191d7c4e5c52365e97b08a69563c | refs/heads/master | "2021-05-28T20:49:14.846000" | "2015-07-06T03:26:18" | "2015-07-06T03:26:18" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2013 Simon Willeke
* contact: hamstercount@hotmail.com
*/
/*
This file is part of Blockinger.
Blockinger is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Blockinger is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Blockinger. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mobvoi.knowledgegraph.wearcontroltetris.pieces;
import android.content.Context;
import com.mobvoi.knowledgegraph.wearcontroltetris.Square;
public class ZPiece extends Piece3x3 {
private Square zSquare;
public ZPiece(Context c) {
super(c);
zSquare = new Square(type_Z,c);
pattern[1][0] = zSquare;
pattern[1][1] = zSquare;
pattern[2][1] = zSquare;
pattern[2][2] = zSquare;
reDraw();
}
@Override
public void reset(Context c) {
super.reset(c);
pattern[1][0] = zSquare;
pattern[1][1] = zSquare;
pattern[2][1] = zSquare;
pattern[2][2] = zSquare;
reDraw();
}
}
| UTF-8 | Java | 1,375 | java | ZPiece.java | Java | [
{
"context": "/*\n * Copyright 2013 Simon Willeke\n * contact: hamstercount@hotmail.com\n */\n\n/*\n ",
"end": 34,
"score": 0.9997520446777344,
"start": 21,
"tag": "NAME",
"value": "Simon Willeke"
},
{
"context": "/*\n * Copyright 2013 Simon Willeke\n * contact: hamstercount@hotmail.com\n */\n\n/*\n This file is part of Blockinger.\n\n ",
"end": 71,
"score": 0.9999330043792725,
"start": 47,
"tag": "EMAIL",
"value": "hamstercount@hotmail.com"
}
] | null | [] | /*
* Copyright 2013 <NAME>
* contact: <EMAIL>
*/
/*
This file is part of Blockinger.
Blockinger is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Blockinger is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Blockinger. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mobvoi.knowledgegraph.wearcontroltetris.pieces;
import android.content.Context;
import com.mobvoi.knowledgegraph.wearcontroltetris.Square;
public class ZPiece extends Piece3x3 {
private Square zSquare;
public ZPiece(Context c) {
super(c);
zSquare = new Square(type_Z,c);
pattern[1][0] = zSquare;
pattern[1][1] = zSquare;
pattern[2][1] = zSquare;
pattern[2][2] = zSquare;
reDraw();
}
@Override
public void reset(Context c) {
super.reset(c);
pattern[1][0] = zSquare;
pattern[1][1] = zSquare;
pattern[2][1] = zSquare;
pattern[2][2] = zSquare;
reDraw();
}
}
| 1,351 | 0.710545 | 0.693818 | 54 | 24.462963 | 24.08143 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.018519 | false | false | 4 |
6f3382ac4a9e9cd993c103c76743a90c3364835d | 18,803,366,862,631 | 7d6060d29268b316d2f28870c9af8364ec3679a1 | /CRE/src/br/unifesspa/cre/core/Experiments.java | 0bf3ccb0613793a54ea8fb48f7214834dc072a82 | [] | no_license | hkuribayashi/CRE | https://github.com/hkuribayashi/CRE | 1bb83aa63dd517b1303b79910acc5566275206c4 | 89cfd95e75d54e95cd8807ed01863dcc6423692b | refs/heads/master | "2020-04-23T12:32:55.391000" | "2019-06-10T14:40:21" | "2019-06-10T14:40:21" | 171,172,704 | 0 | 0 | null | false | "2019-06-10T14:40:22" | "2019-02-17T21:09:05" | "2019-06-10T14:35:53" | "2019-06-10T14:40:22" | 2,351 | 0 | 0 | 0 | Java | false | false | package br.unifesspa.cre.core;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import br.unifesspa.cre.config.CREEnv;
import br.unifesspa.cre.hetnet.Scenario;
import br.unifesspa.cre.model.Result;
import br.unifesspa.cre.util.Util;
public class Experiments {
/**
*
* @param env
* @param simulations
* @return
*/
public static List<Result> getExperiment01(CREEnv env) {
int simulations = env.getSimulationNumber();
List<Result> noBiasResults = new ArrayList<Result>();
List<Result> results = new ArrayList<Result>();
List<Thread> threadList = new ArrayList<Thread>();
List<NoBiasEngine> engineList = new ArrayList<NoBiasEngine>();
for (int j=0; j<simulations; j++) {
Scenario scenario = new Scenario(env);
NoBiasEngine eNB = new NoBiasEngine(scenario);
engineList.add(eNB);
Thread tNB = new Thread(engineList.get(engineList.size()-1));
tNB.start();
threadList.add(tNB);
}
for (Thread thread : threadList) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (NoBiasEngine n : engineList) {
results.add(n.getResult());
}
noBiasResults.add( Util.getMean(results) );
return noBiasResults;
}
public static List<Result> getExperiment02(CREEnv env) {
// This storages the results of all Simulations
List<Result> allResults = new ArrayList<Result>();
//Auxiliary vars for thread functioning
List<Thread> threadList = new ArrayList<Thread>();
List<StaticBiasEngine> engineList = new ArrayList<StaticBiasEngine>();
int totalBias = env.getTotalBias();
double biasStep = env.getBiasStep();
double initialBias = env.getInitialBias();
Double[] biasOffset = new Double[totalBias];
for (int i=0; i<totalBias; i++) {
biasOffset[i] = initialBias + (i * biasStep);
}
//For each bias value
for (int j=0; j<totalBias; j++) {
//Analyze this scenario over all bias values
StaticBiasEngine eSB = new StaticBiasEngine(env, biasOffset[j]);
engineList.add(eSB);
//Starts the thread
Thread tSB = new Thread(engineList.get(engineList.size()-1));
tSB.start();
threadList.add(tSB);
}
for (Thread t: threadList) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (StaticBiasEngine s: engineList) {
allResults.add( Util.getMean(s.getResults()) );
}
return allResults;
}
/**
*
* @param scenario
* @return
*/
public static HashMap<String, List<Result>> getExperiment03(Scenario scenario) {
HashMap<String, List<Result>> results = new HashMap<String, List<Result>>();
List<Result> rNoBias = new ArrayList<Result>();
List<Result> rStaticBias = new ArrayList<Result>();
NoBiasEngine eNB = new NoBiasEngine(scenario);
Thread tNB = new Thread(eNB);
tNB.start();
StaticBiasEngine eSB = new StaticBiasEngine(scenario.getEnv(), 0.0);
Thread tSB = new Thread(eSB);
tSB.start();
try {
tNB.join();
tSB.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
rNoBias.add(eNB.getResult());
rStaticBias.add(Collections.max(eSB.getResults()));
results.put("NoBias", rNoBias);
results.put("StaticBias", rStaticBias);
return results;
}
public static List<Result> getExperiment04(Scenario scenario) {
List<Result> results = new ArrayList<Result>();
GAEngine eGA = new GAEngine(scenario);
Thread tGA = new Thread(eGA);
tGA.start();
try {
tGA.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
results.add(eGA.getResult());
return results;
}
public static List<Result> getExperiment05(Scenario scenario) {
List<Result> results = new ArrayList<Result>();
PSOEngine ePSO = new PSOEngine(scenario);
Thread tPSO = new Thread(ePSO);
tPSO.start();
try {
tPSO.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
results.add(ePSO.getResult());
return results;
}
} | UTF-8 | Java | 3,990 | java | Experiments.java | Java | [] | null | [] | package br.unifesspa.cre.core;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import br.unifesspa.cre.config.CREEnv;
import br.unifesspa.cre.hetnet.Scenario;
import br.unifesspa.cre.model.Result;
import br.unifesspa.cre.util.Util;
public class Experiments {
/**
*
* @param env
* @param simulations
* @return
*/
public static List<Result> getExperiment01(CREEnv env) {
int simulations = env.getSimulationNumber();
List<Result> noBiasResults = new ArrayList<Result>();
List<Result> results = new ArrayList<Result>();
List<Thread> threadList = new ArrayList<Thread>();
List<NoBiasEngine> engineList = new ArrayList<NoBiasEngine>();
for (int j=0; j<simulations; j++) {
Scenario scenario = new Scenario(env);
NoBiasEngine eNB = new NoBiasEngine(scenario);
engineList.add(eNB);
Thread tNB = new Thread(engineList.get(engineList.size()-1));
tNB.start();
threadList.add(tNB);
}
for (Thread thread : threadList) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (NoBiasEngine n : engineList) {
results.add(n.getResult());
}
noBiasResults.add( Util.getMean(results) );
return noBiasResults;
}
public static List<Result> getExperiment02(CREEnv env) {
// This storages the results of all Simulations
List<Result> allResults = new ArrayList<Result>();
//Auxiliary vars for thread functioning
List<Thread> threadList = new ArrayList<Thread>();
List<StaticBiasEngine> engineList = new ArrayList<StaticBiasEngine>();
int totalBias = env.getTotalBias();
double biasStep = env.getBiasStep();
double initialBias = env.getInitialBias();
Double[] biasOffset = new Double[totalBias];
for (int i=0; i<totalBias; i++) {
biasOffset[i] = initialBias + (i * biasStep);
}
//For each bias value
for (int j=0; j<totalBias; j++) {
//Analyze this scenario over all bias values
StaticBiasEngine eSB = new StaticBiasEngine(env, biasOffset[j]);
engineList.add(eSB);
//Starts the thread
Thread tSB = new Thread(engineList.get(engineList.size()-1));
tSB.start();
threadList.add(tSB);
}
for (Thread t: threadList) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (StaticBiasEngine s: engineList) {
allResults.add( Util.getMean(s.getResults()) );
}
return allResults;
}
/**
*
* @param scenario
* @return
*/
public static HashMap<String, List<Result>> getExperiment03(Scenario scenario) {
HashMap<String, List<Result>> results = new HashMap<String, List<Result>>();
List<Result> rNoBias = new ArrayList<Result>();
List<Result> rStaticBias = new ArrayList<Result>();
NoBiasEngine eNB = new NoBiasEngine(scenario);
Thread tNB = new Thread(eNB);
tNB.start();
StaticBiasEngine eSB = new StaticBiasEngine(scenario.getEnv(), 0.0);
Thread tSB = new Thread(eSB);
tSB.start();
try {
tNB.join();
tSB.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
rNoBias.add(eNB.getResult());
rStaticBias.add(Collections.max(eSB.getResults()));
results.put("NoBias", rNoBias);
results.put("StaticBias", rStaticBias);
return results;
}
public static List<Result> getExperiment04(Scenario scenario) {
List<Result> results = new ArrayList<Result>();
GAEngine eGA = new GAEngine(scenario);
Thread tGA = new Thread(eGA);
tGA.start();
try {
tGA.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
results.add(eGA.getResult());
return results;
}
public static List<Result> getExperiment05(Scenario scenario) {
List<Result> results = new ArrayList<Result>();
PSOEngine ePSO = new PSOEngine(scenario);
Thread tPSO = new Thread(ePSO);
tPSO.start();
try {
tPSO.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
results.add(ePSO.getResult());
return results;
}
} | 3,990 | 0.681203 | 0.676942 | 179 | 21.296089 | 21.110683 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.98324 | false | false | 4 |
ee90f4ffbc1ae4664918a9a66149dd5027c98aea | 29,420,526,044,337 | 84f464a14dfbf8688d3aca240ec09e30cf1ea271 | /src/com/ickovitz/operating_systems/MetricsPanel.java | fd3b10ffb6a6f83352af0cddb8d402477fcc17ff | [] | no_license | mickTouro/FDU | https://github.com/mickTouro/FDU | cf27b2c9b112007595fd41e69d068a33955f2b9b | 07ee5e73c24bb15fb72e117dd0b26f008d1bb3dd | refs/heads/master | "2020-06-18T09:54:07.519000" | "2019-10-28T00:25:49" | "2019-10-28T00:25:49" | 75,145,126 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ickovitz.operating_systems;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class MetricsPanel extends JPanel {
private JTable table;
private DefaultTableModel dtm;
public MetricsPanel() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
resetTable();
}
public void resetTable() {
this.table = new JTable();
this.dtm = new DefaultTableModel();
table.setVisible(true);
table.setModel(dtm);
add(table.getTableHeader());
add(table);
}
public void displayMetrics(String algorithm, Map<String, Double> map) {
if (table.getColumnCount() == 0) {
dtm.addColumn("");
}
// add metric name to column headers
if (table.getColumnCount() == 1) {
for (String metricName : map.keySet()) {
dtm.addColumn(metricName);
}
}
Object o[] = new Object[map.size() + 1];
o[0] = algorithm;
int col = 1;
for (String metricName : map.keySet()) {
o[col] = map.get(metricName);
col++;
}
dtm.addRow(o);
}
// removes all metrics
public void reset() {
this.removeAll();
this.repaint();
}
} | UTF-8 | Java | 1,241 | java | MetricsPanel.java | Java | [
{
"context": "package com.ickovitz.operating_systems;\r\n\r\nimport java.util.Map;\r\nimpo",
"end": 20,
"score": 0.807590901851654,
"start": 12,
"tag": "USERNAME",
"value": "ickovitz"
}
] | null | [] | package com.ickovitz.operating_systems;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class MetricsPanel extends JPanel {
private JTable table;
private DefaultTableModel dtm;
public MetricsPanel() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
resetTable();
}
public void resetTable() {
this.table = new JTable();
this.dtm = new DefaultTableModel();
table.setVisible(true);
table.setModel(dtm);
add(table.getTableHeader());
add(table);
}
public void displayMetrics(String algorithm, Map<String, Double> map) {
if (table.getColumnCount() == 0) {
dtm.addColumn("");
}
// add metric name to column headers
if (table.getColumnCount() == 1) {
for (String metricName : map.keySet()) {
dtm.addColumn(metricName);
}
}
Object o[] = new Object[map.size() + 1];
o[0] = algorithm;
int col = 1;
for (String metricName : map.keySet()) {
o[col] = map.get(metricName);
col++;
}
dtm.addRow(o);
}
// removes all metrics
public void reset() {
this.removeAll();
this.repaint();
}
} | 1,241 | 0.651088 | 0.647059 | 56 | 20.214285 | 16.421583 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.839286 | false | false | 4 |
2deb6084dbba4b1c49a9d5ded7edd3d1d6ef2c5b | 17,841,294,153,496 | ef44d044ff58ebc6c0052962b04b0130025a102b | /com.freevisiontech.fvmobile_source_from_JADX/sources/com/googlecode/mp4parser/boxes/apple/PixelAspectRationAtom.java | 44cc5ddd271714c231d030a209697c28f868c70b | [] | no_license | thedemoncat/FVShare | https://github.com/thedemoncat/FVShare | e610bac0f2dc394534ac0ccec86941ff523e2dfd | bd1e52defaec868f0d1f9b4f2039625c8ff3ee4a | refs/heads/master | "2023-08-06T04:11:16.403000" | "2021-09-25T10:11:13" | "2021-09-25T10:11:13" | 410,232,121 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.googlecode.mp4parser.boxes.apple;
import com.freevisiontech.fvmobile.common.BleConstant;
import com.googlecode.mp4parser.AbstractBox;
import com.googlecode.mp4parser.RequiresParseDetailAspect;
import java.nio.ByteBuffer;
import org.mp4parser.aspectj.lang.JoinPoint;
import org.mp4parser.aspectj.lang.Signature;
import org.mp4parser.aspectj.runtime.internal.Conversions;
import org.mp4parser.aspectj.runtime.reflect.Factory;
public class PixelAspectRationAtom extends AbstractBox {
public static final String TYPE = "pasp";
private static final JoinPoint.StaticPart ajc$tjp_0 = null;
private static final JoinPoint.StaticPart ajc$tjp_1 = null;
private static final JoinPoint.StaticPart ajc$tjp_2 = null;
private static final JoinPoint.StaticPart ajc$tjp_3 = null;
private int hSpacing;
private int vSpacing;
static {
ajc$preClinit();
}
private static void ajc$preClinit() {
Factory factory = new Factory("PixelAspectRationAtom.java", PixelAspectRationAtom.class);
ajc$tjp_0 = factory.makeSJP(JoinPoint.METHOD_EXECUTION, (Signature) factory.makeMethodSig(BleConstant.SHUTTER, "gethSpacing", "com.googlecode.mp4parser.boxes.apple.PixelAspectRationAtom", "", "", "", "int"), 35);
ajc$tjp_1 = factory.makeSJP(JoinPoint.METHOD_EXECUTION, (Signature) factory.makeMethodSig(BleConstant.SHUTTER, "sethSpacing", "com.googlecode.mp4parser.boxes.apple.PixelAspectRationAtom", "int", "hSpacing", "", "void"), 39);
ajc$tjp_2 = factory.makeSJP(JoinPoint.METHOD_EXECUTION, (Signature) factory.makeMethodSig(BleConstant.SHUTTER, "getvSpacing", "com.googlecode.mp4parser.boxes.apple.PixelAspectRationAtom", "", "", "", "int"), 43);
ajc$tjp_3 = factory.makeSJP(JoinPoint.METHOD_EXECUTION, (Signature) factory.makeMethodSig(BleConstant.SHUTTER, "setvSpacing", "com.googlecode.mp4parser.boxes.apple.PixelAspectRationAtom", "int", "vSpacing", "", "void"), 47);
}
public PixelAspectRationAtom() {
super(TYPE);
}
public int gethSpacing() {
RequiresParseDetailAspect.aspectOf().before(Factory.makeJP(ajc$tjp_0, this, this));
return this.hSpacing;
}
public void sethSpacing(int hSpacing2) {
RequiresParseDetailAspect.aspectOf().before(Factory.makeJP(ajc$tjp_1, (Object) this, (Object) this, Conversions.intObject(hSpacing2)));
this.hSpacing = hSpacing2;
}
public int getvSpacing() {
RequiresParseDetailAspect.aspectOf().before(Factory.makeJP(ajc$tjp_2, this, this));
return this.vSpacing;
}
public void setvSpacing(int vSpacing2) {
RequiresParseDetailAspect.aspectOf().before(Factory.makeJP(ajc$tjp_3, (Object) this, (Object) this, Conversions.intObject(vSpacing2)));
this.vSpacing = vSpacing2;
}
/* access modifiers changed from: protected */
public long getContentSize() {
return 8;
}
/* access modifiers changed from: protected */
public void getContent(ByteBuffer byteBuffer) {
byteBuffer.putInt(this.hSpacing);
byteBuffer.putInt(this.vSpacing);
}
/* access modifiers changed from: protected */
public void _parseDetails(ByteBuffer content) {
this.hSpacing = content.getInt();
this.vSpacing = content.getInt();
}
}
| UTF-8 | Java | 3,297 | java | PixelAspectRationAtom.java | Java | [] | null | [] | package com.googlecode.mp4parser.boxes.apple;
import com.freevisiontech.fvmobile.common.BleConstant;
import com.googlecode.mp4parser.AbstractBox;
import com.googlecode.mp4parser.RequiresParseDetailAspect;
import java.nio.ByteBuffer;
import org.mp4parser.aspectj.lang.JoinPoint;
import org.mp4parser.aspectj.lang.Signature;
import org.mp4parser.aspectj.runtime.internal.Conversions;
import org.mp4parser.aspectj.runtime.reflect.Factory;
public class PixelAspectRationAtom extends AbstractBox {
public static final String TYPE = "pasp";
private static final JoinPoint.StaticPart ajc$tjp_0 = null;
private static final JoinPoint.StaticPart ajc$tjp_1 = null;
private static final JoinPoint.StaticPart ajc$tjp_2 = null;
private static final JoinPoint.StaticPart ajc$tjp_3 = null;
private int hSpacing;
private int vSpacing;
static {
ajc$preClinit();
}
private static void ajc$preClinit() {
Factory factory = new Factory("PixelAspectRationAtom.java", PixelAspectRationAtom.class);
ajc$tjp_0 = factory.makeSJP(JoinPoint.METHOD_EXECUTION, (Signature) factory.makeMethodSig(BleConstant.SHUTTER, "gethSpacing", "com.googlecode.mp4parser.boxes.apple.PixelAspectRationAtom", "", "", "", "int"), 35);
ajc$tjp_1 = factory.makeSJP(JoinPoint.METHOD_EXECUTION, (Signature) factory.makeMethodSig(BleConstant.SHUTTER, "sethSpacing", "com.googlecode.mp4parser.boxes.apple.PixelAspectRationAtom", "int", "hSpacing", "", "void"), 39);
ajc$tjp_2 = factory.makeSJP(JoinPoint.METHOD_EXECUTION, (Signature) factory.makeMethodSig(BleConstant.SHUTTER, "getvSpacing", "com.googlecode.mp4parser.boxes.apple.PixelAspectRationAtom", "", "", "", "int"), 43);
ajc$tjp_3 = factory.makeSJP(JoinPoint.METHOD_EXECUTION, (Signature) factory.makeMethodSig(BleConstant.SHUTTER, "setvSpacing", "com.googlecode.mp4parser.boxes.apple.PixelAspectRationAtom", "int", "vSpacing", "", "void"), 47);
}
public PixelAspectRationAtom() {
super(TYPE);
}
public int gethSpacing() {
RequiresParseDetailAspect.aspectOf().before(Factory.makeJP(ajc$tjp_0, this, this));
return this.hSpacing;
}
public void sethSpacing(int hSpacing2) {
RequiresParseDetailAspect.aspectOf().before(Factory.makeJP(ajc$tjp_1, (Object) this, (Object) this, Conversions.intObject(hSpacing2)));
this.hSpacing = hSpacing2;
}
public int getvSpacing() {
RequiresParseDetailAspect.aspectOf().before(Factory.makeJP(ajc$tjp_2, this, this));
return this.vSpacing;
}
public void setvSpacing(int vSpacing2) {
RequiresParseDetailAspect.aspectOf().before(Factory.makeJP(ajc$tjp_3, (Object) this, (Object) this, Conversions.intObject(vSpacing2)));
this.vSpacing = vSpacing2;
}
/* access modifiers changed from: protected */
public long getContentSize() {
return 8;
}
/* access modifiers changed from: protected */
public void getContent(ByteBuffer byteBuffer) {
byteBuffer.putInt(this.hSpacing);
byteBuffer.putInt(this.vSpacing);
}
/* access modifiers changed from: protected */
public void _parseDetails(ByteBuffer content) {
this.hSpacing = content.getInt();
this.vSpacing = content.getInt();
}
}
| 3,297 | 0.717319 | 0.705793 | 73 | 44.164383 | 53.265686 | 232 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.082192 | false | false | 4 |
28b81f5afe43788e33ded39eaf92c93c08f4c5ba | 317,827,604,654 | 2e1abd1236a6c0ea4b9b8ecf97b604d9cb9a8582 | /src/bl/playerbl/PlayerBLSort.java | b55e3585dc294c2d4b2ef4a701a37eb090eae5c2 | [] | no_license | doraczp/NBADataAnalyzer | https://github.com/doraczp/NBADataAnalyzer | df8cb1f6965012c5e1db3a61141a1e666044a1a3 | 2d5c236b2a07b3d5fd2f7e95b0271f146f9cbbf9 | refs/heads/master | "2021-05-29T02:21:04.324000" | "2015-05-10T15:33:45" | "2015-05-10T15:33:45" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bl.playerbl;
import java.util.ArrayList;
import po.playerInSingleMatchPO;
import po.playerPO;
import vo.playerVO;
import vo.teamVO;
import constantinfo.SortBy;
public class PlayerBLSort {
ArrayList<playerVO> playerlist;
ArrayList<playerVO> freeplayerlist;
ArrayList<playerInSingleMatchPO> dailyplayerlist;
SortBy sortby;
boolean isUP;
public PlayerBLSort(ArrayList<playerVO> playerlist,SortBy sortby,boolean isUP){
this.playerlist=playerlist;
this.sortby=sortby;
this.isUP=isUP;
checkEmpty();
}
public PlayerBLSort(ArrayList<playerInSingleMatchPO> dailyplayerlist,SortBy sortby){
this.dailyplayerlist=dailyplayerlist;
this.sortby=sortby;
}
public void sort(ArrayList<playerVO> playerlist,int l,int r){
int middle;
if(l<r){
middle=partition(playerlist,l,r);
sort(playerlist,l,middle-1);
sort(playerlist,middle+1,r);
}
if(freeplayerlist.size()>0){
for(playerVO freeplayer:freeplayerlist)
playerlist.add(freeplayer);
freeplayerlist.clear();
}
}
public void dailysort(ArrayList<playerInSingleMatchPO> dailyplayerlist,int l,int r){
int middle;
if(l<r){
middle=dailypartition(dailyplayerlist,l,r);
dailysort(dailyplayerlist,l,middle-1);
dailysort(dailyplayerlist,middle+1,r);
}
/*if(freeplayerlist.size()>0){
for(playerVO freeplayer:freeplayerlist)
playerlist.add(freeplayer);
freeplayerlist.clear();
}*/
}
public int partition(ArrayList<playerVO> playerlist,int l,int r){
int i=l;
int j=r;
playerVO x=playerlist.get(i);
switch (sortby){
case SCREEN_SCORE:{
while(i<j){
if (isUP)
while(i<j && playerlist.get(j).totalScores>=x.totalScores)
j--;
else
while(i<j && playerlist.get(j).totalScores<=x.totalScores)
j--;
if(i<j){
playerlist.set(i, playerlist.get(j));
}
if (isUP)
while(i<j&& playerlist.get(i).totalScores<x.totalScores)
i++;
else
while(i<j&& playerlist.get(i).totalScores>x.totalScores)
i++;
if(i<j){
playerlist.set(j, playerlist.get(i));
}
}
break;
}
case PLAYER_AVERAGESCORES:{
while(i<j){
if (isUP)
while(i<j && ((double)playerlist.get(j).totalScores/(double)playerlist.get(j).totalMatches)>=((double)x.totalScores/(double)x.totalMatches))
j--;
else
while(i<j && ((double)playerlist.get(j).totalScores/(double)playerlist.get(j).totalMatches)<=((double)x.totalScores/(double)x.totalMatches))
j--;
if(i<j){
playerlist.set(i, playerlist.get(j));
}
if (isUP)
while(i<j&& (double)playerlist.get(i).totalScores/(double)playerlist.get(j).totalMatches<=(double)x.totalScores/(double)x.totalMatches)
i++;
else
while(i<j&& (double)playerlist.get(i).totalScores/(double)playerlist.get(j).totalMatches>=(double)x.totalScores/(double)x.totalMatches)
i++;
if(i<j){
playerlist.set(j, playerlist.get(i));
}
}
break;
}
case PROGRESS_AVERAGE_SCORE:{
while(i<j){
if (isUP)
while(i<j && playerlist.get(j).progress>=x.progress)
j--;
else
while(i<j && playerlist.get(j).progress<=x.progress)
j--;
if(i<j){
playerlist.set(i, playerlist.get(j));
}
if (isUP)
while(i<j&& playerlist.get(i).progress<=x.progress)
i++;
else
while(i<j&& playerlist.get(i).progress>=x.progress)
i++;
if(i<j){
playerlist.set(j, playerlist.get(i));
}
}
break;
}
default:{}
}
playerlist.set(i,x);
return i;
}
public int dailypartition(ArrayList<playerInSingleMatchPO> dailyplayerlist,int l,int r){
int i=l;
int j=r;
playerInSingleMatchPO x=dailyplayerlist.get(i);
switch (sortby){
case PLAYER_DAILY_SCORE:{
while(i<j){
while(i<j && dailyplayerlist.get(j).getScore()<=x.getScore())
j--;
if(i<j){
dailyplayerlist.set(i, dailyplayerlist.get(j));
}
while(i<j&& dailyplayerlist.get(i).getScore()>x.getScore())
i++;
if(i<j){
dailyplayerlist.set(j, dailyplayerlist.get(i));
}
}
break;
}
}
dailyplayerlist.set(i,x);
return i;
}
public void checkEmpty(){
freeplayerlist=new ArrayList<playerVO>();
int length=0;
for(playerVO singleplayer:playerlist ){
if(singleplayer.team.equals("")){
freeplayerlist.add(singleplayer);
}
length++;
}
playerlist.removeAll(freeplayerlist);
}
}
| UTF-8 | Java | 4,493 | java | PlayerBLSort.java | Java | [] | null | [] | package bl.playerbl;
import java.util.ArrayList;
import po.playerInSingleMatchPO;
import po.playerPO;
import vo.playerVO;
import vo.teamVO;
import constantinfo.SortBy;
public class PlayerBLSort {
ArrayList<playerVO> playerlist;
ArrayList<playerVO> freeplayerlist;
ArrayList<playerInSingleMatchPO> dailyplayerlist;
SortBy sortby;
boolean isUP;
public PlayerBLSort(ArrayList<playerVO> playerlist,SortBy sortby,boolean isUP){
this.playerlist=playerlist;
this.sortby=sortby;
this.isUP=isUP;
checkEmpty();
}
public PlayerBLSort(ArrayList<playerInSingleMatchPO> dailyplayerlist,SortBy sortby){
this.dailyplayerlist=dailyplayerlist;
this.sortby=sortby;
}
public void sort(ArrayList<playerVO> playerlist,int l,int r){
int middle;
if(l<r){
middle=partition(playerlist,l,r);
sort(playerlist,l,middle-1);
sort(playerlist,middle+1,r);
}
if(freeplayerlist.size()>0){
for(playerVO freeplayer:freeplayerlist)
playerlist.add(freeplayer);
freeplayerlist.clear();
}
}
public void dailysort(ArrayList<playerInSingleMatchPO> dailyplayerlist,int l,int r){
int middle;
if(l<r){
middle=dailypartition(dailyplayerlist,l,r);
dailysort(dailyplayerlist,l,middle-1);
dailysort(dailyplayerlist,middle+1,r);
}
/*if(freeplayerlist.size()>0){
for(playerVO freeplayer:freeplayerlist)
playerlist.add(freeplayer);
freeplayerlist.clear();
}*/
}
public int partition(ArrayList<playerVO> playerlist,int l,int r){
int i=l;
int j=r;
playerVO x=playerlist.get(i);
switch (sortby){
case SCREEN_SCORE:{
while(i<j){
if (isUP)
while(i<j && playerlist.get(j).totalScores>=x.totalScores)
j--;
else
while(i<j && playerlist.get(j).totalScores<=x.totalScores)
j--;
if(i<j){
playerlist.set(i, playerlist.get(j));
}
if (isUP)
while(i<j&& playerlist.get(i).totalScores<x.totalScores)
i++;
else
while(i<j&& playerlist.get(i).totalScores>x.totalScores)
i++;
if(i<j){
playerlist.set(j, playerlist.get(i));
}
}
break;
}
case PLAYER_AVERAGESCORES:{
while(i<j){
if (isUP)
while(i<j && ((double)playerlist.get(j).totalScores/(double)playerlist.get(j).totalMatches)>=((double)x.totalScores/(double)x.totalMatches))
j--;
else
while(i<j && ((double)playerlist.get(j).totalScores/(double)playerlist.get(j).totalMatches)<=((double)x.totalScores/(double)x.totalMatches))
j--;
if(i<j){
playerlist.set(i, playerlist.get(j));
}
if (isUP)
while(i<j&& (double)playerlist.get(i).totalScores/(double)playerlist.get(j).totalMatches<=(double)x.totalScores/(double)x.totalMatches)
i++;
else
while(i<j&& (double)playerlist.get(i).totalScores/(double)playerlist.get(j).totalMatches>=(double)x.totalScores/(double)x.totalMatches)
i++;
if(i<j){
playerlist.set(j, playerlist.get(i));
}
}
break;
}
case PROGRESS_AVERAGE_SCORE:{
while(i<j){
if (isUP)
while(i<j && playerlist.get(j).progress>=x.progress)
j--;
else
while(i<j && playerlist.get(j).progress<=x.progress)
j--;
if(i<j){
playerlist.set(i, playerlist.get(j));
}
if (isUP)
while(i<j&& playerlist.get(i).progress<=x.progress)
i++;
else
while(i<j&& playerlist.get(i).progress>=x.progress)
i++;
if(i<j){
playerlist.set(j, playerlist.get(i));
}
}
break;
}
default:{}
}
playerlist.set(i,x);
return i;
}
public int dailypartition(ArrayList<playerInSingleMatchPO> dailyplayerlist,int l,int r){
int i=l;
int j=r;
playerInSingleMatchPO x=dailyplayerlist.get(i);
switch (sortby){
case PLAYER_DAILY_SCORE:{
while(i<j){
while(i<j && dailyplayerlist.get(j).getScore()<=x.getScore())
j--;
if(i<j){
dailyplayerlist.set(i, dailyplayerlist.get(j));
}
while(i<j&& dailyplayerlist.get(i).getScore()>x.getScore())
i++;
if(i<j){
dailyplayerlist.set(j, dailyplayerlist.get(i));
}
}
break;
}
}
dailyplayerlist.set(i,x);
return i;
}
public void checkEmpty(){
freeplayerlist=new ArrayList<playerVO>();
int length=0;
for(playerVO singleplayer:playerlist ){
if(singleplayer.team.equals("")){
freeplayerlist.add(singleplayer);
}
length++;
}
playerlist.removeAll(freeplayerlist);
}
}
| 4,493 | 0.636991 | 0.635433 | 206 | 20.81068 | 25.773247 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.514563 | false | false | 4 |
ae52471bf7b66f75d2284064e4c9c0f8878eaa24 | 21,199,958,581,211 | fd937a17d66c0322d0783426adba0c167d69bf2b | /NullChat/src/com/nullchat/service/Header.java | 7096b39c3fb879ca3887246dac08879eea567ed1 | [] | no_license | fgssdfs/nullchat | https://github.com/fgssdfs/nullchat | cc928b061e6b16187a542ff6735306435bd381cf | 64ed2c7989aa93bf6972e8262b2f7003d8bce517 | refs/heads/master | "2018-01-07T08:00:21.408000" | "2013-01-23T20:35:15" | "2013-01-23T20:35:15" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nullchat.service;
import com.nullchat.network.ByteConverter;
public class Header {
private byte[] length = null;
private byte type;
public final static byte DEFAULT = 0x00;
public final static byte POST = 0x01;
public final static byte ONLINE = 0x02;
public final static byte ERROR = 0x03;
public final static byte RADIO = 0x04;
public final static byte IMAGE = 0x05;
public final static byte CLEAR = 0x07;
public Header(byte[] length, byte type) {
this.type = type;
this.length = length;
}
public Header(byte type) {
this.type = type;
}
public byte[] getBytes() {
byte[] header = new byte[3];
header[0] = length[0];
header[1] = length[1];
header[3] = type;
return header;
}
public void computeLength(int l) {
if (length==null)
length = ByteConverter.convertUnsignedInt(l);
}
public byte getType() {
return type;
}
}
| UTF-8 | Java | 922 | java | Header.java | Java | [] | null | [] | package com.nullchat.service;
import com.nullchat.network.ByteConverter;
public class Header {
private byte[] length = null;
private byte type;
public final static byte DEFAULT = 0x00;
public final static byte POST = 0x01;
public final static byte ONLINE = 0x02;
public final static byte ERROR = 0x03;
public final static byte RADIO = 0x04;
public final static byte IMAGE = 0x05;
public final static byte CLEAR = 0x07;
public Header(byte[] length, byte type) {
this.type = type;
this.length = length;
}
public Header(byte type) {
this.type = type;
}
public byte[] getBytes() {
byte[] header = new byte[3];
header[0] = length[0];
header[1] = length[1];
header[3] = type;
return header;
}
public void computeLength(int l) {
if (length==null)
length = ByteConverter.convertUnsignedInt(l);
}
public byte getType() {
return type;
}
}
| 922 | 0.659436 | 0.630152 | 43 | 19.44186 | 15.69521 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.465116 | false | false | 4 |
f00c5b55ef7a50ba7a2d7a6506073a88e5d23fab | 28,630,252,014,199 | 7585d2b6dbf2ccd97637a866e2958540307fab88 | /Sistema_de_Seguranca/src/br/com/pict/controler/MenuController.java | fa6dde2aebfac1e109eb4ec0d437e4d42aabaedb | [
"MIT"
] | permissive | Rytokirin21/Cientific_Iniciation | https://github.com/Rytokirin21/Cientific_Iniciation | 577de2f270e45979cb08388cef1a8f35e9b79251 | 15180a5e444e739f254f2cb2493da1e219ebcd6a | refs/heads/master | "2023-06-25T16:55:43.031000" | "2021-07-23T15:30:03" | "2021-07-23T15:30:03" | 336,364,043 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.pict.controler;
import br.com.pict.authenticate.LoginController;
import br.com.pict.main.SistemaFXMain;
import br.com.pict.util.OpenCV;
import com.jfoenix.controls.JFXButton;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javax.swing.JOptionPane;
/**
* FXML Controller class
*
* @author Iarley
*/
public class MenuController implements Initializable {
@FXML
private AnchorPane menu;
@FXML
private HBox hboxRelatorios;
@FXML
private Button btnLogout;
@FXML
private HBox hboxCadastrar;
@FXML
private AnchorPane AnchorPanePerfis;
@FXML
private JFXButton btnSair;
@Override
public void initialize(URL url, ResourceBundle rb) {
}
@FXML
private void onClick$hboxCadastrar(MouseEvent event) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/br/com/pict/view/Cadastro.fxml"));
Stage stage = new Stage();
Scene scene = new Scene(root);
stage.setTitle("Cadastrar");
stage.setScene(scene);
stage.initStyle(StageStyle.UNDECORATED);
stage.show();
} catch (IOException ex) {
Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
}
}
@FXML
private void onClick$btnLogout(ActionEvent event) {
if (OpenCV.cameraActive) {
JOptionPane.showMessageDialog(null, "Sistema não foi desilgado!");
} else {
LoginController.stageMenu.close();
SistemaFXMain.stageLogin.show();
}
}
@FXML
private void onClick$hboxRelatorios(MouseEvent event) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/br/com/pict/view/ConsultaLogs.fxml"));
Stage stage = new Stage();
Scene scene = new Scene(root);
stage.setTitle("Cosultas");
stage.setScene(scene);
stage.initStyle(StageStyle.UNDECORATED);
stage.show();
} catch (IOException ex) {
Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
}
}
@FXML
private void onClick$btnSair() {
Stage stage = (Stage) menu.getScene().getWindow();
stage.close();
}
}
| UTF-8 | Java | 2,724 | java | MenuController.java | Java | [
{
"context": "nPane;\n\n/**\n * FXML Controller class\n *\n * @author Iarley\n */\npublic class MenuController implements Initia",
"end": 747,
"score": 0.9996611475944519,
"start": 741,
"tag": "NAME",
"value": "Iarley"
}
] | null | [] | package br.com.pict.controler;
import br.com.pict.authenticate.LoginController;
import br.com.pict.main.SistemaFXMain;
import br.com.pict.util.OpenCV;
import com.jfoenix.controls.JFXButton;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javax.swing.JOptionPane;
/**
* FXML Controller class
*
* @author Iarley
*/
public class MenuController implements Initializable {
@FXML
private AnchorPane menu;
@FXML
private HBox hboxRelatorios;
@FXML
private Button btnLogout;
@FXML
private HBox hboxCadastrar;
@FXML
private AnchorPane AnchorPanePerfis;
@FXML
private JFXButton btnSair;
@Override
public void initialize(URL url, ResourceBundle rb) {
}
@FXML
private void onClick$hboxCadastrar(MouseEvent event) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/br/com/pict/view/Cadastro.fxml"));
Stage stage = new Stage();
Scene scene = new Scene(root);
stage.setTitle("Cadastrar");
stage.setScene(scene);
stage.initStyle(StageStyle.UNDECORATED);
stage.show();
} catch (IOException ex) {
Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
}
}
@FXML
private void onClick$btnLogout(ActionEvent event) {
if (OpenCV.cameraActive) {
JOptionPane.showMessageDialog(null, "Sistema não foi desilgado!");
} else {
LoginController.stageMenu.close();
SistemaFXMain.stageLogin.show();
}
}
@FXML
private void onClick$hboxRelatorios(MouseEvent event) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/br/com/pict/view/ConsultaLogs.fxml"));
Stage stage = new Stage();
Scene scene = new Scene(root);
stage.setTitle("Cosultas");
stage.setScene(scene);
stage.initStyle(StageStyle.UNDECORATED);
stage.show();
} catch (IOException ex) {
Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
}
}
@FXML
private void onClick$btnSair() {
Stage stage = (Stage) menu.getScene().getWindow();
stage.close();
}
}
| 2,724 | 0.653324 | 0.653324 | 95 | 27.663158 | 22.433344 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578947 | false | false | 4 |
b6c9e62c04dc64b63b84bed82e56e8ba1b4b8744 | 17,995,912,987,712 | 89bd6e39b1d9faca09d04d973a49d5862e5c74d0 | /src/Reclame/TimerReclame.java | 1ba8502125ad3067b84a6e9b40bcc68b73da082c | [] | no_license | Chriton/Agenda | https://github.com/Chriton/Agenda | 09ca727f36a4793d628aa6627b9e798f69e0f135 | 41239ec45dd0c9863c5492982fd21ff1fbb71f06 | refs/heads/master | "2021-04-26T04:22:46.265000" | "2018-03-06T14:37:59" | "2018-03-06T14:37:59" | 121,382,657 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Reclame;
import java.util.Timer;
import javax.swing.JLabel;
/**
* @author dorumuntean
*/
public class TimerReclame extends Timer {
private JLabel label;
private int delay;
private int interval;
public TimerReclame(JLabel label) {
this(label, 0, 3000);
}
public TimerReclame(JLabel label, int delay, int interval) {
super("Timer Reclame");
this.label = label;
this.delay = delay;
this.interval = interval;
}
public void porneste() {
this.schedule(new TaskReclame(label), delay, interval);
}
public void opreste() {
this.cancel();
}
} | UTF-8 | Java | 649 | java | TimerReclame.java | Java | [
{
"context": ".Timer;\nimport javax.swing.JLabel;\n\n/**\n * @author dorumuntean\n */\npublic class TimerReclame extends Timer {\n\n ",
"end": 96,
"score": 0.9990198612213135,
"start": 85,
"tag": "USERNAME",
"value": "dorumuntean"
}
] | null | [] | package Reclame;
import java.util.Timer;
import javax.swing.JLabel;
/**
* @author dorumuntean
*/
public class TimerReclame extends Timer {
private JLabel label;
private int delay;
private int interval;
public TimerReclame(JLabel label) {
this(label, 0, 3000);
}
public TimerReclame(JLabel label, int delay, int interval) {
super("Timer Reclame");
this.label = label;
this.delay = delay;
this.interval = interval;
}
public void porneste() {
this.schedule(new TaskReclame(label), delay, interval);
}
public void opreste() {
this.cancel();
}
} | 649 | 0.620955 | 0.613251 | 33 | 18.69697 | 17.298599 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.575758 | false | false | 4 |
130da1616430ede92506c2ba8cae983097181acd | 21,861,383,569,555 | a5ea7f5cb16251ec0877aab3a2aebce7ae5f0e46 | /src/ru/ekipogh/sud/controllers/LauncherController.java | 9d25ee6d7e180187df5b7912e57840c99dada779 | [
"MIT"
] | permissive | Ekipogh/TheSUD2 | https://github.com/Ekipogh/TheSUD2 | 5f9d179ce672f19b4f355ab1a335ee8c79c34e9d | aba257fdcde8a62fa5045a1c96a15c401db9bd2d | refs/heads/master | "2020-05-21T22:52:37.163000" | "2020-02-25T17:46:38" | "2020-02-25T17:46:38" | 34,454,446 | 0 | 0 | MIT | false | "2020-02-24T13:33:54" | "2015-04-23T12:18:40" | "2018-12-23T13:38:49" | "2020-02-24T13:33:53" | 6,349 | 0 | 0 | 9 | Java | false | false | package ru.ekipogh.sud.controllers;
import javafx.fxml.FXML;
/**
* Created by Ektril Pogh on 13.06.2018.
*/
public class LauncherController {
@FXML
public void initialize() {
ScreenController.setController("launcher", this);
}
public void startEditor() {
ScreenController.activate("editor");
}
public void startPlayer() {
ScreenController.activate("player");
}
}
| UTF-8 | Java | 421 | java | LauncherController.java | Java | [
{
"context": "lers;\n\nimport javafx.fxml.FXML;\n\n/**\n * Created by Ektril Pogh on 13.06.2018.\n */\npublic class LauncherControlle",
"end": 92,
"score": 0.9998852014541626,
"start": 81,
"tag": "NAME",
"value": "Ektril Pogh"
}
] | null | [] | package ru.ekipogh.sud.controllers;
import javafx.fxml.FXML;
/**
* Created by <NAME> on 13.06.2018.
*/
public class LauncherController {
@FXML
public void initialize() {
ScreenController.setController("launcher", this);
}
public void startEditor() {
ScreenController.activate("editor");
}
public void startPlayer() {
ScreenController.activate("player");
}
}
| 416 | 0.653207 | 0.634204 | 21 | 19.047619 | 18.243006 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 4 |
852c17bc994a6c7d44c14a9e2b428dd121a60612 | 11,871,289,627,983 | fc907b4506b2cffac0e3092bcbbd67dbdfcca179 | /src/data/dao/mysql/MySQLModelVozilaDAO.java | 7fe6ec459a5c3b194783b9c898df3694678109ca | [] | no_license | BorislavBosnic/Auto-servis-Maric | https://github.com/BorislavBosnic/Auto-servis-Maric | 0e8a1ec46582950ec3272b0f3ff78fa9e648ee67 | 738b5cd66572d4e747af8ee0ef315eedaf8bd403 | refs/heads/master | "2021-09-17T07:53:49.452000" | "2018-06-29T08:50:04" | "2018-06-29T08:50:04" | 114,247,213 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package data.dao.mysql;
import data.dao.ModelVozilaDAO;
import data.dto.KupacDTO;
import data.dto.ModelVozilaDTO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class MySQLModelVozilaDAO implements ModelVozilaDAO {
@Override
public ArrayList<ModelVozilaDTO> sviModeli() {
ArrayList<ModelVozilaDTO> retVal = new ArrayList<ModelVozilaDTO>();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT IdModelVozila, Marka, Model "
+ "FROM model_vozila "
+ "WHERE Aktivan!= false "
+ "ORDER BY IdModelVozila ASC ";
try {
conn = ConnectionPool.getInstance().checkOut();
ps = conn.prepareStatement(query);
rs = ps.executeQuery();
while (rs.next())
retVal.add(new ModelVozilaDTO(rs.getInt("IdModelVozila"), rs.getString("Marka"), rs.getString("Model")));
} catch (SQLException e) {
e.printStackTrace();
DBUtilities.getInstance().showSQLException(e);
} finally {
ConnectionPool.getInstance().checkIn(conn);
DBUtilities.getInstance().close(ps, rs);
}
return retVal;
}
@Override
public ArrayList<ModelVozilaDTO> getModeli(String marka){
ArrayList<ModelVozilaDTO> retVal = new ArrayList<ModelVozilaDTO>();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT IdModelVozila, Marka, Model "
+ "FROM model_vozila "
+ "WHERE Marka=? AND Aktivan!=false "
+ "ORDER BY IdModelVozila ASC ";
try {
conn = ConnectionPool.getInstance().checkOut();
ps = conn.prepareStatement(query);
ps.setString(1, marka);
rs = ps.executeQuery();
while (rs.next())
retVal.add(new ModelVozilaDTO(rs.getInt("IdModelVozila"), rs.getString("Marka"), rs.getString("Model")));
} catch (SQLException e) {
e.printStackTrace();
DBUtilities.getInstance().showSQLException(e);
} finally {
ConnectionPool.getInstance().checkIn(conn);
DBUtilities.getInstance().close(ps, rs);
}
return retVal;
}
@Override
public boolean dodajModel(ModelVozilaDTO model) {
boolean retVal = false;
Connection conn = null;
PreparedStatement ps = null;
String query = "INSERT INTO model_vozila(Marka, Model) VALUES "
+ "(?, ?) ";
try {
conn = ConnectionPool.getInstance().checkOut();
ps = conn.prepareStatement(query);
ps.setString(1, model.getMarka());
ps.setString(2, model.getModel());
retVal = ps.executeUpdate() == 1;
} catch (SQLException e) {
e.printStackTrace();
DBUtilities.getInstance().showSQLException(e);
} finally {
ConnectionPool.getInstance().checkIn(conn);
DBUtilities.getInstance().close(ps);
}
return retVal;
}
@Override
public boolean azurirajModel(ModelVozilaDTO model) {
boolean retVal = false;
Connection conn = null;
PreparedStatement ps = null;
String query = "UPDATE model_vozila SET "
+ "Marka=?, "
+ "Model=? "
+ "WHERE IdModelVozila=? ";
try {
conn = ConnectionPool.getInstance().checkOut();
ps = conn.prepareStatement(query);
ps.setString(1, model.getMarka());
ps.setString(2, model.getModel());
ps.setInt(3, model.getIdModelVozila());
retVal = ps.executeUpdate() == 1;
} catch (SQLException e) {
e.printStackTrace();
DBUtilities.getInstance().showSQLException(e);
} finally {
ConnectionPool.getInstance().checkIn(conn);
DBUtilities.getInstance().close(ps);
}
return retVal;
}
@Override
public boolean obrisiModel(ModelVozilaDTO model) {
boolean retVal = false;
Connection conn = null;
PreparedStatement ps = null;
String query = "UPDATE model_vozila "
+ "SET Aktivan=false "
+ "WHERE IdModelVozila=? ";
try {
conn = ConnectionPool.getInstance().checkOut();
ps = conn.prepareStatement(query);
ps.setInt(1, model.getIdModelVozila());
retVal = ps.executeUpdate() == 1;
} catch (SQLException e) {
e.printStackTrace();
DBUtilities.getInstance().showSQLException(e);
} finally {
ConnectionPool.getInstance().checkIn(conn);
DBUtilities.getInstance().close(ps);
}
return retVal;
}
@Override
public ModelVozilaDTO model(String marka, String model) {
ModelVozilaDTO retVal = null;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT IdModelVozila, Marka, Model "
+ "FROM model_vozila "
+ "WHERE Marka LIKE ? "
+ "AND Model LIKE ? AND Aktivan!=false ";
try {
conn = ConnectionPool.getInstance().checkOut();
ps = conn.prepareStatement(query);
ps.setString(1, marka);
ps.setString(2, model);
rs = ps.executeQuery();
if (rs.next())
retVal = new ModelVozilaDTO(rs.getInt("IdModelVozila"), rs.getString("Marka"), rs.getString("Model"));
} catch (SQLException e) {
e.printStackTrace();
DBUtilities.getInstance().showSQLException(e);
} finally {
ConnectionPool.getInstance().checkIn(conn);
DBUtilities.getInstance().close(ps, rs);
}
return retVal;
}
@Override
public ModelVozilaDTO model(int id) {
ModelVozilaDTO retVal = null;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT IdModelVozila, Marka, Model "
+ "FROM model_vozila "
+ "WHERE IdModelVozila=? ";
try {
conn = ConnectionPool.getInstance().checkOut();
ps = conn.prepareStatement(query);
ps.setInt(1, id);
rs = ps.executeQuery();
if (rs.next())
retVal = new ModelVozilaDTO(rs.getInt("IdModelVozila"), rs.getString("Marka"), rs.getString("Model"));
} catch (SQLException e) {
e.printStackTrace();
DBUtilities.getInstance().showSQLException(e);
} finally {
ConnectionPool.getInstance().checkIn(conn);
DBUtilities.getInstance().close(ps, rs);
}
return retVal;
}
@Override
public boolean postojiLiVoziloSaOvimModelom(ModelVozilaDTO model) {
boolean retVal = true;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String query = "select IdModelVozila\n" +
"from vozilo\n" +
"where IdModelVozila=? AND Izbrisano!=true\n" +
"group by IdModelVozila\n" +
"having count(IdModelVozila) > 0;";
try {
conn = ConnectionPool.getInstance().checkOut();
ps = conn.prepareStatement(query);
ps.setInt(1, model.getIdModelVozila());
rs = ps.executeQuery();
if (rs.next()){
return true;
}
else return false;
} catch (SQLException e) {
e.printStackTrace();
DBUtilities.getInstance().showSQLException(e);
} finally {
ConnectionPool.getInstance().checkIn(conn);
DBUtilities.getInstance().close(ps, rs);
}
return retVal;
}
}
| UTF-8 | Java | 7,522 | java | MySQLModelVozilaDAO.java | Java | [] | null | [] | package data.dao.mysql;
import data.dao.ModelVozilaDAO;
import data.dto.KupacDTO;
import data.dto.ModelVozilaDTO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class MySQLModelVozilaDAO implements ModelVozilaDAO {
@Override
public ArrayList<ModelVozilaDTO> sviModeli() {
ArrayList<ModelVozilaDTO> retVal = new ArrayList<ModelVozilaDTO>();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT IdModelVozila, Marka, Model "
+ "FROM model_vozila "
+ "WHERE Aktivan!= false "
+ "ORDER BY IdModelVozila ASC ";
try {
conn = ConnectionPool.getInstance().checkOut();
ps = conn.prepareStatement(query);
rs = ps.executeQuery();
while (rs.next())
retVal.add(new ModelVozilaDTO(rs.getInt("IdModelVozila"), rs.getString("Marka"), rs.getString("Model")));
} catch (SQLException e) {
e.printStackTrace();
DBUtilities.getInstance().showSQLException(e);
} finally {
ConnectionPool.getInstance().checkIn(conn);
DBUtilities.getInstance().close(ps, rs);
}
return retVal;
}
@Override
public ArrayList<ModelVozilaDTO> getModeli(String marka){
ArrayList<ModelVozilaDTO> retVal = new ArrayList<ModelVozilaDTO>();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT IdModelVozila, Marka, Model "
+ "FROM model_vozila "
+ "WHERE Marka=? AND Aktivan!=false "
+ "ORDER BY IdModelVozila ASC ";
try {
conn = ConnectionPool.getInstance().checkOut();
ps = conn.prepareStatement(query);
ps.setString(1, marka);
rs = ps.executeQuery();
while (rs.next())
retVal.add(new ModelVozilaDTO(rs.getInt("IdModelVozila"), rs.getString("Marka"), rs.getString("Model")));
} catch (SQLException e) {
e.printStackTrace();
DBUtilities.getInstance().showSQLException(e);
} finally {
ConnectionPool.getInstance().checkIn(conn);
DBUtilities.getInstance().close(ps, rs);
}
return retVal;
}
@Override
public boolean dodajModel(ModelVozilaDTO model) {
boolean retVal = false;
Connection conn = null;
PreparedStatement ps = null;
String query = "INSERT INTO model_vozila(Marka, Model) VALUES "
+ "(?, ?) ";
try {
conn = ConnectionPool.getInstance().checkOut();
ps = conn.prepareStatement(query);
ps.setString(1, model.getMarka());
ps.setString(2, model.getModel());
retVal = ps.executeUpdate() == 1;
} catch (SQLException e) {
e.printStackTrace();
DBUtilities.getInstance().showSQLException(e);
} finally {
ConnectionPool.getInstance().checkIn(conn);
DBUtilities.getInstance().close(ps);
}
return retVal;
}
@Override
public boolean azurirajModel(ModelVozilaDTO model) {
boolean retVal = false;
Connection conn = null;
PreparedStatement ps = null;
String query = "UPDATE model_vozila SET "
+ "Marka=?, "
+ "Model=? "
+ "WHERE IdModelVozila=? ";
try {
conn = ConnectionPool.getInstance().checkOut();
ps = conn.prepareStatement(query);
ps.setString(1, model.getMarka());
ps.setString(2, model.getModel());
ps.setInt(3, model.getIdModelVozila());
retVal = ps.executeUpdate() == 1;
} catch (SQLException e) {
e.printStackTrace();
DBUtilities.getInstance().showSQLException(e);
} finally {
ConnectionPool.getInstance().checkIn(conn);
DBUtilities.getInstance().close(ps);
}
return retVal;
}
@Override
public boolean obrisiModel(ModelVozilaDTO model) {
boolean retVal = false;
Connection conn = null;
PreparedStatement ps = null;
String query = "UPDATE model_vozila "
+ "SET Aktivan=false "
+ "WHERE IdModelVozila=? ";
try {
conn = ConnectionPool.getInstance().checkOut();
ps = conn.prepareStatement(query);
ps.setInt(1, model.getIdModelVozila());
retVal = ps.executeUpdate() == 1;
} catch (SQLException e) {
e.printStackTrace();
DBUtilities.getInstance().showSQLException(e);
} finally {
ConnectionPool.getInstance().checkIn(conn);
DBUtilities.getInstance().close(ps);
}
return retVal;
}
@Override
public ModelVozilaDTO model(String marka, String model) {
ModelVozilaDTO retVal = null;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT IdModelVozila, Marka, Model "
+ "FROM model_vozila "
+ "WHERE Marka LIKE ? "
+ "AND Model LIKE ? AND Aktivan!=false ";
try {
conn = ConnectionPool.getInstance().checkOut();
ps = conn.prepareStatement(query);
ps.setString(1, marka);
ps.setString(2, model);
rs = ps.executeQuery();
if (rs.next())
retVal = new ModelVozilaDTO(rs.getInt("IdModelVozila"), rs.getString("Marka"), rs.getString("Model"));
} catch (SQLException e) {
e.printStackTrace();
DBUtilities.getInstance().showSQLException(e);
} finally {
ConnectionPool.getInstance().checkIn(conn);
DBUtilities.getInstance().close(ps, rs);
}
return retVal;
}
@Override
public ModelVozilaDTO model(int id) {
ModelVozilaDTO retVal = null;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT IdModelVozila, Marka, Model "
+ "FROM model_vozila "
+ "WHERE IdModelVozila=? ";
try {
conn = ConnectionPool.getInstance().checkOut();
ps = conn.prepareStatement(query);
ps.setInt(1, id);
rs = ps.executeQuery();
if (rs.next())
retVal = new ModelVozilaDTO(rs.getInt("IdModelVozila"), rs.getString("Marka"), rs.getString("Model"));
} catch (SQLException e) {
e.printStackTrace();
DBUtilities.getInstance().showSQLException(e);
} finally {
ConnectionPool.getInstance().checkIn(conn);
DBUtilities.getInstance().close(ps, rs);
}
return retVal;
}
@Override
public boolean postojiLiVoziloSaOvimModelom(ModelVozilaDTO model) {
boolean retVal = true;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String query = "select IdModelVozila\n" +
"from vozilo\n" +
"where IdModelVozila=? AND Izbrisano!=true\n" +
"group by IdModelVozila\n" +
"having count(IdModelVozila) > 0;";
try {
conn = ConnectionPool.getInstance().checkOut();
ps = conn.prepareStatement(query);
ps.setInt(1, model.getIdModelVozila());
rs = ps.executeQuery();
if (rs.next()){
return true;
}
else return false;
} catch (SQLException e) {
e.printStackTrace();
DBUtilities.getInstance().showSQLException(e);
} finally {
ConnectionPool.getInstance().checkIn(conn);
DBUtilities.getInstance().close(ps, rs);
}
return retVal;
}
}
| 7,522 | 0.608615 | 0.606621 | 245 | 28.702042 | 21.226595 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.306123 | false | false | 4 |
75d0b56d1cb626400d4baf1c947416e22aa9dde8 | 13,632,226,223,757 | 86f33b4fbc579e4f7747f0e314fda322ff81f97c | /java/src/test/java/com/leetcode/s341/NestedIteratorTest.java | 5d917ad5ac92bdc6550adc046a5d3b40a650d431 | [] | no_license | TangGuoHua/leetcode | https://github.com/TangGuoHua/leetcode | 3251ee97a4f238d36f2350ea977d3709c829f2e6 | e209dac2763e2dddf5e15bde70618f1490589dc0 | refs/heads/main | "2023-06-03T01:05:28.101000" | "2021-06-08T13:19:50" | "2021-06-08T13:20:07" | 318,691,442 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.leetcode.s341;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class NestedIteratorTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test1() {
//[1,[4,[6]]]
//expect 1 4 6
NestedInteger e6 = new NestedInteger(6);
NestedInteger list = new NestedInteger();
list.add2List(e6);
NestedInteger e4 = new NestedInteger();
e4.add2List(new NestedInteger(4));
e4.add2List(list);
NestedInteger e1 = new NestedInteger();
e1.add2List(new NestedInteger(1));
e1.add2List(e4);
List<NestedInteger> input = new ArrayList<>();
input.add(e1);
NestedIterator it = new NestedIterator(input);
while(it.hasNext()) {
System.out.println(it.next());
}
}
@Test
public void test2() {
//[[],[3]]
NestedInteger list1 = new NestedInteger();
NestedInteger list2 = new NestedInteger();
list2.add2List(new NestedInteger(3));
List<NestedInteger> input = new ArrayList<>();
input.add(list1);
input.add(list2);
NestedIterator it = new NestedIterator(input);
while(it.hasNext()) {
System.out.println(it.next());
}
}
@Test
public void test3() {
//[[],[3]]
NestedInteger list1 = new NestedInteger();
List<NestedInteger> input = new ArrayList<>();
input.add(list1);
NestedIterator it = new NestedIterator(input);
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
| UTF-8 | Java | 1,525 | java | NestedIteratorTest.java | Java | [] | null | [] | package com.leetcode.s341;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class NestedIteratorTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test1() {
//[1,[4,[6]]]
//expect 1 4 6
NestedInteger e6 = new NestedInteger(6);
NestedInteger list = new NestedInteger();
list.add2List(e6);
NestedInteger e4 = new NestedInteger();
e4.add2List(new NestedInteger(4));
e4.add2List(list);
NestedInteger e1 = new NestedInteger();
e1.add2List(new NestedInteger(1));
e1.add2List(e4);
List<NestedInteger> input = new ArrayList<>();
input.add(e1);
NestedIterator it = new NestedIterator(input);
while(it.hasNext()) {
System.out.println(it.next());
}
}
@Test
public void test2() {
//[[],[3]]
NestedInteger list1 = new NestedInteger();
NestedInteger list2 = new NestedInteger();
list2.add2List(new NestedInteger(3));
List<NestedInteger> input = new ArrayList<>();
input.add(list1);
input.add(list2);
NestedIterator it = new NestedIterator(input);
while(it.hasNext()) {
System.out.println(it.next());
}
}
@Test
public void test3() {
//[[],[3]]
NestedInteger list1 = new NestedInteger();
List<NestedInteger> input = new ArrayList<>();
input.add(list1);
NestedIterator it = new NestedIterator(input);
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
| 1,525 | 0.668852 | 0.641967 | 73 | 19.876713 | 16.712677 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.90411 | false | false | 4 |
485a4fb8fec21e307bf0c7dd165997b07a8db569 | 29,334,626,647,560 | 702522aef31c8fe9b181d942adc121cf965b3e8b | /DMOJ/Poetry.java | 7892caf0a70fdd9f4aaf8a462bc90f22babfc780 | [] | no_license | Andy-Rock/contests | https://github.com/Andy-Rock/contests | 4eeab575e54e6bdf28374d1264f63859867b4d66 | 010c89023ec1531d82d7c6bf532006fcf98866ff | refs/heads/master | "2018-02-15T05:15:25.907000" | "2017-09-26T07:23:42" | "2017-09-26T07:23:42" | 36,151,745 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* Andy Rock
* August 24, 2016
*
* TLE '16 P3 - Poetry: dmoj.ca/problem/tle16p3
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Poetry
{
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(in.readLine());
int[] C = new int[N];
for(int i=0;i<N;i++)
C[i] = Integer.parseInt(in.readLine());
String[] words = in.readLine().split(" ");
int linIndex = 0, wordIndex = 0, cycIndex = 0;
for(int i=0;i<words.length;i++)
if(linIndex + words[i].length() - wordIndex <= C[cycIndex % N])
{
System.out.print(words[i].substring(wordIndex)+" ");
linIndex += words[i].length()-wordIndex+1;
wordIndex = 0;
}
else if(linIndex != 0)
{
System.out.println();
linIndex = 0;
cycIndex++;
i--;
}
else
{
System.out.println(words[i].substring(wordIndex, wordIndex + C[cycIndex % N]));
linIndex = 0;
wordIndex += C[cycIndex % N];
cycIndex++;
i--;
}
}
} | UTF-8 | Java | 1,096 | java | Poetry.java | Java | [
{
"context": "/* Andy Rock\n * August 24, 2016\n * \n * TLE '16 P3 - Poetry: dm",
"end": 12,
"score": 0.9998563528060913,
"start": 3,
"tag": "NAME",
"value": "Andy Rock"
}
] | null | [] | /* <NAME>
* August 24, 2016
*
* TLE '16 P3 - Poetry: dmoj.ca/problem/tle16p3
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Poetry
{
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(in.readLine());
int[] C = new int[N];
for(int i=0;i<N;i++)
C[i] = Integer.parseInt(in.readLine());
String[] words = in.readLine().split(" ");
int linIndex = 0, wordIndex = 0, cycIndex = 0;
for(int i=0;i<words.length;i++)
if(linIndex + words[i].length() - wordIndex <= C[cycIndex % N])
{
System.out.print(words[i].substring(wordIndex)+" ");
linIndex += words[i].length()-wordIndex+1;
wordIndex = 0;
}
else if(linIndex != 0)
{
System.out.println();
linIndex = 0;
cycIndex++;
i--;
}
else
{
System.out.println(words[i].substring(wordIndex, wordIndex + C[cycIndex % N]));
linIndex = 0;
wordIndex += C[cycIndex % N];
cycIndex++;
i--;
}
}
} | 1,093 | 0.620438 | 0.600365 | 49 | 21.387754 | 21.518682 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.530612 | false | false | 4 |
b0014b29a47eb1114cb256b251c5b4a9e3c21087 | 23,751,169,173,791 | 489c0cdae450b3842778c9c2106896a0046dbebb | /Company_Tagged_Question/Facebook/Remove_Invalid_Parenthesis.java | 551366106c2f67e9d3f0cbb8e86b56218e3eaf4f | [] | no_license | mayankkt9/Competetive_Programming | https://github.com/mayankkt9/Competetive_Programming | 0c5e5dc574dd769b01416a2389cb5d08c6f87a46 | f00fc5e5a4ab101f9f08cea09f872c715c1e5fda | refs/heads/master | "2022-11-16T00:40:32.334000" | "2020-07-01T05:20:03" | "2020-07-01T05:20:03" | 186,657,570 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
class RemoveInvalidParentheses {
int min = Integer.MAX_VALUE;
List<String> answer = new ArrayList<>();
public List<String> removeInvalidParentheses(String s) {
System.out.println("Hello");
int paren[] = calculateParenthesis(s);
// dfs_1(s, 0, 0);
// dfs_2(s, 0, 0, 0, 0);
// dfs_3(s, 0, 0, new StringBuilder());
// dfs_4(s, 0, 0, new StringBuilder(), 0, 0);
// dfs_5(s, 0, 0, new StringBuilder(), 0, 0, paren[0], paren[1]);
bfs(s);
Set<String> set = new HashSet<>(answer);
List<String> list = new ArrayList<>(set);
System.out.println(list);
return null;
}
public void bfs(String str) {
Queue<String> q = new LinkedList<>();
q.add(str);
HashSet<String> visited = new HashSet<>();
visited.add(str);
boolean found = false;
while (!q.isEmpty()) {
int n = q.size();
if (found) {
n = 0;
break;
}
for (int i = 1; i <= n; i++) {
String temp = q.poll();
if (valid(temp)) {
answer.add(temp);
found = true;
}
for (int j = 0; j < temp.length(); j++) {
if (Character.isLetter(temp.charAt(j)))
continue;
String form = temp.substring(0, j) + temp.substring(j + 1);
if (!visited.contains(form)){
q.add(form);
visited.add(form);
}
}
}
}
}
public void dfs_5(String str, int idx, int rem, StringBuilder cur_str, int left, int right, int leftrem,
int rightrem) {
if (idx == str.length()) {
if (valid(cur_str.toString())) {
if (rem == min) {
answer.add(cur_str.toString());
} else if (rem < min) {
answer.clear();
answer.add(cur_str.toString());
min = rem;
}
}
} else {
char ch = str.charAt(idx);
if (ch == '(' || ch == ')') {
if (ch == '(') {
if (leftrem > 0)
dfs_5(str, idx + 1, rem + 1, cur_str, left, right, leftrem - 1, rightrem);
cur_str.append(ch);
dfs_5(str, idx + 1, rem, cur_str, left + 1, right, leftrem, rightrem);
cur_str.deleteCharAt(cur_str.length() - 1);
} else {
if (rightrem > 0)
dfs_5(str, idx + 1, rem + 1, cur_str, left, right, leftrem, rightrem - 1);
if (left > right) {
cur_str.append(ch);
dfs_5(str, idx + 1, rem, cur_str, left, right + 1, leftrem, rightrem);
cur_str.deleteCharAt(cur_str.length() - 1);
}
}
} else {
cur_str.append(ch);
dfs_4(str, idx + 1, rem, cur_str, left, right);
cur_str.deleteCharAt(cur_str.length() - 1);
}
}
}
public void dfs_4(String str, int idx, int rem, StringBuilder cur_str, int left, int right) {
if (idx == str.length()) {
if (valid(cur_str.toString())) {
if (rem == min) {
answer.add(cur_str.toString());
} else if (rem < min) {
answer.clear();
answer.add(cur_str.toString());
min = rem;
}
}
} else {
char ch = str.charAt(idx);
if (ch == '(' || ch == ')') {
if (ch == '(') {
dfs_4(str, idx + 1, rem + 1, cur_str, left, right);
cur_str.append(ch);
dfs_4(str, idx + 1, rem, cur_str, left + 1, right);
cur_str.deleteCharAt(cur_str.length() - 1);
} else {
dfs_4(str, idx + 1, rem + 1, cur_str, left, right);
if (left > right) {
cur_str.append(ch);
dfs_4(str, idx + 1, rem, cur_str, left, right + 1);
cur_str.deleteCharAt(cur_str.length() - 1);
}
}
} else {
cur_str.append(ch);
dfs_4(str, idx + 1, rem, cur_str, left, right);
cur_str.deleteCharAt(cur_str.length() - 1);
}
}
}
public void dfs_3(String str, int idx, int rem, StringBuilder cur_str) {
if (idx == str.length()) {
if (valid(cur_str.toString())) {
if (rem == min) {
answer.add(cur_str.toString());
} else if (rem < min) {
answer.clear();
answer.add(cur_str.toString());
min = rem;
}
}
} else {
char ch = str.charAt(idx);
if (ch == '(' || ch == ')') {
dfs_3(str, idx + 1, rem + 1, cur_str);
cur_str.append(ch);
dfs_3(str, idx + 1, rem, cur_str);
cur_str.deleteCharAt(cur_str.length() - 1);
} else {
cur_str.append(ch);
dfs_3(str, idx + 1, rem, cur_str);
cur_str.deleteCharAt(cur_str.length() - 1);
}
}
}
public void dfs_1(String str, int idx, int rem) {
if (idx == str.length()) {
if (valid(str)) {
if (rem == min) {
answer.add(str);
} else if (rem < min) {
answer.clear();
answer.add(str);
min = rem;
}
}
} else {
char ch = str.charAt(idx);
if (ch == '(' || ch == ')') {
String remStr = str.substring(0, idx) + str.substring(idx + 1, str.length());
dfs_1(remStr, idx, rem + 1);
dfs_1(str, idx + 1, rem);
} else {
dfs_1(str, idx + 1, rem);
}
}
}
private boolean valid(String str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '(')
count += 1;
else if (str.charAt(i) == ')')
count -= 1;
if (count < 0)
return false;
}
if (count == 0)
return true;
else
return false;
}
public int[] calculateParenthesis(String s) {
int c = 0;
int rightParen = 0;
int leftParen = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(')
c++;
else if (s.charAt(i) == ')')
c--;
if (c < 0) {
c = 0;
rightParen++;
}
}
c = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == ')')
c++;
else if (s.charAt(i) == '(')
c--;
if (c < 0) {
c = 0;
leftParen++;
}
}
// System.out.println(leftParen + " " + rightParen);
return new int[] { leftParen, rightParen };
}
public static void main(String[] args) {
RemoveInvalidParentheses obj = new RemoveInvalidParentheses();
obj.removeInvalidParentheses("()(((((((()");
}
} | UTF-8 | Java | 7,927 | java | Remove_Invalid_Parenthesis.java | Java | [] | null | [] | import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
class RemoveInvalidParentheses {
int min = Integer.MAX_VALUE;
List<String> answer = new ArrayList<>();
public List<String> removeInvalidParentheses(String s) {
System.out.println("Hello");
int paren[] = calculateParenthesis(s);
// dfs_1(s, 0, 0);
// dfs_2(s, 0, 0, 0, 0);
// dfs_3(s, 0, 0, new StringBuilder());
// dfs_4(s, 0, 0, new StringBuilder(), 0, 0);
// dfs_5(s, 0, 0, new StringBuilder(), 0, 0, paren[0], paren[1]);
bfs(s);
Set<String> set = new HashSet<>(answer);
List<String> list = new ArrayList<>(set);
System.out.println(list);
return null;
}
public void bfs(String str) {
Queue<String> q = new LinkedList<>();
q.add(str);
HashSet<String> visited = new HashSet<>();
visited.add(str);
boolean found = false;
while (!q.isEmpty()) {
int n = q.size();
if (found) {
n = 0;
break;
}
for (int i = 1; i <= n; i++) {
String temp = q.poll();
if (valid(temp)) {
answer.add(temp);
found = true;
}
for (int j = 0; j < temp.length(); j++) {
if (Character.isLetter(temp.charAt(j)))
continue;
String form = temp.substring(0, j) + temp.substring(j + 1);
if (!visited.contains(form)){
q.add(form);
visited.add(form);
}
}
}
}
}
public void dfs_5(String str, int idx, int rem, StringBuilder cur_str, int left, int right, int leftrem,
int rightrem) {
if (idx == str.length()) {
if (valid(cur_str.toString())) {
if (rem == min) {
answer.add(cur_str.toString());
} else if (rem < min) {
answer.clear();
answer.add(cur_str.toString());
min = rem;
}
}
} else {
char ch = str.charAt(idx);
if (ch == '(' || ch == ')') {
if (ch == '(') {
if (leftrem > 0)
dfs_5(str, idx + 1, rem + 1, cur_str, left, right, leftrem - 1, rightrem);
cur_str.append(ch);
dfs_5(str, idx + 1, rem, cur_str, left + 1, right, leftrem, rightrem);
cur_str.deleteCharAt(cur_str.length() - 1);
} else {
if (rightrem > 0)
dfs_5(str, idx + 1, rem + 1, cur_str, left, right, leftrem, rightrem - 1);
if (left > right) {
cur_str.append(ch);
dfs_5(str, idx + 1, rem, cur_str, left, right + 1, leftrem, rightrem);
cur_str.deleteCharAt(cur_str.length() - 1);
}
}
} else {
cur_str.append(ch);
dfs_4(str, idx + 1, rem, cur_str, left, right);
cur_str.deleteCharAt(cur_str.length() - 1);
}
}
}
public void dfs_4(String str, int idx, int rem, StringBuilder cur_str, int left, int right) {
if (idx == str.length()) {
if (valid(cur_str.toString())) {
if (rem == min) {
answer.add(cur_str.toString());
} else if (rem < min) {
answer.clear();
answer.add(cur_str.toString());
min = rem;
}
}
} else {
char ch = str.charAt(idx);
if (ch == '(' || ch == ')') {
if (ch == '(') {
dfs_4(str, idx + 1, rem + 1, cur_str, left, right);
cur_str.append(ch);
dfs_4(str, idx + 1, rem, cur_str, left + 1, right);
cur_str.deleteCharAt(cur_str.length() - 1);
} else {
dfs_4(str, idx + 1, rem + 1, cur_str, left, right);
if (left > right) {
cur_str.append(ch);
dfs_4(str, idx + 1, rem, cur_str, left, right + 1);
cur_str.deleteCharAt(cur_str.length() - 1);
}
}
} else {
cur_str.append(ch);
dfs_4(str, idx + 1, rem, cur_str, left, right);
cur_str.deleteCharAt(cur_str.length() - 1);
}
}
}
public void dfs_3(String str, int idx, int rem, StringBuilder cur_str) {
if (idx == str.length()) {
if (valid(cur_str.toString())) {
if (rem == min) {
answer.add(cur_str.toString());
} else if (rem < min) {
answer.clear();
answer.add(cur_str.toString());
min = rem;
}
}
} else {
char ch = str.charAt(idx);
if (ch == '(' || ch == ')') {
dfs_3(str, idx + 1, rem + 1, cur_str);
cur_str.append(ch);
dfs_3(str, idx + 1, rem, cur_str);
cur_str.deleteCharAt(cur_str.length() - 1);
} else {
cur_str.append(ch);
dfs_3(str, idx + 1, rem, cur_str);
cur_str.deleteCharAt(cur_str.length() - 1);
}
}
}
public void dfs_1(String str, int idx, int rem) {
if (idx == str.length()) {
if (valid(str)) {
if (rem == min) {
answer.add(str);
} else if (rem < min) {
answer.clear();
answer.add(str);
min = rem;
}
}
} else {
char ch = str.charAt(idx);
if (ch == '(' || ch == ')') {
String remStr = str.substring(0, idx) + str.substring(idx + 1, str.length());
dfs_1(remStr, idx, rem + 1);
dfs_1(str, idx + 1, rem);
} else {
dfs_1(str, idx + 1, rem);
}
}
}
private boolean valid(String str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '(')
count += 1;
else if (str.charAt(i) == ')')
count -= 1;
if (count < 0)
return false;
}
if (count == 0)
return true;
else
return false;
}
public int[] calculateParenthesis(String s) {
int c = 0;
int rightParen = 0;
int leftParen = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(')
c++;
else if (s.charAt(i) == ')')
c--;
if (c < 0) {
c = 0;
rightParen++;
}
}
c = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == ')')
c++;
else if (s.charAt(i) == '(')
c--;
if (c < 0) {
c = 0;
leftParen++;
}
}
// System.out.println(leftParen + " " + rightParen);
return new int[] { leftParen, rightParen };
}
public static void main(String[] args) {
RemoveInvalidParentheses obj = new RemoveInvalidParentheses();
obj.removeInvalidParentheses("()(((((((()");
}
} | 7,927 | 0.391699 | 0.37858 | 252 | 30.460318 | 22.09778 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.964286 | false | false | 4 |
31cc7f95151a37c4fb5489c71ca1861ee39693af | 29,394,756,174,726 | b964b59c131053eccdebcd2113dcfe109cf71c62 | /ODIExtension/src/com/likya/xsd/myra/ext/odi/impl/OdiExtPropertiesImpl.java | 3d928604eb5ed52c29f7bae72485a3d50f9c929c | [] | no_license | nihavend/pinaragroup | https://github.com/nihavend/pinaragroup | dcb495da080a914358a8c494585b147ca07fd867 | 3beaac10860f349ae2cb14441f73d7c3c222588f | refs/heads/master | "2022-02-27T06:35:10.414000" | "2017-09-19T21:31:00" | "2017-09-19T21:31:00" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* XML Type: odiExtProperties
* Namespace: http://www.likyateknoloji.com/odi-ext
* Java type: com.likya.xsd.myra.ext.odi.OdiExtProperties
*
* Automatically generated - do not modify.
*/
package com.likya.xsd.myra.ext.odi.impl;
/**
* An XML odiExtProperties(@http://www.likyateknoloji.com/odi-ext).
*
* This is a complex type.
*/
public class OdiExtPropertiesImpl extends com.likya.xsd.myra.model.joblist.impl.AbstractJobTypeImpl implements com.likya.xsd.myra.ext.odi.OdiExtProperties
{
private static final long serialVersionUID = 1L;
public OdiExtPropertiesImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName ODIEXTPARAMS$0 =
new javax.xml.namespace.QName("http://www.likyateknoloji.com/odi-ext", "odiExtParams");
/**
* Gets the "odiExtParams" element
*/
public com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams getOdiExtParams()
{
synchronized (monitor())
{
check_orphaned();
com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams target = null;
target = (com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams)get_store().find_element_user(ODIEXTPARAMS$0, 0);
if (target == null)
{
return null;
}
return target;
}
}
/**
* Sets the "odiExtParams" element
*/
public void setOdiExtParams(com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams odiExtParams)
{
synchronized (monitor())
{
check_orphaned();
com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams target = null;
target = (com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams)get_store().find_element_user(ODIEXTPARAMS$0, 0);
if (target == null)
{
target = (com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams)get_store().add_element_user(ODIEXTPARAMS$0);
}
target.set(odiExtParams);
}
}
/**
* Appends and returns a new empty "odiExtParams" element
*/
public com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams addNewOdiExtParams()
{
synchronized (monitor())
{
check_orphaned();
com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams target = null;
target = (com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams)get_store().add_element_user(ODIEXTPARAMS$0);
return target;
}
}
}
| UTF-8 | Java | 2,649 | java | OdiExtPropertiesImpl.java | Java | [] | null | [] | /*
* XML Type: odiExtProperties
* Namespace: http://www.likyateknoloji.com/odi-ext
* Java type: com.likya.xsd.myra.ext.odi.OdiExtProperties
*
* Automatically generated - do not modify.
*/
package com.likya.xsd.myra.ext.odi.impl;
/**
* An XML odiExtProperties(@http://www.likyateknoloji.com/odi-ext).
*
* This is a complex type.
*/
public class OdiExtPropertiesImpl extends com.likya.xsd.myra.model.joblist.impl.AbstractJobTypeImpl implements com.likya.xsd.myra.ext.odi.OdiExtProperties
{
private static final long serialVersionUID = 1L;
public OdiExtPropertiesImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName ODIEXTPARAMS$0 =
new javax.xml.namespace.QName("http://www.likyateknoloji.com/odi-ext", "odiExtParams");
/**
* Gets the "odiExtParams" element
*/
public com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams getOdiExtParams()
{
synchronized (monitor())
{
check_orphaned();
com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams target = null;
target = (com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams)get_store().find_element_user(ODIEXTPARAMS$0, 0);
if (target == null)
{
return null;
}
return target;
}
}
/**
* Sets the "odiExtParams" element
*/
public void setOdiExtParams(com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams odiExtParams)
{
synchronized (monitor())
{
check_orphaned();
com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams target = null;
target = (com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams)get_store().find_element_user(ODIEXTPARAMS$0, 0);
if (target == null)
{
target = (com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams)get_store().add_element_user(ODIEXTPARAMS$0);
}
target.set(odiExtParams);
}
}
/**
* Appends and returns a new empty "odiExtParams" element
*/
public com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams addNewOdiExtParams()
{
synchronized (monitor())
{
check_orphaned();
com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams target = null;
target = (com.likya.xsd.myra.ext.odi.OdiExtParamsDocument.OdiExtParams)get_store().add_element_user(ODIEXTPARAMS$0);
return target;
}
}
}
| 2,649 | 0.636467 | 0.633447 | 76 | 33.855263 | 38.377182 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.276316 | false | false | 4 |
993a3ec57d3bb6e3ccbd0dd761dae98abfff2502 | 33,363,305,987,214 | 2ff85b401feca5a1205ae538fe5e4d3f41e1230a | /trade-common-infrastructure/src/main/java/com/trade/common/infrastructure/util/httpclient/OkHttpClientUtils.java | 3206d0b899b9afeb1bf787136be2a76971897761 | [] | no_license | axlwish/itrade-master | https://github.com/axlwish/itrade-master | 79964017469cb13154c1b176dad91b10c4620c22 | bfd1bcd22be94783aefbf2f0ea0bce6a590953ac | refs/heads/master | "2020-04-01T06:39:13.127000" | "2018-12-17T09:33:12" | "2018-12-17T09:33:12" | 152,957,460 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.trade.common.infrastructure.util.httpclient;
import com.google.common.base.Strings;
import com.trade.common.infrastructure.util.proxyserver.ProxyServerStatusUtils;
import okhttp3.*;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.HttpHostConnectException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.time.LocalTime;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class OkHttpClientUtils {
// Logger
protected static final Logger s_logger = LoggerFactory.getLogger(OkHttpClientUtils.class);
// 相关常量
public static final String mediaTypeJson = "application/json";
// s_okHttpClient
private static final OkHttpClient s_okHttpClient;
static {
s_okHttpClient = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS).readTimeout(180, TimeUnit.SECONDS).build();
}
/**
* 抓取目标页面源代码(GET)
*
* @param url
* @return
*/
public static String getHTML(String url) {
return doGetHTML(s_okHttpClient, url, null, "", "", null, true);
}
public static String postJson(String postUrl, String json) {
String result = "";
Request.Builder builder = new Request.Builder();
builder.url(postUrl);
//设置 postData
if (json != null) {
builder.post(RequestBody.create(MediaType.parse("application/json"), json));
}
try {
Request request = builder.build();
Response response = s_okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
result = response.body().string();
}
} catch (SocketTimeoutException ex) {
if (ex != null) {
s_logger.error("ConnectTimeoutException:" + calErrorLogInfo(postUrl, null, ex.toString()));
}
} catch (ConnectTimeoutException ex) {
if (ex != null) {
s_logger.error("ConnectTimeoutException:" + calErrorLogInfo(postUrl, null, ex.toString()));
}
} catch (HttpHostConnectException ex) {
if (ex != null) {
s_logger.error("HttpHostConnectException:" + calErrorLogInfo(postUrl, null, ex.toString()));
}
} catch (Exception ex) {
s_logger.error("HttpHostConnectException:" + calErrorLogInfo(postUrl, null, ex.toString()));
}
return result;
}
/**
* 抓取目标页面源代码
*
* @param url
* @param postData
* @param proxyServer
* @param refererUrl
* @param additionalHeaders
* @return
*/
public static String getHTML(String url, RequestBody postData, String proxyServer, String refererUrl, Map<String, String> additionalHeaders) {
return OkHttpClientUtils.doGetHTML(s_okHttpClient, url, postData, proxyServer, refererUrl, additionalHeaders, true);
}
/**
* 执行抓取目标页面源代码
*
* @param okHttpClient
* @param postUrl
* @param postData
* @param proxyServer
* @param refererUrl
* @param additionalHeaders
* @param isInitBrowserHeader
* @return
*/
public static String doGetHTML(OkHttpClient okHttpClient, final String postUrl, final RequestBody postData,
final String proxyServer, final String refererUrl, final Map<String, String> additionalHeaders,
boolean isInitBrowserHeader) {
String result = "";
// 计算相关变量
LocalTime startTime = LocalTime.now();
boolean hasAdditionalHeaders = additionalHeaders != null && additionalHeaders.size() > 0;
boolean isRemoveProxyServer = false;
Request.Builder builder = new Request.Builder();
builder.url(postUrl);
//设置 postData
if (postData != null) {
builder.post(postData);
}
// 设置其他 Header
if (isInitBrowserHeader) {
// for (Header header : HttpClientUtils.s_headers) {
// builder.addHeader(header.getName(), header.getValue());
// }
}
if (hasAdditionalHeaders) {
for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
builder.addHeader(entry.getKey(), entry.getValue());
}
}
if (!refererUrl.equals("")) {
builder.addHeader("Referer", refererUrl);
}
try {
Request request = builder.build();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
result = response.body().string();
}
} catch (SocketTimeoutException ex) {
if (ex != null) {
isRemoveProxyServer = true;
s_logger.error("ConnectTimeoutException:" + calErrorLogInfo(postUrl, proxyServer, ex.toString()));
}
} catch (ConnectTimeoutException ex) {
if (ex != null) {
isRemoveProxyServer = true;
s_logger.error("ConnectTimeoutException:" + calErrorLogInfo(postUrl, proxyServer, ex.toString()));
}
} catch (HttpHostConnectException ex) {
if (ex != null) {
isRemoveProxyServer = true;
s_logger.error("HttpHostConnectException:" + calErrorLogInfo(postUrl, proxyServer, ex.toString()));
}
} catch (Exception ex) {
s_logger.error("HttpHostConnectException:" + calErrorLogInfo(postUrl, proxyServer, ex.toString()));
}
//记录proxy状态
ProxyServerStatusUtils.recordProxyStatus(postUrl, proxyServer, isRemoveProxyServer, startTime, s_logger);
return result;
}
public static InputStream getStream(final String url) {
Request.Builder builder = new Request.Builder();
builder.url(url);
try {
Request request = builder.build();
Response response = s_okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().byteStream();
}
} catch (Exception ex) {
s_logger.error("HttpHostConnectException:" + url);
}
return null;
}
/**
* 创建 RequestBody
*
* @param mediaType
* @param postData
* @return
*/
public static RequestBody buildRequestBody(String mediaType, String postData) {
return RequestBody.create(MediaType.parse(mediaType), postData);
}
/**
* 创建出错时的错误信息
*
* @param postUrl
* @param proxyServer
* @param exString
* @return
*/
public static String calErrorLogInfo(final String postUrl, final String proxyServer, final String exString) {
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("postUrl=\"");
sBuilder.append(postUrl);
sBuilder.append("\", proxyServer=\"");
sBuilder.append(proxyServer);
sBuilder.append("\"");
if (!Strings.isNullOrEmpty(exString)) {
sBuilder.append(", exString=\"");
sBuilder.append(exString);
sBuilder.append("\"");
}
return sBuilder.toString();
}
/**
* OkHttpClient downloadFile
*
* @param saveFullPath
* @param downloadUrl
*/
public static void downloadFile(String saveFullPath, String downloadUrl) {
try {
Request request = new Request.Builder().url(downloadUrl).build();
Response response = s_okHttpClient.newCall(request).execute();
if (!response.isSuccessful()) {
s_logger.error(String.format("Failed to download file: response=%s", response));
return;
}
File f = new File(saveFullPath);
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
FileOutputStream fos = new FileOutputStream(saveFullPath);
fos.write(response.body().bytes());
fos.close();
} catch (Exception ex) {
s_logger.error(String.format("downloadFileSync error=%s", ex.toString()));
}
}
/**
* OkHttpClient downloadFileBytes
*
* @param downloadUrl
*/
public static byte[] downloadFileBytes(String downloadUrl) {
byte[] result = null;
try {
Request request = new Request.Builder().url(downloadUrl).build();
Response response = s_okHttpClient.newCall(request).execute();
if (!response.isSuccessful()) {
s_logger.error(String.format("Failed to download file: response=%s", response));
return null;
}
result = response.body().bytes();
} catch (Exception ex) {
s_logger.error(String.format("downloadFileSync error=%s", ex.toString()));
}
return result;
}
}
| UTF-8 | Java | 7,869 | java | OkHttpClientUtils.java | Java | [] | null | [] | package com.trade.common.infrastructure.util.httpclient;
import com.google.common.base.Strings;
import com.trade.common.infrastructure.util.proxyserver.ProxyServerStatusUtils;
import okhttp3.*;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.HttpHostConnectException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.time.LocalTime;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class OkHttpClientUtils {
// Logger
protected static final Logger s_logger = LoggerFactory.getLogger(OkHttpClientUtils.class);
// 相关常量
public static final String mediaTypeJson = "application/json";
// s_okHttpClient
private static final OkHttpClient s_okHttpClient;
static {
s_okHttpClient = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS).readTimeout(180, TimeUnit.SECONDS).build();
}
/**
* 抓取目标页面源代码(GET)
*
* @param url
* @return
*/
public static String getHTML(String url) {
return doGetHTML(s_okHttpClient, url, null, "", "", null, true);
}
public static String postJson(String postUrl, String json) {
String result = "";
Request.Builder builder = new Request.Builder();
builder.url(postUrl);
//设置 postData
if (json != null) {
builder.post(RequestBody.create(MediaType.parse("application/json"), json));
}
try {
Request request = builder.build();
Response response = s_okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
result = response.body().string();
}
} catch (SocketTimeoutException ex) {
if (ex != null) {
s_logger.error("ConnectTimeoutException:" + calErrorLogInfo(postUrl, null, ex.toString()));
}
} catch (ConnectTimeoutException ex) {
if (ex != null) {
s_logger.error("ConnectTimeoutException:" + calErrorLogInfo(postUrl, null, ex.toString()));
}
} catch (HttpHostConnectException ex) {
if (ex != null) {
s_logger.error("HttpHostConnectException:" + calErrorLogInfo(postUrl, null, ex.toString()));
}
} catch (Exception ex) {
s_logger.error("HttpHostConnectException:" + calErrorLogInfo(postUrl, null, ex.toString()));
}
return result;
}
/**
* 抓取目标页面源代码
*
* @param url
* @param postData
* @param proxyServer
* @param refererUrl
* @param additionalHeaders
* @return
*/
public static String getHTML(String url, RequestBody postData, String proxyServer, String refererUrl, Map<String, String> additionalHeaders) {
return OkHttpClientUtils.doGetHTML(s_okHttpClient, url, postData, proxyServer, refererUrl, additionalHeaders, true);
}
/**
* 执行抓取目标页面源代码
*
* @param okHttpClient
* @param postUrl
* @param postData
* @param proxyServer
* @param refererUrl
* @param additionalHeaders
* @param isInitBrowserHeader
* @return
*/
public static String doGetHTML(OkHttpClient okHttpClient, final String postUrl, final RequestBody postData,
final String proxyServer, final String refererUrl, final Map<String, String> additionalHeaders,
boolean isInitBrowserHeader) {
String result = "";
// 计算相关变量
LocalTime startTime = LocalTime.now();
boolean hasAdditionalHeaders = additionalHeaders != null && additionalHeaders.size() > 0;
boolean isRemoveProxyServer = false;
Request.Builder builder = new Request.Builder();
builder.url(postUrl);
//设置 postData
if (postData != null) {
builder.post(postData);
}
// 设置其他 Header
if (isInitBrowserHeader) {
// for (Header header : HttpClientUtils.s_headers) {
// builder.addHeader(header.getName(), header.getValue());
// }
}
if (hasAdditionalHeaders) {
for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
builder.addHeader(entry.getKey(), entry.getValue());
}
}
if (!refererUrl.equals("")) {
builder.addHeader("Referer", refererUrl);
}
try {
Request request = builder.build();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
result = response.body().string();
}
} catch (SocketTimeoutException ex) {
if (ex != null) {
isRemoveProxyServer = true;
s_logger.error("ConnectTimeoutException:" + calErrorLogInfo(postUrl, proxyServer, ex.toString()));
}
} catch (ConnectTimeoutException ex) {
if (ex != null) {
isRemoveProxyServer = true;
s_logger.error("ConnectTimeoutException:" + calErrorLogInfo(postUrl, proxyServer, ex.toString()));
}
} catch (HttpHostConnectException ex) {
if (ex != null) {
isRemoveProxyServer = true;
s_logger.error("HttpHostConnectException:" + calErrorLogInfo(postUrl, proxyServer, ex.toString()));
}
} catch (Exception ex) {
s_logger.error("HttpHostConnectException:" + calErrorLogInfo(postUrl, proxyServer, ex.toString()));
}
//记录proxy状态
ProxyServerStatusUtils.recordProxyStatus(postUrl, proxyServer, isRemoveProxyServer, startTime, s_logger);
return result;
}
public static InputStream getStream(final String url) {
Request.Builder builder = new Request.Builder();
builder.url(url);
try {
Request request = builder.build();
Response response = s_okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().byteStream();
}
} catch (Exception ex) {
s_logger.error("HttpHostConnectException:" + url);
}
return null;
}
/**
* 创建 RequestBody
*
* @param mediaType
* @param postData
* @return
*/
public static RequestBody buildRequestBody(String mediaType, String postData) {
return RequestBody.create(MediaType.parse(mediaType), postData);
}
/**
* 创建出错时的错误信息
*
* @param postUrl
* @param proxyServer
* @param exString
* @return
*/
public static String calErrorLogInfo(final String postUrl, final String proxyServer, final String exString) {
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("postUrl=\"");
sBuilder.append(postUrl);
sBuilder.append("\", proxyServer=\"");
sBuilder.append(proxyServer);
sBuilder.append("\"");
if (!Strings.isNullOrEmpty(exString)) {
sBuilder.append(", exString=\"");
sBuilder.append(exString);
sBuilder.append("\"");
}
return sBuilder.toString();
}
/**
* OkHttpClient downloadFile
*
* @param saveFullPath
* @param downloadUrl
*/
public static void downloadFile(String saveFullPath, String downloadUrl) {
try {
Request request = new Request.Builder().url(downloadUrl).build();
Response response = s_okHttpClient.newCall(request).execute();
if (!response.isSuccessful()) {
s_logger.error(String.format("Failed to download file: response=%s", response));
return;
}
File f = new File(saveFullPath);
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
FileOutputStream fos = new FileOutputStream(saveFullPath);
fos.write(response.body().bytes());
fos.close();
} catch (Exception ex) {
s_logger.error(String.format("downloadFileSync error=%s", ex.toString()));
}
}
/**
* OkHttpClient downloadFileBytes
*
* @param downloadUrl
*/
public static byte[] downloadFileBytes(String downloadUrl) {
byte[] result = null;
try {
Request request = new Request.Builder().url(downloadUrl).build();
Response response = s_okHttpClient.newCall(request).execute();
if (!response.isSuccessful()) {
s_logger.error(String.format("Failed to download file: response=%s", response));
return null;
}
result = response.body().bytes();
} catch (Exception ex) {
s_logger.error(String.format("downloadFileSync error=%s", ex.toString()));
}
return result;
}
}
| 7,869 | 0.695309 | 0.694147 | 282 | 26.443262 | 29.189257 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.148936 | false | false | 4 |
459363d8515592fc5a57b92e1a40262b5fde73cd | 11,802,570,145,648 | 55b5bfc5111a29dd4f3dd13ac56ec456a745fcee | /kunde/src/main/java/de/hska/kunde/config/dev/LogAlleKunden.java | 5cc333cec938a51311c1518a5f35a2e5764cc736 | [
"MIT"
] | permissive | LangeJustin/CRM-Microservice | https://github.com/LangeJustin/CRM-Microservice | 208a536e48e0c9e2bb0165f831255aeae2d1e242 | fdb0caf512141c36e650ab1ea07f319f5415af1a | refs/heads/master | "2021-06-23T01:50:19.744000" | "2017-08-04T15:44:27" | "2017-08-04T15:44:27" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.hska.kunde.config.dev;
import de.hska.kunde.service.KundeService;
import lombok.val;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Description;
import org.springframework.context.annotation.Profile;
import static de.hska.kunde.config.Settings.DEV_PROFILE;
import static org.apache.logging.log4j.LogManager.getLogger;
/**
* Einen CommandLineRunner zur Ausgabe aller bereitstellen.
* @author <a href="mailto:Juergen.Zimmermann@HS-Karlsruhe.de">
* Jürgen Zimmermann</a>
*/
public interface LogAlleKunden {
/**
* Spring Bean, um einen CommandLineRunner für das Profil "dev"
* bereitzustellen.
* @param kundeService Injiziertes Service-Objekt, um die Kunden auszulesen
* @return CommandLineRunner
*/
@Bean
@Qualifier("LogAlleKundenRunner")
@Description("Ausgabe aller Kunden beim Start des Microservice")
@Profile(DEV_PROFILE)
default CommandLineRunner logAlleKunden(KundeService kundeService) {
final val log = getLogger();
return args -> kundeService.findAll().forEach(log::warn);
}
}
| UTF-8 | Java | 1,912 | java | LogAlleKunden.java | Java | [
{
"context": "e aller bereitstellen.\n * @author <a href=\"mailto:Juergen.Zimmermann@HS-Karlsruhe.de\">\n * Jürgen Zimmermann</a>\n */\npubli",
"end": 1281,
"score": 0.9997453093528748,
"start": 1247,
"tag": "EMAIL",
"value": "Juergen.Zimmermann@HS-Karlsruhe.de"
},
{
"context": "to:Juergen.Zimmermann@HS-Karlsruhe.de\">\n * Jürgen Zimmermann</a>\n */\npublic interface LogAlleKunden {\n /**\n",
"end": 1317,
"score": 0.9915878772735596,
"start": 1295,
"tag": "NAME",
"value": "Jürgen Zimmermann"
}
] | null | [] | /*
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.hska.kunde.config.dev;
import de.hska.kunde.service.KundeService;
import lombok.val;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Description;
import org.springframework.context.annotation.Profile;
import static de.hska.kunde.config.Settings.DEV_PROFILE;
import static org.apache.logging.log4j.LogManager.getLogger;
/**
* Einen CommandLineRunner zur Ausgabe aller bereitstellen.
* @author <a href="mailto:<EMAIL>">
* <NAME></a>
*/
public interface LogAlleKunden {
/**
* Spring Bean, um einen CommandLineRunner für das Profil "dev"
* bereitzustellen.
* @param kundeService Injiziertes Service-Objekt, um die Kunden auszulesen
* @return CommandLineRunner
*/
@Bean
@Qualifier("LogAlleKundenRunner")
@Description("Ausgabe aller Kunden beim Start des Microservice")
@Profile(DEV_PROFILE)
default CommandLineRunner logAlleKunden(KundeService kundeService) {
final val log = getLogger();
return args -> kundeService.findAll().forEach(log::warn);
}
}
| 1,869 | 0.748431 | 0.747385 | 50 | 37.240002 | 27.216583 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.42 | false | false | 4 |
ac7e5b06d10287736ba3ecab1c88266e3eac7261 | 12,833,362,292,073 | 77195c85690b8c4ec72332e83ce7aa83b00adae9 | /src/main/java/me/suesslab/rogueblight/uix/gui/NotificationWindow.java | 8011a58f28d2f836dba78a6849abb65c7ca3bd74 | [] | no_license | RazeLighter777/sirenhead | https://github.com/RazeLighter777/sirenhead | d7d378b38dd35dd27eefdc8385dcc9bb5515ceb9 | eba01fbc7ad60c2829b1dfeb8d799e9530fe6b39 | refs/heads/master | "2023-01-02T20:43:05.327000" | "2020-05-28T15:06:01" | "2020-05-28T15:06:01" | 262,660,945 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.suesslab.rogueblight.uix.gui;
import com.googlecode.lanterna.gui2.*;
import java.util.Arrays;
public class NotificationWindow extends BasicWindow {
public NotificationWindow(String header, String notification) {
super(header);
setHints(Arrays.asList(Hint.CENTERED));
Panel panel = new Panel();
Label label = new Label(notification);
Button button = new Button("OK", () -> close());
panel.addComponent(label);
panel.addComponent(button);
setComponent(panel);
}
}
| UTF-8 | Java | 549 | java | NotificationWindow.java | Java | [] | null | [] | package me.suesslab.rogueblight.uix.gui;
import com.googlecode.lanterna.gui2.*;
import java.util.Arrays;
public class NotificationWindow extends BasicWindow {
public NotificationWindow(String header, String notification) {
super(header);
setHints(Arrays.asList(Hint.CENTERED));
Panel panel = new Panel();
Label label = new Label(notification);
Button button = new Button("OK", () -> close());
panel.addComponent(label);
panel.addComponent(button);
setComponent(panel);
}
}
| 549 | 0.668488 | 0.666667 | 19 | 27.894737 | 21.058552 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.684211 | false | false | 4 |
58c3c4c8311f4c6251a14181a4fe25a35b97cb4d | 12,833,362,290,512 | 3e208f2bbdb83f5ee1de0e770f53cab6efd8cf07 | /iDost/src/com/example/idost/receiver/ResponsePoliceInfoReceiver.java | 9dd56add1a1cb11adb0fba5f56e99ec1f12fa8c8 | [] | no_license | androidgithubapp/iDost1.0 | https://github.com/androidgithubapp/iDost1.0 | 47916533c5f9aa976109c330b87402ba410331a8 | 164a856795a1e709adb3cfc7bf244423ccc97313 | refs/heads/master | "2020-06-04T14:04:15.356000" | "2014-01-28T17:42:14" | "2014-01-28T17:42:14" | 10,156,173 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.idost.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.widget.Button;
import com.example.idost.constant.AppCommonConstantsClass;
import com.example.idost.service.PoliceAddService;
public class ResponsePoliceInfoReceiver extends BroadcastReceiver{
public static final String ACTION_POL_ADD_RESP = "com.example.idost.service.POLICERESPONSE";
public static Button callPlcBtn;;
@Override
public void onReceive(Context context, Intent intent) {
if(!PoliceAddService.isPoliceExceptionOccured)
{
callPlcBtn.setText(AppCommonConstantsClass.CALL_POL);
AnimationDrawable callBtnLeft = (AnimationDrawable)callPlcBtn.getCompoundDrawables()[0];
if(callBtnLeft != null)
{
callBtnLeft.stop();
}
callPlcBtn.setCompoundDrawablesWithIntrinsicBounds( 0, 0, 0, 0);
callPlcBtn.setEnabled(true);
}
else{
callPlcBtn.setText(AppCommonConstantsClass.SERVICE_EXP);
callPlcBtn.setCompoundDrawablesWithIntrinsicBounds( 0, 0, 0, 0);
callPlcBtn.setEnabled(false);
}
}
}
| UTF-8 | Java | 1,219 | java | ResponsePoliceInfoReceiver.java | Java | [] | null | [] | package com.example.idost.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.widget.Button;
import com.example.idost.constant.AppCommonConstantsClass;
import com.example.idost.service.PoliceAddService;
public class ResponsePoliceInfoReceiver extends BroadcastReceiver{
public static final String ACTION_POL_ADD_RESP = "com.example.idost.service.POLICERESPONSE";
public static Button callPlcBtn;;
@Override
public void onReceive(Context context, Intent intent) {
if(!PoliceAddService.isPoliceExceptionOccured)
{
callPlcBtn.setText(AppCommonConstantsClass.CALL_POL);
AnimationDrawable callBtnLeft = (AnimationDrawable)callPlcBtn.getCompoundDrawables()[0];
if(callBtnLeft != null)
{
callBtnLeft.stop();
}
callPlcBtn.setCompoundDrawablesWithIntrinsicBounds( 0, 0, 0, 0);
callPlcBtn.setEnabled(true);
}
else{
callPlcBtn.setText(AppCommonConstantsClass.SERVICE_EXP);
callPlcBtn.setCompoundDrawablesWithIntrinsicBounds( 0, 0, 0, 0);
callPlcBtn.setEnabled(false);
}
}
}
| 1,219 | 0.746514 | 0.73913 | 37 | 30.945946 | 27.352499 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.945946 | false | false | 4 |
abc8a089cc08451fb9fcb6e766c4ee6834b949f0 | 6,442,450,975,967 | a081c909bc7c4329e076cd871c8d87c21649fe8a | /src/main/java/Abstraccion/RealMadrid.java | ef8a429724fbed2e7a99019b82a2b6a1aa75bd6f | [] | no_license | Josuegomez03/Encapsulamientoyabstraccio | https://github.com/Josuegomez03/Encapsulamientoyabstraccio | 69f90471ff49be6d3524531ae8c6c9a63834addd | a494c87a5384ea036312e934eb13dd6e180e0961 | refs/heads/master | "2023-06-15T18:54:08.605000" | "2021-07-14T03:42:51" | "2021-07-14T03:42:51" | 385,487,859 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Abstraccion;
public class RealMadrid extends Equipo{
@Override
public String getequipo() {
return "Real Madrid";
}
@Override
public String getcapitan() {
return "Sergio Ramoz";
}
}
| UTF-8 | Java | 254 | java | RealMadrid.java | Java | [] | null | [] |
package Abstraccion;
public class RealMadrid extends Equipo{
@Override
public String getequipo() {
return "Real Madrid";
}
@Override
public String getcapitan() {
return "Sergio Ramoz";
}
}
| 254 | 0.566929 | 0.566929 | 16 | 13.75 | 13.727254 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1875 | false | false | 4 |
e5529f19ede5bf7d18f68e552f92431cb4d4aa4b | 7,327,214,272,018 | 6bb47c9bfe8081a4c1f2748f3c62a3e6f57cbff6 | /src/Automatas/Dibujar.java | c6dd94d2aa16fbfecbb5665b558be46e5e68c0f4 | [] | no_license | Juampa852/Automatas1 | https://github.com/Juampa852/Automatas1 | 59b75750542c53791fb51485d9c5788c3a3736c3 | 2c05d12185c298eb63c6b4f192ca247c7f831df7 | refs/heads/master | "2021-01-18T13:12:30.765000" | "2017-04-24T17:39:26" | "2017-04-24T17:39:26" | 80,737,179 | 0 | 0 | null | false | "2017-04-24T16:10:05" | "2017-02-02T15:14:24" | "2017-02-02T15:18:49" | "2017-04-24T16:10:05" | 162 | 0 | 0 | 0 | Java | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Automatas;
import Excepciones.EstadoNoExiste;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**Clase que hereda de JPanel
*permite dibujar un automata en una frame
* @author Roberto Arriola
*/
public class Dibujar extends JPanel{
JFrame ventana= new JFrame("Automata");//Se crea un nuevo frame
private Automata automataPrueba=new Automata();
private boolean arrastrando=false;
private int xAnterior=0, yAnterior=0;
estadoG estadoArrastrado=null;
private ArrayList<estadoG> estados=new ArrayList<>();
private MouseMotionListener mm= new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
if(!arrastrando)
{
xAnterior=e.getX();
yAnterior=e.getY();
arrastrando=true;
estadoArrastrado=estaDentroDeCirculo(xAnterior, yAnterior);
}
else
{
if(estadoArrastrado!=null)
{
estadoArrastrado.x=estadoArrastrado.x+(e.getX()-xAnterior);
estadoArrastrado.y=estadoArrastrado.y+(e.getY()-yAnterior);
xAnterior=e.getX();
yAnterior=e.getY();
repaint();
}
}
}
@Override
public void mouseMoved(MouseEvent e) {
arrastrando=false;
}
};
private MouseListener ml= new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
};
/**
* Constructor de la clase que dibuja el automata
* Genera un arreglo de estados graficos marcando en la primera posicion el estado inicial
* @param auto automata a dibujar
* @throws Excepciones.EstadoNoExiste
* @throws java.lang.InterruptedException
*/
public Dibujar(Automata auto) throws EstadoNoExiste, InterruptedException
{
if(auto.getPocEstadoInicial()>-1)
{
actualizar(auto);
this.setBackground(Color.WHITE);
ventana.addMouseListener(ml);
ventana.addMouseMotionListener(mm);
ventana.add(this);//Añade el lienzo al frame
ventana.setVisible(true);//Hace visible todo el frame
}
}
/**
* metodo para actualizar el dibujo del automata
* @param auto automata a sibujar
* @throws Excepciones.EstadoNoExiste
* @throws java.lang.InterruptedException
*/
public void actualizar(Automata auto) throws EstadoNoExiste, InterruptedException
{
estados=new ArrayList<>();
int cuadrado=1;//se inicia un contador para calcular la raiz cuadrada exacta minima necesaria
//para distribuir los estados en una matriz cuadrada
while(Math.pow(cuadrado, 2)<auto.noEstados())//Cuando el cuadrado de la base es mayor al numero de estados
//se encuentra la raiz minima
{
cuadrado++;
}
estadoG ini= new estadoG(auto.getEstado(auto.getPocEstadoInicial()),50, 50);//se genera el estado grafico inicial
estadoG est;
estados.add(ini);//se añade como primer elemento el estado inicial al arreglo de estados graficos
int col=1, fil=0;
for(int o=0;o<auto.noEstados();o++)//se recorre el arreglo de estados del automata, para agregarlas a un estado grafico
//y añadirlos en el arreglo de la clase dibujar
{
est = new estadoG(auto.getEstado(o),150*col+50, 50+150*fil);//se les asignan posiciones en X y Y dependiendo del recorrido
if(!ini.est.getNombre().equals(est.est.getNombre()))//se evita agregar el estado inicial dos veces
{
estados.add(est);
col++;
if(col==cuadrado)
{
col=0;
fil++;
}
}
}
calcularDimensiones();
repaint();
ventana.setVisible(true);//Hace visible todo el frame
}
/**
* Método que genera las dimensiones de la ventana dependiendo del numero de estados
* Este mpetodo busca que las dimensiones permitan dibujar los estados como una matriz cuadrada
* utilizando el cuadrado entero superior, por ejemplo, si existen 7 estados, se acomodan en una matriz de 3x3 (9)
*/
private void calcularDimensiones()
{
int cuadrado=1;//Entero que almacena la raiz exacta minima N, de forma que pudan guardarse los estados como una matriz NxN
while(Math.pow(cuadrado, 2)<estados.size())
{
cuadrado++;
}
int x=cuadrado, y=1;
while(y*x<estados.size())//se calculan las dimensiones, calculando cuantos estados iran en X y cuantos en Y
{
y++;
}
x=(x)*100+(x+1)*50; //Se multiplican el numero de estados en X por 2 veces el radio de los ovalos
//y se suman la cantidad de espacios entre estados*radio
y=(y)*100+(y+2)*50; //se calcula igual que x
ventana.setSize(x,y);//se le da al frame estas dimensiones
}
@Override
public void paint(Graphics g)
{
super.paint(g);
for(int i=0;i<estados.size();i++)
{
dibujarEstado(i,estados.get(i),g);
}
}
/**
* Metodo que dibuja en el panel un estado grafico, una flecha si este es inicial,un doble circulo si es final
* @param posicion posicion que tiene el estado grafico en el arreglo de la clase
* @param estG el objeto estado grafico a dibujar
* @param g objeto de tipo graphics que permite realizar dibujos en el panel
*/
private void dibujarEstado(int posicion, estadoG estG,Graphics g){
Graphics2D g2d= (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if(posicion==0)
{
g2d.drawLine(estG.x-30,estG.y+20, estG.x,estG.y+50);
g2d.drawLine(estG.x-30,estG.y+80, estG.x,estG.y+50);
}
g2d.setColor(asignarColor(posicion));
g2d.fillOval(estG.x,estG.y,100,100);
g2d.setColor(Color.BLACK);
g2d.drawOval(estG.x,estG.y,100,100);
if(estG.est.isFinal())
{
g2d.drawOval(estG.x+10,estG.y+10,80,80);
}
g2d.drawChars(estG.est.getNombre().toCharArray(), 0,estG.est.getNombre().length() ,estG.x+50,estG.y+50);
g2d.setColor(asignarColor(posicion));
if(estG.est.getTransiciones().size()>0)
{
for (Transicion trans : estG.est.getTransiciones()) {
estadoG t=buscarEstado(trans);
String caracteres=concatenar(t,estG.est.getTransiciones());
if(!estG.est.getNombre().equals(t.est.getNombre()))
{
double angulo=Math.atan2(t.y-estG.y, t.x-estG.x);
g2d.drawLine(estG.x+50+(int)(Math.cos(angulo)*50), estG.y+50+(int)(Math.sin(angulo)*50), t.x+50-(int)(Math.cos(angulo)*50), t.y+50-(int)(Math.sin(angulo)*50));
g2d.fillOval(t.x+50-(int)(Math.cos(angulo)*50)-3, t.y+50-(int)(Math.sin(angulo)*50)-3, 7, 7);
double lx,ly,L,dx,dy;
lx=t.x-estG.x-(Math.cos(angulo)*100);
ly=t.y-estG.y-(Math.sin(angulo)*100);
L=(Math.sqrt(Math.pow(lx, 2)+Math.pow(ly, 2)))/2;
if(0<=Math.acos(angulo))
{
dx=(10+caracteres.length()*5)*Math.sin(angulo);
}
else
{
dx=10*Math.sin(angulo);
}
if(0<=Math.asin(angulo))
{
dy=15*Math.cos(angulo);
}
else
{
dy=10*Math.cos(angulo);
}
g2d.drawChars(caracteres.toCharArray(),0,caracteres.length(),estG.x+50+(int)((L+50)*Math.cos(angulo)+dx),estG.y+50+(int)((L+50)*Math.sin(angulo)+dy));
}
else
{
g2d.drawOval(estG.x+30-(int)(50*Math.sin(45)), estG.y+30-(int)(50*Math.sin(45)), 30, 30);
g2d.fillOval(estG.x+50-(int)(50*Math.sin(45))+3, estG.y+50-(int)(50*Math.sin(45))+3, 6, 6);
g2d.drawChars(caracteres.toCharArray(),0,caracteres.length(),estG.x+30-(int)(50*Math.sin(45)), estG.y+30-(int)(50*Math.sin(45)));
}
}
}
}
/**
* Clase estado grafico, es una clase interna de la clase Dibujar
* Su funcion es almacenar un estado y la posicion que se le dara en el panel
* de esa forma, al graficar una transicion, puede conocerse las posiciones de los estados en el lienzo
*/
private class estadoG{
int x, y;
Estado est;
public estadoG(Estado est, int x, int y)
{
this.est=est;
this.x=x;
this.y=y;
}
}
/**
* Funcion que retorna una cadena con los caracteres que lleven a un mismo estado
* @param destino estado grafico al que se quiere acceder
* @param array arreglo de transiciones de un estado
* @return caracteres que llevan al estado destino
*/
private String concatenar(estadoG destino, ArrayList<Transicion> array)
{
String cadena="";
for (Transicion array1 : array) {
if(array1.getSiguiente().equals(destino.est.getNombre()))
cadena=cadena+array1.getLetra();
if(!array1.equals(array.get(array.size()-1)))
cadena=cadena+",";
}
if(cadena.length()<3)
{
String[] cadena1=cadena.split(",");
cadena="";
for (String cadena11 : cadena1) {
cadena += cadena11;
}
return cadena;
}
else
return cadena;
}
/**
* Funcion que busca un estadoGrafico en el arreglo de la clase y lo returna
* @param trans Onjeto trancision que se quiere buscar
* @return Estado buscado a partir de una transicion
*/
private estadoG buscarEstado(Transicion trans)
{
trans.getSiguiente();
for (estadoG estado : estados) {
if(estado.est.getNombre().equals(trans.getSiguiente()))
return estado;
}
return null;
}
/**
* Funcion que retorna colores, dependiendo del numero, teniendo 9 posibilidades
* @param posicion posicion en el arreglo de Estados gráficos
* @return color para dibujar el estado y sus transiciones
*/
private Color asignarColor(int posicion)
{
while(posicion>8)
{ posicion=posicion-9;}
switch (posicion) {
//case 1:
//return Color.BLACK;
case 1:
return Color.CYAN;
case 2:
return Color.GREEN;
case 3:
return Color.MAGENTA;
case 4:
return Color.ORANGE;
case 5:
return Color.RED;
case 6:
return Color.PINK;
case 7:
return Color.YELLOW;
default:
return Color.BLUE;
}
}
private estadoG estaDentroDeCirculo(int mouseX, int mouseY)
{
for(estadoG estado: estados)
{
if(mouseX>=estado.x && mouseX<=estado.x+100 && mouseY>=estado.y && mouseY<=estado.y+100)
{
return estado;
}
}
return null;
}
}
| UTF-8 | Java | 12,836 | java | Dibujar.java | Java | [
{
"context": "ermite dibujar un automata en una frame\n * @author Roberto Arriola\n */\npublic class Dibujar extends JPanel{\n JFra",
"end": 677,
"score": 0.9998873472213745,
"start": 662,
"tag": "NAME",
"value": "Roberto Arriola"
}
] | 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 Automatas;
import Excepciones.EstadoNoExiste;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**Clase que hereda de JPanel
*permite dibujar un automata en una frame
* @author <NAME>
*/
public class Dibujar extends JPanel{
JFrame ventana= new JFrame("Automata");//Se crea un nuevo frame
private Automata automataPrueba=new Automata();
private boolean arrastrando=false;
private int xAnterior=0, yAnterior=0;
estadoG estadoArrastrado=null;
private ArrayList<estadoG> estados=new ArrayList<>();
private MouseMotionListener mm= new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
if(!arrastrando)
{
xAnterior=e.getX();
yAnterior=e.getY();
arrastrando=true;
estadoArrastrado=estaDentroDeCirculo(xAnterior, yAnterior);
}
else
{
if(estadoArrastrado!=null)
{
estadoArrastrado.x=estadoArrastrado.x+(e.getX()-xAnterior);
estadoArrastrado.y=estadoArrastrado.y+(e.getY()-yAnterior);
xAnterior=e.getX();
yAnterior=e.getY();
repaint();
}
}
}
@Override
public void mouseMoved(MouseEvent e) {
arrastrando=false;
}
};
private MouseListener ml= new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
};
/**
* Constructor de la clase que dibuja el automata
* Genera un arreglo de estados graficos marcando en la primera posicion el estado inicial
* @param auto automata a dibujar
* @throws Excepciones.EstadoNoExiste
* @throws java.lang.InterruptedException
*/
public Dibujar(Automata auto) throws EstadoNoExiste, InterruptedException
{
if(auto.getPocEstadoInicial()>-1)
{
actualizar(auto);
this.setBackground(Color.WHITE);
ventana.addMouseListener(ml);
ventana.addMouseMotionListener(mm);
ventana.add(this);//Añade el lienzo al frame
ventana.setVisible(true);//Hace visible todo el frame
}
}
/**
* metodo para actualizar el dibujo del automata
* @param auto automata a sibujar
* @throws Excepciones.EstadoNoExiste
* @throws java.lang.InterruptedException
*/
public void actualizar(Automata auto) throws EstadoNoExiste, InterruptedException
{
estados=new ArrayList<>();
int cuadrado=1;//se inicia un contador para calcular la raiz cuadrada exacta minima necesaria
//para distribuir los estados en una matriz cuadrada
while(Math.pow(cuadrado, 2)<auto.noEstados())//Cuando el cuadrado de la base es mayor al numero de estados
//se encuentra la raiz minima
{
cuadrado++;
}
estadoG ini= new estadoG(auto.getEstado(auto.getPocEstadoInicial()),50, 50);//se genera el estado grafico inicial
estadoG est;
estados.add(ini);//se añade como primer elemento el estado inicial al arreglo de estados graficos
int col=1, fil=0;
for(int o=0;o<auto.noEstados();o++)//se recorre el arreglo de estados del automata, para agregarlas a un estado grafico
//y añadirlos en el arreglo de la clase dibujar
{
est = new estadoG(auto.getEstado(o),150*col+50, 50+150*fil);//se les asignan posiciones en X y Y dependiendo del recorrido
if(!ini.est.getNombre().equals(est.est.getNombre()))//se evita agregar el estado inicial dos veces
{
estados.add(est);
col++;
if(col==cuadrado)
{
col=0;
fil++;
}
}
}
calcularDimensiones();
repaint();
ventana.setVisible(true);//Hace visible todo el frame
}
/**
* Método que genera las dimensiones de la ventana dependiendo del numero de estados
* Este mpetodo busca que las dimensiones permitan dibujar los estados como una matriz cuadrada
* utilizando el cuadrado entero superior, por ejemplo, si existen 7 estados, se acomodan en una matriz de 3x3 (9)
*/
private void calcularDimensiones()
{
int cuadrado=1;//Entero que almacena la raiz exacta minima N, de forma que pudan guardarse los estados como una matriz NxN
while(Math.pow(cuadrado, 2)<estados.size())
{
cuadrado++;
}
int x=cuadrado, y=1;
while(y*x<estados.size())//se calculan las dimensiones, calculando cuantos estados iran en X y cuantos en Y
{
y++;
}
x=(x)*100+(x+1)*50; //Se multiplican el numero de estados en X por 2 veces el radio de los ovalos
//y se suman la cantidad de espacios entre estados*radio
y=(y)*100+(y+2)*50; //se calcula igual que x
ventana.setSize(x,y);//se le da al frame estas dimensiones
}
@Override
public void paint(Graphics g)
{
super.paint(g);
for(int i=0;i<estados.size();i++)
{
dibujarEstado(i,estados.get(i),g);
}
}
/**
* Metodo que dibuja en el panel un estado grafico, una flecha si este es inicial,un doble circulo si es final
* @param posicion posicion que tiene el estado grafico en el arreglo de la clase
* @param estG el objeto estado grafico a dibujar
* @param g objeto de tipo graphics que permite realizar dibujos en el panel
*/
private void dibujarEstado(int posicion, estadoG estG,Graphics g){
Graphics2D g2d= (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if(posicion==0)
{
g2d.drawLine(estG.x-30,estG.y+20, estG.x,estG.y+50);
g2d.drawLine(estG.x-30,estG.y+80, estG.x,estG.y+50);
}
g2d.setColor(asignarColor(posicion));
g2d.fillOval(estG.x,estG.y,100,100);
g2d.setColor(Color.BLACK);
g2d.drawOval(estG.x,estG.y,100,100);
if(estG.est.isFinal())
{
g2d.drawOval(estG.x+10,estG.y+10,80,80);
}
g2d.drawChars(estG.est.getNombre().toCharArray(), 0,estG.est.getNombre().length() ,estG.x+50,estG.y+50);
g2d.setColor(asignarColor(posicion));
if(estG.est.getTransiciones().size()>0)
{
for (Transicion trans : estG.est.getTransiciones()) {
estadoG t=buscarEstado(trans);
String caracteres=concatenar(t,estG.est.getTransiciones());
if(!estG.est.getNombre().equals(t.est.getNombre()))
{
double angulo=Math.atan2(t.y-estG.y, t.x-estG.x);
g2d.drawLine(estG.x+50+(int)(Math.cos(angulo)*50), estG.y+50+(int)(Math.sin(angulo)*50), t.x+50-(int)(Math.cos(angulo)*50), t.y+50-(int)(Math.sin(angulo)*50));
g2d.fillOval(t.x+50-(int)(Math.cos(angulo)*50)-3, t.y+50-(int)(Math.sin(angulo)*50)-3, 7, 7);
double lx,ly,L,dx,dy;
lx=t.x-estG.x-(Math.cos(angulo)*100);
ly=t.y-estG.y-(Math.sin(angulo)*100);
L=(Math.sqrt(Math.pow(lx, 2)+Math.pow(ly, 2)))/2;
if(0<=Math.acos(angulo))
{
dx=(10+caracteres.length()*5)*Math.sin(angulo);
}
else
{
dx=10*Math.sin(angulo);
}
if(0<=Math.asin(angulo))
{
dy=15*Math.cos(angulo);
}
else
{
dy=10*Math.cos(angulo);
}
g2d.drawChars(caracteres.toCharArray(),0,caracteres.length(),estG.x+50+(int)((L+50)*Math.cos(angulo)+dx),estG.y+50+(int)((L+50)*Math.sin(angulo)+dy));
}
else
{
g2d.drawOval(estG.x+30-(int)(50*Math.sin(45)), estG.y+30-(int)(50*Math.sin(45)), 30, 30);
g2d.fillOval(estG.x+50-(int)(50*Math.sin(45))+3, estG.y+50-(int)(50*Math.sin(45))+3, 6, 6);
g2d.drawChars(caracteres.toCharArray(),0,caracteres.length(),estG.x+30-(int)(50*Math.sin(45)), estG.y+30-(int)(50*Math.sin(45)));
}
}
}
}
/**
* Clase estado grafico, es una clase interna de la clase Dibujar
* Su funcion es almacenar un estado y la posicion que se le dara en el panel
* de esa forma, al graficar una transicion, puede conocerse las posiciones de los estados en el lienzo
*/
private class estadoG{
int x, y;
Estado est;
public estadoG(Estado est, int x, int y)
{
this.est=est;
this.x=x;
this.y=y;
}
}
/**
* Funcion que retorna una cadena con los caracteres que lleven a un mismo estado
* @param destino estado grafico al que se quiere acceder
* @param array arreglo de transiciones de un estado
* @return caracteres que llevan al estado destino
*/
private String concatenar(estadoG destino, ArrayList<Transicion> array)
{
String cadena="";
for (Transicion array1 : array) {
if(array1.getSiguiente().equals(destino.est.getNombre()))
cadena=cadena+array1.getLetra();
if(!array1.equals(array.get(array.size()-1)))
cadena=cadena+",";
}
if(cadena.length()<3)
{
String[] cadena1=cadena.split(",");
cadena="";
for (String cadena11 : cadena1) {
cadena += cadena11;
}
return cadena;
}
else
return cadena;
}
/**
* Funcion que busca un estadoGrafico en el arreglo de la clase y lo returna
* @param trans Onjeto trancision que se quiere buscar
* @return Estado buscado a partir de una transicion
*/
private estadoG buscarEstado(Transicion trans)
{
trans.getSiguiente();
for (estadoG estado : estados) {
if(estado.est.getNombre().equals(trans.getSiguiente()))
return estado;
}
return null;
}
/**
* Funcion que retorna colores, dependiendo del numero, teniendo 9 posibilidades
* @param posicion posicion en el arreglo de Estados gráficos
* @return color para dibujar el estado y sus transiciones
*/
private Color asignarColor(int posicion)
{
while(posicion>8)
{ posicion=posicion-9;}
switch (posicion) {
//case 1:
//return Color.BLACK;
case 1:
return Color.CYAN;
case 2:
return Color.GREEN;
case 3:
return Color.MAGENTA;
case 4:
return Color.ORANGE;
case 5:
return Color.RED;
case 6:
return Color.PINK;
case 7:
return Color.YELLOW;
default:
return Color.BLUE;
}
}
private estadoG estaDentroDeCirculo(int mouseX, int mouseY)
{
for(estadoG estado: estados)
{
if(mouseX>=estado.x && mouseX<=estado.x+100 && mouseY>=estado.y && mouseY<=estado.y+100)
{
return estado;
}
}
return null;
}
}
| 12,827 | 0.550698 | 0.532382 | 337 | 37.074184 | 31.670088 | 179 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.620178 | false | false | 4 |
62381ff77878a1c5fdabf40b7a6d58ba88dd3b85 | 26,285,199,877,343 | 7805cac43c94200567d328a37d5b1ea01bd4289a | /src/main/java/com/xym/myJava/head_first/_04/ChicagoPepperoniPizza.java | 65999dddc2bc53beac463e08e0d01175e047fbe7 | [] | no_license | xym-loveit/myJavaBaseProject | https://github.com/xym-loveit/myJavaBaseProject | 58c6606e4102b5c2395d5ddcf3db9de7575c53e8 | dd2dd52cdd59539b37e40d4f22590b451feed2f3 | refs/heads/master | "2022-12-21T05:55:07.838000" | "2019-08-26T09:39:39" | "2019-08-26T09:39:39" | 141,161,163 | 0 | 0 | null | false | "2022-12-10T03:18:13" | "2018-07-16T15:55:19" | "2019-08-26T09:39:55" | "2022-12-10T03:18:13" | 999 | 0 | 0 | 12 | Java | false | false | package com.xym.myJava.head_first._04;
/**
* 纽约风味
*
* @author xym
* @create 2019-04-10 10:40
*/
public class ChicagoPepperoniPizza extends Pizza {
PizzaIngredientFactory ingredientFactory;
/**
* 要制作pizza需要工厂提供原料,所以每个比萨类都需要从构造函数中得到一个工厂,并把工厂存储在实例变量中
*
* @param ingredientFactory
*/
public ChicagoPepperoniPizza(PizzaIngredientFactory ingredientFactory) {
this.ingredientFactory = ingredientFactory;
}
@Override
void prepare() {
System.out.println("Preparing " + getName());
this.dough = ingredientFactory.createDough();
this.sauce = ingredientFactory.createSauce();
this.cheese = ingredientFactory.createCheese();
}
@Override
public String getName() {
return "";
}
}
| UTF-8 | Java | 885 | java | ChicagoPepperoniPizza.java | Java | [
{
"context": ".myJava.head_first._04;\n\n/**\n * 纽约风味\n *\n * @author xym\n * @create 2019-04-10 10:40\n */\npublic class Chic",
"end": 69,
"score": 0.9996719360351562,
"start": 66,
"tag": "USERNAME",
"value": "xym"
}
] | null | [] | package com.xym.myJava.head_first._04;
/**
* 纽约风味
*
* @author xym
* @create 2019-04-10 10:40
*/
public class ChicagoPepperoniPizza extends Pizza {
PizzaIngredientFactory ingredientFactory;
/**
* 要制作pizza需要工厂提供原料,所以每个比萨类都需要从构造函数中得到一个工厂,并把工厂存储在实例变量中
*
* @param ingredientFactory
*/
public ChicagoPepperoniPizza(PizzaIngredientFactory ingredientFactory) {
this.ingredientFactory = ingredientFactory;
}
@Override
void prepare() {
System.out.println("Preparing " + getName());
this.dough = ingredientFactory.createDough();
this.sauce = ingredientFactory.createSauce();
this.cheese = ingredientFactory.createCheese();
}
@Override
public String getName() {
return "";
}
}
| 885 | 0.660281 | 0.642401 | 34 | 22.029411 | 22.261131 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.235294 | false | false | 4 |
5e26a810784616d567859bfda1a30062a6ad4356 | 10,153,302,736,741 | b1cb66a85c34cd6179f8ba20d78bbc82c6c1f25a | /app/src/main/java/com/amanachintyanikhil/blogapp/UserActivity.java | a835e56190d3ce6aaa609459268687bb5cc3cd2e | [] | no_license | codebu5ter/Sentiment-Analysis | https://github.com/codebu5ter/Sentiment-Analysis | 8bd5f9e8898433eccd91335a79a02a9a65dd051d | 58463ba4a2d843366b3ce7acb7eb97929ab40b72 | refs/heads/master | "2020-03-16T07:09:58.954000" | "2018-05-09T20:43:39" | "2018-05-09T20:43:39" | 132,570,321 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.amanachintyanikhil.blogapp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import twitter4j.ResponseList;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
/**
* Demonstrates how to use a twitter application keys to access a user's timeline
*/
public class UserActivity extends Activity {
String ScreenName;
final static String LOG_TAG = "rnc";
ListView lv_list;
Button analyze_all;
ArrayList<String> al_text = new ArrayList<>();
TweetAdapter obj_adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
ScreenName = getIntent().getStringExtra("user");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tweet);
lv_list = (ListView) findViewById(R.id.lv_list);
analyze_all = (Button) findViewById(R.id.button5);
downloadTweets();
}
// download twitter timeline after first checking to see if there is a network connection
public void downloadTweets() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadTwitterTask().execute(ScreenName);
} else {
Toast.makeText(getApplicationContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
}
}
// Uses an AsyncTask to download a Twitter user's timeline
private class DownloadTwitterTask extends AsyncTask<String, Void, String> {
final ProgressDialog dialog = new ProgressDialog(UserActivity.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setTitle("Loading");
dialog.setMessage("Please wait");
dialog.show();
}
@Override
protected String doInBackground(String... screenNames) {
try {
al_text.clear();
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("y5Bg6YO2fM9Y9S3gwBrdnNIH7")
.setOAuthConsumerSecret("Omi4lTpahtod9qYshJqPSyEJBpX3ZmApjxIsiqfbWIiXrDkf32")
.setOAuthAccessToken("970702870881361920-QhETWfuuLQ5k3f08CsuMSsyEKVj5Sri")
.setOAuthAccessTokenSecret("UALezWaAcH2UFXcfauDvFKWE0UCwrzgGEFa0StoUyU0ZP");
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
ResponseList<twitter4j.Status> statuses = twitter.getMentionsTimeline();
for (twitter4j.Status status : statuses) {
al_text.add(status.getText());
}
} catch (TwitterException e){
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
// onPostExecute convert the JSON results into a Twitter object (which is an Array list of tweets
@Override
protected void onPostExecute(String result) {
dialog.dismiss();
// send the tweets to the adapter for rendering
obj_adapter = new TweetAdapter(getApplicationContext(), al_text);
lv_list.setAdapter(obj_adapter);
lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String item = (String) lv_list.getItemAtPosition(i);
Intent intent = new Intent(UserActivity.this, ResultActivity.class);
intent.putExtra("TWEET", item);
startActivity(intent);
}
});
analyze_all.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String item = "";
for (int i = 0; i < lv_list.getCount(); i++) {
String iter = (String) lv_list.getItemAtPosition(i);
item = item + iter;
}
Intent intent = new Intent(UserActivity.this, ResultActivity.class);
intent.putExtra("TWEET", item);
startActivity(intent);
}
});
}
}
} | UTF-8 | Java | 4,982 | java | UserActivity.java | Java | [
{
"context": "package com.amanachintyanikhil.blogapp;\n\nimport android.app.Activity;\nimport and",
"end": 30,
"score": 0.8454088568687439,
"start": 12,
"tag": "USERNAME",
"value": "amanachintyanikhil"
},
{
"context": "ue)\n .setOAuthConsumerKey(\"y5Bg6YO2fM9Y9S3gwBrdnNIH7\")\n .setOAuthConsumerSecret",
"end": 2703,
"score": 0.8623466491699219,
"start": 2678,
"tag": "KEY",
"value": "y5Bg6YO2fM9Y9S3gwBrdnNIH7"
},
{
"context": "\n .setOAuthConsumerSecret(\"Omi4lTpahtod9qYshJqPSyEJBpX3ZmApjxIsiqfbWIiXrDkf32\")\n .setOAuthAccessToken(\"9",
"end": 2805,
"score": 0.9997687339782715,
"start": 2755,
"tag": "KEY",
"value": "Omi4lTpahtod9qYshJqPSyEJBpX3ZmApjxIsiqfbWIiXrDkf32"
},
{
"context": "2\")\n .setOAuthAccessToken(\"970702870881361920-QhETWfuuLQ5k3f08CsuMSsyEKVj5Sri\")\n .setOAuthAccessTokenSec",
"end": 2904,
"score": 0.9983581304550171,
"start": 2854,
"tag": "KEY",
"value": "970702870881361920-QhETWfuuLQ5k3f08CsuMSsyEKVj5Sri"
},
{
"context": " .setOAuthAccessTokenSecret(\"UALezWaAcH2UFXcfauDvFKWE0UCwrzgGEFa0StoUyU0ZP\");\n\n Twitter twitter = new Twitter",
"end": 3004,
"score": 0.9995689392089844,
"start": 2959,
"tag": "KEY",
"value": "UALezWaAcH2UFXcfauDvFKWE0UCwrzgGEFa0StoUyU0ZP"
}
] | null | [] | package com.amanachintyanikhil.blogapp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import twitter4j.ResponseList;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
/**
* Demonstrates how to use a twitter application keys to access a user's timeline
*/
public class UserActivity extends Activity {
String ScreenName;
final static String LOG_TAG = "rnc";
ListView lv_list;
Button analyze_all;
ArrayList<String> al_text = new ArrayList<>();
TweetAdapter obj_adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
ScreenName = getIntent().getStringExtra("user");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tweet);
lv_list = (ListView) findViewById(R.id.lv_list);
analyze_all = (Button) findViewById(R.id.button5);
downloadTweets();
}
// download twitter timeline after first checking to see if there is a network connection
public void downloadTweets() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadTwitterTask().execute(ScreenName);
} else {
Toast.makeText(getApplicationContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
}
}
// Uses an AsyncTask to download a Twitter user's timeline
private class DownloadTwitterTask extends AsyncTask<String, Void, String> {
final ProgressDialog dialog = new ProgressDialog(UserActivity.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setTitle("Loading");
dialog.setMessage("Please wait");
dialog.show();
}
@Override
protected String doInBackground(String... screenNames) {
try {
al_text.clear();
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("<KEY>")
.setOAuthConsumerSecret("<KEY>")
.setOAuthAccessToken("<KEY>")
.setOAuthAccessTokenSecret("<KEY>");
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
ResponseList<twitter4j.Status> statuses = twitter.getMentionsTimeline();
for (twitter4j.Status status : statuses) {
al_text.add(status.getText());
}
} catch (TwitterException e){
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
// onPostExecute convert the JSON results into a Twitter object (which is an Array list of tweets
@Override
protected void onPostExecute(String result) {
dialog.dismiss();
// send the tweets to the adapter for rendering
obj_adapter = new TweetAdapter(getApplicationContext(), al_text);
lv_list.setAdapter(obj_adapter);
lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String item = (String) lv_list.getItemAtPosition(i);
Intent intent = new Intent(UserActivity.this, ResultActivity.class);
intent.putExtra("TWEET", item);
startActivity(intent);
}
});
analyze_all.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String item = "";
for (int i = 0; i < lv_list.getCount(); i++) {
String iter = (String) lv_list.getItemAtPosition(i);
item = item + iter;
}
Intent intent = new Intent(UserActivity.this, ResultActivity.class);
intent.putExtra("TWEET", item);
startActivity(intent);
}
});
}
}
} | 4,832 | 0.625251 | 0.615616 | 130 | 37.330769 | 29.207582 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615385 | false | false | 4 |