blob_id stringlengths 40 40 | __id__ int64 225 39,780B | directory_id stringlengths 40 40 | path stringlengths 6 313 | content_id stringlengths 40 40 | detected_licenses list | license_type stringclasses 2
values | repo_name stringlengths 6 132 | repo_url stringlengths 25 151 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 70 | visit_date timestamp[ns] | revision_date timestamp[ns] | committer_date timestamp[ns] | github_id int64 7.28k 689M ⌀ | star_events_count int64 0 131k | fork_events_count int64 0 48k | gha_license_id stringclasses 23
values | gha_fork bool 2
classes | gha_event_created_at timestamp[ns] | gha_created_at timestamp[ns] | gha_updated_at timestamp[ns] | gha_pushed_at timestamp[ns] | gha_size int64 0 40.4M ⌀ | gha_stargazers_count int32 0 112k ⌀ | gha_forks_count int32 0 39.4k ⌀ | gha_open_issues_count int32 0 11k ⌀ | gha_language stringlengths 1 21 ⌀ | gha_archived bool 2
classes | gha_disabled bool 1
class | content stringlengths 7 4.37M | src_encoding stringlengths 3 16 | language stringclasses 1
value | length_bytes int64 7 4.37M | extension stringclasses 24
values | filename stringlengths 4 174 | language_id stringclasses 1
value | entities list | contaminating_dataset stringclasses 0
values | malware_signatures list | redacted_content stringlengths 7 4.37M | redacted_length_bytes int64 7 4.37M | alphanum_fraction float32 0.25 0.94 | alpha_fraction float32 0.25 0.94 | num_lines int32 1 84k | avg_line_length float32 0.76 99.9 | std_line_length float32 0 220 | max_line_length int32 5 998 | is_vendor bool 2
classes | is_generated bool 1
class | max_hex_length int32 0 319 | hex_fraction float32 0 0.38 | max_unicode_length int32 0 408 | unicode_fraction float32 0 0.36 | max_base64_length int32 0 506 | base64_fraction float32 0 0.5 | avg_csv_sep_count float32 0 4 | is_autogen_header bool 1
class | is_empty_html bool 1
class | shard stringclasses 16
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6b28989cf8f5302d602ac10a7d0db7a63ca58c6d | 22,497,038,706,175 | 9d011b4e18df2af66bc68ee36fe00f0cef2e359c | /socialite/src/main/java/com/vinelab/android/socialite/sharing/email/EmailShareProvider.java | 932c7fe03a8bbaedf9b4782c48bab52403734539 | [] | no_license | Vinelab/socialite-android | https://github.com/Vinelab/socialite-android | 6d6f5ffabec12172482ece7ef6faae85f63f71e3 | 45a8c5859ac9b1ef2aa862d96543d2e04fef5e3d | refs/heads/master | 2020-12-24T07:11:39.065000 | 2016-10-06T09:13:16 | 2016-10-06T09:13:16 | 45,188,365 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vinelab.android.socialite.sharing.email;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.Nullable;
/**
* Created by Nabil Souk on 11/2/2015.
*
* <p>
* Class providing sharing functionality through any mail client on the device.
* </p>
*/
public class EmailShareProvider {
/**
* Requests the system to share some content via email (compose a new email). By default, the system
* will open a dialog to choose one of the installed mail client apps.
* @param activity The activity requesting the share.
* @param dialogTitle The title of the mail client chooser dialog.
* @param subject The subject of the email to be preset.
* @param body The body of the email to be preset.
*/
public static void shareMessage(Activity activity, @Nullable String dialogTitle, String subject, String body) {
shareMessage(activity, dialogTitle, "", subject, body);
}
/**
* Requests the system to share some content via email (compose a new email). By default, the system
* will open a dialog to choose one of the installed mail client apps.
* @param activity The activity requesting the share.
* @param dialogTitle The title of the mail client chooser dialog.
* @param mailTo The recipient email.
* @param subject The subject of the email to be preset.
* @param body The body of the email to be preset.
*/
public static void shareMessage(Activity activity, @Nullable String dialogTitle, @Nullable String mailTo, String subject, String body) {
Intent intent = createComposeIntent(mailTo, subject, body);
activity.startActivity(Intent.createChooser(intent, dialogTitle));
}
/**
* Returns a compose email intent.
* @param mailTo The recipient email.
* @param subject The subject of the email to be preset.
* @param body The body of the email to be preset.
*/
private static Intent createComposeIntent(String mailTo, String subject, String body) {
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", mailTo != null? mailTo: "", null));
intent.putExtra(Intent.EXTRA_SUBJECT, subject != null? subject: "");
intent.putExtra(Intent.EXTRA_TEXT, body != null? body: "");
return intent;
}
}
| UTF-8 | Java | 2,367 | java | EmailShareProvider.java | Java | [
{
"context": "id.support.annotation.Nullable;\n\n/**\n * Created by Nabil Souk on 11/2/2015.\n *\n * <p>\n * Class providing sh",
"end": 211,
"score": 0.9997671842575073,
"start": 201,
"tag": "NAME",
"value": "Nabil Souk"
}
] | null | [] | package com.vinelab.android.socialite.sharing.email;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.Nullable;
/**
* Created by <NAME> on 11/2/2015.
*
* <p>
* Class providing sharing functionality through any mail client on the device.
* </p>
*/
public class EmailShareProvider {
/**
* Requests the system to share some content via email (compose a new email). By default, the system
* will open a dialog to choose one of the installed mail client apps.
* @param activity The activity requesting the share.
* @param dialogTitle The title of the mail client chooser dialog.
* @param subject The subject of the email to be preset.
* @param body The body of the email to be preset.
*/
public static void shareMessage(Activity activity, @Nullable String dialogTitle, String subject, String body) {
shareMessage(activity, dialogTitle, "", subject, body);
}
/**
* Requests the system to share some content via email (compose a new email). By default, the system
* will open a dialog to choose one of the installed mail client apps.
* @param activity The activity requesting the share.
* @param dialogTitle The title of the mail client chooser dialog.
* @param mailTo The recipient email.
* @param subject The subject of the email to be preset.
* @param body The body of the email to be preset.
*/
public static void shareMessage(Activity activity, @Nullable String dialogTitle, @Nullable String mailTo, String subject, String body) {
Intent intent = createComposeIntent(mailTo, subject, body);
activity.startActivity(Intent.createChooser(intent, dialogTitle));
}
/**
* Returns a compose email intent.
* @param mailTo The recipient email.
* @param subject The subject of the email to be preset.
* @param body The body of the email to be preset.
*/
private static Intent createComposeIntent(String mailTo, String subject, String body) {
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", mailTo != null? mailTo: "", null));
intent.putExtra(Intent.EXTRA_SUBJECT, subject != null? subject: "");
intent.putExtra(Intent.EXTRA_TEXT, body != null? body: "");
return intent;
}
}
| 2,363 | 0.694973 | 0.692015 | 55 | 42.036366 | 36.170788 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false | 3 |
e25f1a0077cf81cffbcf489b79b0c90a94ea03d0 | 1,889,785,614,583 | e6b01afaf98908e736129f8c345f8e3fd157244e | /src/Reader/ReadFile.java | 58687877c61ec276ccce91ef28cb549cdd1e46a0 | [] | no_license | mgkhaleque/PnT1 | https://github.com/mgkhaleque/PnT1 | 289e633ae97756bd188756071f674335851d689d | eea6876dc241cb2742adfde835b52acb7885e77f | refs/heads/master | 2020-04-13T00:57:16.261000 | 2018-12-23T03:47:21 | 2018-12-23T03:47:21 | 162,859,473 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Reader;
import java.io.*;
public class ReadFile {
public static void main(String []args) throws IOException {
String path = "/Users/zibonibrahim/Documents/MGK/gd.text";
FileReader fr = null;
BufferedReader br = null;
fr = new FileReader(path);
br = new BufferedReader(fr);
String data = " ";
while ((data = br.readLine()) !=null){
System.out.println(data);
}
}
}
| UTF-8 | Java | 461 | java | ReadFile.java | Java | [
{
"context": "rows IOException {\n\n String path = \"/Users/zibonibrahim/Documents/MGK/gd.text\";\n\n FileReader fr = ",
"end": 167,
"score": 0.9983996748924255,
"start": 155,
"tag": "USERNAME",
"value": "zibonibrahim"
}
] | null | [] | package Reader;
import java.io.*;
public class ReadFile {
public static void main(String []args) throws IOException {
String path = "/Users/zibonibrahim/Documents/MGK/gd.text";
FileReader fr = null;
BufferedReader br = null;
fr = new FileReader(path);
br = new BufferedReader(fr);
String data = " ";
while ((data = br.readLine()) !=null){
System.out.println(data);
}
}
}
| 461 | 0.574837 | 0.574837 | 21 | 20.952381 | 20.469435 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 3 |
23dec82bc183cf17a1a79e4f50b1ff8176243071 | 1,889,785,611,087 | 8b02f2a9216f964aa16ddf15da75661b9c226109 | /TeamCode/src/main/java/org/whitneyrobotics/ftc/teamcode/lib/purepursuit/swervetotarget/SwerveRobotConstants.java | 4fb5c3ae8d6ce9bf46a9a1d439ba50fecd56c567 | [
"BSD-3-Clause"
] | permissive | WHSRobotics/542_20-21_ftc | https://github.com/WHSRobotics/542_20-21_ftc | aa4c5bfd97810367883d08ed142a980cab208743 | 85dcb536ffdd984e5257cee84e0e0dcc82850235 | refs/heads/master | 2023-04-05T12:34:28.487000 | 2021-04-14T22:16:42 | 2021-04-14T22:16:42 | 296,753,092 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.whitneyrobotics.ftc.teamcode.lib.purepursuit.swervetotarget;
public class SwerveRobotConstants {
// Based on robot physical properties
private double kV, kA, kP;
public double getkV() {
return kV;
}
public void setkV(double kV) {
this.kV = kV;
}
public double getkA() {
return kA;
}
public void setkA(double kA) {
this.kA = kA;
}
public double getkP() {
return kP;
}
public void setkP(double kP) {
this.kP = kP;
}
public SwerveRobotConstants(double kV, double kA, double kP) {
this.kV = kV;
this.kA = kA;
this.kP = kP;
}
}
| UTF-8 | Java | 681 | java | SwerveRobotConstants.java | Java | [] | null | [] | package org.whitneyrobotics.ftc.teamcode.lib.purepursuit.swervetotarget;
public class SwerveRobotConstants {
// Based on robot physical properties
private double kV, kA, kP;
public double getkV() {
return kV;
}
public void setkV(double kV) {
this.kV = kV;
}
public double getkA() {
return kA;
}
public void setkA(double kA) {
this.kA = kA;
}
public double getkP() {
return kP;
}
public void setkP(double kP) {
this.kP = kP;
}
public SwerveRobotConstants(double kV, double kA, double kP) {
this.kV = kV;
this.kA = kA;
this.kP = kP;
}
}
| 681 | 0.566814 | 0.566814 | 38 | 16.921053 | 17.707241 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.394737 | false | false | 3 |
91fb862d288785ee00780aedcdba9f3a03e3f104 | 20,023,137,551,485 | 8d40896308a72d0a739fb66b9ab643831391bac0 | /PasteIt/src/reminder/Reminder.java | a62629aaa24857b7f1681a804102038d939ee0dd | [] | no_license | ChuHueiYun/JavaFinalProject | https://github.com/ChuHueiYun/JavaFinalProject | ca3ca6bada200936949d6bddfe35622000e58504 | 7521f2c8103f946b09fee02dc1a0d59029c55235 | refs/heads/master | 2021-05-05T07:39:29.426000 | 2017-10-02T11:25:37 | 2017-10-02T11:25:37 | 105,526,797 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package reminder;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.plaf.basic.BasicInternalFrameUI;
import com.github.lgooddatepicker.components.DatePicker;
import com.github.lgooddatepicker.components.TimePicker;
import com.github.lgooddatepicker.components.TimePickerSettings;
import com.github.lgooddatepicker.components.TimePickerSettings.TimeArea;
import utility.ComponentMover;
public class Reminder extends TimerTask{
private JDesktopPane desktopPane;
private JInternalFrame setTimeFrame;
private JButton checkButton;
private JButton cancelButton;
private JButton exitButton;
private JLabel setTimeLable;
private JLabel setTimeTitle;
private DatePicker datePicker;
private TimePicker timePicker;
private Timer timer;
private Date inputTime;
private JInternalFrame targetFrame;
private String timeString;
public JInternalFrame getSetTimeFrame() {
return setTimeFrame;
}
public String getTimeString() {
return timeString;
}
public void setTimeString(String timeString) {
this.timeString = timeString;
}
//constructor
public Reminder(JDesktopPane desktop, JInternalFrame inputFrame, String reminderTime){
desktopPane = desktop;
targetFrame = inputFrame;
setTimeString(reminderTime);
setTimeWindow(reminderTime);
if(!"".equals(reminderTime)){ //reminderTime有紀錄
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
inputTime = dateFormatter.parse(reminderTime); //String轉Date
setSchedule(targetFrame ,inputTime);
} catch (ParseException e) {
System.out.println("輸入的日期字串格式有誤");
}
}
}
//設定時間視窗
public void setTimeWindow(String reminderTime){
Color backgroundColor = new Color(36, 121, 158);
Color textColor = new Color(255, 224, 102);
setTimeFrame = new JInternalFrame("設定提醒時間:",false,false,false,false);
setTimeFrame.setBorder(null);
setTimeFrame.getContentPane().setBackground(backgroundColor);
setTimeFrame.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
setTimeFrame.setSize(250, 250);
//setTimeFrame.setLocationRelativeTo(null);
BasicInternalFrameUI basicInternalFrameUI = (BasicInternalFrameUI)setTimeFrame.getUI();
basicInternalFrameUI.setNorthPane(null);
//選擇日期 :
JPanel selectDatePanel = new JPanel(new FlowLayout(FlowLayout.LEFT ,10, 10));
selectDatePanel.setPreferredSize(new Dimension(250, 50));
selectDatePanel.setBackground(backgroundColor);
JLabel dateLable = new JLabel(new ImageIcon(Reminder.class.getResource("/images/calendar.png")));
dateLable.setToolTipText( "選擇日期" );
selectDatePanel.add(dateLable);
datePicker = new DatePicker();
selectDatePanel.add(datePicker);
setTimeFrame.add(selectDatePanel);
//選擇時間 :
JPanel selectTimePanel = new JPanel(new FlowLayout(FlowLayout.LEFT ,10, 10));
selectTimePanel.setPreferredSize(new Dimension(250, 50));
selectTimePanel.setBackground(backgroundColor);
JLabel timeLable = new JLabel(new ImageIcon(Reminder.class.getResource("/images/clock.png")));
timeLable.setToolTipText( "選擇時間" );
selectTimePanel.add(timeLable);
TimePickerSettings timeSettings = new TimePickerSettings();
timeSettings.setColor(TimeArea.TimePickerTextValidTime, Color.black);
timeSettings.initialTime = LocalTime.now();
timePicker = new TimePicker(timeSettings);
selectTimePanel.add(timePicker);
setTimeFrame.add(selectTimePanel);
//中間按鈕
JPanel centerButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 50, 10));
centerButtonPanel.setPreferredSize(new Dimension(250, 50));
centerButtonPanel.setBackground(backgroundColor);
//取消按鈕
cancelButton = new JButton(new ImageIcon(Reminder.class.getResource("/images/cancel.png")));
cancelButton.setRolloverIcon(new ImageIcon(Reminder.class.getResource("/images/cancel_Rollover.png")) );
cancelButton.setContentAreaFilled(false);
cancelButton.setFocusPainted(false);
cancelButton.setBorderPainted(false);
cancelButton.setBorder(null);
cancelButton.setToolTipText( "清除已設定的提醒" );
centerButtonPanel.add(cancelButton);
//確認按鈕
checkButton = new JButton(new ImageIcon(Reminder.class.getResource("/images/check.png")));
checkButton.setRolloverIcon(new ImageIcon(Reminder.class.getResource("/images/check_Rollover.png")));
checkButton.setContentAreaFilled(false);
checkButton.setFocusPainted(false);
checkButton.setBorderPainted(false);
checkButton.setBorder(null);
checkButton.setToolTipText( "新增提醒時間" );
centerButtonPanel.add(checkButton);
setTimeFrame.add(centerButtonPanel);
//底部文字區塊
JPanel buttomTextPanel = new JPanel(new GridLayout(2, 1, 20, 20));
buttomTextPanel.setPreferredSize(new Dimension(250, 50));
buttomTextPanel.setBackground(backgroundColor);
setTimeTitle = new JLabel(" 已設定的提醒時間:");
setTimeTitle.setFont(new Font("微軟正黑體", Font.BOLD, 15));
setTimeTitle.setForeground(Color.WHITE);
buttomTextPanel.add(setTimeTitle);
if("".equals(reminderTime)){ //reminderTime有紀錄
setTimeLable = new JLabel(" 無");
}
else{
setTimeLable = new JLabel(reminderTime);
}
setTimeLable.setFont(new Font("微軟正黑體", Font.BOLD, 18));
setTimeLable.setForeground(textColor);
buttomTextPanel.add(setTimeLable);
setTimeFrame.add(buttomTextPanel);
//離開按鈕
JPanel exitButtonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 20, 10));
exitButtonPanel.setPreferredSize(new Dimension(250, 50));
exitButtonPanel.setBackground(backgroundColor);
exitButton = new JButton(new ImageIcon(Reminder.class.getResource("/images/exit.png")));
exitButton.setRolloverIcon( new ImageIcon(Reminder.class.getResource("/images/exit_Rollover.png")) );
exitButton.setContentAreaFilled(false);
exitButton.setFocusPainted(false);
exitButton.setBorderPainted(false);
exitButton.setBorder(null);
exitButton.setToolTipText( "離開" );
exitButtonPanel.add(exitButton);
setTimeFrame.add(exitButtonPanel);
setTimeFrame.setVisible(false); //隱藏設定時間視窗
@SuppressWarnings("unused")
ComponentMover componentMover = new ComponentMover(setTimeFrame, setTimeFrame);
desktopPane.add(setTimeFrame); //加入Reminder到desktopPane中
//註冊事件監聽器
ButtonHandler handler = new ButtonHandler();
checkButton.addActionListener( handler );
cancelButton.addActionListener( handler );
exitButton.addActionListener( handler );
}
private class ButtonHandler implements ActionListener {
// handle button event
@Override
public void actionPerformed( ActionEvent event ){
if(event.getSource() == checkButton){
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
inputTime = dateFormatter.parse(datePicker.getDateStringOrEmptyString() + " " + timePicker.getTimeStringOrEmptyString());
setSchedule(targetFrame ,inputTime); //排程
setTimeString(datePicker.getDateStringOrEmptyString() + " " + timePicker.getTimeStringOrEmptyString());
setTimeLable.setText(" " + getTimeString());
} catch (ParseException e) {
//e.printStackTrace();
setTimeLable.setText(" 輸入日期格式有誤");
}
}
else if(event.getSource() == cancelButton){
setTimeLable.setText("無");
cancelSchedule();
}
else if(event.getSource() == exitButton){
setTimeFrame.setVisible(false);
}
}
}
public void setSchedule(JInternalFrame frame, Date inputTime){
System.out.println("Reminder的設定時間: " + inputTime);
if(timer == null){
timer = new Timer();
timer.schedule(new TimerTask(){
public void run() {
frame.setVisible(true);
}
}
, inputTime);
}
else{
System.out.println("修改Reminder的設定時間:");
timer.cancel();
timer.purge();
timer = new Timer();
timer.schedule(new TimerTask(){
public void run() {
frame.setVisible(true);
}
}
, inputTime);
}
}
public void cancelSchedule(){
if(timer != null){
timer.cancel();
timer.purge();
}
}
@Override
public void run() {
System.out.println("Reminder於指定時間執行");
}
} | UTF-8 | Java | 9,472 | java | Reminder.java | Java | [] | null | [] | package reminder;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.plaf.basic.BasicInternalFrameUI;
import com.github.lgooddatepicker.components.DatePicker;
import com.github.lgooddatepicker.components.TimePicker;
import com.github.lgooddatepicker.components.TimePickerSettings;
import com.github.lgooddatepicker.components.TimePickerSettings.TimeArea;
import utility.ComponentMover;
public class Reminder extends TimerTask{
private JDesktopPane desktopPane;
private JInternalFrame setTimeFrame;
private JButton checkButton;
private JButton cancelButton;
private JButton exitButton;
private JLabel setTimeLable;
private JLabel setTimeTitle;
private DatePicker datePicker;
private TimePicker timePicker;
private Timer timer;
private Date inputTime;
private JInternalFrame targetFrame;
private String timeString;
public JInternalFrame getSetTimeFrame() {
return setTimeFrame;
}
public String getTimeString() {
return timeString;
}
public void setTimeString(String timeString) {
this.timeString = timeString;
}
//constructor
public Reminder(JDesktopPane desktop, JInternalFrame inputFrame, String reminderTime){
desktopPane = desktop;
targetFrame = inputFrame;
setTimeString(reminderTime);
setTimeWindow(reminderTime);
if(!"".equals(reminderTime)){ //reminderTime有紀錄
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
inputTime = dateFormatter.parse(reminderTime); //String轉Date
setSchedule(targetFrame ,inputTime);
} catch (ParseException e) {
System.out.println("輸入的日期字串格式有誤");
}
}
}
//設定時間視窗
public void setTimeWindow(String reminderTime){
Color backgroundColor = new Color(36, 121, 158);
Color textColor = new Color(255, 224, 102);
setTimeFrame = new JInternalFrame("設定提醒時間:",false,false,false,false);
setTimeFrame.setBorder(null);
setTimeFrame.getContentPane().setBackground(backgroundColor);
setTimeFrame.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
setTimeFrame.setSize(250, 250);
//setTimeFrame.setLocationRelativeTo(null);
BasicInternalFrameUI basicInternalFrameUI = (BasicInternalFrameUI)setTimeFrame.getUI();
basicInternalFrameUI.setNorthPane(null);
//選擇日期 :
JPanel selectDatePanel = new JPanel(new FlowLayout(FlowLayout.LEFT ,10, 10));
selectDatePanel.setPreferredSize(new Dimension(250, 50));
selectDatePanel.setBackground(backgroundColor);
JLabel dateLable = new JLabel(new ImageIcon(Reminder.class.getResource("/images/calendar.png")));
dateLable.setToolTipText( "選擇日期" );
selectDatePanel.add(dateLable);
datePicker = new DatePicker();
selectDatePanel.add(datePicker);
setTimeFrame.add(selectDatePanel);
//選擇時間 :
JPanel selectTimePanel = new JPanel(new FlowLayout(FlowLayout.LEFT ,10, 10));
selectTimePanel.setPreferredSize(new Dimension(250, 50));
selectTimePanel.setBackground(backgroundColor);
JLabel timeLable = new JLabel(new ImageIcon(Reminder.class.getResource("/images/clock.png")));
timeLable.setToolTipText( "選擇時間" );
selectTimePanel.add(timeLable);
TimePickerSettings timeSettings = new TimePickerSettings();
timeSettings.setColor(TimeArea.TimePickerTextValidTime, Color.black);
timeSettings.initialTime = LocalTime.now();
timePicker = new TimePicker(timeSettings);
selectTimePanel.add(timePicker);
setTimeFrame.add(selectTimePanel);
//中間按鈕
JPanel centerButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 50, 10));
centerButtonPanel.setPreferredSize(new Dimension(250, 50));
centerButtonPanel.setBackground(backgroundColor);
//取消按鈕
cancelButton = new JButton(new ImageIcon(Reminder.class.getResource("/images/cancel.png")));
cancelButton.setRolloverIcon(new ImageIcon(Reminder.class.getResource("/images/cancel_Rollover.png")) );
cancelButton.setContentAreaFilled(false);
cancelButton.setFocusPainted(false);
cancelButton.setBorderPainted(false);
cancelButton.setBorder(null);
cancelButton.setToolTipText( "清除已設定的提醒" );
centerButtonPanel.add(cancelButton);
//確認按鈕
checkButton = new JButton(new ImageIcon(Reminder.class.getResource("/images/check.png")));
checkButton.setRolloverIcon(new ImageIcon(Reminder.class.getResource("/images/check_Rollover.png")));
checkButton.setContentAreaFilled(false);
checkButton.setFocusPainted(false);
checkButton.setBorderPainted(false);
checkButton.setBorder(null);
checkButton.setToolTipText( "新增提醒時間" );
centerButtonPanel.add(checkButton);
setTimeFrame.add(centerButtonPanel);
//底部文字區塊
JPanel buttomTextPanel = new JPanel(new GridLayout(2, 1, 20, 20));
buttomTextPanel.setPreferredSize(new Dimension(250, 50));
buttomTextPanel.setBackground(backgroundColor);
setTimeTitle = new JLabel(" 已設定的提醒時間:");
setTimeTitle.setFont(new Font("微軟正黑體", Font.BOLD, 15));
setTimeTitle.setForeground(Color.WHITE);
buttomTextPanel.add(setTimeTitle);
if("".equals(reminderTime)){ //reminderTime有紀錄
setTimeLable = new JLabel(" 無");
}
else{
setTimeLable = new JLabel(reminderTime);
}
setTimeLable.setFont(new Font("微軟正黑體", Font.BOLD, 18));
setTimeLable.setForeground(textColor);
buttomTextPanel.add(setTimeLable);
setTimeFrame.add(buttomTextPanel);
//離開按鈕
JPanel exitButtonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 20, 10));
exitButtonPanel.setPreferredSize(new Dimension(250, 50));
exitButtonPanel.setBackground(backgroundColor);
exitButton = new JButton(new ImageIcon(Reminder.class.getResource("/images/exit.png")));
exitButton.setRolloverIcon( new ImageIcon(Reminder.class.getResource("/images/exit_Rollover.png")) );
exitButton.setContentAreaFilled(false);
exitButton.setFocusPainted(false);
exitButton.setBorderPainted(false);
exitButton.setBorder(null);
exitButton.setToolTipText( "離開" );
exitButtonPanel.add(exitButton);
setTimeFrame.add(exitButtonPanel);
setTimeFrame.setVisible(false); //隱藏設定時間視窗
@SuppressWarnings("unused")
ComponentMover componentMover = new ComponentMover(setTimeFrame, setTimeFrame);
desktopPane.add(setTimeFrame); //加入Reminder到desktopPane中
//註冊事件監聽器
ButtonHandler handler = new ButtonHandler();
checkButton.addActionListener( handler );
cancelButton.addActionListener( handler );
exitButton.addActionListener( handler );
}
private class ButtonHandler implements ActionListener {
// handle button event
@Override
public void actionPerformed( ActionEvent event ){
if(event.getSource() == checkButton){
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
inputTime = dateFormatter.parse(datePicker.getDateStringOrEmptyString() + " " + timePicker.getTimeStringOrEmptyString());
setSchedule(targetFrame ,inputTime); //排程
setTimeString(datePicker.getDateStringOrEmptyString() + " " + timePicker.getTimeStringOrEmptyString());
setTimeLable.setText(" " + getTimeString());
} catch (ParseException e) {
//e.printStackTrace();
setTimeLable.setText(" 輸入日期格式有誤");
}
}
else if(event.getSource() == cancelButton){
setTimeLable.setText("無");
cancelSchedule();
}
else if(event.getSource() == exitButton){
setTimeFrame.setVisible(false);
}
}
}
public void setSchedule(JInternalFrame frame, Date inputTime){
System.out.println("Reminder的設定時間: " + inputTime);
if(timer == null){
timer = new Timer();
timer.schedule(new TimerTask(){
public void run() {
frame.setVisible(true);
}
}
, inputTime);
}
else{
System.out.println("修改Reminder的設定時間:");
timer.cancel();
timer.purge();
timer = new Timer();
timer.schedule(new TimerTask(){
public void run() {
frame.setVisible(true);
}
}
, inputTime);
}
}
public void cancelSchedule(){
if(timer != null){
timer.cancel();
timer.purge();
}
}
@Override
public void run() {
System.out.println("Reminder於指定時間執行");
}
} | 9,472 | 0.693717 | 0.685428 | 266 | 33.469925 | 25.808451 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.789474 | false | false | 3 |
b79a0ea797e1a2e377a0653075a5fa37a447ebf6 | 20,023,137,552,195 | 0f76f64b9a215edcce8e4319357b8fc47799f34f | /src/main/java/com/hourmaps/data/bingmaps/enums/TravelModeEnum.java | 26cdbfbe8207fa3fcdee1715a320af57f2338b35 | [] | no_license | christopheryang/TravelTimeAndDistance | https://github.com/christopheryang/TravelTimeAndDistance | eda7751fae0855c71a3278c3a9342c9835adb1bf | ffb503f7b3f9c63eb61a8c59ca43b0e25a36d7a2 | refs/heads/master | 2015-08-20T15:24:11.390000 | 2015-08-20T08:51:45 | 2015-08-20T08:51:45 | 30,729,364 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hourmaps.data.bingmaps.enums;
public enum TravelModeEnum {
Transit,
Driving,
}
| UTF-8 | Java | 94 | java | TravelModeEnum.java | Java | [] | null | [] | package com.hourmaps.data.bingmaps.enums;
public enum TravelModeEnum {
Transit,
Driving,
}
| 94 | 0.776596 | 0.776596 | 6 | 14.666667 | 14.929463 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false | 3 |
5f02aec0e97e3fee1aa2a3232493375394cffe05 | 20,048,907,396,970 | d49ea83bbf7ae2fd9d36b80e624cbb7c3ba6dcac | /src/main/java/com/dsi/parallax/optimization/linesearch/BackTrackLineSearch.java | d70e56776134fd285d5e26e1681f2bfc950436c3 | [] | no_license | jattenberg/parallax | https://github.com/jattenberg/parallax | c319d557487dc4ceb1ce9ad6353ef6900820ae04 | 00908adcea680b9a7d306332934fd61676abc370 | refs/heads/master | 2022-10-26T05:14:00.620000 | 2022-10-11T15:42:58 | 2022-10-11T15:42:58 | 8,838,383 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*******************************************************************************
* Copyright 2012 Josh Attenberg. Not for re-use or redistribution.
******************************************************************************/
package com.dsi.parallax.optimization.linesearch;
import com.dsi.parallax.ml.vector.LinearVector;
import com.dsi.parallax.ml.vector.LinearVectorFactory;
import com.dsi.parallax.ml.vector.util.VectorUtils;
import com.dsi.parallax.optimization.GradientOptimizable;
//"Line Searches and Backtracking", p385, "Numeric Recipes in C"
public class BackTrackLineSearch extends AbstractLineOptimizer implements
GradientLineOptimizer {
private final int maxIterations = 100;
private final double stpmax = 100;
// termination conditions: either
// a) abs(delta x/x) < REL_TOLX for all coordinates
// b) abs(delta x) < ABS_TOLX for all coordinates
// c) sufficient function increase (uses ALF)
private double relTolx = 1e-7;
private final double ALF = 1e-4;
private double absTolx = 1e-4;
private GradientOptimizable function;
public BackTrackLineSearch(GradientOptimizable optimizable) {
this.function = optimizable;
}
/**
* Sets the tolerance of relative diff in function value. Line search
* converges if <tt>abs(delta x / x) < tolx</tt> for all coordinates.
*/
public void setRelTolx(double tolx) {
relTolx = tolx;
}
/**
* Sets the tolerance of absolute diff in function value. Line search
* converges if <tt>abs(delta x) < tolx</tt> for all coordinates.
*/
public void setAbsTolx(double tolx) {
absTolx = tolx;
}
// initialStep is ignored. This is b/c if the initial step is not 1.0,
// it sometimes confuses the backtracking for reasons I don't
// understand. (That is, the jump gets LARGER on iteration 1.)
// returns fraction of step size (alam) if found a good step
// returns 0.0 if could not step in direction
@Override
public double optimize(LinearVector line, double initialStep) {
LinearVector g, x, oldParameters;
double slope, temp, test, alamin, alam, alam2, tmplam;
double rhs1, rhs2, a, b, disc, oldAlam;
double f, fold, f2;
int size = function.getNumParameters();
x = function.getVector();
oldParameters = LinearVectorFactory.getVector(x);
g = function.getValueGradient();
alam2 = tmplam = 0.0;
f2 = fold = function.computeLoss();
if (logger.isInfoEnabled()) {
logger.info("ENTERING BACKTRACK\n");
logger.info("Entering BackTrackLnSrch, value=" + fold
+ ",\ndirection.oneNorm:" + line.L1Norm()
+ " direction.infNorm:" + line.LInfinityNorm());
}
double sum = line.L2Norm();
if (sum > stpmax) {
logger.warn("attempted step too big. scaling: sum=" + sum
+ ", stpmax=" + stpmax);
line.timesEquals(stpmax / sum);
}
slope = VectorUtils.dotProduct(g, line);
logger.info("slope=" + slope);
if (slope <= 0)
throw new RuntimeException(
"invalid slope, must be positive. given: " + slope);
// find maximum lambda
// converge when (delta x) / x < REL_TOLX for all coordinates.
// the largest step size that triggers this threshold is
// precomputed and saved in alamin
test = 0.0;
for (int i = 0; i < size; i++) {
temp = Math.abs(line.getValue(i))
/ Math.max(Math.abs(oldParameters.getValue(i)), 1.0);
if (temp > test)
test = temp;
}
alamin = relTolx / test;
alam = 1.0;
oldAlam = 0.0;
int iteration = 0;
// look for step size in direction given by "line"
for (iteration = 0; iteration < maxIterations; iteration++) {
// x = oldParameters + alam*line
// initially, alam = 1.0, i.e. take full Newton step
logger.info("BackTrack loop iteration " + iteration + ": alam="
+ alam + " oldAlam=" + oldAlam);
logger.info("before step, x.1norm: " + x.L1Norm() + "\nalam: "
+ alam + "\noldAlam: " + oldAlam);
x.plusEqualsVectorTimes(line, alam - oldAlam); // step
logger.info("after step, x.1norm: " + x.L1Norm());
// check for convergence
// convergence on delta x
if ((alam < alamin)
|| VectorUtils.smallAbsDiff(oldParameters, x, absTolx)) {
function.setParameters(oldParameters);
f = function.computeLoss();
logger.warn("EXITING BACKTRACK: Jump too small (alamin="
+ alamin + "). Exiting and using xold. Value=" + f);
return 0.0;
}
function.setParameters(x);
oldAlam = alam;
f = function.computeLoss();
logger.info("value=" + f);
// sufficient function increase (Wolf condition)
if (f >= fold + ALF * alam * slope) {
logger.info("EXITING BACKTRACK: value=" + f);
if (f < fold)
throw new IllegalStateException(
"Function did not increase: f=" + f + " < " + fold
+ "=fold");
return alam;
}
// if value is infinite, i.e. we've
// jumped to unstable territory, then scale down jump
else if (Double.isInfinite(f) || Double.isInfinite(f2)) {
logger.warn("Value is infinite after jump " + oldAlam + ". f="
+ f + ", f2=" + f2 + ". Scaling back step size...");
tmplam = .2 * alam;
if (alam < alamin) { // convergence on delta x
function.setParameters(oldParameters);
f = function.computeLoss();
logger.warn("EXITING BACKTRACK: Jump too small. Exiting and using xold. Value="
+ f);
return 0.0;
}
} else { // backtrack
if (alam == 1.0) // first time through
tmplam = -slope / (2.0 * (f - fold - slope));
else {
rhs1 = f - fold - alam * slope;
rhs2 = f2 - fold - alam2 * slope;
a = (rhs1 / (alam * alam) - rhs2 / (alam2 * alam2))
/ (alam - alam2);
b = (-alam2 * rhs1 / (alam * alam) + alam * rhs2
/ (alam2 * alam2))
/ (alam - alam2);
if (a == 0.0)
tmplam = -slope / (2.0 * b);
else {
disc = b * b - 3.0 * a * slope;
if (disc < 0.0) {
tmplam = .5 * alam;
} else if (b <= 0.0)
tmplam = (-b + Math.sqrt(disc)) / (3.0 * a);
else
tmplam = -slope / (b + Math.sqrt(disc));
}
if (tmplam > .5 * alam)
tmplam = .5 * alam; // lambda <= .5 lambda_1
}
}
alam2 = alam;
f2 = f;
logger.info("tmplam:" + tmplam);
alam = Math.max(tmplam, .1 * alam); // lambda >= .1*Lambda_1
}
if (iteration >= maxIterations)
throw new IllegalStateException("Too many iterations.");
return 0.0;
}
}
| UTF-8 | Java | 6,295 | java | BackTrackLineSearch.java | Java | [
{
"context": "********************************\n * Copyright 2012 Josh Attenberg. Not for re-use or redistribution.\n *************",
"end": 113,
"score": 0.9995096325874329,
"start": 99,
"tag": "NAME",
"value": "Josh Attenberg"
}
] | null | [] | /*******************************************************************************
* Copyright 2012 <NAME>. Not for re-use or redistribution.
******************************************************************************/
package com.dsi.parallax.optimization.linesearch;
import com.dsi.parallax.ml.vector.LinearVector;
import com.dsi.parallax.ml.vector.LinearVectorFactory;
import com.dsi.parallax.ml.vector.util.VectorUtils;
import com.dsi.parallax.optimization.GradientOptimizable;
//"Line Searches and Backtracking", p385, "Numeric Recipes in C"
public class BackTrackLineSearch extends AbstractLineOptimizer implements
GradientLineOptimizer {
private final int maxIterations = 100;
private final double stpmax = 100;
// termination conditions: either
// a) abs(delta x/x) < REL_TOLX for all coordinates
// b) abs(delta x) < ABS_TOLX for all coordinates
// c) sufficient function increase (uses ALF)
private double relTolx = 1e-7;
private final double ALF = 1e-4;
private double absTolx = 1e-4;
private GradientOptimizable function;
public BackTrackLineSearch(GradientOptimizable optimizable) {
this.function = optimizable;
}
/**
* Sets the tolerance of relative diff in function value. Line search
* converges if <tt>abs(delta x / x) < tolx</tt> for all coordinates.
*/
public void setRelTolx(double tolx) {
relTolx = tolx;
}
/**
* Sets the tolerance of absolute diff in function value. Line search
* converges if <tt>abs(delta x) < tolx</tt> for all coordinates.
*/
public void setAbsTolx(double tolx) {
absTolx = tolx;
}
// initialStep is ignored. This is b/c if the initial step is not 1.0,
// it sometimes confuses the backtracking for reasons I don't
// understand. (That is, the jump gets LARGER on iteration 1.)
// returns fraction of step size (alam) if found a good step
// returns 0.0 if could not step in direction
@Override
public double optimize(LinearVector line, double initialStep) {
LinearVector g, x, oldParameters;
double slope, temp, test, alamin, alam, alam2, tmplam;
double rhs1, rhs2, a, b, disc, oldAlam;
double f, fold, f2;
int size = function.getNumParameters();
x = function.getVector();
oldParameters = LinearVectorFactory.getVector(x);
g = function.getValueGradient();
alam2 = tmplam = 0.0;
f2 = fold = function.computeLoss();
if (logger.isInfoEnabled()) {
logger.info("ENTERING BACKTRACK\n");
logger.info("Entering BackTrackLnSrch, value=" + fold
+ ",\ndirection.oneNorm:" + line.L1Norm()
+ " direction.infNorm:" + line.LInfinityNorm());
}
double sum = line.L2Norm();
if (sum > stpmax) {
logger.warn("attempted step too big. scaling: sum=" + sum
+ ", stpmax=" + stpmax);
line.timesEquals(stpmax / sum);
}
slope = VectorUtils.dotProduct(g, line);
logger.info("slope=" + slope);
if (slope <= 0)
throw new RuntimeException(
"invalid slope, must be positive. given: " + slope);
// find maximum lambda
// converge when (delta x) / x < REL_TOLX for all coordinates.
// the largest step size that triggers this threshold is
// precomputed and saved in alamin
test = 0.0;
for (int i = 0; i < size; i++) {
temp = Math.abs(line.getValue(i))
/ Math.max(Math.abs(oldParameters.getValue(i)), 1.0);
if (temp > test)
test = temp;
}
alamin = relTolx / test;
alam = 1.0;
oldAlam = 0.0;
int iteration = 0;
// look for step size in direction given by "line"
for (iteration = 0; iteration < maxIterations; iteration++) {
// x = oldParameters + alam*line
// initially, alam = 1.0, i.e. take full Newton step
logger.info("BackTrack loop iteration " + iteration + ": alam="
+ alam + " oldAlam=" + oldAlam);
logger.info("before step, x.1norm: " + x.L1Norm() + "\nalam: "
+ alam + "\noldAlam: " + oldAlam);
x.plusEqualsVectorTimes(line, alam - oldAlam); // step
logger.info("after step, x.1norm: " + x.L1Norm());
// check for convergence
// convergence on delta x
if ((alam < alamin)
|| VectorUtils.smallAbsDiff(oldParameters, x, absTolx)) {
function.setParameters(oldParameters);
f = function.computeLoss();
logger.warn("EXITING BACKTRACK: Jump too small (alamin="
+ alamin + "). Exiting and using xold. Value=" + f);
return 0.0;
}
function.setParameters(x);
oldAlam = alam;
f = function.computeLoss();
logger.info("value=" + f);
// sufficient function increase (Wolf condition)
if (f >= fold + ALF * alam * slope) {
logger.info("EXITING BACKTRACK: value=" + f);
if (f < fold)
throw new IllegalStateException(
"Function did not increase: f=" + f + " < " + fold
+ "=fold");
return alam;
}
// if value is infinite, i.e. we've
// jumped to unstable territory, then scale down jump
else if (Double.isInfinite(f) || Double.isInfinite(f2)) {
logger.warn("Value is infinite after jump " + oldAlam + ". f="
+ f + ", f2=" + f2 + ". Scaling back step size...");
tmplam = .2 * alam;
if (alam < alamin) { // convergence on delta x
function.setParameters(oldParameters);
f = function.computeLoss();
logger.warn("EXITING BACKTRACK: Jump too small. Exiting and using xold. Value="
+ f);
return 0.0;
}
} else { // backtrack
if (alam == 1.0) // first time through
tmplam = -slope / (2.0 * (f - fold - slope));
else {
rhs1 = f - fold - alam * slope;
rhs2 = f2 - fold - alam2 * slope;
a = (rhs1 / (alam * alam) - rhs2 / (alam2 * alam2))
/ (alam - alam2);
b = (-alam2 * rhs1 / (alam * alam) + alam * rhs2
/ (alam2 * alam2))
/ (alam - alam2);
if (a == 0.0)
tmplam = -slope / (2.0 * b);
else {
disc = b * b - 3.0 * a * slope;
if (disc < 0.0) {
tmplam = .5 * alam;
} else if (b <= 0.0)
tmplam = (-b + Math.sqrt(disc)) / (3.0 * a);
else
tmplam = -slope / (b + Math.sqrt(disc));
}
if (tmplam > .5 * alam)
tmplam = .5 * alam; // lambda <= .5 lambda_1
}
}
alam2 = alam;
f2 = f;
logger.info("tmplam:" + tmplam);
alam = Math.max(tmplam, .1 * alam); // lambda >= .1*Lambda_1
}
if (iteration >= maxIterations)
throw new IllegalStateException("Too many iterations.");
return 0.0;
}
}
| 6,287 | 0.617951 | 0.601589 | 193 | 31.616581 | 22.520184 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.186528 | false | false | 3 |
c3c4ead06a57f0cfb1c06de90438685092814223 | 360,777,257,792 | 921dd73072f5adf415a9b2bccddadf34ddae91ef | /src/main/java/com/cesfam/presmo/backend/apirest/models/dao/IEntregadoDao.java | c96843b54cfc76b45300542fa10c2f39b3208c83 | [] | no_license | Frank-Mujica/presmo-backend-apirest | https://github.com/Frank-Mujica/presmo-backend-apirest | 7c3462168a65734df99f27ebfda0fa4be323e811 | dd737a58545f77e2247f668d739ffa867f216f1a | refs/heads/master | 2020-06-01T23:03:29.601000 | 2019-07-09T10:34:39 | 2019-07-09T10:34:39 | 190,950,524 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cesfam.presmo.backend.apirest.models.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.cesfam.presmo.backend.apirest.models.entity.Entregado;
import com.cesfam.presmo.backend.apirest.models.entity.Farmaceutico;
import com.cesfam.presmo.backend.apirest.models.entity.Partida;
import com.cesfam.presmo.backend.apirest.models.entity.RecetaDetalle;
public interface IEntregadoDao extends JpaRepository<Entregado, Long>{
@Query("from Farmaceutico")
public List<Farmaceutico> findAllfarmaceuticos();
@Query("from Partida")
public List<Partida> findAllPartidas();
@Query("from RecetaDetalle")
public List<RecetaDetalle> findAllReceta_Detalles();
} | UTF-8 | Java | 777 | java | IEntregadoDao.java | Java | [] | null | [] | package com.cesfam.presmo.backend.apirest.models.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.cesfam.presmo.backend.apirest.models.entity.Entregado;
import com.cesfam.presmo.backend.apirest.models.entity.Farmaceutico;
import com.cesfam.presmo.backend.apirest.models.entity.Partida;
import com.cesfam.presmo.backend.apirest.models.entity.RecetaDetalle;
public interface IEntregadoDao extends JpaRepository<Entregado, Long>{
@Query("from Farmaceutico")
public List<Farmaceutico> findAllfarmaceuticos();
@Query("from Partida")
public List<Partida> findAllPartidas();
@Query("from RecetaDetalle")
public List<RecetaDetalle> findAllReceta_Detalles();
} | 777 | 0.810811 | 0.810811 | 24 | 31.416666 | 27.363171 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.875 | false | false | 3 |
91f70cac039f98817aed0f2572d1cab9ccfa70e2 | 6,657,199,331,336 | 9c6755241eafce525184949f8c5dd11d2e6cefd1 | /src/leetcode/algorithms/LastStoneWeight.java | 86e8028366c274385a870bd9eaa30fb519642c35 | [] | no_license | Baltan/leetcode | https://github.com/Baltan/leetcode | 782491c3281ad04efbe01dd0dcba2d9a71637a31 | 0951d7371ab93800e04429fa48ce99c51284d4c4 | refs/heads/master | 2023-08-17T00:47:41.880000 | 2023-08-16T16:04:32 | 2023-08-16T16:04:32 | 172,838,932 | 13 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package leetcode.algorithms;
import java.util.PriorityQueue;
import java.util.Queue;
/**
* Description: 1046. Last Stone Weight
*
* @author Baltan
* @date 2019-05-19 14:04
*/
public class LastStoneWeight {
public static void main(String[] args) {
System.out.println(lastStoneWeight(new int[]{2, 7, 4, 1, 8, 1}));
System.out.println(lastStoneWeight(new int[]{43, 5, 4, 2, 54, 76, 54, 4, 23, 13, 64, 67, 76}));
System.out.println(lastStoneWeight(new int[]{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}));
}
public static int lastStoneWeight(int[] stones) {
Queue<Integer> queue = new PriorityQueue<>((x, y) -> y - x);
for (int stone : stones) {
queue.offer(stone);
}
while (queue.size() > 1) {
int a = queue.poll();
int b = queue.poll();
if (a > b) {
queue.offer(a - b);
}
}
return queue.isEmpty() ? 0 : queue.poll();
}
}
| UTF-8 | Java | 978 | java | LastStoneWeight.java | Java | [
{
"context": "Description: 1046. Last Stone Weight\n *\n * @author Baltan\n * @date 2019-05-19 14:04\n */\npublic class LastSt",
"end": 151,
"score": 0.999578058719635,
"start": 145,
"tag": "NAME",
"value": "Baltan"
}
] | null | [] | package leetcode.algorithms;
import java.util.PriorityQueue;
import java.util.Queue;
/**
* Description: 1046. Last Stone Weight
*
* @author Baltan
* @date 2019-05-19 14:04
*/
public class LastStoneWeight {
public static void main(String[] args) {
System.out.println(lastStoneWeight(new int[]{2, 7, 4, 1, 8, 1}));
System.out.println(lastStoneWeight(new int[]{43, 5, 4, 2, 54, 76, 54, 4, 23, 13, 64, 67, 76}));
System.out.println(lastStoneWeight(new int[]{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}));
}
public static int lastStoneWeight(int[] stones) {
Queue<Integer> queue = new PriorityQueue<>((x, y) -> y - x);
for (int stone : stones) {
queue.offer(stone);
}
while (queue.size() > 1) {
int a = queue.poll();
int b = queue.poll();
if (a > b) {
queue.offer(a - b);
}
}
return queue.isEmpty() ? 0 : queue.poll();
}
}
| 978 | 0.538855 | 0.481595 | 35 | 26.942858 | 25.57336 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.114286 | false | false | 3 |
4c7583e00a4e77f79e23247ca82e32858ec176b3 | 755,914,257,314 | bf80838c4f4ee88f009dfaa1d500778d7a482f8e | /Java/Servlets/StopWatch/src/com/stopwatch/models/Timer.java | fb60133c6400534c83f43ae96a86b5dd89c6a737 | [] | no_license | clauviscarra/DojoAssignments2 | https://github.com/clauviscarra/DojoAssignments2 | 2bb1a27279c9833ce8721718b41fa2b7f0a05060 | fe151d3af3cc5516021d6b069cc80f2f9abc0985 | refs/heads/master | 2020-12-02T19:30:15.742000 | 2017-07-13T16:07:51 | 2017-07-13T16:07:51 | 95,503,421 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.stopwatch.models;
import java.time.LocalTime;
public class Timer {
public Timer() {
// TODO Auto-generated constructor stub
}
}
| UTF-8 | Java | 147 | java | Timer.java | Java | [] | null | [] | package com.stopwatch.models;
import java.time.LocalTime;
public class Timer {
public Timer() {
// TODO Auto-generated constructor stub
}
}
| 147 | 0.727891 | 0.727891 | 10 | 13.7 | 14.38089 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 3 |
2ffe2531b162833a7ad5388009a55b8819df7e34 | 25,331,717,174,256 | 00a33dcbb28568b1484b79aaabda97a2c8d8a3b9 | /votacao-almoco-service/src/main/java/com/votacaoalmoco/properties/VotacaoProperties.java | d948f36b7184a4e272d389ed71b4633d98b5133f | [] | no_license | augustobb/augustobb-msn.com | https://github.com/augustobb/augustobb-msn.com | 09b9f4b72e77f7a7b282e49cff03b136934e0b38 | 80bc2bf88026bff4cc749ddca784b667893757a7 | refs/heads/master | 2021-04-23T02:13:32.815000 | 2020-03-26T19:50:45 | 2020-03-26T19:50:45 | 249,889,307 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.votacaoalmoco.properties;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.time.LocalTime;
@Getter
@Component
public class VotacaoProperties {
@Value("${votacao.horaLimite}")
private LocalTime horaLimite;
}
| UTF-8 | Java | 341 | java | VotacaoProperties.java | Java | [] | null | [] | package com.votacaoalmoco.properties;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.time.LocalTime;
@Getter
@Component
public class VotacaoProperties {
@Value("${votacao.horaLimite}")
private LocalTime horaLimite;
}
| 341 | 0.759531 | 0.759531 | 16 | 19.3125 | 18.919958 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 3 |
856fabb3af5b69c3ff03a02aebaca90a6e3706a8 | 30,648,886,689,141 | 69a4f2d51ebeea36c4d8192e25cfb5f3f77bef5e | /methods/Method_50750.java | 3289fa68627153316a6a9eb12a4a84a3698cdec2 | [] | no_license | P79N6A/icse_20_user_study | https://github.com/P79N6A/icse_20_user_study | 5b9c42c6384502fdc9588430899f257761f1f506 | 8a3676bc96059ea2c4f6d209016f5088a5628f3c | refs/heads/master | 2020-06-24T08:25:22.606000 | 2019-07-25T15:31:16 | 2019-07-25T15:31:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | private void validateCRUDCheckPresent(final AbstractApexNode<?> node,final Object data,final String crudMethod,final String typeCheck){
if (!typeToDMLOperationMapping.containsKey(typeCheck)) {
if (!isProperESAPICheckForDML(typeCheck,crudMethod)) {
addViolation(data,node);
}
}
else {
boolean properChecksHappened=false;
List<String> dmlOperationsChecked=typeToDMLOperationMapping.get(typeCheck);
for ( String dmlOp : dmlOperationsChecked) {
if (dmlOp.equalsIgnoreCase(crudMethod)) {
properChecksHappened=true;
break;
}
if (crudMethod.equals(ANY)) {
properChecksHappened=true;
break;
}
}
if (!properChecksHappened) {
addViolation(data,node);
}
}
}
| UTF-8 | Java | 757 | java | Method_50750.java | Java | [] | null | [] | private void validateCRUDCheckPresent(final AbstractApexNode<?> node,final Object data,final String crudMethod,final String typeCheck){
if (!typeToDMLOperationMapping.containsKey(typeCheck)) {
if (!isProperESAPICheckForDML(typeCheck,crudMethod)) {
addViolation(data,node);
}
}
else {
boolean properChecksHappened=false;
List<String> dmlOperationsChecked=typeToDMLOperationMapping.get(typeCheck);
for ( String dmlOp : dmlOperationsChecked) {
if (dmlOp.equalsIgnoreCase(crudMethod)) {
properChecksHappened=true;
break;
}
if (crudMethod.equals(ANY)) {
properChecksHappened=true;
break;
}
}
if (!properChecksHappened) {
addViolation(data,node);
}
}
}
| 757 | 0.685601 | 0.685601 | 24 | 30.541666 | 30.367168 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 3 |
3d6c3db09c6862ab907d07ac0db3878c5328e33f | 19,439,022,013,124 | b2b6fd1a8012a7bcb52a0f13aa881d1fbab08969 | /teeda/teeda-extension/src/main/java/org/seasar/teeda/extension/render/html/THtmlScriptRenderer.java | aeb6b8fc2e588faf6b37177388d65caee2eaf58d | [
"Apache-2.0"
] | permissive | kojisano/teeda | https://github.com/kojisano/teeda | 3655ef1466ce4d6fd1bff8f4f6b44a88fbde554d | c2cc8062e7280212e4a888a9efe06070f2b30572 | refs/heads/master | 2021-01-17T18:59:23.218000 | 2014-11-11T09:34:03 | 2014-11-11T09:34:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2004-2011 the Seasar Foundation and the Others.
*
* 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.seasar.teeda.extension.render.html;
import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.internal.IgnoreAttribute;
import org.seasar.framework.util.StringUtil;
import org.seasar.teeda.core.JsfConstants;
import org.seasar.teeda.core.render.AbstractRenderer;
import org.seasar.teeda.core.util.RendererUtil;
import org.seasar.teeda.extension.component.html.THtmlScript;
import org.seasar.teeda.extension.util.PathUtil;
import org.seasar.teeda.extension.util.VirtualResource;
/**
* @author shot
*/
public class THtmlScriptRenderer extends AbstractRenderer {
public static final String COMPONENT_FAMILY = THtmlScript.COMPONENT_FAMILY;
public static final String RENDERER_TYPE = THtmlScript.DEFAULT_RENDERER_TYPE;
private static final IgnoreAttribute IGNORE_COMPONENT;
static {
IGNORE_COMPONENT = buildIgnoreComponent();
}
public void encodeBegin(FacesContext context, UIComponent component)
throws IOException {
assertNotNull(context, component);
if (!component.isRendered()) {
return;
}
encodeTHtmlScriptBegin(context, (THtmlScript) component);
}
protected void encodeTHtmlScriptBegin(FacesContext context,
THtmlScript script) throws IOException {
ResponseWriter writer = context.getResponseWriter();
writer.startElement(JsfConstants.SCRIPT_ELEM, script);
RendererUtil.renderIdAttributeIfNecessary(writer, script,
getIdForRender(context, script));
String type = script.getType();
if (!StringUtil.isEmpty(type)) {
RendererUtil.renderAttribute(writer, JsfConstants.TYPE_ATTR, type,
null);
}
String lang = script.getLanguage();
if (!StringUtil.isEmpty(lang)) {
RendererUtil.renderAttribute(writer, JsfConstants.LANGUAGE_ATTR,
lang, null);
}
String src = script.getSrc();
if (!StringUtil.isEmpty(src)) {
if (VirtualResource.startsWithVirtualPath(src)) {
src = context.getExternalContext().getRequestContextPath() +
src;
} else {
final String baseViewId = script.getBaseViewId();
src = PathUtil.toAbsolutePath(context, src, baseViewId);
}
RendererUtil.renderAttribute(writer, JsfConstants.SRC_ATTR, src,
null);
}
renderRemainAttributes(script, writer, IGNORE_COMPONENT);
}
public void encodeEnd(FacesContext context, UIComponent component)
throws IOException {
assertNotNull(context, component);
if (!component.isRendered()) {
return;
}
encodeTHtmlScriptEnd(context, (THtmlScript) component);
}
protected void encodeTHtmlScriptEnd(FacesContext context, THtmlScript script)
throws IOException {
ResponseWriter writer = context.getResponseWriter();
writer.endElement(JsfConstants.SCRIPT_ELEM);
}
protected static IgnoreAttribute buildIgnoreComponent() {
IgnoreAttribute ignore = new IgnoreAttribute();
ignore.addAttributeName(JsfConstants.TYPE_ATTR);
ignore.addAttributeName(JsfConstants.LANGUAGE_ATTR);
ignore.addAttributeName(JsfConstants.SRC_ATTR);
ignore.addAttributeName("baseViewId");
return ignore;
}
} | UTF-8 | Java | 4,273 | java | THtmlScriptRenderer.java | Java | [
{
"context": "extension.util.VirtualResource;\r\n\r\n/**\r\n * @author shot\r\n */\r\npublic class THtmlScriptRenderer extends Abst",
"end": 1286,
"score": 0.9513187408447266,
"start": 1282,
"tag": "USERNAME",
"value": "shot"
}
] | null | [] | /*
* Copyright 2004-2011 the Seasar Foundation and the Others.
*
* 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.seasar.teeda.extension.render.html;
import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.internal.IgnoreAttribute;
import org.seasar.framework.util.StringUtil;
import org.seasar.teeda.core.JsfConstants;
import org.seasar.teeda.core.render.AbstractRenderer;
import org.seasar.teeda.core.util.RendererUtil;
import org.seasar.teeda.extension.component.html.THtmlScript;
import org.seasar.teeda.extension.util.PathUtil;
import org.seasar.teeda.extension.util.VirtualResource;
/**
* @author shot
*/
public class THtmlScriptRenderer extends AbstractRenderer {
public static final String COMPONENT_FAMILY = THtmlScript.COMPONENT_FAMILY;
public static final String RENDERER_TYPE = THtmlScript.DEFAULT_RENDERER_TYPE;
private static final IgnoreAttribute IGNORE_COMPONENT;
static {
IGNORE_COMPONENT = buildIgnoreComponent();
}
public void encodeBegin(FacesContext context, UIComponent component)
throws IOException {
assertNotNull(context, component);
if (!component.isRendered()) {
return;
}
encodeTHtmlScriptBegin(context, (THtmlScript) component);
}
protected void encodeTHtmlScriptBegin(FacesContext context,
THtmlScript script) throws IOException {
ResponseWriter writer = context.getResponseWriter();
writer.startElement(JsfConstants.SCRIPT_ELEM, script);
RendererUtil.renderIdAttributeIfNecessary(writer, script,
getIdForRender(context, script));
String type = script.getType();
if (!StringUtil.isEmpty(type)) {
RendererUtil.renderAttribute(writer, JsfConstants.TYPE_ATTR, type,
null);
}
String lang = script.getLanguage();
if (!StringUtil.isEmpty(lang)) {
RendererUtil.renderAttribute(writer, JsfConstants.LANGUAGE_ATTR,
lang, null);
}
String src = script.getSrc();
if (!StringUtil.isEmpty(src)) {
if (VirtualResource.startsWithVirtualPath(src)) {
src = context.getExternalContext().getRequestContextPath() +
src;
} else {
final String baseViewId = script.getBaseViewId();
src = PathUtil.toAbsolutePath(context, src, baseViewId);
}
RendererUtil.renderAttribute(writer, JsfConstants.SRC_ATTR, src,
null);
}
renderRemainAttributes(script, writer, IGNORE_COMPONENT);
}
public void encodeEnd(FacesContext context, UIComponent component)
throws IOException {
assertNotNull(context, component);
if (!component.isRendered()) {
return;
}
encodeTHtmlScriptEnd(context, (THtmlScript) component);
}
protected void encodeTHtmlScriptEnd(FacesContext context, THtmlScript script)
throws IOException {
ResponseWriter writer = context.getResponseWriter();
writer.endElement(JsfConstants.SCRIPT_ELEM);
}
protected static IgnoreAttribute buildIgnoreComponent() {
IgnoreAttribute ignore = new IgnoreAttribute();
ignore.addAttributeName(JsfConstants.TYPE_ATTR);
ignore.addAttributeName(JsfConstants.LANGUAGE_ATTR);
ignore.addAttributeName(JsfConstants.SRC_ATTR);
ignore.addAttributeName("baseViewId");
return ignore;
}
} | 4,273 | 0.669085 | 0.666277 | 111 | 36.513512 | 25.98193 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 3 |
0c825e287da56f3c30d6e53bf66c02cba47e3bb2 | 31,456,340,524,830 | 32de861bc2cccaf59b84c18f77a40b80743af084 | /artifact/release/JPonyo/trunk/jponyo/src/main/java/net/sf/ponyo/jponyo/stream/ContinuousMotionStream.java | f7da94bba047ffec7a156d80686703aaa39f27b3 | [] | no_license | christophpickl/ponyo-svn | https://github.com/christophpickl/ponyo-svn | f2419d9e880c3dc0da2f8863fb5766a94b60ac4a | 99971a27e7f9ee803ac70e5aabbaccaa3a82c1ed | refs/heads/master | 2021-03-08T19:28:49.379000 | 2012-09-14T20:50:57 | 2012-09-14T20:50:57 | 56,807,836 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.sf.ponyo.jponyo.stream;
import java.util.Collection;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import net.sf.ponyo.jponyo.common.async.DefaultAsync;
import net.sf.ponyo.jponyo.core.GlobalSpace;
import net.sf.ponyo.jponyo.user.User;
import net.sf.ponyo.jponyo.user.UserChangeListener;
import net.sf.ponyo.jponyo.user.UserState;
/**
* @since 0.1
*/
public class ContinuousMotionStream
extends DefaultAsync<MotionStreamListener>
implements MotionStreamListener, UserChangeListener {
private static final Log LOG = LogFactory.getLog(ContinuousMotionStream.class);
private final MotionStream internalStream;
private final GlobalSpace space;
private User currentlyTrackedUser;
public ContinuousMotionStream(MotionStream internalStream, GlobalSpace space) {
this.internalStream = internalStream;
this.space = space;
}
public void initAttachingToUser() {
final Collection<User> trackedUsers = this.space.getFilteredUsers(UserState.TRACKING);
LOG.debug("initAttachingToUser() ... trackedUsers.size=" + trackedUsers.size());
if(trackedUsers.isEmpty() == false) {
// return next == first == oldest user to reattach as our next victim, wuhahaha ;)
this.startListeningTo(trackedUsers.iterator().next());
}
}
public void onMotion(MotionData data) {
// LOG.info("onMotion(data="+data+") ... this.currentlyTrackedUser=" + this.currentlyTrackedUser);
if(this.currentlyTrackedUser != null && this.currentlyTrackedUser == data.getUser()) {
for (MotionStreamListener listener : this.getListeners()) {
listener.onMotion(data);
}
}
}
public void onUserChanged(User user, UserState state) {
if(state == UserState.TRACKING && this.currentlyTrackedUser == null) {
this.startListeningTo(user);
} else if(state == UserState.LOST && this.currentlyTrackedUser == user) {
this.stopListeningTo();
}
}
private void startListeningTo(User user) {
LOG.debug("startListeningTo(user=" + user + ")");
this.currentlyTrackedUser = user;
this.internalStream.addListenerFor(this.currentlyTrackedUser, this);
}
private void stopListeningTo() {
LOG.debug("stopListeningTo()");
this.internalStream.removeListenerFor(this.currentlyTrackedUser, this);
this.currentlyTrackedUser = null;
this.initAttachingToUser(); // retry
}
}
| UTF-8 | Java | 2,348 | java | ContinuousMotionStream.java | Java | [] | null | [] | package net.sf.ponyo.jponyo.stream;
import java.util.Collection;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import net.sf.ponyo.jponyo.common.async.DefaultAsync;
import net.sf.ponyo.jponyo.core.GlobalSpace;
import net.sf.ponyo.jponyo.user.User;
import net.sf.ponyo.jponyo.user.UserChangeListener;
import net.sf.ponyo.jponyo.user.UserState;
/**
* @since 0.1
*/
public class ContinuousMotionStream
extends DefaultAsync<MotionStreamListener>
implements MotionStreamListener, UserChangeListener {
private static final Log LOG = LogFactory.getLog(ContinuousMotionStream.class);
private final MotionStream internalStream;
private final GlobalSpace space;
private User currentlyTrackedUser;
public ContinuousMotionStream(MotionStream internalStream, GlobalSpace space) {
this.internalStream = internalStream;
this.space = space;
}
public void initAttachingToUser() {
final Collection<User> trackedUsers = this.space.getFilteredUsers(UserState.TRACKING);
LOG.debug("initAttachingToUser() ... trackedUsers.size=" + trackedUsers.size());
if(trackedUsers.isEmpty() == false) {
// return next == first == oldest user to reattach as our next victim, wuhahaha ;)
this.startListeningTo(trackedUsers.iterator().next());
}
}
public void onMotion(MotionData data) {
// LOG.info("onMotion(data="+data+") ... this.currentlyTrackedUser=" + this.currentlyTrackedUser);
if(this.currentlyTrackedUser != null && this.currentlyTrackedUser == data.getUser()) {
for (MotionStreamListener listener : this.getListeners()) {
listener.onMotion(data);
}
}
}
public void onUserChanged(User user, UserState state) {
if(state == UserState.TRACKING && this.currentlyTrackedUser == null) {
this.startListeningTo(user);
} else if(state == UserState.LOST && this.currentlyTrackedUser == user) {
this.stopListeningTo();
}
}
private void startListeningTo(User user) {
LOG.debug("startListeningTo(user=" + user + ")");
this.currentlyTrackedUser = user;
this.internalStream.addListenerFor(this.currentlyTrackedUser, this);
}
private void stopListeningTo() {
LOG.debug("stopListeningTo()");
this.internalStream.removeListenerFor(this.currentlyTrackedUser, this);
this.currentlyTrackedUser = null;
this.initAttachingToUser(); // retry
}
}
| 2,348 | 0.75 | 0.749148 | 76 | 29.894737 | 28.377892 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.710526 | false | false | 3 |
a1653c0fe9a3a5ddbeb3204692b7337d2d976cac | 16,965,120,869,142 | 1ac4266168fe559bdbeed5b3c488c4729d5294fb | /src/main/java/uk/ac/ebi/pride/archive/repo/services/file/FileService.java | af9151a2858fde2488f595d4b3b0f8352f3b2568 | [
"Apache-2.0"
] | permissive | selvaebi/repo | https://github.com/selvaebi/repo | f7abf7e8250cfb34533eb566f562bfc6a4f1b939 | d4d28ca29ebb2aa404475aaaf588c749b9215411 | refs/heads/master | 2022-10-18T02:51:11.028000 | 2020-06-12T00:21:10 | 2020-06-12T00:21:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uk.ac.ebi.pride.archive.repo.services.file;
import java.util.Collection;
/**
* @author Jose A. Dianes
* @author Rui Wang
* @version $Id$
*/
public interface FileService {
FileSummary findById(Long fileId) throws FileAccessException;
Collection<FileSummary> findAllByProjectAccession(String projectAccession)
throws FileAccessException;
Collection<FileSummary> findAllByAssayAccession(String assayAccession) throws FileAccessException;
Collection<FileSummary> findAllByProjectId(Long projectId) throws FileAccessException;
Collection<FileSummary> findAllByAssayId(Long assayId) throws FileAccessException;
}
| UTF-8 | Java | 642 | java | FileService.java | Java | [
{
"context": "ile;\n\nimport java.util.Collection;\n\n/**\n * @author Jose A. Dianes\n * @author Rui Wang\n * @version $Id$\n */\npublic i",
"end": 112,
"score": 0.9998669624328613,
"start": 98,
"tag": "NAME",
"value": "Jose A. Dianes"
},
{
"context": "lection;\n\n/**\n * @author Jos... | null | [] | package uk.ac.ebi.pride.archive.repo.services.file;
import java.util.Collection;
/**
* @author <NAME>
* @author <NAME>
* @version $Id$
*/
public interface FileService {
FileSummary findById(Long fileId) throws FileAccessException;
Collection<FileSummary> findAllByProjectAccession(String projectAccession)
throws FileAccessException;
Collection<FileSummary> findAllByAssayAccession(String assayAccession) throws FileAccessException;
Collection<FileSummary> findAllByProjectId(Long projectId) throws FileAccessException;
Collection<FileSummary> findAllByAssayId(Long assayId) throws FileAccessException;
}
| 632 | 0.805296 | 0.805296 | 22 | 28.181818 | 32.82687 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.318182 | false | false | 3 |
21d976326df88cd07e579aa90ed3abaac08d4b6d | 31,026,843,764,724 | 0d11833d7b7235b25648d30e91d19f3b44f744ed | /src/main/java/svenhjol/charm/world/feature/EndermitePowder.java | c0071bf410e9c443abeedac87562623df0d03965 | [
"MIT"
] | permissive | SokyranTheDragon/Charm | https://github.com/SokyranTheDragon/Charm | a43c033869f605c4d346e8514d8fd713d5184cc4 | 76e6906e30c24f4190564dd60a46d9f880a68457 | refs/heads/master | 2023-02-02T14:56:30.258000 | 2020-08-16T00:32:53 | 2020-08-16T00:32:53 | 286,748,472 | 0 | 0 | MIT | true | 2020-08-11T13:13:34 | 2020-08-11T13:13:33 | 2020-08-09T05:30:15 | 2020-08-11T03:20:19 | 17,481 | 0 | 0 | 0 | null | false | false | package svenhjol.charm.world.feature;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.monster.EntityEndermite;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.event.entity.living.LivingDropsEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import svenhjol.charm.Charm;
import svenhjol.charm.base.CharmEntityIDs;
import svenhjol.charm.world.entity.EntityEndermitePowder;
import svenhjol.charm.world.item.ItemEndermitePowder;
import svenhjol.meson.Feature;
public class EndermitePowder extends Feature
{
public static ItemEndermitePowder endermitePowder;
public static double dropChance;
public static double lootingBoost;
@Override
public String getDescription()
{
return "Endermite Powder has a chance of being dropped from an Endermite.\n" +
"Use it in the End to help locate an End City.";
}
@Override
public void configure()
{
super.configure();
dropChance = propDouble(
"Drop chance",
"Chance (out of 1.0) of an endermite dropping Endermite Powder when killed by the player.",
0.5D
);
// internal
lootingBoost = 0.1D;
}
@Override
public void preInit(FMLPreInitializationEvent event)
{
super.preInit(event);
endermitePowder = new ItemEndermitePowder();
String name = Charm.MOD_ID + ":endermite_powder";
EntityRegistry.registerModEntity(new ResourceLocation(name), EntityEndermitePowder.class, name, CharmEntityIDs.ENDERMITE_POWDER, Charm.instance, 80, 10, false);
}
@SubscribeEvent
public void onDrops(LivingDropsEvent event)
{
if (!event.getEntityLiving().world.isRemote
&& event.getEntityLiving() instanceof EntityEndermite
&& event.getSource().getTrueSource() instanceof EntityPlayer
&& event.getEntityLiving().world.rand.nextFloat() <= (dropChance + lootingBoost * event.getLootingLevel())
) {
Entity entity = event.getEntity();
ItemStack item = new ItemStack(endermitePowder);
event.getDrops().add(new EntityItem(entity.getEntityWorld(), entity.posX, entity.posY, entity.posZ, item));
}
}
@Override
public boolean hasSubscriptions()
{
return true;
}
}
| UTF-8 | Java | 2,617 | java | EndermitePowder.java | Java | [] | null | [] | package svenhjol.charm.world.feature;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.monster.EntityEndermite;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.event.entity.living.LivingDropsEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import svenhjol.charm.Charm;
import svenhjol.charm.base.CharmEntityIDs;
import svenhjol.charm.world.entity.EntityEndermitePowder;
import svenhjol.charm.world.item.ItemEndermitePowder;
import svenhjol.meson.Feature;
public class EndermitePowder extends Feature
{
public static ItemEndermitePowder endermitePowder;
public static double dropChance;
public static double lootingBoost;
@Override
public String getDescription()
{
return "Endermite Powder has a chance of being dropped from an Endermite.\n" +
"Use it in the End to help locate an End City.";
}
@Override
public void configure()
{
super.configure();
dropChance = propDouble(
"Drop chance",
"Chance (out of 1.0) of an endermite dropping Endermite Powder when killed by the player.",
0.5D
);
// internal
lootingBoost = 0.1D;
}
@Override
public void preInit(FMLPreInitializationEvent event)
{
super.preInit(event);
endermitePowder = new ItemEndermitePowder();
String name = Charm.MOD_ID + ":endermite_powder";
EntityRegistry.registerModEntity(new ResourceLocation(name), EntityEndermitePowder.class, name, CharmEntityIDs.ENDERMITE_POWDER, Charm.instance, 80, 10, false);
}
@SubscribeEvent
public void onDrops(LivingDropsEvent event)
{
if (!event.getEntityLiving().world.isRemote
&& event.getEntityLiving() instanceof EntityEndermite
&& event.getSource().getTrueSource() instanceof EntityPlayer
&& event.getEntityLiving().world.rand.nextFloat() <= (dropChance + lootingBoost * event.getLootingLevel())
) {
Entity entity = event.getEntity();
ItemStack item = new ItemStack(endermitePowder);
event.getDrops().add(new EntityItem(entity.getEntityWorld(), entity.posX, entity.posY, entity.posZ, item));
}
}
@Override
public boolean hasSubscriptions()
{
return true;
}
}
| 2,617 | 0.706152 | 0.702331 | 75 | 33.893333 | 32.062679 | 168 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.586667 | false | false | 3 |
a2b81d9c8cff9193eba30d7fefa7061ee567418c | 22,917,945,535,667 | d73649cf71e0cd52c1002e427c3d9958c0fc84fb | /Test1/src/musicalInstruments/Keyboard.java | 226e885c6f7ea10cf8766c3b73629c7f1bb3ecb6 | [] | no_license | bogonenko/h1 | https://github.com/bogonenko/h1 | bb71f734311fabd9894e3fdbc536fab86b718da7 | 1d98f822125f69c223d93fb9065731660b453e34 | refs/heads/master | 2021-01-01T19:01:06.593000 | 2015-03-24T18:22:21 | 2015-03-24T18:22:21 | 31,548,838 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package musicalInstruments;
public abstract class Keyboard extends MusicalInstrument {
@Override
public void play() {
System.out.println("Playing the "
+ this.getClass().getSimpleName().toLowerCase());
System.out.println();
}
@Override
public void tune() {
checkKeys();
System.out.println("Tuning the "
+ this.getClass().getSimpleName().toLowerCase());
}
private void checkKeys() {
System.out.println("Checking instrument's keys");
}
}
| UTF-8 | Java | 469 | java | Keyboard.java | Java | [] | null | [] | package musicalInstruments;
public abstract class Keyboard extends MusicalInstrument {
@Override
public void play() {
System.out.println("Playing the "
+ this.getClass().getSimpleName().toLowerCase());
System.out.println();
}
@Override
public void tune() {
checkKeys();
System.out.println("Tuning the "
+ this.getClass().getSimpleName().toLowerCase());
}
private void checkKeys() {
System.out.println("Checking instrument's keys");
}
}
| 469 | 0.697228 | 0.697228 | 25 | 17.76 | 19.345863 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.28 | false | false | 3 |
fa970e37de52c43932413b9d232ef18d6a9ec4a3 | 15,161,234,580,415 | dbe46e26e0bd6f62c68511c985b1666c7545940b | /src/cn/edu/nju/gqx/provider/TaskService.java | 374d3a58ffc62219ee420671b6238eec967ffb46 | [] | no_license | gqx/dubboserver | https://github.com/gqx/dubboserver | 4088aa77fec7ae0a2fa5e085ee2852badc53f3f6 | 011423ef76c745fb5b287b3c575eb3d094b4588c | refs/heads/master | 2021-01-18T14:44:59.722000 | 2014-10-05T15:21:55 | 2014-10-05T15:21:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.edu.nju.gqx.provider;
import java.util.ArrayList;
import java.util.List;
import cn.edu.nju.gqx.db.po.Switch;
import cn.edu.nju.gqx.db.po.Task;
public interface TaskService {
public List getAll();
public int setClock(int[] sid,String tname,String onTime,String offTime);
public void initTask();
public int setClock(ArrayList<Switch> switchList,String tname, String onTime, String offTime);
public int setClock(String[] names, String tname,String onTime, String offTime);
public Task getTaskById(int id);
public int updateTask(int tid,String onTime,String offTime);
public int deleteTaskById(int id);
}
| UTF-8 | Java | 641 | java | TaskService.java | Java | [] | null | [] | package cn.edu.nju.gqx.provider;
import java.util.ArrayList;
import java.util.List;
import cn.edu.nju.gqx.db.po.Switch;
import cn.edu.nju.gqx.db.po.Task;
public interface TaskService {
public List getAll();
public int setClock(int[] sid,String tname,String onTime,String offTime);
public void initTask();
public int setClock(ArrayList<Switch> switchList,String tname, String onTime, String offTime);
public int setClock(String[] names, String tname,String onTime, String offTime);
public Task getTaskById(int id);
public int updateTask(int tid,String onTime,String offTime);
public int deleteTaskById(int id);
}
| 641 | 0.75507 | 0.75507 | 18 | 33.611111 | 27.156212 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.777778 | false | false | 3 |
d6fa71c1d13c1f622d28d6a9fa9edf17e3971a9c | 11,381,663,360,751 | 1e243dc3004c82ae024507469db648704da3995d | /app/src/main/java/com/janlishak/keepappworkouts/services/persistance/IPlanRepository.java | 34a4dafb4e1b1b6436c06dc14ec19b7f88551ef3 | [] | no_license | janlishak/keep-app-workouts | https://github.com/janlishak/keep-app-workouts | 654a3fa81996c23fd827c0ffa73059a41e1abbf1 | 9f51f737218adc049b3ea8e768bccc5fd96bcebc | refs/heads/main | 2023-04-28T09:05:49.040000 | 2021-05-20T21:49:10 | 2021-05-20T21:49:10 | 348,144,432 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.janlishak.keepappworkouts.services.persistance;
import androidx.lifecycle.LiveData;
import com.janlishak.keepappworkouts.model.Plan;
import java.util.List;
public interface IPlanRepository {
LiveData<List<Plan>> getPlans();
void setCurrentPlan(Plan selectedPlan);
LiveData<Plan> getSelectedPlan();
void removePlan(Plan Plan);
void createPlan(Plan Plan);
}
| UTF-8 | Java | 407 | java | IPlanRepository.java | Java | [] | null | [] | package com.janlishak.keepappworkouts.services.persistance;
import androidx.lifecycle.LiveData;
import com.janlishak.keepappworkouts.model.Plan;
import java.util.List;
public interface IPlanRepository {
LiveData<List<Plan>> getPlans();
void setCurrentPlan(Plan selectedPlan);
LiveData<Plan> getSelectedPlan();
void removePlan(Plan Plan);
void createPlan(Plan Plan);
}
| 407 | 0.744472 | 0.744472 | 15 | 25.133333 | 19.342068 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 3 |
7c727dddaded54d749c3194416a8172ca3859798 | 15,590,731,345,686 | 7c045cde82be15b0d669d3db24eb165b696bc14e | /src/main/java/the_gatherer/actions/EnchantAction.java | 9f9557db1092e540c95cd4408951df11b5907e25 | [
"MIT"
] | permissive | Celicath/GathererMod | https://github.com/Celicath/GathererMod | b5d8362db344ee96a52115936ed7a1b3ae2a792c | b8c9604bc14a56faa9994756f2c567545b51c2a9 | refs/heads/master | 2023-02-03T09:02:06.207000 | 2023-01-28T18:54:02 | 2023-01-28T18:57:15 | 152,971,941 | 2 | 5 | MIT | false | 2019-05-02T14:19:19 | 2018-10-14T12:34:13 | 2019-05-01T02:48:33 | 2019-05-02T14:19:18 | 24,049 | 1 | 3 | 0 | Java | false | false | package the_gatherer.actions;
import com.megacrit.cardcrawl.actions.AbstractGameAction;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.core.Settings;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.localization.UIStrings;
import the_gatherer.GathererMod;
import the_gatherer.cards.MiningStrike;
import the_gatherer.cards.WitheringStrike;
import java.util.ArrayList;
public class EnchantAction extends AbstractGameAction {
private static final UIStrings uiStrings = CardCrawlGame.languagePack.getUIString("Gatherer:EnchantAction");
public static final String[] TEXT = uiStrings.TEXT;
private AbstractPlayer p;
private ArrayList<AbstractCard> notStrike = new ArrayList<>();
private int amount;
public EnchantAction(int amount) {
this.actionType = ActionType.CARD_MANIPULATION;
this.p = AbstractDungeon.player;
this.duration = Settings.ACTION_DUR_FAST;
this.amount = amount;
}
public void update() {
if (this.duration == Settings.ACTION_DUR_FAST) {
if (AbstractDungeon.getMonsters().areMonstersBasicallyDead()) {
this.isDone = true;
return;
}
for (AbstractCard c : this.p.hand.group) {
if (!c.hasTag(AbstractCard.CardTags.STRIKE)) {
notStrike.add(c);
}
}
if (this.notStrike.size() == this.p.hand.group.size()) {
this.isDone = true;
return;
} else if (this.p.hand.group.size() - this.notStrike.size() == 1) {
for (AbstractCard c : this.p.hand.group) {
if (!notStrike.contains(c)) {
doEnchant(c, amount);
this.isDone = true;
return;
}
}
}
this.p.hand.group.removeAll(this.notStrike);
GathererMod.cardSelectScreenCard = null;
GathererMod.enchantAmount = amount;
AbstractDungeon.handCardSelectScreen.open(TEXT[0], 1, false, false, false, true);
this.tickDuration();
return;
}
if (!AbstractDungeon.handCardSelectScreen.wereCardsRetrieved) {
for (AbstractCard c : AbstractDungeon.handCardSelectScreen.selectedCards.group) {
if (!notStrike.contains(c)) {
doEnchant(c, amount);
this.p.hand.addToTop(c);
}
}
this.returnCards();
AbstractDungeon.handCardSelectScreen.wereCardsRetrieved = true;
AbstractDungeon.handCardSelectScreen.selectedCards.group.clear();
GathererMod.enchantAmount = 0;
this.isDone = true;
}
this.tickDuration();
}
public static void doEnchant(AbstractCard c, int amount) {
c.updateCost(1);
c.baseDamage += amount;
if (c.baseMagicNumber != -1) {
int delta = 1;
if (c instanceof MiningStrike) {
delta = -1;
if (c.baseMagicNumber + delta < 5)
delta = 0;
}
c.baseMagicNumber += delta;
c.magicNumber = c.baseMagicNumber;
if (c instanceof WitheringStrike && WitheringStrike.EXTENDED_DESCRIPTION != null) {
c.rawDescription = WitheringStrike.EXTENDED_DESCRIPTION[0];
c.initializeDescription();
}
}
c.superFlash();
}
private void returnCards() {
for (AbstractCard c : this.notStrike) {
this.p.hand.addToTop(c);
}
this.p.hand.refreshHandLayout();
}
}
| UTF-8 | Java | 3,176 | java | EnchantAction.java | Java | [] | null | [] | package the_gatherer.actions;
import com.megacrit.cardcrawl.actions.AbstractGameAction;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.core.Settings;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.localization.UIStrings;
import the_gatherer.GathererMod;
import the_gatherer.cards.MiningStrike;
import the_gatherer.cards.WitheringStrike;
import java.util.ArrayList;
public class EnchantAction extends AbstractGameAction {
private static final UIStrings uiStrings = CardCrawlGame.languagePack.getUIString("Gatherer:EnchantAction");
public static final String[] TEXT = uiStrings.TEXT;
private AbstractPlayer p;
private ArrayList<AbstractCard> notStrike = new ArrayList<>();
private int amount;
public EnchantAction(int amount) {
this.actionType = ActionType.CARD_MANIPULATION;
this.p = AbstractDungeon.player;
this.duration = Settings.ACTION_DUR_FAST;
this.amount = amount;
}
public void update() {
if (this.duration == Settings.ACTION_DUR_FAST) {
if (AbstractDungeon.getMonsters().areMonstersBasicallyDead()) {
this.isDone = true;
return;
}
for (AbstractCard c : this.p.hand.group) {
if (!c.hasTag(AbstractCard.CardTags.STRIKE)) {
notStrike.add(c);
}
}
if (this.notStrike.size() == this.p.hand.group.size()) {
this.isDone = true;
return;
} else if (this.p.hand.group.size() - this.notStrike.size() == 1) {
for (AbstractCard c : this.p.hand.group) {
if (!notStrike.contains(c)) {
doEnchant(c, amount);
this.isDone = true;
return;
}
}
}
this.p.hand.group.removeAll(this.notStrike);
GathererMod.cardSelectScreenCard = null;
GathererMod.enchantAmount = amount;
AbstractDungeon.handCardSelectScreen.open(TEXT[0], 1, false, false, false, true);
this.tickDuration();
return;
}
if (!AbstractDungeon.handCardSelectScreen.wereCardsRetrieved) {
for (AbstractCard c : AbstractDungeon.handCardSelectScreen.selectedCards.group) {
if (!notStrike.contains(c)) {
doEnchant(c, amount);
this.p.hand.addToTop(c);
}
}
this.returnCards();
AbstractDungeon.handCardSelectScreen.wereCardsRetrieved = true;
AbstractDungeon.handCardSelectScreen.selectedCards.group.clear();
GathererMod.enchantAmount = 0;
this.isDone = true;
}
this.tickDuration();
}
public static void doEnchant(AbstractCard c, int amount) {
c.updateCost(1);
c.baseDamage += amount;
if (c.baseMagicNumber != -1) {
int delta = 1;
if (c instanceof MiningStrike) {
delta = -1;
if (c.baseMagicNumber + delta < 5)
delta = 0;
}
c.baseMagicNumber += delta;
c.magicNumber = c.baseMagicNumber;
if (c instanceof WitheringStrike && WitheringStrike.EXTENDED_DESCRIPTION != null) {
c.rawDescription = WitheringStrike.EXTENDED_DESCRIPTION[0];
c.initializeDescription();
}
}
c.superFlash();
}
private void returnCards() {
for (AbstractCard c : this.notStrike) {
this.p.hand.addToTop(c);
}
this.p.hand.refreshHandLayout();
}
}
| 3,176 | 0.715995 | 0.712532 | 108 | 28.407408 | 23.826937 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.759259 | false | false | 3 |
f8c181a41a892a1a4a38e01f3dac364f9960bf46 | 17,128,329,604,353 | aff8b058d37eb0c6ace1dea1d1f2c3ebdf768474 | /src/main/java/com/lolaage/swagger/SwaggerConfig.java | 654cfe8b0992b48f694b9ee18b80c43fd75dab16 | [] | no_license | huangxuanheng/http-netty5.0 | https://github.com/huangxuanheng/http-netty5.0 | c0c20c2b186c6ca895e220f1c1385ef71bf4e9aa | c1876d015200c97b7c176f87bc666bdbad40ba1b | refs/heads/master | 2020-03-30T04:43:47.042000 | 2018-10-01T05:24:58 | 2018-10-01T05:24:58 | 150,759,151 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lolaage.swagger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* <p>作者 yaohua.liu
* <p>日期 2017-09-19 20:01
* <p>说明 swagger配置
*/
/*@Configuration
@EnableSwagger2*/
public class SwaggerConfig extends WebMvcConfigurationSupport {
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2).host("192.168.43.110:7200")
.select()
.apis(RequestHandlerSelectors.basePackage("com.lolaage.helper.controller"))
//.paths(regex("/product.*"))
.build();
}
}
| UTF-8 | Java | 986 | java | SwaggerConfig.java | Java | [
{
"context": "swagger2.annotations.EnableSwagger2;\n\n/**\n * <p>作者 yaohua.liu\n * <p>日期 2017-09-19 20:01\n * <p>说明 swagg",
"end": 488,
"score": 0.5083121657371521,
"start": 487,
"tag": "NAME",
"value": "y"
},
{
"context": "agger2.annotations.EnableSwagger2;\n\n/**\n * <p>作者 yaohua.l... | null | [] | package com.lolaage.swagger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* <p>作者 yaohua.liu
* <p>日期 2017-09-19 20:01
* <p>说明 swagger配置
*/
/*@Configuration
@EnableSwagger2*/
public class SwaggerConfig extends WebMvcConfigurationSupport {
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2).host("192.168.43.110:7200")
.select()
.apis(RequestHandlerSelectors.basePackage("com.lolaage.helper.controller"))
//.paths(regex("/product.*"))
.build();
}
}
| 986 | 0.739175 | 0.707217 | 27 | 34.925926 | 27.889896 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 3 |
6a428da62b7af68116a2bf6a02b109eb8188202c | 11,398,843,266,936 | 3e01b7f60f474f90f31a08f71d93a79ff5528f68 | /CS_2/Pong_java/Pong/Seconds.java | 8c0cf6defa275ef399c22c2f80210a68babe6a06 | [] | no_license | juspurplan/old_code | https://github.com/juspurplan/old_code | 73b8eb22ac294165f65929ce433d4870294921ec | 49e67aca12c1246ab894284411b9e95cc76c1e4c | refs/heads/master | 2020-12-14T08:52:40.763000 | 2017-07-13T01:14:21 | 2017-07-13T01:14:21 | 95,519,866 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Seconds
{
public static void main (String[]args)
{
final int year = 365;
final int day = 24;
final int hour = 60;
final int minute = 60;
int total = year*day*hour*minute;
System.out.println("There are " +total + " seconds in one year.");
}
} | UTF-8 | Java | 275 | java | Seconds.java | Java | [] | null | [] | class Seconds
{
public static void main (String[]args)
{
final int year = 365;
final int day = 24;
final int hour = 60;
final int minute = 60;
int total = year*day*hour*minute;
System.out.println("There are " +total + " seconds in one year.");
}
} | 275 | 0.618182 | 0.585455 | 13 | 19.307692 | 19.080336 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.615385 | false | false | 3 |
f6976cfb422fcee98a963a19caff5ec96f626bec | 29,334,626,679,051 | d1109fe804dec979d90ec5b3c0e0de7930e9b2bf | /CRM/CRM/CRM-ejb/src/main/java/tn/esprit/CRM/persistence/Proposition.java | 9b31b83ba810ebaa4ac9316a3c275f78ef7a6277 | [] | no_license | OnsBellazreg/CRM-for-PhoneOperator | https://github.com/OnsBellazreg/CRM-for-PhoneOperator | a542b34207c782f265546d769b5d4e3da919f839 | 59724b34c675c2f9f1bb7da3ef4e325a32f73bab | refs/heads/master | 2022-12-04T11:26:03.301000 | 2019-09-02T11:10:47 | 2019-09-02T11:10:47 | 205,838,150 | 0 | 0 | null | false | 2022-11-24T04:25:04 | 2019-09-02T11:03:53 | 2019-09-02T11:21:30 | 2022-11-24T04:25:03 | 64,442 | 0 | 0 | 3 | CSS | false | false | package tn.esprit.CRM.persistence;
import java.io.Serializable;
import java.lang.Integer;
import java.lang.String;
import javax.persistence.*;
/**
* Entity implementation class for Entity: Proposition
*
*/
@Entity
public class Proposition implements Serializable {
@Id
private Integer id_proposition;
private String Description;
private Integer oui;
private Integer non;
private static final long serialVersionUID = 1L;
@ManyToOne
private User user3;
public User getUser3() {
return user3;
}
public void setUser3(User user3) {
this.user3 = user3;
}
public Proposition() {
super();
}
public Integer getId_proposition() {
return this.id_proposition;
}
public void setId_proposition(Integer id_proposition) {
this.id_proposition = id_proposition;
}
public String getDescription() {
return this.Description;
}
public void setDescription(String Description) {
this.Description = Description;
}
public Integer getOui() {
return oui;
}
public void setOui(Integer oui) {
this.oui = oui;
}
public Integer getNon() {
return non;
}
public void setNon(Integer non) {
this.non = non;
}
}
| UTF-8 | Java | 1,156 | java | Proposition.java | Java | [] | null | [] | package tn.esprit.CRM.persistence;
import java.io.Serializable;
import java.lang.Integer;
import java.lang.String;
import javax.persistence.*;
/**
* Entity implementation class for Entity: Proposition
*
*/
@Entity
public class Proposition implements Serializable {
@Id
private Integer id_proposition;
private String Description;
private Integer oui;
private Integer non;
private static final long serialVersionUID = 1L;
@ManyToOne
private User user3;
public User getUser3() {
return user3;
}
public void setUser3(User user3) {
this.user3 = user3;
}
public Proposition() {
super();
}
public Integer getId_proposition() {
return this.id_proposition;
}
public void setId_proposition(Integer id_proposition) {
this.id_proposition = id_proposition;
}
public String getDescription() {
return this.Description;
}
public void setDescription(String Description) {
this.Description = Description;
}
public Integer getOui() {
return oui;
}
public void setOui(Integer oui) {
this.oui = oui;
}
public Integer getNon() {
return non;
}
public void setNon(Integer non) {
this.non = non;
}
}
| 1,156 | 0.713668 | 0.706747 | 64 | 17.0625 | 15.965661 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.203125 | false | false | 3 |
72c37ec8be641cc9957c0384d561b59ef2099741 | 6,717,328,910,691 | a8f9932905efafde74773d8844928c51982423b2 | /app/src/main/java/com/hera/hng/heralios/Electronics.java | 5a0b4ced21f024986e90a96fa95f253ec04e5a03 | [] | no_license | hngi/Team-Hera-Mobile-Solar-Calculator | https://github.com/hngi/Team-Hera-Mobile-Solar-Calculator | 3556c15b13f9eb9bbe54b626b1c3e6f6afadca16 | 5751b4556c34f5e99310ef08c0d0d28566f6cff2 | refs/heads/master | 2020-07-30T20:46:08.676000 | 2019-10-02T13:56:21 | 2019-10-02T13:56:21 | 210,353,822 | 0 | 2 | null | false | 2019-10-02T13:56:23 | 2019-09-23T12:49:30 | 2019-09-30T10:42:33 | 2019-10-02T13:56:22 | 2,165 | 0 | 2 | 0 | Java | false | false | package com.hera.hng.heralios;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class Electronics extends Fragment implements AdapterView.OnItemSelectedListener {
Button add;
ListView electronics_list;
List<String> electronics_names=new ArrayList<>();
DatabaseHelper helper;
EditText input;
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_electronics, container, false);
electronics_list = (ListView) view.findViewById(R.id.listView2);
input = (EditText) view.findViewById(R.id.editText);
helper = new DatabaseHelper(this.getContext());
helper.insertElectronics();
List<Electronic> Es = helper.getAllElectronics();
for(Electronic e: Es){
electronics_names.add(e.getName());
}
final ArrayAdapter adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1 , electronics_names);
electronics_list.setAdapter(adapter);
add = view.findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
boolean found = false;
if(TextUtils.isEmpty(input.getText())){
input.setError("Text box cannot be empty");
}else{
String input_value = input.getText().toString();
String input_value_lower = input.getText().toString().toLowerCase();
for(int i=0; i<electronics_names.size();i++) {
String lower_electronic = electronics_names.get(i).toLowerCase();
if (input_value_lower.equals(lower_electronic)) {
found = true;
break;
}
}
if(found == true){
input.setError("Electronic already in list");
}else{
helper.addElectronic(input_value);
electronics_names.add(input_value);
input.setText("");
Toast.makeText(getActivity(), input_value + " added",
Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
electronics_list.smoothScrollToPosition(adapter.getCount() - 1);
}
}
/*
// Perform action on click
Intent activityChangeIntent = new Intent(getActivity(), EditCalculation.class);
// currentContext.startActivity(activityChangeIntent);
getActivity().startActivity(activityChangeIntent);*/
}
});
return view;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
| UTF-8 | Java | 3,704 | java | Electronics.java | Java | [] | null | [] | package com.hera.hng.heralios;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class Electronics extends Fragment implements AdapterView.OnItemSelectedListener {
Button add;
ListView electronics_list;
List<String> electronics_names=new ArrayList<>();
DatabaseHelper helper;
EditText input;
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_electronics, container, false);
electronics_list = (ListView) view.findViewById(R.id.listView2);
input = (EditText) view.findViewById(R.id.editText);
helper = new DatabaseHelper(this.getContext());
helper.insertElectronics();
List<Electronic> Es = helper.getAllElectronics();
for(Electronic e: Es){
electronics_names.add(e.getName());
}
final ArrayAdapter adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1 , electronics_names);
electronics_list.setAdapter(adapter);
add = view.findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
boolean found = false;
if(TextUtils.isEmpty(input.getText())){
input.setError("Text box cannot be empty");
}else{
String input_value = input.getText().toString();
String input_value_lower = input.getText().toString().toLowerCase();
for(int i=0; i<electronics_names.size();i++) {
String lower_electronic = electronics_names.get(i).toLowerCase();
if (input_value_lower.equals(lower_electronic)) {
found = true;
break;
}
}
if(found == true){
input.setError("Electronic already in list");
}else{
helper.addElectronic(input_value);
electronics_names.add(input_value);
input.setText("");
Toast.makeText(getActivity(), input_value + " added",
Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
electronics_list.smoothScrollToPosition(adapter.getCount() - 1);
}
}
/*
// Perform action on click
Intent activityChangeIntent = new Intent(getActivity(), EditCalculation.class);
// currentContext.startActivity(activityChangeIntent);
getActivity().startActivity(activityChangeIntent);*/
}
});
return view;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
| 3,704 | 0.594762 | 0.593143 | 105 | 34.276192 | 28.640795 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.638095 | false | false | 3 |
3ba725ebaff1dd4a86b91bd1c0451a91f3ebd1d2 | 30,331,059,113,147 | 1b0ff0d78795e374b3b9c4c50b9d3a86b8256f6e | /src/main/java/com/opencsi/jscepcli/Constants.java | ad66182400a29e15e5f18f064ea3f9ba5123b551 | [] | no_license | ip6li/jscep-cli | https://github.com/ip6li/jscep-cli | a63cf6e31eed85913fdd5d1de117b7006c9bbd49 | 38babee21e4c50d0ef920dbee29847da9a991675 | refs/heads/master | 2021-07-02T00:27:32.607000 | 2017-09-17T06:10:18 | 2017-09-17T06:10:18 | 103,630,786 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.opencsi.jscepcli;
public final class Constants {
public static final String algorithm ="SHA256withRSA";
public static final String privateKeyBegin = "-----BEGIN PRIVATE KEY-----";
public static final String privateKeyEnd = "-----END PRIVATE KEY-----";
public static final String csrBegin = "-----BEGIN CERTIFICATE REQUEST-----";
public static final String csrEnd = "-----END CERTIFICATE REQUEST-----";
}
| UTF-8 | Java | 439 | java | Constants.java | Java | [] | null | [] | package com.opencsi.jscepcli;
public final class Constants {
public static final String algorithm ="SHA256withRSA";
public static final String privateKeyBegin = "-----BEGIN PRIVATE KEY-----";
public static final String privateKeyEnd = "-----END PRIVATE KEY-----";
public static final String csrBegin = "-----BEGIN CERTIFICATE REQUEST-----";
public static final String csrEnd = "-----END CERTIFICATE REQUEST-----";
}
| 439 | 0.685649 | 0.678815 | 11 | 38.909092 | 33.703129 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 3 |
51d289e403f4623d69af1d62121e13bd49771a4e | 17,085,379,967,982 | f91fea19a9be149e2923062f3624f901c4449e54 | /src/main/java/com/koko/service/CarImgService.java | 399cd825a98105da7a5cf44ef0cdd5d9a8ba5c83 | [] | no_license | obfield/car_rental | https://github.com/obfield/car_rental | b1f9fb3d7641aef00a40d5d915033a1357d1b80c | 0ebb4342cd1ca23d2b1030c0c66b79d029363465 | refs/heads/main | 2023-03-29T21:11:38.389000 | 2021-03-30T04:02:56 | 2021-03-30T04:02:56 | 322,229,251 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.koko.service;
import com.koko.pojo.CarImg;
import java.util.List;
/**
* @author 13629
* @create 2021/2/24 12:46
*/
public interface CarImgService {
int addCarImg(Integer carId, String imgUrl);
List<String> queryBycarId(Integer carId);
int delectByCarId(Integer carId);
}
| UTF-8 | Java | 322 | java | CarImgService.java | Java | [
{
"context": "Img;\r\n\r\nimport java.util.List;\r\n\r\n/**\r\n * @author 13629\r\n * @create 2021/2/24 12:46\r\n */\r\npublic interfac",
"end": 108,
"score": 0.9992191195487976,
"start": 103,
"tag": "USERNAME",
"value": "13629"
}
] | null | [] | package com.koko.service;
import com.koko.pojo.CarImg;
import java.util.List;
/**
* @author 13629
* @create 2021/2/24 12:46
*/
public interface CarImgService {
int addCarImg(Integer carId, String imgUrl);
List<String> queryBycarId(Integer carId);
int delectByCarId(Integer carId);
}
| 322 | 0.670807 | 0.621118 | 18 | 15.888889 | 16.702923 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false | 3 |
766c19e2b44ecd5d3dfc2622fa6c36c64cfc92c5 | 12,335,146,077,109 | 8d8776f923e7cc844196f4c70c21a337e5f5552e | /shared/src/main/java/se/spaced/client/resources/zone/ZoneXmlWriter.java | 23460e640e1e14652d9a0bc096743015b7ee179a | [] | no_license | FearlessGames/spaced | https://github.com/FearlessGames/spaced | 7853599f11258daf62a72ba4c8f40ef8c88beb85 | 27690cd19867c5b9b64186a1e9a26bd813497c87 | refs/heads/master | 2020-04-25T04:28:54.189000 | 2017-09-08T21:10:58 | 2017-09-08T21:10:58 | 172,511,474 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package se.spaced.client.resources.zone;
import se.spaced.shared.resources.zone.Zone;
public interface ZoneXmlWriter {
void saveZone(String zoneFile, Zone zone);
} | UTF-8 | Java | 172 | java | ZoneXmlWriter.java | Java | [] | null | [] | package se.spaced.client.resources.zone;
import se.spaced.shared.resources.zone.Zone;
public interface ZoneXmlWriter {
void saveZone(String zoneFile, Zone zone);
} | 172 | 0.773256 | 0.773256 | 7 | 22.857143 | 19.830917 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 3 |
8a7f8876c1bb9dad9f1d05ade4cc5e3b0c244c95 | 4,080,218,972,206 | 2fdf9bb8c2804f4bb016b93bf9d133663d3266d1 | /CaptAmerica.java | cc2338105b46a70ade1925c56522bce1814711db | [] | no_license | david30f/hello-world | https://github.com/david30f/hello-world | 9ec5083d56e60721b2c350e7856b0a0dd4fa9b25 | 926bdcdc9c34481639c108d9f851cb95135bc992 | refs/heads/master | 2021-01-01T05:22:55.792000 | 2016-05-26T20:12:16 | 2016-05-26T20:12:16 | 59,754,079 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class CaptAmerica {
public CaptAmerica() {
attack();
}
public static void attack() {
System.out.println("Captain America attacked with shield");
}
} | UTF-8 | Java | 173 | java | CaptAmerica.java | Java | [] | null | [] | public class CaptAmerica {
public CaptAmerica() {
attack();
}
public static void attack() {
System.out.println("Captain America attacked with shield");
}
} | 173 | 0.66474 | 0.66474 | 9 | 17.444445 | 18.909792 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.222222 | false | false | 3 |
ae9735e1892847203128de2fb0f5e308db83f618 | 15,307,263,503,845 | 9903cc6703f602209aa52617b6729a7d5d7351a7 | /src/sogoodwawiui/edit/element/CnNameEditingSupport.java | ea8380701c51562a5b88db564993125c5ef26a31 | [] | no_license | xsun1213/sogoodwawiui | https://github.com/xsun1213/sogoodwawiui | b541a03b0ebc51a995513ec471c7fe40c0920375 | b37d36b27d42fc34e59a4bb3e90b0658c0f8ff1e | refs/heads/master | 2018-12-22T23:00:30.767000 | 2018-12-20T13:12:59 | 2018-12-20T13:12:59 | 95,942,422 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sogoodwawiui.edit.element;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import sogoodwawiui.dialog.EntellitradeDialog;
import sogoodwawiui.model.Element;
import sogoodwawiui.util.CommonUtil;
import sogoodwawiui.util.EntellitradeUtil;
/**
* @author xiaobo
*
*/
public class CnNameEditingSupport extends EditingSupport {
private final TableViewer viewer;
private EntellitradeDialog dialog;
public CnNameEditingSupport(TableViewer viewer, EntellitradeDialog dialog) {
super(viewer);
this.viewer = viewer;
this.dialog = dialog;
}
@Override
protected CellEditor getCellEditor(Object element) {
return new TextCellEditor(viewer.getTable());
}
@Override
protected boolean canEdit(Object element) {
return true;
}
@Override
protected Object getValue(Object element) {
Element e = (Element) element;
return e.getCnName();
}
@Override
protected void setValue(Object element, Object value) {
Element e = (Element) element;
String oldCnName = e.getCnName();
if (oldCnName.equals(value.toString())) {
return;
}
StringBuilder info = CommonUtil.textConsoleBefore(dialog.getTextConsole(), "Uploading old cnName " + oldCnName + " newCnName " + value.toString() + " is starting... ");
if (EntellitradeUtil.editElementUnMarshallCnName(e.getId(), value.toString(), info)) {
e.setCnName(value.toString());
viewer.update(element, null);
}
CommonUtil.textConsoleAfter(dialog.getTextConsole(), info);
}
}
| UTF-8 | Java | 1,665 | java | CnNameEditingSupport.java | Java | [
{
"context": "odwawiui.util.EntellitradeUtil;\r\n\r\n/**\r\n * @author xiaobo\r\n * \r\n */\r\npublic class CnNameEditingSupport exte",
"end": 423,
"score": 0.9993420243263245,
"start": 417,
"tag": "USERNAME",
"value": "xiaobo"
}
] | null | [] | package sogoodwawiui.edit.element;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import sogoodwawiui.dialog.EntellitradeDialog;
import sogoodwawiui.model.Element;
import sogoodwawiui.util.CommonUtil;
import sogoodwawiui.util.EntellitradeUtil;
/**
* @author xiaobo
*
*/
public class CnNameEditingSupport extends EditingSupport {
private final TableViewer viewer;
private EntellitradeDialog dialog;
public CnNameEditingSupport(TableViewer viewer, EntellitradeDialog dialog) {
super(viewer);
this.viewer = viewer;
this.dialog = dialog;
}
@Override
protected CellEditor getCellEditor(Object element) {
return new TextCellEditor(viewer.getTable());
}
@Override
protected boolean canEdit(Object element) {
return true;
}
@Override
protected Object getValue(Object element) {
Element e = (Element) element;
return e.getCnName();
}
@Override
protected void setValue(Object element, Object value) {
Element e = (Element) element;
String oldCnName = e.getCnName();
if (oldCnName.equals(value.toString())) {
return;
}
StringBuilder info = CommonUtil.textConsoleBefore(dialog.getTextConsole(), "Uploading old cnName " + oldCnName + " newCnName " + value.toString() + " is starting... ");
if (EntellitradeUtil.editElementUnMarshallCnName(e.getId(), value.toString(), info)) {
e.setCnName(value.toString());
viewer.update(element, null);
}
CommonUtil.textConsoleAfter(dialog.getTextConsole(), info);
}
}
| 1,665 | 0.73033 | 0.73033 | 61 | 25.295082 | 28.977291 | 170 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.426229 | false | false | 3 |
d26d3e4e6ef7b4495558908423bfa5de13a94338 | 17,523,466,633,325 | b89128a2bfdc4a1592643981d892089afbf28e45 | /src/pokerface/Sad/proxy/Main.java | 426c43a4bbdb3411ec40a552336cf436ff498879 | [] | no_license | pokerfaceSad/ProxyDB | https://github.com/pokerfaceSad/ProxyDB | 236010cd14e19fcd3d5b4fa33dd0f831f3c23c7f | 7e91d3e71b948f2f8f1a54085e982fd8bbfe5487 | refs/heads/master | 2020-09-02T14:09:48.200000 | 2017-09-14T11:45:57 | 2017-09-14T11:45:57 | 98,381,608 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pokerface.Sad.proxy;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.ConnectException;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import pokerface.Sad.util.DBUtil;
public class Main {
static AtomicInteger proxyNum = new AtomicInteger(-1);
static Logger logger = null;
static {
PropertyConfigurator.configure("log4j.properties");
logger = Logger.getLogger(Main.class);
}
/**
* @param args
*/
public static void main(String[] args){
Thread t_checkExisted = new Thread(new CheckExisted());
t_checkExisted.setName("t_checkExisted");
synchronized (Main.proxyNum) {
t_checkExisted.start();
Properties pro = null;
int proxyNumStandard = 0;
while(true)
{
try {
Main.proxyNum.wait();
} catch (InterruptedException e1) {
logger.error("中断异常",e1);
}
try {
pro = DBUtil.getProperties();
proxyNumStandard = new Integer(pro.getProperty("proxyNumStandard"));
} catch (IOException e) {
logger.error("配置文件读取抓取标准异常,取默认值100",e);
proxyNumStandard = 100;
}
//若代理数量小于标准则开始抓取
if(Main.proxyNum.get() < proxyNumStandard)
{
logger.info("代理数量小于"+proxyNumStandard+",开始抓取");
Thread t_crawlKuaiDaiLiIntoDB = new Thread(new CrawlIntoDB("getKuaiDaiLi"));
t_crawlKuaiDaiLiIntoDB.setName("t_crawlKuaiDaiLiIntoDB");
Thread t_crawlDaiLi66IntoDB = new Thread(new CrawlIntoDB("getDaiLi66"));
t_crawlDaiLi66IntoDB.setName("t_crawlDaiLi66IntoDB");
Thread t_crawlXiCiDaiLiIntoDB = new Thread(new CrawlIntoDB("getFromXiCiDaiLi"));
t_crawlXiCiDaiLiIntoDB.setName("t_crawlXiCiDaiLiIntoDB");
Thread t_crawl89IPIntoDB = new Thread(new CrawlIntoDB("get89IP"));
t_crawl89IPIntoDB.setName("t_crawl89IPIntoDB");
Thread t_crawlIP181IntoDB = new Thread(new CrawlIntoDB("getIP181"));
t_crawlIP181IntoDB.setName("t_crawlIP181IntoDB");
t_crawlKuaiDaiLiIntoDB.start();
t_crawlDaiLi66IntoDB.start();
t_crawlXiCiDaiLiIntoDB.start();
t_crawl89IPIntoDB.start();
t_crawlIP181IntoDB.start();
//若有抓取线程未结束,则主线程阻塞
while(t_crawlKuaiDaiLiIntoDB.isAlive() || t_crawlDaiLi66IntoDB.isAlive() || t_crawlXiCiDaiLiIntoDB.isAlive() ||
t_crawl89IPIntoDB.isAlive() || t_crawlIP181IntoDB.isAlive());
logger.info("所有线程抓取完成");
}
}
}
}
}
/**
* 检查数据库中已有的Proxy,删除已失效的
*
*/
class CheckExisted implements Runnable{
static Logger logger = null;
static {
PropertyConfigurator.configure("log4j.properties");
logger = Logger.getLogger(CheckExisted.class);
}
@Override
public void run() {
while(true)
{
synchronized (Main.proxyNum) {
logger.info(Thread.currentThread().getName()+"线程启动");
List<Proxy> dbProxyList = Util.readFromDB();
logger.info("数据库读取完成");
try {
Util.markUseless(dbProxyList); //markUseless()方法跑出ConnectException说明网络连接异常
logger.info("标记失效完成");
Util.deleteUselessFromDB(dbProxyList);
logger.info("删除失效完成");
Main.proxyNum.set( dbProxyList.size());
logger.info("更新代理池中代理数量为"+Main.proxyNum.get());
Main.proxyNum.notify();
logger.info("唤醒主线程");
} catch (ConnectException e) {
logger.error("网络连接异常,线程提前休眠",e);
}
}
logger.info(Thread.currentThread().getName()+"线程休眠");
try {
Thread.sleep(1000*60*30); //休眠半小时
} catch (InterruptedException e) {
logger.error("中断异常",e);
}
}
}
}
/**
* 抓取Proxy检测后写入DB
*
*/
class CrawlIntoDB implements Runnable{
static Logger logger = null;
static {
PropertyConfigurator.configure("log4j.properties");
logger = Logger.getLogger(CrawlIntoDB.class);
}
private String methodName;
public CrawlIntoDB(String methodName)
{
this.methodName = methodName;
}
@Override
public void run() {
logger.info(Thread.currentThread().getName()+"线程启动");
//反射调用Util类的抓取方法
Class cls = null;
List<Proxy> proxyList = null;
try {
System.out.println(methodName);
cls = Class.forName("pokerface.Sad.proxy.ProxyGetter");
proxyList = (List<Proxy>) cls.getDeclaredMethod(methodName).invoke(cls);
} catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
logger.error("工具类加载异常", e);
}
try {
Util.markUseless(proxyList);
} catch (ConnectException e) {
logger.error("网络连接异常,线程终止",e);
}
Util.removeUseless(proxyList);
if(Util.writeProxyListIntoDB(proxyList))
logger.info("写入完成");
logger.info(Thread.currentThread().getName()+"线程终止");
}
} | UTF-8 | Java | 5,233 | java | Main.java | Java | [] | null | [] | package pokerface.Sad.proxy;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.ConnectException;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import pokerface.Sad.util.DBUtil;
public class Main {
static AtomicInteger proxyNum = new AtomicInteger(-1);
static Logger logger = null;
static {
PropertyConfigurator.configure("log4j.properties");
logger = Logger.getLogger(Main.class);
}
/**
* @param args
*/
public static void main(String[] args){
Thread t_checkExisted = new Thread(new CheckExisted());
t_checkExisted.setName("t_checkExisted");
synchronized (Main.proxyNum) {
t_checkExisted.start();
Properties pro = null;
int proxyNumStandard = 0;
while(true)
{
try {
Main.proxyNum.wait();
} catch (InterruptedException e1) {
logger.error("中断异常",e1);
}
try {
pro = DBUtil.getProperties();
proxyNumStandard = new Integer(pro.getProperty("proxyNumStandard"));
} catch (IOException e) {
logger.error("配置文件读取抓取标准异常,取默认值100",e);
proxyNumStandard = 100;
}
//若代理数量小于标准则开始抓取
if(Main.proxyNum.get() < proxyNumStandard)
{
logger.info("代理数量小于"+proxyNumStandard+",开始抓取");
Thread t_crawlKuaiDaiLiIntoDB = new Thread(new CrawlIntoDB("getKuaiDaiLi"));
t_crawlKuaiDaiLiIntoDB.setName("t_crawlKuaiDaiLiIntoDB");
Thread t_crawlDaiLi66IntoDB = new Thread(new CrawlIntoDB("getDaiLi66"));
t_crawlDaiLi66IntoDB.setName("t_crawlDaiLi66IntoDB");
Thread t_crawlXiCiDaiLiIntoDB = new Thread(new CrawlIntoDB("getFromXiCiDaiLi"));
t_crawlXiCiDaiLiIntoDB.setName("t_crawlXiCiDaiLiIntoDB");
Thread t_crawl89IPIntoDB = new Thread(new CrawlIntoDB("get89IP"));
t_crawl89IPIntoDB.setName("t_crawl89IPIntoDB");
Thread t_crawlIP181IntoDB = new Thread(new CrawlIntoDB("getIP181"));
t_crawlIP181IntoDB.setName("t_crawlIP181IntoDB");
t_crawlKuaiDaiLiIntoDB.start();
t_crawlDaiLi66IntoDB.start();
t_crawlXiCiDaiLiIntoDB.start();
t_crawl89IPIntoDB.start();
t_crawlIP181IntoDB.start();
//若有抓取线程未结束,则主线程阻塞
while(t_crawlKuaiDaiLiIntoDB.isAlive() || t_crawlDaiLi66IntoDB.isAlive() || t_crawlXiCiDaiLiIntoDB.isAlive() ||
t_crawl89IPIntoDB.isAlive() || t_crawlIP181IntoDB.isAlive());
logger.info("所有线程抓取完成");
}
}
}
}
}
/**
* 检查数据库中已有的Proxy,删除已失效的
*
*/
class CheckExisted implements Runnable{
static Logger logger = null;
static {
PropertyConfigurator.configure("log4j.properties");
logger = Logger.getLogger(CheckExisted.class);
}
@Override
public void run() {
while(true)
{
synchronized (Main.proxyNum) {
logger.info(Thread.currentThread().getName()+"线程启动");
List<Proxy> dbProxyList = Util.readFromDB();
logger.info("数据库读取完成");
try {
Util.markUseless(dbProxyList); //markUseless()方法跑出ConnectException说明网络连接异常
logger.info("标记失效完成");
Util.deleteUselessFromDB(dbProxyList);
logger.info("删除失效完成");
Main.proxyNum.set( dbProxyList.size());
logger.info("更新代理池中代理数量为"+Main.proxyNum.get());
Main.proxyNum.notify();
logger.info("唤醒主线程");
} catch (ConnectException e) {
logger.error("网络连接异常,线程提前休眠",e);
}
}
logger.info(Thread.currentThread().getName()+"线程休眠");
try {
Thread.sleep(1000*60*30); //休眠半小时
} catch (InterruptedException e) {
logger.error("中断异常",e);
}
}
}
}
/**
* 抓取Proxy检测后写入DB
*
*/
class CrawlIntoDB implements Runnable{
static Logger logger = null;
static {
PropertyConfigurator.configure("log4j.properties");
logger = Logger.getLogger(CrawlIntoDB.class);
}
private String methodName;
public CrawlIntoDB(String methodName)
{
this.methodName = methodName;
}
@Override
public void run() {
logger.info(Thread.currentThread().getName()+"线程启动");
//反射调用Util类的抓取方法
Class cls = null;
List<Proxy> proxyList = null;
try {
System.out.println(methodName);
cls = Class.forName("pokerface.Sad.proxy.ProxyGetter");
proxyList = (List<Proxy>) cls.getDeclaredMethod(methodName).invoke(cls);
} catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
logger.error("工具类加载异常", e);
}
try {
Util.markUseless(proxyList);
} catch (ConnectException e) {
logger.error("网络连接异常,线程终止",e);
}
Util.removeUseless(proxyList);
if(Util.writeProxyListIntoDB(proxyList))
logger.info("写入完成");
logger.info(Thread.currentThread().getName()+"线程终止");
}
} | 5,233 | 0.692212 | 0.678712 | 173 | 26.83815 | 24.768229 | 162 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.277457 | false | false | 3 |
96563990995e5f195a5d014930716b1884b41137 | 22,866,405,946,877 | b4e4ab3fdaf818b8a48fe945391ae1be74b4008f | /source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestAll4Redis.java | 9dd3ea109f7e00dbdac6a5d4011b9e00e8977d5d | [
"Apache-2.0"
] | permissive | Spark3122/jdchain | https://github.com/Spark3122/jdchain | 78ef86ffdec066a1514c3152b35a42955fa2866d | 3378c0321b2fcffa5b91eb9739001784751742c5 | refs/heads/master | 2020-07-27T20:27:35.258000 | 2019-09-04T17:51:15 | 2019-09-04T17:51:15 | 209,207,377 | 1 | 0 | Apache-2.0 | true | 2019-09-18T03:17:36 | 2019-09-18T03:17:36 | 2019-09-18T03:17:34 | 2019-09-05T04:09:04 | 7,988 | 0 | 0 | 0 | null | false | false | package test.com.jd.blockchain.intgr;
import com.jd.blockchain.crypto.*;
import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig;
import com.jd.blockchain.ledger.BytesValue;
import com.jd.blockchain.ledger.*;
import com.jd.blockchain.ledger.core.DataAccount;
import com.jd.blockchain.ledger.core.DataAccountSet;
import com.jd.blockchain.ledger.core.LedgerManage;
import com.jd.blockchain.ledger.core.LedgerRepository;
import com.jd.blockchain.ledger.core.impl.LedgerManager;
import com.jd.blockchain.sdk.BlockchainService;
import com.jd.blockchain.sdk.client.GatewayServiceFactory;
import com.jd.blockchain.storage.service.DbConnection;
import com.jd.blockchain.storage.service.DbConnectionFactory;
import com.jd.blockchain.tools.initializer.LedgerBindingConfig;
import com.jd.blockchain.tools.initializer.LedgerInitProperties;
import com.jd.blockchain.tools.keygen.KeyGenCommand;
import com.jd.blockchain.utils.Bytes;
import com.jd.blockchain.utils.codec.HexUtils;
import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback;
import com.jd.blockchain.utils.net.NetworkAddress;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import test.com.jd.blockchain.intgr.contract.AssetContract;
import test.com.jd.blockchain.intgr.initializer.LedgerInitializeWeb4SingleStepsTest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import static org.junit.Assert.*;
public class IntegrationTestAll4Redis {
public static final String PASSWORD = "abc";
public static final String[] PUB_KEYS = { "3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9",
"3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX",
"3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x",
"3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk" };
public static final String[] PRIV_KEYS = {
"177gjzHTznYdPgWqZrH43W3yp37onm74wYXT4v9FukpCHBrhRysBBZh7Pzdo5AMRyQGJD7x",
"177gju9p5zrNdHJVEQnEEKF4ZjDDYmAXyfG84V5RPGVc5xFfmtwnHA7j51nyNLUFffzz5UT",
"177gjtwLgmSx5v1hFb46ijh7L9kdbKUpJYqdKVf9afiEmAuLgo8Rck9yu5UuUcHknWJuWaF",
"177gk1pudweTq5zgJTh8y3ENCTwtSFsKyX7YnpuKPo7rKgCkCBXVXh5z2syaTCPEMbuWRns" };
// batch transactions keys
BlockchainKeypair userKey = BlockchainKeyGenerator.getInstance().generate();
BlockchainKeypair dataKey = BlockchainKeyGenerator.getInstance().generate();
// 合约测试使用的初始化数据;
BlockchainKeypair contractDataKey = BlockchainKeyGenerator.getInstance().generate();
BlockchainKeypair contractDeployKey = BlockchainKeyGenerator.getInstance().generate();
private String contractZipName = "AssetContract1.contract";
private String eventName = "issue-asset";
HashDigest txContentHash;
String pubKeyVal = "jd.com" + System.currentTimeMillis();
// String userPubKeyVal = "this is user's pubKey";
// 保存资产总数的键;
private static final String KEY_TOTAL = "TOTAL";
// 第二个参数;
private static final String KEY_ABC = "abc";
@Test
public void test() {
NetworkAddress peerSrvAddr0 = new NetworkAddress("127.0.0.1", 10200);
LedgerBindingConfig bindingConfig0 = loadBindingConfig(0);
PeerTestRunner peer0 = new PeerTestRunner(peerSrvAddr0, bindingConfig0);
NetworkAddress peerSrvAddr1 = new NetworkAddress("127.0.0.1", 10210);
LedgerBindingConfig bindingConfig1 = loadBindingConfig(1);
PeerTestRunner peer1 = new PeerTestRunner(peerSrvAddr1, bindingConfig1);
NetworkAddress peerSrvAddr2 = new NetworkAddress("127.0.0.1", 10220);
LedgerBindingConfig bindingConfig2 = loadBindingConfig(2);
PeerTestRunner peer2 = new PeerTestRunner(peerSrvAddr2, bindingConfig2);
NetworkAddress peerSrvAddr3 = new NetworkAddress("127.0.0.1", 10230);
LedgerBindingConfig bindingConfig3 = loadBindingConfig(3);
PeerTestRunner peer3 = new PeerTestRunner(peerSrvAddr3, bindingConfig3);
AsyncCallback<Object> peerStarting0 = peer0.start();
AsyncCallback<Object> peerStarting1 = peer1.start();
AsyncCallback<Object> peerStarting2 = peer2.start();
AsyncCallback<Object> peerStarting3 = peer3.start();
peerStarting0.waitReturn();
peerStarting1.waitReturn();
peerStarting2.waitReturn();
peerStarting3.waitReturn();
DbConnectionFactory dbConnectionFactory0 = peer0.getDBConnectionFactory();
DbConnectionFactory dbConnectionFactory1 = peer1.getDBConnectionFactory();
DbConnectionFactory dbConnectionFactory2 = peer2.getDBConnectionFactory();
DbConnectionFactory dbConnectionFactory3 = peer3.getDBConnectionFactory();
String encodedBase58Pwd = KeyGenCommand.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD);
KeyPairConfig gwkey0 = new KeyPairConfig();
gwkey0.setPubKeyValue(PUB_KEYS[0]);
gwkey0.setPrivKeyValue(PRIV_KEYS[0]);
gwkey0.setPrivKeyPassword(encodedBase58Pwd);
GatewayTestRunner gateway0 = new GatewayTestRunner("127.0.0.1", 11000, gwkey0, peerSrvAddr0);
AsyncCallback<Object> gwStarting0 = gateway0.start();
gwStarting0.waitReturn();
// 执行测试用例之前,校验每个节点的一致性;
LedgerRepository[] ledgers = buildLedgers(
new LedgerBindingConfig[] { bindingConfig0, bindingConfig1, bindingConfig2, bindingConfig3 },
new DbConnectionFactory[] { dbConnectionFactory0, dbConnectionFactory1, dbConnectionFactory2,
dbConnectionFactory3 });
testConsistencyAmongNodes(ledgers);
PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD);
PrivKey privkey1 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD);
PrivKey privkey2 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD);
PrivKey privkey3 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD);
PubKey pubKey0 = KeyGenCommand.decodePubKey(PUB_KEYS[0]);
PubKey pubKey1 = KeyGenCommand.decodePubKey(PUB_KEYS[1]);
PubKey pubKey2 = KeyGenCommand.decodePubKey(PUB_KEYS[2]);
PubKey pubKey3 = KeyGenCommand.decodePubKey(PUB_KEYS[3]);
AsymmetricKeypair adminKey = new AsymmetricKeypair(pubKey0, privkey0);
testWriteBatchTransactions(gateway0, adminKey, ledgers[0]);
testSDK(gateway0, adminKey, ledgers[0]);
// 执行测试用例之后,校验每个节点的一致性;
testConsistencyAmongNodes(ledgers);
}
private LedgerBindingConfig loadBindingConfig(int id) {
ClassPathResource res = new ClassPathResource("ledger-binding-redis-" + id + ".conf");
try (InputStream in = res.getInputStream()) {
return LedgerBindingConfig.resolve(in);
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
private LedgerRepository[] buildLedgers(LedgerBindingConfig[] bindingConfigs,
DbConnectionFactory[] dbConnectionFactories) {
int[] ids = { 0, 1, 2, 3 };
LedgerRepository[] ledgers = new LedgerRepository[ids.length];
LedgerManager[] ledgerManagers = new LedgerManager[ids.length];
for (int i = 0; i < ids.length; i++) {
ledgerManagers[i] = new LedgerManager();
HashDigest ledgerHash = bindingConfigs[0].getLedgerHashs()[0];
DbConnection conn = dbConnectionFactories[i].connect(
bindingConfigs[i].getLedger(ledgerHash).getDbConnection().getUri(),
bindingConfigs[i].getLedger(ledgerHash).getDbConnection().getPassword());
ledgers[i] = ledgerManagers[i].register(ledgerHash, conn.getStorageService());
}
return ledgers;
}
private void testConsistencyAmongNodes(LedgerRepository[] ledgers) {
LedgerRepository ledger0 = ledgers[0];
LedgerBlock latestBlock0 = ledger0.retrieveLatestBlock();
for (int i = 1; i < ledgers.length; i++) {
LedgerRepository otherLedger = ledgers[i];
LedgerBlock otherLatestBlock = otherLedger.retrieveLatestBlock();
assertEquals(ledger0.getHash(), otherLedger.getHash());
assertEquals(ledger0.getLatestBlockHeight(), otherLedger.getLatestBlockHeight());
assertEquals(latestBlock0.getHeight(), otherLatestBlock.getHeight());
assertEquals(latestBlock0.getAdminAccountHash(), otherLatestBlock.getAdminAccountHash());
assertEquals(latestBlock0.getUserAccountSetHash(), otherLatestBlock.getUserAccountSetHash());
assertEquals(latestBlock0.getDataAccountSetHash(), otherLatestBlock.getDataAccountSetHash());
assertEquals(latestBlock0.getContractAccountSetHash(), otherLatestBlock.getContractAccountSetHash());
assertEquals(latestBlock0.getPreviousHash(), otherLatestBlock.getPreviousHash());
assertEquals(latestBlock0.getTransactionSetHash(), otherLatestBlock.getTransactionSetHash());
assertEquals(ledger0.getLatestBlockHash(), otherLedger.getLatestBlockHash());
assertEquals(latestBlock0.getHash(), otherLatestBlock.getHash());
}
}
// 测试一个区块包含多个交易的写入情况,并验证写入结果;
private void testWriteBatchTransactions(GatewayTestRunner gateway, AsymmetricKeypair adminKey,
LedgerRepository ledgerRepository) {
// 连接网关;
GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress());
BlockchainService blockchainService = gwsrvFact.getBlockchainService();
HashDigest[] ledgerHashs = blockchainService.getLedgerHashs();
TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHashs[0]);
// regist user account
txTpl.users().register(userKey.getIdentity());
// regist data account
txTpl.dataAccounts().register(dataKey.getIdentity());
// add kv ops for data account
DataAccountKVSetOperation dataKvsetOP = txTpl.dataAccount(dataKey.getAddress()).setText("A", "Value_A_0", -1)
.setText("B", "Value_B_0", -1).setText("C", "Value_C_0", -1).setText("D", "Value_D_0", -1)
.getOperation();
// 签名;
PreparedTransaction ptx = txTpl.prepare();
ptx.sign(adminKey);
// 提交并等待共识返回;
TransactionResponse txResp = ptx.commit();
assertTrue(txResp.isSuccess());
assertEquals(ledgerRepository.retrieveLatestBlockHeight(), txResp.getBlockHeight());
assertEquals("Value_A_0", ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock())
.getDataAccount(dataKey.getAddress()).getBytes("A").getValue().toUTF8String());
assertEquals("Value_B_0", ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock())
.getDataAccount(dataKey.getAddress()).getBytes("B").getValue().toUTF8String());
assertEquals("Value_C_0", ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock())
.getDataAccount(dataKey.getAddress()).getBytes("C").getValue().toUTF8String());
assertEquals("Value_D_0", ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock())
.getDataAccount(dataKey.getAddress()).getBytes("D").getValue().toUTF8String());
assertEquals(0, ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock())
.getDataAccount(dataKey.getAddress()).getDataVersion("A"));
assertEquals(0, ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock())
.getDataAccount(dataKey.getAddress()).getDataVersion("B"));
assertEquals(0, ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock())
.getDataAccount(dataKey.getAddress()).getDataVersion("C"));
assertEquals(0, ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock())
.getDataAccount(dataKey.getAddress()).getDataVersion("D"));
return;
}
private void testSDK(GatewayTestRunner gateway, AsymmetricKeypair adminKey, LedgerRepository ledgerRepository) {
// 连接网关;
GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress());
BlockchainService bcsrv = gwsrvFact.getBlockchainService();
HashDigest[] ledgerHashs = bcsrv.getLedgerHashs();
BlockchainKeypair newUserAcount = testSDK_RegisterUser(adminKey, ledgerHashs[0], bcsrv, ledgerRepository);
BlockchainKeypair newDataAccount = testSDK_RegisterDataAccount(adminKey, ledgerHashs[0], bcsrv,
ledgerRepository);
testSDK_InsertData(adminKey, ledgerHashs[0], bcsrv, newDataAccount.getAddress(), ledgerRepository);
LedgerBlock latestBlock = testSDK_Contract(adminKey, ledgerHashs[0], bcsrv, ledgerRepository);
}
private void testSDK_InsertData(AsymmetricKeypair adminKey, HashDigest ledgerHash,
BlockchainService blockchainService, Bytes dataAccountAddress, LedgerRepository ledgerRepository) {
// 在本地定义注册账号的 TX;
TransactionTemplate txTemp = blockchainService.newTransaction(ledgerHash);
// --------------------------------------
// 将商品信息写入到指定的账户中;
// 对象将被序列化为 JSON 形式存储,并基于 JSON 结构建立查询索引;
Bytes dataAccount = dataAccountAddress;
String dataKey = "jingdong" + new Random().nextInt(100000);
String dataVal = "www.jd.com";
txTemp.dataAccount(dataAccount).setText(dataKey, dataVal, -1);
// TX 准备就绪;
PreparedTransaction prepTx = txTemp.prepare();
// 使用私钥进行签名;
prepTx.sign(adminKey);
// 提交交易;
TransactionResponse txResp = prepTx.commit();
ledgerRepository.retrieveLatestBlock(); // 更新内存
// 先验证应答
assertEquals(TransactionState.SUCCESS, txResp.getExecutionState());
assertEquals(txResp.getBlockHeight(), ledgerRepository.getLatestBlockHeight());
assertEquals(txResp.getContentHash(), prepTx.getHash());
assertEquals(txResp.getBlockHash(), ledgerRepository.getLatestBlockHash());
KVDataEntry[] kvDataEntries = blockchainService.getDataEntries(ledgerHash, dataAccountAddress.toString(),
dataKey);
for (KVDataEntry kvDataEntry : kvDataEntries) {
assertEquals(dataKey, kvDataEntry.getKey());
String valHexText = (String) kvDataEntry.getValue();
byte[] valBytes = HexUtils.decode(valHexText);
String valText = new String(valBytes);
System.out.println(valText);
}
}
private BlockchainKeypair testSDK_RegisterDataAccount(AsymmetricKeypair adminKey, HashDigest ledgerHash,
BlockchainService blockchainService, LedgerRepository ledgerRepository) {
// 注册数据账户,并验证最终写入;
BlockchainKeypair dataAccount = BlockchainKeyGenerator.getInstance().generate();
// 定义交易;
TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash);
txTpl.dataAccounts().register(dataAccount.getIdentity());
// 签名;
PreparedTransaction ptx = txTpl.prepare();
HashDigest transactionHash = ptx.getHash();
ptx.sign(adminKey);
// 提交并等待共识返回;
TransactionResponse txResp = ptx.commit();
// 验证结果;
// LedgerRepository ledgerOfNode0 =
// node0.getLedgerManager().getLedger(ledgerHash);
LedgerManage ledgerManager = new LedgerManager();
long latestBlockHeight = ledgerRepository.retrieveLatestBlockHeight();
assertEquals(txResp.getExecutionState(), TransactionState.SUCCESS);
assertEquals(txResp.getBlockHeight(), latestBlockHeight);
assertEquals(txResp.getContentHash(), transactionHash);
assertEquals(txResp.getBlockHash(), ledgerRepository.getLatestBlockHash());
assertNotNull(ledgerRepository.getDataAccountSet(ledgerRepository.getLatestBlock())
.getDataAccount(dataAccount.getAddress()));
return dataAccount;
}
private BlockchainKeypair testSDK_RegisterUser(AsymmetricKeypair adminKey, HashDigest ledgerHash,
BlockchainService blockchainService, LedgerRepository ledgerRepository) {
// 注册用户,并验证最终写入;
BlockchainKeypair user = BlockchainKeyGenerator.getInstance().generate();
// 定义交易;
TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash);
txTpl.users().register(user.getIdentity());
// 签名;
PreparedTransaction ptx = txTpl.prepare();
HashDigest transactionHash = ptx.getHash();
ptx.sign(adminKey);
// 提交并等待共识返回;
TransactionResponse txResp = ptx.commit();
// 验证结果;
LedgerManage ledgerManager = new LedgerManager();
assertEquals(txResp.getExecutionState(), TransactionState.SUCCESS);
assertEquals(txResp.getBlockHeight(), ledgerRepository.getLatestBlockHeight());
assertEquals(txResp.getContentHash(), transactionHash);
assertEquals(txResp.getBlockHash(), ledgerRepository.getLatestBlockHash());
assertTrue(ledgerRepository.getUserAccountSet(ledgerRepository.getLatestBlock()).contains(user.getAddress()));
return user;
}
public static LedgerInitProperties loadInitSetting_integration() {
ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger_init_test_integration.init");
try (InputStream in = ledgerInitSettingResource.getInputStream()) {
LedgerInitProperties setting = LedgerInitProperties.resolve(in);
return setting;
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
private LedgerBlock testSDK_Contract(AsymmetricKeypair adminKey, HashDigest ledgerHash,
BlockchainService blockchainService, LedgerRepository ledgerRepository) {
System.out.println("adminKey=" + AddressEncoding.generateAddress(adminKey.getPubKey()));
BlockchainKeypair userKey = BlockchainKeyGenerator.getInstance().generate();
System.out.println("userKey=" + userKey.getAddress());
// valid the basic data in contract;
// prepareContractData(adminKey, ledgerHash,
// blockchainService,ledgerRepository);
TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash);
txTpl.users().register(userKey.getIdentity());
// 定义交易;
// 注册数据账户,并验证最终写入;
txTpl.dataAccounts().register(contractDataKey.getIdentity());
// dataAccountSet.getDataAccount(dataAddress)
DataAccount dataAccount = ledgerRepository.getDataAccountSet(ledgerRepository.getLatestBlock())
.getDataAccount(contractDataKey.getAddress());
DataAccountKVSetOperation kvsetOP = txTpl.dataAccount(contractDataKey.getAddress())
.setText("A", "Value_A_0", -1).setText("B", "Value_B_0", -1)
.setText(KEY_TOTAL, "total value,dataAccount", -1).setText(KEY_ABC, "abc value,dataAccount", -1)
// 所有的模拟数据都在这个dataAccount中填充;
.setBytes("ledgerHash", ledgerHash.getRawDigest(), -1).getOperation();
byte[] contractCode = getChainCodeBytes();
txTpl.contracts().deploy(contractDeployKey.getIdentity(), contractCode);
// 签名;
PreparedTransaction ptx = txTpl.prepare();
ptx.sign(adminKey);
// 提交并等待共识返回;
TransactionResponse txResp = ptx.commit();
assertTrue(txResp.isSuccess());
// 验证结果;
txResp.getContentHash();
LedgerBlock block = ledgerRepository.getBlock(txResp.getBlockHeight());
byte[] contractCodeInDb = ledgerRepository.getContractAccountSet(block)
.getContract(contractDeployKey.getAddress()).getChainCode();
assertArrayEquals(contractCode, contractCodeInDb);
txContentHash = ptx.getHash();
// execute the contract;
testContractExe(adminKey, ledgerHash, userKey, blockchainService, ledgerRepository);
return block;
}
private void testContractExe(AsymmetricKeypair adminKey, HashDigest ledgerHash, BlockchainKeypair userKey,
BlockchainService blockchainService, LedgerRepository ledgerRepository) {
LedgerInfo ledgerInfo = blockchainService.getLedger(ledgerHash);
LedgerBlock previousBlock = blockchainService.getBlock(ledgerHash, ledgerInfo.getLatestBlockHeight() - 1);
// 定义交易;
TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash);
txTpl.contract(contractDeployKey.getAddress(), AssetContract.class).issue(10,"abc");
// 签名;
PreparedTransaction ptx = txTpl.prepare();
ptx.sign(adminKey);
// 提交并等待共识返回;
TransactionResponse txResp = ptx.commit();
// 验证结果;
txResp.getContentHash();
LedgerInfo latestLedgerInfo = blockchainService.getLedger(ledgerHash);
assertEquals(ledgerInfo.getLatestBlockHeight() + 1, latestLedgerInfo.getLatestBlockHeight());
assertEquals(txResp.getBlockHeight(), latestLedgerInfo.getLatestBlockHeight());
LedgerBlock backgroundLedgerBlock = ledgerRepository.retrieveLatestBlock();
assertEquals(txResp.getBlockHeight(), backgroundLedgerBlock.getHeight());
// 验证合约中的赋值,外部可以获得;
DataAccountSet dataAccountSet = ledgerRepository.getDataAccountSet(backgroundLedgerBlock);
AsymmetricKeypair key = Crypto.getSignatureFunction("ED25519").generateKeypair();
PubKey pubKey = key.getPubKey();
Bytes dataAddress = AddressEncoding.generateAddress(pubKey);
assertEquals(dataAddress, dataAccountSet.getDataAccount(dataAddress).getAddress());
assertEquals("hello",
dataAccountSet.getDataAccount(dataAddress).getBytes(KEY_TOTAL, -1).getValue().toUTF8String());
// 验证userAccount,从合约内部赋值,然后外部验证;内部定义动态key,外部不便于得到,临时屏蔽;
// UserAccountSet userAccountSet =
// ledgerRepository.getUserAccountSet(backgroundLedgerBlock);
// PubKey userPubKey = new PubKey(CryptoAlgorithm.ED25519,
// userPubKeyVal.getBytes());
// String userAddress = AddressEncoding.generateAddress(userPubKey);
// assertEquals(userAddress, userAccountSet.getUser(userAddress).getAddress());
}
private void prepareContractData(AsymmetricKeypair adminKey, HashDigest ledgerHash,
BlockchainService blockchainService, LedgerRepository ledgerRepository) {
// 定义交易;
TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash);
// 签名;
PreparedTransaction ptx = txTpl.prepare();
ptx.sign(adminKey);
// 提交并等待共识返回;
TransactionResponse txResp = ptx.commit();
assertTrue(txResp.isSuccess());
// 验证结果;
LedgerBlock block = ledgerRepository.getBlock(txResp.getBlockHeight());
BytesValue val1InDb = ledgerRepository.getDataAccountSet(block).getDataAccount(contractDataKey.getAddress())
.getBytes("A");
BytesValue val2InDb = ledgerRepository.getDataAccountSet(block).getDataAccount(contractDataKey.getAddress())
.getBytes(KEY_TOTAL);
assertEquals("Value_A_0", val1InDb.getValue().toUTF8String());
assertEquals("total value,dataAccount", val2InDb.getValue().toUTF8String());
}
/**
* 根据合约构建字节数组;
*
* @return
*/
private byte[] getChainCodeBytes() {
// 构建合约的字节数组;
byte[] contractCode = null;
File file = null;
InputStream input = null;
try {
ClassPathResource contractPath = new ClassPathResource(contractZipName);
file = new File(contractPath.getURI());
assertTrue("contract zip file is not exist.", file.exists() == true);
input = new FileInputStream(file);
// 这种暴力的读取压缩包,在class解析时有问题,所有需要改进;
contractCode = new byte[input.available()];
input.read(contractCode);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return contractCode;
}
}
| UTF-8 | Java | 22,845 | java | IntegrationTestAll4Redis.java | Java | [
{
"context": "4Redis {\n\n\tpublic static final String PASSWORD = \"abc\";\n\n\tpublic static final String[] PUB_KEYS = { \"3s",
"end": 1581,
"score": 0.9964148998260498,
"start": 1578,
"tag": "PASSWORD",
"value": "abc"
},
{
"context": "bc\";\n\n\tpublic static final String[] PUB_KEY... | null | [] | package test.com.jd.blockchain.intgr;
import com.jd.blockchain.crypto.*;
import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig;
import com.jd.blockchain.ledger.BytesValue;
import com.jd.blockchain.ledger.*;
import com.jd.blockchain.ledger.core.DataAccount;
import com.jd.blockchain.ledger.core.DataAccountSet;
import com.jd.blockchain.ledger.core.LedgerManage;
import com.jd.blockchain.ledger.core.LedgerRepository;
import com.jd.blockchain.ledger.core.impl.LedgerManager;
import com.jd.blockchain.sdk.BlockchainService;
import com.jd.blockchain.sdk.client.GatewayServiceFactory;
import com.jd.blockchain.storage.service.DbConnection;
import com.jd.blockchain.storage.service.DbConnectionFactory;
import com.jd.blockchain.tools.initializer.LedgerBindingConfig;
import com.jd.blockchain.tools.initializer.LedgerInitProperties;
import com.jd.blockchain.tools.keygen.KeyGenCommand;
import com.jd.blockchain.utils.Bytes;
import com.jd.blockchain.utils.codec.HexUtils;
import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback;
import com.jd.blockchain.utils.net.NetworkAddress;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import test.com.jd.blockchain.intgr.contract.AssetContract;
import test.com.jd.blockchain.intgr.initializer.LedgerInitializeWeb4SingleStepsTest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import static org.junit.Assert.*;
public class IntegrationTestAll4Redis {
public static final String PASSWORD = "abc";
public static final String[] PUB_KEYS = { "<KEY>",
"<KEY>",
"<KEY>",
"<KEY>" };
public static final String[] PRIV_KEYS = {
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>" };
// batch transactions keys
BlockchainKeypair userKey = BlockchainKeyGenerator.getInstance().generate();
BlockchainKeypair dataKey = BlockchainKeyGenerator.getInstance().generate();
// 合约测试使用的初始化数据;
BlockchainKeypair contractDataKey = BlockchainKeyGenerator.getInstance().generate();
BlockchainKeypair contractDeployKey = BlockchainKeyGenerator.getInstance().generate();
private String contractZipName = "AssetContract1.contract";
private String eventName = "issue-asset";
HashDigest txContentHash;
String pubKeyVal = "jd.com" + System.currentTimeMillis();
// String userPubKeyVal = "this is user's pubKey";
// 保存资产总数的键;
private static final String KEY_TOTAL = "TOTAL";
// 第二个参数;
private static final String KEY_ABC = "abc";
@Test
public void test() {
NetworkAddress peerSrvAddr0 = new NetworkAddress("127.0.0.1", 10200);
LedgerBindingConfig bindingConfig0 = loadBindingConfig(0);
PeerTestRunner peer0 = new PeerTestRunner(peerSrvAddr0, bindingConfig0);
NetworkAddress peerSrvAddr1 = new NetworkAddress("127.0.0.1", 10210);
LedgerBindingConfig bindingConfig1 = loadBindingConfig(1);
PeerTestRunner peer1 = new PeerTestRunner(peerSrvAddr1, bindingConfig1);
NetworkAddress peerSrvAddr2 = new NetworkAddress("127.0.0.1", 10220);
LedgerBindingConfig bindingConfig2 = loadBindingConfig(2);
PeerTestRunner peer2 = new PeerTestRunner(peerSrvAddr2, bindingConfig2);
NetworkAddress peerSrvAddr3 = new NetworkAddress("127.0.0.1", 10230);
LedgerBindingConfig bindingConfig3 = loadBindingConfig(3);
PeerTestRunner peer3 = new PeerTestRunner(peerSrvAddr3, bindingConfig3);
AsyncCallback<Object> peerStarting0 = peer0.start();
AsyncCallback<Object> peerStarting1 = peer1.start();
AsyncCallback<Object> peerStarting2 = peer2.start();
AsyncCallback<Object> peerStarting3 = peer3.start();
peerStarting0.waitReturn();
peerStarting1.waitReturn();
peerStarting2.waitReturn();
peerStarting3.waitReturn();
DbConnectionFactory dbConnectionFactory0 = peer0.getDBConnectionFactory();
DbConnectionFactory dbConnectionFactory1 = peer1.getDBConnectionFactory();
DbConnectionFactory dbConnectionFactory2 = peer2.getDBConnectionFactory();
DbConnectionFactory dbConnectionFactory3 = peer3.getDBConnectionFactory();
String encodedBase58Pwd = KeyGenCommand.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD);
KeyPairConfig gwkey0 = new KeyPairConfig();
gwkey0.setPubKeyValue(PUB_KEYS[0]);
gwkey0.setPrivKeyValue(PRIV_KEYS[0]);
gwkey0.setPrivKeyPassword(<PASSWORD>Base58Pwd);
GatewayTestRunner gateway0 = new GatewayTestRunner("127.0.0.1", 11000, gwkey0, peerSrvAddr0);
AsyncCallback<Object> gwStarting0 = gateway0.start();
gwStarting0.waitReturn();
// 执行测试用例之前,校验每个节点的一致性;
LedgerRepository[] ledgers = buildLedgers(
new LedgerBindingConfig[] { bindingConfig0, bindingConfig1, bindingConfig2, bindingConfig3 },
new DbConnectionFactory[] { dbConnectionFactory0, dbConnectionFactory1, dbConnectionFactory2,
dbConnectionFactory3 });
testConsistencyAmongNodes(ledgers);
PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD);
PrivKey privkey1 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD);
PrivKey privkey2 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD);
PrivKey privkey3 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD);
PubKey pubKey0 = KeyGenCommand.decodePubKey(PUB_KEYS[0]);
PubKey pubKey1 = KeyGenCommand.decodePubKey(PUB_KEYS[1]);
PubKey pubKey2 = KeyGenCommand.decodePubKey(PUB_KEYS[2]);
PubKey pubKey3 = KeyGenCommand.decodePubKey(PUB_KEYS[3]);
AsymmetricKeypair adminKey = new AsymmetricKeypair(pubKey0, privkey0);
testWriteBatchTransactions(gateway0, adminKey, ledgers[0]);
testSDK(gateway0, adminKey, ledgers[0]);
// 执行测试用例之后,校验每个节点的一致性;
testConsistencyAmongNodes(ledgers);
}
private LedgerBindingConfig loadBindingConfig(int id) {
ClassPathResource res = new ClassPathResource("ledger-binding-redis-" + id + ".conf");
try (InputStream in = res.getInputStream()) {
return LedgerBindingConfig.resolve(in);
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
private LedgerRepository[] buildLedgers(LedgerBindingConfig[] bindingConfigs,
DbConnectionFactory[] dbConnectionFactories) {
int[] ids = { 0, 1, 2, 3 };
LedgerRepository[] ledgers = new LedgerRepository[ids.length];
LedgerManager[] ledgerManagers = new LedgerManager[ids.length];
for (int i = 0; i < ids.length; i++) {
ledgerManagers[i] = new LedgerManager();
HashDigest ledgerHash = bindingConfigs[0].getLedgerHashs()[0];
DbConnection conn = dbConnectionFactories[i].connect(
bindingConfigs[i].getLedger(ledgerHash).getDbConnection().getUri(),
bindingConfigs[i].getLedger(ledgerHash).getDbConnection().getPassword());
ledgers[i] = ledgerManagers[i].register(ledgerHash, conn.getStorageService());
}
return ledgers;
}
private void testConsistencyAmongNodes(LedgerRepository[] ledgers) {
LedgerRepository ledger0 = ledgers[0];
LedgerBlock latestBlock0 = ledger0.retrieveLatestBlock();
for (int i = 1; i < ledgers.length; i++) {
LedgerRepository otherLedger = ledgers[i];
LedgerBlock otherLatestBlock = otherLedger.retrieveLatestBlock();
assertEquals(ledger0.getHash(), otherLedger.getHash());
assertEquals(ledger0.getLatestBlockHeight(), otherLedger.getLatestBlockHeight());
assertEquals(latestBlock0.getHeight(), otherLatestBlock.getHeight());
assertEquals(latestBlock0.getAdminAccountHash(), otherLatestBlock.getAdminAccountHash());
assertEquals(latestBlock0.getUserAccountSetHash(), otherLatestBlock.getUserAccountSetHash());
assertEquals(latestBlock0.getDataAccountSetHash(), otherLatestBlock.getDataAccountSetHash());
assertEquals(latestBlock0.getContractAccountSetHash(), otherLatestBlock.getContractAccountSetHash());
assertEquals(latestBlock0.getPreviousHash(), otherLatestBlock.getPreviousHash());
assertEquals(latestBlock0.getTransactionSetHash(), otherLatestBlock.getTransactionSetHash());
assertEquals(ledger0.getLatestBlockHash(), otherLedger.getLatestBlockHash());
assertEquals(latestBlock0.getHash(), otherLatestBlock.getHash());
}
}
// 测试一个区块包含多个交易的写入情况,并验证写入结果;
private void testWriteBatchTransactions(GatewayTestRunner gateway, AsymmetricKeypair adminKey,
LedgerRepository ledgerRepository) {
// 连接网关;
GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress());
BlockchainService blockchainService = gwsrvFact.getBlockchainService();
HashDigest[] ledgerHashs = blockchainService.getLedgerHashs();
TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHashs[0]);
// regist user account
txTpl.users().register(userKey.getIdentity());
// regist data account
txTpl.dataAccounts().register(dataKey.getIdentity());
// add kv ops for data account
DataAccountKVSetOperation dataKvsetOP = txTpl.dataAccount(dataKey.getAddress()).setText("A", "Value_A_0", -1)
.setText("B", "Value_B_0", -1).setText("C", "Value_C_0", -1).setText("D", "Value_D_0", -1)
.getOperation();
// 签名;
PreparedTransaction ptx = txTpl.prepare();
ptx.sign(adminKey);
// 提交并等待共识返回;
TransactionResponse txResp = ptx.commit();
assertTrue(txResp.isSuccess());
assertEquals(ledgerRepository.retrieveLatestBlockHeight(), txResp.getBlockHeight());
assertEquals("Value_A_0", ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock())
.getDataAccount(dataKey.getAddress()).getBytes("A").getValue().toUTF8String());
assertEquals("Value_B_0", ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock())
.getDataAccount(dataKey.getAddress()).getBytes("B").getValue().toUTF8String());
assertEquals("Value_C_0", ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock())
.getDataAccount(dataKey.getAddress()).getBytes("C").getValue().toUTF8String());
assertEquals("Value_D_0", ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock())
.getDataAccount(dataKey.getAddress()).getBytes("D").getValue().toUTF8String());
assertEquals(0, ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock())
.getDataAccount(dataKey.getAddress()).getDataVersion("A"));
assertEquals(0, ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock())
.getDataAccount(dataKey.getAddress()).getDataVersion("B"));
assertEquals(0, ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock())
.getDataAccount(dataKey.getAddress()).getDataVersion("C"));
assertEquals(0, ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock())
.getDataAccount(dataKey.getAddress()).getDataVersion("D"));
return;
}
private void testSDK(GatewayTestRunner gateway, AsymmetricKeypair adminKey, LedgerRepository ledgerRepository) {
// 连接网关;
GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress());
BlockchainService bcsrv = gwsrvFact.getBlockchainService();
HashDigest[] ledgerHashs = bcsrv.getLedgerHashs();
BlockchainKeypair newUserAcount = testSDK_RegisterUser(adminKey, ledgerHashs[0], bcsrv, ledgerRepository);
BlockchainKeypair newDataAccount = testSDK_RegisterDataAccount(adminKey, ledgerHashs[0], bcsrv,
ledgerRepository);
testSDK_InsertData(adminKey, ledgerHashs[0], bcsrv, newDataAccount.getAddress(), ledgerRepository);
LedgerBlock latestBlock = testSDK_Contract(adminKey, ledgerHashs[0], bcsrv, ledgerRepository);
}
private void testSDK_InsertData(AsymmetricKeypair adminKey, HashDigest ledgerHash,
BlockchainService blockchainService, Bytes dataAccountAddress, LedgerRepository ledgerRepository) {
// 在本地定义注册账号的 TX;
TransactionTemplate txTemp = blockchainService.newTransaction(ledgerHash);
// --------------------------------------
// 将商品信息写入到指定的账户中;
// 对象将被序列化为 JSON 形式存储,并基于 JSON 结构建立查询索引;
Bytes dataAccount = dataAccountAddress;
String dataKey = "jingdong" + new Random().nextInt(100000);
String dataVal = "www.jd.com";
txTemp.dataAccount(dataAccount).setText(dataKey, dataVal, -1);
// TX 准备就绪;
PreparedTransaction prepTx = txTemp.prepare();
// 使用私钥进行签名;
prepTx.sign(adminKey);
// 提交交易;
TransactionResponse txResp = prepTx.commit();
ledgerRepository.retrieveLatestBlock(); // 更新内存
// 先验证应答
assertEquals(TransactionState.SUCCESS, txResp.getExecutionState());
assertEquals(txResp.getBlockHeight(), ledgerRepository.getLatestBlockHeight());
assertEquals(txResp.getContentHash(), prepTx.getHash());
assertEquals(txResp.getBlockHash(), ledgerRepository.getLatestBlockHash());
KVDataEntry[] kvDataEntries = blockchainService.getDataEntries(ledgerHash, dataAccountAddress.toString(),
dataKey);
for (KVDataEntry kvDataEntry : kvDataEntries) {
assertEquals(dataKey, kvDataEntry.getKey());
String valHexText = (String) kvDataEntry.getValue();
byte[] valBytes = HexUtils.decode(valHexText);
String valText = new String(valBytes);
System.out.println(valText);
}
}
private BlockchainKeypair testSDK_RegisterDataAccount(AsymmetricKeypair adminKey, HashDigest ledgerHash,
BlockchainService blockchainService, LedgerRepository ledgerRepository) {
// 注册数据账户,并验证最终写入;
BlockchainKeypair dataAccount = BlockchainKeyGenerator.getInstance().generate();
// 定义交易;
TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash);
txTpl.dataAccounts().register(dataAccount.getIdentity());
// 签名;
PreparedTransaction ptx = txTpl.prepare();
HashDigest transactionHash = ptx.getHash();
ptx.sign(adminKey);
// 提交并等待共识返回;
TransactionResponse txResp = ptx.commit();
// 验证结果;
// LedgerRepository ledgerOfNode0 =
// node0.getLedgerManager().getLedger(ledgerHash);
LedgerManage ledgerManager = new LedgerManager();
long latestBlockHeight = ledgerRepository.retrieveLatestBlockHeight();
assertEquals(txResp.getExecutionState(), TransactionState.SUCCESS);
assertEquals(txResp.getBlockHeight(), latestBlockHeight);
assertEquals(txResp.getContentHash(), transactionHash);
assertEquals(txResp.getBlockHash(), ledgerRepository.getLatestBlockHash());
assertNotNull(ledgerRepository.getDataAccountSet(ledgerRepository.getLatestBlock())
.getDataAccount(dataAccount.getAddress()));
return dataAccount;
}
private BlockchainKeypair testSDK_RegisterUser(AsymmetricKeypair adminKey, HashDigest ledgerHash,
BlockchainService blockchainService, LedgerRepository ledgerRepository) {
// 注册用户,并验证最终写入;
BlockchainKeypair user = BlockchainKeyGenerator.getInstance().generate();
// 定义交易;
TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash);
txTpl.users().register(user.getIdentity());
// 签名;
PreparedTransaction ptx = txTpl.prepare();
HashDigest transactionHash = ptx.getHash();
ptx.sign(adminKey);
// 提交并等待共识返回;
TransactionResponse txResp = ptx.commit();
// 验证结果;
LedgerManage ledgerManager = new LedgerManager();
assertEquals(txResp.getExecutionState(), TransactionState.SUCCESS);
assertEquals(txResp.getBlockHeight(), ledgerRepository.getLatestBlockHeight());
assertEquals(txResp.getContentHash(), transactionHash);
assertEquals(txResp.getBlockHash(), ledgerRepository.getLatestBlockHash());
assertTrue(ledgerRepository.getUserAccountSet(ledgerRepository.getLatestBlock()).contains(user.getAddress()));
return user;
}
public static LedgerInitProperties loadInitSetting_integration() {
ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger_init_test_integration.init");
try (InputStream in = ledgerInitSettingResource.getInputStream()) {
LedgerInitProperties setting = LedgerInitProperties.resolve(in);
return setting;
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
private LedgerBlock testSDK_Contract(AsymmetricKeypair adminKey, HashDigest ledgerHash,
BlockchainService blockchainService, LedgerRepository ledgerRepository) {
System.out.println("adminKey=" + AddressEncoding.generateAddress(adminKey.getPubKey()));
BlockchainKeypair userKey = BlockchainKeyGenerator.getInstance().generate();
System.out.println("userKey=" + userKey.getAddress());
// valid the basic data in contract;
// prepareContractData(adminKey, ledgerHash,
// blockchainService,ledgerRepository);
TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash);
txTpl.users().register(userKey.getIdentity());
// 定义交易;
// 注册数据账户,并验证最终写入;
txTpl.dataAccounts().register(contractDataKey.getIdentity());
// dataAccountSet.getDataAccount(dataAddress)
DataAccount dataAccount = ledgerRepository.getDataAccountSet(ledgerRepository.getLatestBlock())
.getDataAccount(contractDataKey.getAddress());
DataAccountKVSetOperation kvsetOP = txTpl.dataAccount(contractDataKey.getAddress())
.setText("A", "Value_A_0", -1).setText("B", "Value_B_0", -1)
.setText(KEY_TOTAL, "total value,dataAccount", -1).setText(KEY_ABC, "abc value,dataAccount", -1)
// 所有的模拟数据都在这个dataAccount中填充;
.setBytes("ledgerHash", ledgerHash.getRawDigest(), -1).getOperation();
byte[] contractCode = getChainCodeBytes();
txTpl.contracts().deploy(contractDeployKey.getIdentity(), contractCode);
// 签名;
PreparedTransaction ptx = txTpl.prepare();
ptx.sign(adminKey);
// 提交并等待共识返回;
TransactionResponse txResp = ptx.commit();
assertTrue(txResp.isSuccess());
// 验证结果;
txResp.getContentHash();
LedgerBlock block = ledgerRepository.getBlock(txResp.getBlockHeight());
byte[] contractCodeInDb = ledgerRepository.getContractAccountSet(block)
.getContract(contractDeployKey.getAddress()).getChainCode();
assertArrayEquals(contractCode, contractCodeInDb);
txContentHash = ptx.getHash();
// execute the contract;
testContractExe(adminKey, ledgerHash, userKey, blockchainService, ledgerRepository);
return block;
}
private void testContractExe(AsymmetricKeypair adminKey, HashDigest ledgerHash, BlockchainKeypair userKey,
BlockchainService blockchainService, LedgerRepository ledgerRepository) {
LedgerInfo ledgerInfo = blockchainService.getLedger(ledgerHash);
LedgerBlock previousBlock = blockchainService.getBlock(ledgerHash, ledgerInfo.getLatestBlockHeight() - 1);
// 定义交易;
TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash);
txTpl.contract(contractDeployKey.getAddress(), AssetContract.class).issue(10,"abc");
// 签名;
PreparedTransaction ptx = txTpl.prepare();
ptx.sign(adminKey);
// 提交并等待共识返回;
TransactionResponse txResp = ptx.commit();
// 验证结果;
txResp.getContentHash();
LedgerInfo latestLedgerInfo = blockchainService.getLedger(ledgerHash);
assertEquals(ledgerInfo.getLatestBlockHeight() + 1, latestLedgerInfo.getLatestBlockHeight());
assertEquals(txResp.getBlockHeight(), latestLedgerInfo.getLatestBlockHeight());
LedgerBlock backgroundLedgerBlock = ledgerRepository.retrieveLatestBlock();
assertEquals(txResp.getBlockHeight(), backgroundLedgerBlock.getHeight());
// 验证合约中的赋值,外部可以获得;
DataAccountSet dataAccountSet = ledgerRepository.getDataAccountSet(backgroundLedgerBlock);
AsymmetricKeypair key = Crypto.getSignatureFunction("ED25519").generateKeypair();
PubKey pubKey = key.getPubKey();
Bytes dataAddress = AddressEncoding.generateAddress(pubKey);
assertEquals(dataAddress, dataAccountSet.getDataAccount(dataAddress).getAddress());
assertEquals("hello",
dataAccountSet.getDataAccount(dataAddress).getBytes(KEY_TOTAL, -1).getValue().toUTF8String());
// 验证userAccount,从合约内部赋值,然后外部验证;内部定义动态key,外部不便于得到,临时屏蔽;
// UserAccountSet userAccountSet =
// ledgerRepository.getUserAccountSet(backgroundLedgerBlock);
// PubKey userPubKey = new PubKey(CryptoAlgorithm.ED25519,
// userPubKeyVal.getBytes());
// String userAddress = AddressEncoding.generateAddress(userPubKey);
// assertEquals(userAddress, userAccountSet.getUser(userAddress).getAddress());
}
private void prepareContractData(AsymmetricKeypair adminKey, HashDigest ledgerHash,
BlockchainService blockchainService, LedgerRepository ledgerRepository) {
// 定义交易;
TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHash);
// 签名;
PreparedTransaction ptx = txTpl.prepare();
ptx.sign(adminKey);
// 提交并等待共识返回;
TransactionResponse txResp = ptx.commit();
assertTrue(txResp.isSuccess());
// 验证结果;
LedgerBlock block = ledgerRepository.getBlock(txResp.getBlockHeight());
BytesValue val1InDb = ledgerRepository.getDataAccountSet(block).getDataAccount(contractDataKey.getAddress())
.getBytes("A");
BytesValue val2InDb = ledgerRepository.getDataAccountSet(block).getDataAccount(contractDataKey.getAddress())
.getBytes(KEY_TOTAL);
assertEquals("Value_A_0", val1InDb.getValue().toUTF8String());
assertEquals("total value,dataAccount", val2InDb.getValue().toUTF8String());
}
/**
* 根据合约构建字节数组;
*
* @return
*/
private byte[] getChainCodeBytes() {
// 构建合约的字节数组;
byte[] contractCode = null;
File file = null;
InputStream input = null;
try {
ClassPathResource contractPath = new ClassPathResource(contractZipName);
file = new File(contractPath.getURI());
assertTrue("contract zip file is not exist.", file.exists() == true);
input = new FileInputStream(file);
// 这种暴力的读取压缩包,在class解析时有问题,所有需要改进;
contractCode = new byte[input.available()];
input.read(contractCode);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return contractCode;
}
}
| 22,388 | 0.780773 | 0.765677 | 523 | 40.92543 | 33.150452 | 113 | false | false | 0 | 0 | 0 | 0 | 71 | 0.012952 | 2.456979 | false | false | 3 |
6d9cf21ccc4c7644f13323c80079e496b5fe1590 | 20,822,001,486,340 | 30e2526caaa671082b3786085bb3d4732f53c208 | /workspace/TrabalhoJDBC/src/PedidoBD.java | a6d85ac1d3b995871fe8a05fa25ae29bd6ca47c9 | [] | no_license | wendellvalois/trabalhoBancoDeDados | https://github.com/wendellvalois/trabalhoBancoDeDados | e63bbe6b63701e0efaef9e9592067c3c494b01d5 | 8213828c4b7d0aeca69b9a008f2b46195de7fc05 | refs/heads/master | 2021-01-17T20:52:21.634000 | 2016-08-01T15:00:54 | 2016-08-01T15:00:54 | 64,607,485 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.sql.*;
import java.math.BigDecimal;
public class PedidoBD{
private BDjdbc conexao;
public PedidoBD(BDjdbc conexao_){
this.conexao = conexao_;
}
/**
* Metodo que grava um item no Banco de Dados
*/
public void AdicionarNotaBD(Nota nota_,int pedido_id)throws Exception{
PreparedStatement Stmt;
Stmt = conexao.getConexao().prepareStatement(
"INSERT INTO NOTA (NOT_NOTA,ALU_MATRICULA) values (?,?)");
// Stmt.setString(1,item_.getDescricao());
// Stmt.setInt(2,item_.getQuantidade());
//Stmt.setBigDecimal(1,BigDecimal.valueOf(nota_.getValorNota()));
Stmt.setDouble(1,nota_.getValorNota());
Stmt.setInt(2,pedido_id); //pedido_id == aluno
Stmt.executeUpdate();
Stmt.close();
conexao.getConexao().commit();
}
/**
* Metodo que grava um pedido no Banco de Dados
*/
public void AdicionarAlunoBD(Pedido pedido_)throws Exception{
PreparedStatement Stmt;
Stmt = conexao.getConexao().prepareStatement(
"INSERT INTO aluno (ALU_MATRICULA,ALU_NOME) VALUES (?,?)");
//coverte de inteiro pra string pois matricula eh charset
Stmt.setString(1,Integer.toString(pedido_.getID().intValue()));
Stmt.setString(2,pedido_.getDescricao());
Stmt.executeUpdate();
Stmt.close();
}
/**
*
*/
public void RemoverAlunoBD(Integer aluno_matricula)throws Exception{
PreparedStatement Stmt;
Stmt = conexao.getConexao().prepareStatement(
"DELETE FROM NOTA WHERE ALU_MATRICULA=?");
Stmt.setString(1,Integer.toString(aluno_matricula.intValue())); //NOTA: converte de int pra string
Stmt.executeUpdate();
Stmt = conexao.getConexao().prepareStatement(
"DELETE FROM ALUNO WHERE ALU_MATRICULA=?");
Stmt.setString(1,Integer.toString(aluno_matricula.intValue())); //NOTA: converte de int pra string
Stmt.executeUpdate();
Stmt.close();
conexao.getConexao().commit();
}
/**
*
*/
//public Pedido ConsultarMediaAlunoBD(Integer aluno_matricula)throws Exception{
public void ConsultarMediaAlunoBD(Integer aluno_matricula)throws Exception{
PreparedStatement Stmt;
ResultSet rs;
Stmt = conexao.getConexao().prepareStatement(
"SELECT AVG(NOT_NOTA) FROM NOTA WHERE ALU_MATRICULA =?");
Stmt.setInt(1,aluno_matricula.intValue());
rs = Stmt.executeQuery();
// if (!(rs.next())) return null;
if (!(rs.next())) return;
System.out.println("A media do aluno:" + rs.getDouble("AVG(NOT_NOTA)")); //imprime a média
// Pedido p = new Pedido(aluno_matricula,rs.getString("AVG(NOT_NOTA)"));
// System.out.println(p.toString());
Stmt.close();
rs.close();
// Stmt = conexao.getConexao().prepareStatement(
// "SELECT DESCRICAO,QUANTIDADE,VALOR FROM ITEM WHERE PEDIDO_ID=?");
// Stmt.setInt(1,aluno_matricula.intValue());
// rs = Stmt.executeQuery();
// while (rs.next()){
//
//
// p.addItem(rs.getDouble("VALOR"));
//
// }
//
// Stmt.close();
// rs.close();
//
//conexao.getConexao().commit();
// return p;
}
public void ConsultarMediaGeralBD()throws Exception{
PreparedStatement Stmt;
ResultSet rs;
Stmt = conexao.getConexao().prepareStatement(
"SELECT AVG(NOT_NOTA) FROM NOTA");
rs = Stmt.executeQuery();
// if (!(rs.next())) return null;
if (!(rs.next())) return;
System.out.println( rs.getDouble("AVG(NOT_NOTA)")); //imprime a média
// Pedido p = new Pedido(aluno_matricula,rs.getString("AVG(NOT_NOTA)"));
// System.out.println(p.toString());
Stmt.close();
rs.close();
}
}
| UTF-8 | Java | 3,896 | java | PedidoBD.java | Java | [] | null | [] | import java.sql.*;
import java.math.BigDecimal;
public class PedidoBD{
private BDjdbc conexao;
public PedidoBD(BDjdbc conexao_){
this.conexao = conexao_;
}
/**
* Metodo que grava um item no Banco de Dados
*/
public void AdicionarNotaBD(Nota nota_,int pedido_id)throws Exception{
PreparedStatement Stmt;
Stmt = conexao.getConexao().prepareStatement(
"INSERT INTO NOTA (NOT_NOTA,ALU_MATRICULA) values (?,?)");
// Stmt.setString(1,item_.getDescricao());
// Stmt.setInt(2,item_.getQuantidade());
//Stmt.setBigDecimal(1,BigDecimal.valueOf(nota_.getValorNota()));
Stmt.setDouble(1,nota_.getValorNota());
Stmt.setInt(2,pedido_id); //pedido_id == aluno
Stmt.executeUpdate();
Stmt.close();
conexao.getConexao().commit();
}
/**
* Metodo que grava um pedido no Banco de Dados
*/
public void AdicionarAlunoBD(Pedido pedido_)throws Exception{
PreparedStatement Stmt;
Stmt = conexao.getConexao().prepareStatement(
"INSERT INTO aluno (ALU_MATRICULA,ALU_NOME) VALUES (?,?)");
//coverte de inteiro pra string pois matricula eh charset
Stmt.setString(1,Integer.toString(pedido_.getID().intValue()));
Stmt.setString(2,pedido_.getDescricao());
Stmt.executeUpdate();
Stmt.close();
}
/**
*
*/
public void RemoverAlunoBD(Integer aluno_matricula)throws Exception{
PreparedStatement Stmt;
Stmt = conexao.getConexao().prepareStatement(
"DELETE FROM NOTA WHERE ALU_MATRICULA=?");
Stmt.setString(1,Integer.toString(aluno_matricula.intValue())); //NOTA: converte de int pra string
Stmt.executeUpdate();
Stmt = conexao.getConexao().prepareStatement(
"DELETE FROM ALUNO WHERE ALU_MATRICULA=?");
Stmt.setString(1,Integer.toString(aluno_matricula.intValue())); //NOTA: converte de int pra string
Stmt.executeUpdate();
Stmt.close();
conexao.getConexao().commit();
}
/**
*
*/
//public Pedido ConsultarMediaAlunoBD(Integer aluno_matricula)throws Exception{
public void ConsultarMediaAlunoBD(Integer aluno_matricula)throws Exception{
PreparedStatement Stmt;
ResultSet rs;
Stmt = conexao.getConexao().prepareStatement(
"SELECT AVG(NOT_NOTA) FROM NOTA WHERE ALU_MATRICULA =?");
Stmt.setInt(1,aluno_matricula.intValue());
rs = Stmt.executeQuery();
// if (!(rs.next())) return null;
if (!(rs.next())) return;
System.out.println("A media do aluno:" + rs.getDouble("AVG(NOT_NOTA)")); //imprime a média
// Pedido p = new Pedido(aluno_matricula,rs.getString("AVG(NOT_NOTA)"));
// System.out.println(p.toString());
Stmt.close();
rs.close();
// Stmt = conexao.getConexao().prepareStatement(
// "SELECT DESCRICAO,QUANTIDADE,VALOR FROM ITEM WHERE PEDIDO_ID=?");
// Stmt.setInt(1,aluno_matricula.intValue());
// rs = Stmt.executeQuery();
// while (rs.next()){
//
//
// p.addItem(rs.getDouble("VALOR"));
//
// }
//
// Stmt.close();
// rs.close();
//
//conexao.getConexao().commit();
// return p;
}
public void ConsultarMediaGeralBD()throws Exception{
PreparedStatement Stmt;
ResultSet rs;
Stmt = conexao.getConexao().prepareStatement(
"SELECT AVG(NOT_NOTA) FROM NOTA");
rs = Stmt.executeQuery();
// if (!(rs.next())) return null;
if (!(rs.next())) return;
System.out.println( rs.getDouble("AVG(NOT_NOTA)")); //imprime a média
// Pedido p = new Pedido(aluno_matricula,rs.getString("AVG(NOT_NOTA)"));
// System.out.println(p.toString());
Stmt.close();
rs.close();
}
}
| 3,896 | 0.602261 | 0.599435 | 130 | 27.938461 | 25.634039 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.846154 | false | false | 3 |
b7d16b3497f75c57eced836b064a8cb1dbd37cfe | 26,800,595,948,209 | f8af02dd6d14287f6bfbb8725e3b11094261875b | /agent-bridge/src/main/java/com/newrelic/agent/bridge/NoOpObjectFieldManager.java | 58499711d5e2a1b4be595521809b465e46e801c9 | [] | no_license | masonmei/mx | https://github.com/masonmei/mx | fca12bedf2c9fef30452a485b81e23d416a0b534 | 38e0909f9a1720f32d59af280d7fd9a591c45f6c | refs/heads/master | 2021-01-11T04:57:18.501000 | 2015-07-30T08:20:28 | 2015-07-30T08:20:31 | 39,553,289 | 2 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.newrelic.agent.bridge;
class NoOpObjectFieldManager implements ObjectFieldManager {
public void initializeFields(String className, Object target, Object fieldContainer) {
}
public Object getFieldContainer(String className, Object target) {
return null;
}
public void createClassObjectFields(String className) {
}
} | UTF-8 | Java | 361 | java | NoOpObjectFieldManager.java | Java | [] | null | [] | package com.newrelic.agent.bridge;
class NoOpObjectFieldManager implements ObjectFieldManager {
public void initializeFields(String className, Object target, Object fieldContainer) {
}
public Object getFieldContainer(String className, Object target) {
return null;
}
public void createClassObjectFields(String className) {
}
} | 361 | 0.750693 | 0.750693 | 13 | 26.846153 | 30.814198 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 3 |
6ec3da50016dc35aaf5c8f1973c8970b3b23300b | 33,663,953,720,354 | 2b558c18dd528d4c43fb8ac6801e4b554ccc2cf7 | /src/com/ordering/product/service/impl/ProductServiceImpl.java | 886f4870ee7563f6eacb64838c4b5f5a5921a907 | [] | no_license | SteveFrank/OnlineSeller | https://github.com/SteveFrank/OnlineSeller | ed98f3e046efd2ea80f62e6a54c0a4c501d4b611 | 90132b5d97c34924a10f642539d615071857b88b | refs/heads/master | 2016-08-12T12:11:34.182000 | 2016-03-15T03:07:01 | 2016-03-15T03:07:01 | 53,231,210 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ordering.product.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ordering.product.dao.ProductDao;
import com.ordering.product.po.Product;
import com.ordering.product.service.ProductService;
import com.ordering.utils.PageBean;
@Service("productService")
public class ProductServiceImpl implements ProductService {
@Resource(name="productDao")
private ProductDao productDao;
@Transactional
@Override
public PageBean<Product> queryAll_PageProduct(String sid,int pageCurrent, int pageSize){
PageBean<Product> pageBean = productDao.findProductBySid(sid, pageCurrent, pageSize);
List<Product> productList = pageBean.getBeanList();
pageBean.setBeanList(productList);
return pageBean;
}
@Transactional
@Override
public void addProduct(Product product, String sid) {
productDao.addProduct(product,sid);
}
}
| UTF-8 | Java | 1,022 | java | ProductServiceImpl.java | Java | [] | null | [] | package com.ordering.product.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ordering.product.dao.ProductDao;
import com.ordering.product.po.Product;
import com.ordering.product.service.ProductService;
import com.ordering.utils.PageBean;
@Service("productService")
public class ProductServiceImpl implements ProductService {
@Resource(name="productDao")
private ProductDao productDao;
@Transactional
@Override
public PageBean<Product> queryAll_PageProduct(String sid,int pageCurrent, int pageSize){
PageBean<Product> pageBean = productDao.findProductBySid(sid, pageCurrent, pageSize);
List<Product> productList = pageBean.getBeanList();
pageBean.setBeanList(productList);
return pageBean;
}
@Transactional
@Override
public void addProduct(Product product, String sid) {
productDao.addProduct(product,sid);
}
}
| 1,022 | 0.777887 | 0.777887 | 35 | 27.200001 | 24.885796 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.257143 | false | false | 3 |
4e638389bd24be1c8ae68fc022825bcd6fb6154f | 28,243,704,996,463 | c34360f5e1c7a906d85f8dc8dc5dfdd2365162b9 | /src/List/List.java | 1693ebec183dc30f415f74db846bd46fd71261bf | [] | no_license | Oriya-Berlin/Data-Structures-Implementaion | https://github.com/Oriya-Berlin/Data-Structures-Implementaion | fbd5e1a9440b22e1b8cea6039b19d1b92ea33d7f | bc2b8e64b58675473ecc44ec1c2fade6e1d40427 | refs/heads/master | 2023-02-20T05:26:51.865000 | 2021-01-18T15:54:32 | 2021-01-18T15:54:32 | 328,756,783 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package List;
// Dynamic Array
public class List {
final private int INITIAL_SIZE = 10; // default size
final private int INCREMENT = 10;
int size; // current cells in use
int capacity = INITIAL_SIZE;
public int Capacity;
Object[] data = new Object[INITIAL_SIZE];
// add a new value to the list
public void Add(Object item){
if(size == capacity)
resizeData();
data[size] = item;
size++;
}
// when list get full
void resizeData(){
Object[] temp = new Object[capacity + INCREMENT];
for(int i=0; i<capacity; i++)
temp[i] = data[i];
capacity = capacity + INCREMENT;
data = temp; // we also release the memory
}
// remove item of specific index
public void remove(int position){
if(position >= size)
throw new ArrayIndexOutOfBoundsException();
for(int i=position+1; i<size; i++ )
data[i-1] = data[i];
size--;
}
public void SetItem(int index, Object value){
data[index] = value;
}
public Object getItem(int index){
return data[index];
}
public static void main(String[] args) {
List myList = new List();
for(int k=0; k<15; k++)
myList.Add("ola_" + k);
for (Object i :myList.data) {
System.out.println(i);
}
}
}
| UTF-8 | Java | 1,451 | java | List.java | Java | [] | null | [] | package List;
// Dynamic Array
public class List {
final private int INITIAL_SIZE = 10; // default size
final private int INCREMENT = 10;
int size; // current cells in use
int capacity = INITIAL_SIZE;
public int Capacity;
Object[] data = new Object[INITIAL_SIZE];
// add a new value to the list
public void Add(Object item){
if(size == capacity)
resizeData();
data[size] = item;
size++;
}
// when list get full
void resizeData(){
Object[] temp = new Object[capacity + INCREMENT];
for(int i=0; i<capacity; i++)
temp[i] = data[i];
capacity = capacity + INCREMENT;
data = temp; // we also release the memory
}
// remove item of specific index
public void remove(int position){
if(position >= size)
throw new ArrayIndexOutOfBoundsException();
for(int i=position+1; i<size; i++ )
data[i-1] = data[i];
size--;
}
public void SetItem(int index, Object value){
data[index] = value;
}
public Object getItem(int index){
return data[index];
}
public static void main(String[] args) {
List myList = new List();
for(int k=0; k<15; k++)
myList.Add("ola_" + k);
for (Object i :myList.data) {
System.out.println(i);
}
}
}
| 1,451 | 0.530668 | 0.523777 | 101 | 13.366337 | 17.429758 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.287129 | false | false | 3 |
800f24aec9029f5af71dd9e78a558048966efb0e | 6,777,458,447,128 | c32de506cca1af47c6cd95427f288f5cd7d8ffde | /Strings/src/occuranceBasedOperation/FirstRepeatedCharInString.java | d86d5f966c8d2a996f47a45440b64154aa72895a | [] | no_license | xabidas-rgb/DataStructures | https://github.com/xabidas-rgb/DataStructures | 584ccbe4004aa9f5f88694bc02844340d6532ac4 | 852f9330d1fa81b9a9ba3afcf5298a40a2fe2343 | refs/heads/master | 2023-01-24T22:00:57.847000 | 2020-11-21T12:42:47 | 2020-11-21T12:42:47 | 307,725,797 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package occuranceBasedOperation;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
/**
* @author abinash
* Given a string, find the repeated character present first in the String
* I/P - geeksforgeeks
* O/P - g [ First repeating character ]
*/
public class FirstRepeatedCharInString {
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
System.out.println("Enter the String : ");
String input = scanner.nextLine();
FirstRepeatedCharInString charInString = new FirstRepeatedCharInString();
System.out.println("First repeated character in String : "
+ charInString.findFirstRepeatCharInString(input));
} catch(Exception e) {
System.out.println("Exception occurred. REASON : " + e.getMessage());
} finally {
scanner.close();
}
}
/**
* Find the first repeating character in String
* @param input, The input String
* @return firstRepeatChar, The first repeat char in String
*/
public char findFirstRepeatCharInString(String input) {
char firstRepeatChar = 0;
Map<Character, Integer> map = new LinkedHashMap<Character, Integer>(); // We need to use LinkedHashMap
// not HashMap
if (input == null || input.length() == 0)
return firstRepeatChar;
char[] array = input.toCharArray();
for(char c : array) {
if(!map.containsKey(c)) {
map.put(c, 1);
} else {
map.put(c, map.get(c)+ 1);
}
}
// Iterate the map
for(Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1) {
firstRepeatChar = entry.getKey();
break;
}
}
return firstRepeatChar;
}
}
| UTF-8 | Java | 1,796 | java | FirstRepeatedCharInString.java | Java | [
{
"context": "p.Entry;\nimport java.util.Scanner;\n\n/**\n * @author abinash\n * Given a string, find the repeated character pr",
"end": 165,
"score": 0.9550511240959167,
"start": 158,
"tag": "USERNAME",
"value": "abinash"
}
] | null | [] | package occuranceBasedOperation;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
/**
* @author abinash
* Given a string, find the repeated character present first in the String
* I/P - geeksforgeeks
* O/P - g [ First repeating character ]
*/
public class FirstRepeatedCharInString {
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
System.out.println("Enter the String : ");
String input = scanner.nextLine();
FirstRepeatedCharInString charInString = new FirstRepeatedCharInString();
System.out.println("First repeated character in String : "
+ charInString.findFirstRepeatCharInString(input));
} catch(Exception e) {
System.out.println("Exception occurred. REASON : " + e.getMessage());
} finally {
scanner.close();
}
}
/**
* Find the first repeating character in String
* @param input, The input String
* @return firstRepeatChar, The first repeat char in String
*/
public char findFirstRepeatCharInString(String input) {
char firstRepeatChar = 0;
Map<Character, Integer> map = new LinkedHashMap<Character, Integer>(); // We need to use LinkedHashMap
// not HashMap
if (input == null || input.length() == 0)
return firstRepeatChar;
char[] array = input.toCharArray();
for(char c : array) {
if(!map.containsKey(c)) {
map.put(c, 1);
} else {
map.put(c, map.get(c)+ 1);
}
}
// Iterate the map
for(Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1) {
firstRepeatChar = entry.getKey();
break;
}
}
return firstRepeatChar;
}
}
| 1,796 | 0.639755 | 0.636971 | 66 | 26.212122 | 24.57118 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.151515 | false | false | 3 |
7946b72b40cf2c8c2ba9900aa9e6fc8f51851119 | 32,469,952,821,098 | 6bf4c97541d4cfa041dcf8c49082883c4bb88a7d | /WebSummitCLI/src/cli/states/TalkSchedules.java | 9023f8f4d1efb204ee180e17ef61f8e8913d6d6f | [] | no_license | margaridaviterbo/MFES_WebSummit | https://github.com/margaridaviterbo/MFES_WebSummit | aa878147563bf03460c4140eba38604878c37bf1 | 8280bb5626a2b99302ee0a5bf81bddd8f45ede79 | refs/heads/master | 2021-09-02T16:14:29.851000 | 2018-01-03T15:21:49 | 2018-01-03T15:21:49 | 114,009,656 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cli.states;
import cli.components.Menu;
import cli.statemanager.Input;
import cli.statemanager.State;
import cli.statemanager.StateManager;
import cli.statemanager.Input.Key;
import cli.utils.Term;
public class TalkSchedules extends State {
private Menu menu = new Menu(sm);
public TalkSchedules(StateManager stateManager) {
super(stateManager);
menu.addOption("View all talks", new AllTalks(sm));
menu.addOption("View talks by day", new TalksByDay(sm));
menu.addOption("View talks by time", new TalksByTime(sm));
menu.addOption("View talks by speaker", new TalksBySpeaker(sm));
menu.addOption("View talks by conference and day", new TalksByConferenceAndDay(sm));
}
@Override
public void handleInput(Input input) {
menu.handleInput(input);
if (input.getType() == Key.ESCAPE) sm.popState();
}
@Override
public void display() {
Term.clear();
Term.println("* Main Menu > Schedule > Talks");
menu.display();
}
}
| UTF-8 | Java | 955 | java | TalkSchedules.java | Java | [] | null | [] | package cli.states;
import cli.components.Menu;
import cli.statemanager.Input;
import cli.statemanager.State;
import cli.statemanager.StateManager;
import cli.statemanager.Input.Key;
import cli.utils.Term;
public class TalkSchedules extends State {
private Menu menu = new Menu(sm);
public TalkSchedules(StateManager stateManager) {
super(stateManager);
menu.addOption("View all talks", new AllTalks(sm));
menu.addOption("View talks by day", new TalksByDay(sm));
menu.addOption("View talks by time", new TalksByTime(sm));
menu.addOption("View talks by speaker", new TalksBySpeaker(sm));
menu.addOption("View talks by conference and day", new TalksByConferenceAndDay(sm));
}
@Override
public void handleInput(Input input) {
menu.handleInput(input);
if (input.getType() == Key.ESCAPE) sm.popState();
}
@Override
public void display() {
Term.clear();
Term.println("* Main Menu > Schedule > Talks");
menu.display();
}
}
| 955 | 0.735079 | 0.735079 | 35 | 26.285715 | 22.457033 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.628571 | false | false | 3 |
9fcc8ebb3c9f854c5e02cbc062a751217a4dbf3e | 29,162,827,999,044 | a9ae14637bdd5367f6fd6a587b9d447ddb08fb7c | /app/src/main/java/com/heking/qsy/activity/regulatory/Food/tab/Details/TB_FoodSalesDetails.java | 5c5f31c4991b152df1ff1daa207d23c4aa321fde | [] | no_license | AnnisLeejj/QSY | https://github.com/AnnisLeejj/QSY | 804b12fd7f9514055568f50d053efcc414783d11 | 7509b73a3c0eb37d94e361f28176eccc83099ed6 | refs/heads/master | 2021-05-07T18:54:23.513000 | 2017-11-21T10:10:26 | 2017-11-21T10:10:26 | 108,837,021 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.heking.qsy.activity.regulatory.Food.tab.Details;
import java.util.ArrayList;
//[Table("food.TB_FoodSalesDetails")]
public class TB_FoodSalesDetails
{
private ArrayList<Data> Data;
public ArrayList<Data> getData() {
return Data;
}
public void setData(ArrayList<Data> data) {
Data = data;
}
public class Data{
private String ID ;//{ get; set; }
private String SalesID ;//{ get; set; }
//[String Length(64)]
private String FoodID ;//{ get; set; }
private String Quantity ;//{ get; set; }
//[String Length(256)]
private String BatchNumber ;//{ get; set; }
private String SellingPrice ;//{ get; set; }
//[String Length(256)]
private String Supplier ;//{ get; set; }
private String ProductionDate ;//{ get; set; }
private String ExpiredDate ;//{ get; set; }
//[String Length(50)]
private String MeasurementUnit ;//{ get; set; }
//[String Length(20)]
private String ShelfLife ;//{ get; set; }
private String SupplierID ;//{ get; set; }
//[NotMapped]
private String GenericName ;//{ get; set; }
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getSalesID() {
return SalesID;
}
public void setSalesID(String salesID) {
SalesID = salesID;
}
public String getFoodID() {
return FoodID;
}
public void setFoodID(String foodID) {
FoodID = foodID;
}
public String getQuantity() {
return Quantity;
}
public void setQuantity(String quantity) {
Quantity = quantity;
}
public String getBatchNumber() {
return BatchNumber;
}
public void setBatchNumber(String batchNumber) {
BatchNumber = batchNumber;
}
public String getSellingPrice() {
return SellingPrice;
}
public void setSellingPrice(String sellingPrice) {
SellingPrice = sellingPrice;
}
public String getSupplier() {
return Supplier;
}
public void setSupplier(String supplier) {
Supplier = supplier;
}
public String getProductionDate() {
return ProductionDate;
}
public void setProductionDate(String productionDate) {
ProductionDate = productionDate;
}
public String getExpiredDate() {
return ExpiredDate;
}
public void setExpiredDate(String expiredDate) {
ExpiredDate = expiredDate;
}
public String getMeasurementUnit() {
return MeasurementUnit;
}
public void setMeasurementUnit(String measurementUnit) {
MeasurementUnit = measurementUnit;
}
public String getShelfLife() {
return ShelfLife;
}
public void setShelfLife(String shelfLife) {
ShelfLife = shelfLife;
}
public String getSupplierID() {
return SupplierID;
}
public void setSupplierID(String supplierID) {
SupplierID = supplierID;
}
public String getGenericName() {
return GenericName;
}
public void setGenericName(String genericName) {
GenericName = genericName;
}
}
}
| UTF-8 | Java | 3,083 | java | TB_FoodSalesDetails.java | Java | [] | null | [] | package com.heking.qsy.activity.regulatory.Food.tab.Details;
import java.util.ArrayList;
//[Table("food.TB_FoodSalesDetails")]
public class TB_FoodSalesDetails
{
private ArrayList<Data> Data;
public ArrayList<Data> getData() {
return Data;
}
public void setData(ArrayList<Data> data) {
Data = data;
}
public class Data{
private String ID ;//{ get; set; }
private String SalesID ;//{ get; set; }
//[String Length(64)]
private String FoodID ;//{ get; set; }
private String Quantity ;//{ get; set; }
//[String Length(256)]
private String BatchNumber ;//{ get; set; }
private String SellingPrice ;//{ get; set; }
//[String Length(256)]
private String Supplier ;//{ get; set; }
private String ProductionDate ;//{ get; set; }
private String ExpiredDate ;//{ get; set; }
//[String Length(50)]
private String MeasurementUnit ;//{ get; set; }
//[String Length(20)]
private String ShelfLife ;//{ get; set; }
private String SupplierID ;//{ get; set; }
//[NotMapped]
private String GenericName ;//{ get; set; }
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getSalesID() {
return SalesID;
}
public void setSalesID(String salesID) {
SalesID = salesID;
}
public String getFoodID() {
return FoodID;
}
public void setFoodID(String foodID) {
FoodID = foodID;
}
public String getQuantity() {
return Quantity;
}
public void setQuantity(String quantity) {
Quantity = quantity;
}
public String getBatchNumber() {
return BatchNumber;
}
public void setBatchNumber(String batchNumber) {
BatchNumber = batchNumber;
}
public String getSellingPrice() {
return SellingPrice;
}
public void setSellingPrice(String sellingPrice) {
SellingPrice = sellingPrice;
}
public String getSupplier() {
return Supplier;
}
public void setSupplier(String supplier) {
Supplier = supplier;
}
public String getProductionDate() {
return ProductionDate;
}
public void setProductionDate(String productionDate) {
ProductionDate = productionDate;
}
public String getExpiredDate() {
return ExpiredDate;
}
public void setExpiredDate(String expiredDate) {
ExpiredDate = expiredDate;
}
public String getMeasurementUnit() {
return MeasurementUnit;
}
public void setMeasurementUnit(String measurementUnit) {
MeasurementUnit = measurementUnit;
}
public String getShelfLife() {
return ShelfLife;
}
public void setShelfLife(String shelfLife) {
ShelfLife = shelfLife;
}
public String getSupplierID() {
return SupplierID;
}
public void setSupplierID(String supplierID) {
SupplierID = supplierID;
}
public String getGenericName() {
return GenericName;
}
public void setGenericName(String genericName) {
GenericName = genericName;
}
}
}
| 3,083 | 0.636717 | 0.632825 | 157 | 18.636942 | 19.008598 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.713376 | false | false | 3 |
eab34460635d9cf6e0fd2179e09edee446d4e7a4 | 14,431,090,185,409 | a94cd89492db661ef461d8231b6180a797e9a61d | /src/com/SearchAlgo/BinarySearch.java | 3dc47a3f14a7b66769ca95369c59e551c03641a7 | [] | no_license | SinghRohit31/Java-DataStructure | https://github.com/SinghRohit31/Java-DataStructure | 5c3d27f1f892868e9c8d23f428a1640a6e50cc1b | fec92a5268ed51111006c00605c5017b069ecb7e | refs/heads/master | 2022-11-12T18:49:28.951000 | 2020-07-05T15:33:09 | 2020-07-05T15:33:09 | 275,728,859 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.SearchAlgo;
public class BinarySearch {
public static void main(String[] args) {
// Limitation of Binary Search is that element should be in sorted order
int a[]={2,5,7,8,9,11,45,56,67,78,99};
int search=99;
int lower=0;
int higher=a.length-1;
int med=(lower+higher)/2;
while(lower<=higher){
if(a[med]==search){
System.out.println("Number is Present at " + med +" Position" );
break;
}else if (a[med]<search) {
lower=med+1;
}else{
higher=med-1;
}
med=(lower+higher)/2;
}
if(lower>higher){
System.out.println("Element Not found in the list");
}
}
}
| UTF-8 | Java | 621 | java | BinarySearch.java | Java | [] | null | [] | package com.SearchAlgo;
public class BinarySearch {
public static void main(String[] args) {
// Limitation of Binary Search is that element should be in sorted order
int a[]={2,5,7,8,9,11,45,56,67,78,99};
int search=99;
int lower=0;
int higher=a.length-1;
int med=(lower+higher)/2;
while(lower<=higher){
if(a[med]==search){
System.out.println("Number is Present at " + med +" Position" );
break;
}else if (a[med]<search) {
lower=med+1;
}else{
higher=med-1;
}
med=(lower+higher)/2;
}
if(lower>higher){
System.out.println("Element Not found in the list");
}
}
}
| 621 | 0.62963 | 0.589372 | 32 | 18.40625 | 19.16843 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.375 | false | false | 3 |
0cc54bde4235b32843663ed25fe7e57fb628b994 | 33,423,435,554,079 | 96de17aa3e2a75f295a2c164f30172e715ee0e40 | /src/main/java/com/dfmy/controller/photo/DataReportController.java | 34d8b86eff7a6f9d667c996a88d59607724e394e | [] | no_license | liu961105/ati-monitor | https://github.com/liu961105/ati-monitor | 9b300f25c2df2e8315ea81bbb5d3ebe12fe5d701 | f5debe0f14803a61da7a6c92090d363aff526bd1 | refs/heads/master | 2022-12-20T23:30:24.052000 | 2019-10-17T08:24:54 | 2019-10-17T08:24:54 | 215,739,961 | 1 | 0 | null | false | 2022-12-16T06:11:39 | 2019-10-17T08:20:35 | 2020-06-02T15:16:29 | 2022-12-16T06:11:36 | 8,987 | 1 | 0 | 19 | JavaScript | false | false | package com.dfmy.controller.photo;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.dfmy.controller.common.BaseController;
import com.dfmy.entity.ResultEntity;
import com.dfmy.entity.dataProduct.ClhzData;
import com.dfmy.entity.device.AtiDeviceDataRecordHistory;
import com.dfmy.entity.project.AtiProject;
import com.dfmy.service.device.AtiDeviceDataRecordHistoryService;
import com.dfmy.service.modelexport.ModelExportService;
import com.dfmy.service.project.AtiProjectService;
import com.dfmy.util.FreeMarkerToWord;
/**
* 数据生成
*
* @author
*
*/
@Controller
@RequestMapping("/dataReport")
public class DataReportController extends BaseController {
@Resource
private AtiDeviceDataRecordHistoryService atiDeviceDataRecordHistoryService;
@Resource
private AtiProjectService atiProjectService;
@Autowired
private ModelExportService modelExportService;
/**
* 数据生成分页
* @param pageCurrent
* @param atiDeviceDataRecordHistory
* @param uploadTimeBegin
* @param uploadTimeEnd
* @param sortOrder
* @return
*/
@RequestMapping("/getableData")
@ResponseBody
public ResultEntity getTableData(@RequestParam(value = "pageCurrent", defaultValue = "1") String pageCurrent, AtiDeviceDataRecordHistory atiDeviceDataRecordHistory,
String uploadTimeBegin,String uploadTimeEnd,@RequestParam(value = "sortOrder", defaultValue = "uploadTime") String sortOrder){
ResultEntity res = new ResultEntity();
try{
Page<AtiDeviceDataRecordHistory> pageInfo = modelExportService.pageList(Integer.parseInt(pageCurrent), PAGESIZE, sortOrder, atiDeviceDataRecordHistory,uploadTimeBegin,uploadTimeEnd);
if (pageInfo.getTotalPages() > 0) {
res.setData(pageInfo);
res.setMessage(GET_SUCCESS);
res.setSuccess(SUCCESS);
} else {
res.setMessage(IS_NULL);
res.setSuccess(NULL);
}
}catch (Exception e) {
e.printStackTrace();
res.setSuccess(ERROR);
}
return res;
}
@RequestMapping("/dataDownload")
@ResponseBody
public String downLoadReport(String projectId, String monitorTypeId, String monitorParamId,String monitorSitesId,
String uploadTimeBegin,String uploadTimeEnd, HttpServletResponse response, HttpServletRequest request) throws IOException, Exception {
// 准备ftl模板
String ftlFileDir = request.getSession().getServletContext().getRealPath("res/ftl"); // ftl文件夹位置--用于配置freemarker
// 报告导出ftl文件
String ftlPath = "aaaa" + ".ftl";
// 默认导出名称
String wordPath = "桥梁结构健康监测参数数据.doc";
// 准备数据
Map<String, Object> dataMap = new HashMap<String, Object>();//最终结果map
//Map<String, Object> resMap = new HashMap<String, Object>();
List<ClhzData> clhzList = new ArrayList<ClhzData>();
List<ClhzData> itemList = new ArrayList<ClhzData>();
List<Map<String, Object>> titleList = modelExportService.getTitle(projectId, monitorParamId,monitorSitesId);
AtiProject atiProject = atiProjectService.findProjectById(projectId);
if (titleList != null && titleList.size()>0) {
for (Map<String, Object> map : titleList) {
ClhzData clhzData = new ClhzData();
clhzList = new ArrayList<ClhzData>();
dataMap.put("title", map.get("monitor_param_name"));
clhzData.setTitle(map.get("monitor_param_name").toString()); //标题
clhzData.setGcmc(atiProject.getProjectName());
clhzData.setCode("无");
clhzData.setGcbw(map.get("site_name").toString());
clhzData.setJcyj("无");
clhzData.setData(map.get("monitor_param_name").toString());
clhzData.setZyyqsb(map.get("device_name")+"("+map.get("device_code")+")");
clhzList.add(clhzData);
dataMap.put("clhzList", clhzList);
}
}
List<AtiDeviceDataRecordHistory> dataHistory = modelExportService.findReportData(projectId, monitorParamId,monitorSitesId,uploadTimeBegin,uploadTimeEnd);
if(dataHistory != null && dataHistory.size() >0) {
for (AtiDeviceDataRecordHistory o : dataHistory) {
ClhzData clhzData = new ClhzData();
clhzData.setSj( o.getUploadTime());
clhzData.setJtl(o.getDeviceUploadData());
itemList.add(clhzData);
}
dataMap.put("itemList",itemList );
}else{
ClhzData clhzData = new ClhzData();
clhzData.setSj("");
clhzData.setJtl("");
itemList.add(clhzData);
dataMap.put("itemList",itemList);
}
File wrodfile = null;
InputStream fin = null;
ServletOutputStream out = null;
try {
// 调用工具类WordGenerator的createDoc方法生成Word文档
wrodfile = FreeMarkerToWord.freeMarkerToWord(ftlFileDir, ftlPath, dataMap, wordPath);
fin = new FileInputStream(wrodfile);
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
// 设置浏览器以下载的方式处理该文件
response.addHeader("Content-Disposition",
"attachment;filename=" + java.net.URLEncoder.encode(wordPath, "UTF-8"));
out = response.getOutputStream();
byte[] buffer = new byte[1024]; // 缓冲区
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
while ((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} finally {
if (fin != null)
fin.close();
if (out != null)
out.close();
if (wrodfile != null)
wrodfile.delete(); // 删除临时文件
}
return null;
}
}
| UTF-8 | Java | 6,124 | java | DataReportController.java | Java | [] | null | [] | package com.dfmy.controller.photo;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.dfmy.controller.common.BaseController;
import com.dfmy.entity.ResultEntity;
import com.dfmy.entity.dataProduct.ClhzData;
import com.dfmy.entity.device.AtiDeviceDataRecordHistory;
import com.dfmy.entity.project.AtiProject;
import com.dfmy.service.device.AtiDeviceDataRecordHistoryService;
import com.dfmy.service.modelexport.ModelExportService;
import com.dfmy.service.project.AtiProjectService;
import com.dfmy.util.FreeMarkerToWord;
/**
* 数据生成
*
* @author
*
*/
@Controller
@RequestMapping("/dataReport")
public class DataReportController extends BaseController {
@Resource
private AtiDeviceDataRecordHistoryService atiDeviceDataRecordHistoryService;
@Resource
private AtiProjectService atiProjectService;
@Autowired
private ModelExportService modelExportService;
/**
* 数据生成分页
* @param pageCurrent
* @param atiDeviceDataRecordHistory
* @param uploadTimeBegin
* @param uploadTimeEnd
* @param sortOrder
* @return
*/
@RequestMapping("/getableData")
@ResponseBody
public ResultEntity getTableData(@RequestParam(value = "pageCurrent", defaultValue = "1") String pageCurrent, AtiDeviceDataRecordHistory atiDeviceDataRecordHistory,
String uploadTimeBegin,String uploadTimeEnd,@RequestParam(value = "sortOrder", defaultValue = "uploadTime") String sortOrder){
ResultEntity res = new ResultEntity();
try{
Page<AtiDeviceDataRecordHistory> pageInfo = modelExportService.pageList(Integer.parseInt(pageCurrent), PAGESIZE, sortOrder, atiDeviceDataRecordHistory,uploadTimeBegin,uploadTimeEnd);
if (pageInfo.getTotalPages() > 0) {
res.setData(pageInfo);
res.setMessage(GET_SUCCESS);
res.setSuccess(SUCCESS);
} else {
res.setMessage(IS_NULL);
res.setSuccess(NULL);
}
}catch (Exception e) {
e.printStackTrace();
res.setSuccess(ERROR);
}
return res;
}
@RequestMapping("/dataDownload")
@ResponseBody
public String downLoadReport(String projectId, String monitorTypeId, String monitorParamId,String monitorSitesId,
String uploadTimeBegin,String uploadTimeEnd, HttpServletResponse response, HttpServletRequest request) throws IOException, Exception {
// 准备ftl模板
String ftlFileDir = request.getSession().getServletContext().getRealPath("res/ftl"); // ftl文件夹位置--用于配置freemarker
// 报告导出ftl文件
String ftlPath = "aaaa" + ".ftl";
// 默认导出名称
String wordPath = "桥梁结构健康监测参数数据.doc";
// 准备数据
Map<String, Object> dataMap = new HashMap<String, Object>();//最终结果map
//Map<String, Object> resMap = new HashMap<String, Object>();
List<ClhzData> clhzList = new ArrayList<ClhzData>();
List<ClhzData> itemList = new ArrayList<ClhzData>();
List<Map<String, Object>> titleList = modelExportService.getTitle(projectId, monitorParamId,monitorSitesId);
AtiProject atiProject = atiProjectService.findProjectById(projectId);
if (titleList != null && titleList.size()>0) {
for (Map<String, Object> map : titleList) {
ClhzData clhzData = new ClhzData();
clhzList = new ArrayList<ClhzData>();
dataMap.put("title", map.get("monitor_param_name"));
clhzData.setTitle(map.get("monitor_param_name").toString()); //标题
clhzData.setGcmc(atiProject.getProjectName());
clhzData.setCode("无");
clhzData.setGcbw(map.get("site_name").toString());
clhzData.setJcyj("无");
clhzData.setData(map.get("monitor_param_name").toString());
clhzData.setZyyqsb(map.get("device_name")+"("+map.get("device_code")+")");
clhzList.add(clhzData);
dataMap.put("clhzList", clhzList);
}
}
List<AtiDeviceDataRecordHistory> dataHistory = modelExportService.findReportData(projectId, monitorParamId,monitorSitesId,uploadTimeBegin,uploadTimeEnd);
if(dataHistory != null && dataHistory.size() >0) {
for (AtiDeviceDataRecordHistory o : dataHistory) {
ClhzData clhzData = new ClhzData();
clhzData.setSj( o.getUploadTime());
clhzData.setJtl(o.getDeviceUploadData());
itemList.add(clhzData);
}
dataMap.put("itemList",itemList );
}else{
ClhzData clhzData = new ClhzData();
clhzData.setSj("");
clhzData.setJtl("");
itemList.add(clhzData);
dataMap.put("itemList",itemList);
}
File wrodfile = null;
InputStream fin = null;
ServletOutputStream out = null;
try {
// 调用工具类WordGenerator的createDoc方法生成Word文档
wrodfile = FreeMarkerToWord.freeMarkerToWord(ftlFileDir, ftlPath, dataMap, wordPath);
fin = new FileInputStream(wrodfile);
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
// 设置浏览器以下载的方式处理该文件
response.addHeader("Content-Disposition",
"attachment;filename=" + java.net.URLEncoder.encode(wordPath, "UTF-8"));
out = response.getOutputStream();
byte[] buffer = new byte[1024]; // 缓冲区
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
while ((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} finally {
if (fin != null)
fin.close();
if (out != null)
out.close();
if (wrodfile != null)
wrodfile.delete(); // 删除临时文件
}
return null;
}
}
| 6,124 | 0.733028 | 0.730821 | 161 | 35.596272 | 31.445581 | 188 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.602484 | false | false | 3 |
210c7ab98ef34e664ad0aea30d23ecd42db8a3de | 17,678,085,452,134 | 53d766ae22a2392c62fad8efb2bca276a13e201d | /src/com/taodaye/entity/Message.java | 31077345277a071eaf5ab322f1141813ff4ca1cb | [] | no_license | BinWayne/weixin | https://github.com/BinWayne/weixin | d046381bd427b04c02852de0375a6e347344e062 | faae3ea8ce4e6065460e0c0246044e183ba3217c | refs/heads/master | 2021-01-20T11:56:27.903000 | 2017-03-07T10:05:43 | 2017-03-07T10:05:43 | 82,639,817 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.taodaye.entity;
public abstract class Message {
public String ToUserName;
public String FromUserName;
public String CreateTime;
public String MsgType;
public String MsgId;
/*
private String Title;
private String Description;
private String Url;
private String MsgId;
private String Content;
private String MsgId;
*
*/
}
| UTF-8 | Java | 355 | java | Message.java | Java | [] | null | [] | package com.taodaye.entity;
public abstract class Message {
public String ToUserName;
public String FromUserName;
public String CreateTime;
public String MsgType;
public String MsgId;
/*
private String Title;
private String Description;
private String Url;
private String MsgId;
private String Content;
private String MsgId;
*
*/
}
| 355 | 0.752113 | 0.752113 | 22 | 15.136364 | 11.698078 | 31 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.227273 | false | false | 3 |
31d1eef962aecdd87b44cd93ad43e0e1279c5ba8 | 6,519,760,357,653 | acb46486ee059fd010571560f99c7cda6c3f492c | /LeandroMaro/Topic0/JdbcBuilder/src/main/java/ConnectionDB.java | a143b897dcd784b1e1a7d6e569cff434664007b3 | [
"Apache-2.0"
] | permissive | Leandromaro/java-bootcamp-2016 | https://github.com/Leandromaro/java-bootcamp-2016 | 36afcf0f9f1d1b279853deb5573b15e3bed0a7a5 | 3e0a8e680822e01b6580a8fc619ce67408d25dc7 | refs/heads/master | 2021-01-17T05:45:47.444000 | 2016-07-01T23:39:44 | 2016-07-01T23:39:44 | 60,366,624 | 0 | 0 | null | true | 2016-06-03T17:44:45 | 2016-06-03T17:44:45 | 2016-03-03T03:15:19 | 2016-03-31T06:30:02 | 16,361 | 0 | 0 | 0 | null | null | null | import java.sql.DriverManager;
/**
* Created by leandromaro on 1/7/16.
*/
public class ConnectionDB implements ConnectionBuilder {
private DataBase dataBase;
private static java.sql.Connection con = null;
public ConnectionDB() {
this.dataBase = new DataBase();
}
public void setConnectionData(String url, String dbName, String driver, String userName, String password) {
dataBase.setUrl(url);
dataBase.setDbName(dbName);
dataBase.setDriver(driver);
dataBase.setUserName(userName);
dataBase.setPassword(password);
}
public void connect() {
try {
Class.forName(dataBase.getDriver()).newInstance();
con = (java.sql.Connection) DriverManager.getConnection(dataBase.getUrl()+dataBase.getDbName(),dataBase.getUserName(),dataBase.getPassword());
} catch (Exception e) {
e.printStackTrace();
}
}
public DataBase getDataBase() {
return dataBase;
}
}
| UTF-8 | Java | 1,005 | java | ConnectionDB.java | Java | [
{
"context": "import java.sql.DriverManager;\n\n/**\n * Created by leandromaro on 1/7/16.\n */\npublic class ConnectionDB implemen",
"end": 61,
"score": 0.9996401071548462,
"start": 50,
"tag": "USERNAME",
"value": "leandromaro"
},
{
"context": "e.setDriver(driver);\n dataBase.... | null | [] | import java.sql.DriverManager;
/**
* Created by leandromaro on 1/7/16.
*/
public class ConnectionDB implements ConnectionBuilder {
private DataBase dataBase;
private static java.sql.Connection con = null;
public ConnectionDB() {
this.dataBase = new DataBase();
}
public void setConnectionData(String url, String dbName, String driver, String userName, String password) {
dataBase.setUrl(url);
dataBase.setDbName(dbName);
dataBase.setDriver(driver);
dataBase.setUserName(userName);
dataBase.setPassword(password);
}
public void connect() {
try {
Class.forName(dataBase.getDriver()).newInstance();
con = (java.sql.Connection) DriverManager.getConnection(dataBase.getUrl()+dataBase.getDbName(),dataBase.getUserName(),dataBase.getPassword());
} catch (Exception e) {
e.printStackTrace();
}
}
public DataBase getDataBase() {
return dataBase;
}
}
| 1,005 | 0.649751 | 0.645771 | 35 | 27.714285 | 31.711712 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.542857 | false | false | 3 |
f1ff9dca1d13a95eefe394f5a33f477057d15a50 | 7,722,351,259,344 | 17e8438486cb3e3073966ca2c14956d3ba9209ea | /dso/tags/2.6.1/code/base/dso-statistics/tests.unit/com/tctest/statistics/retrieval/actions/SRASystemPropertiesTest.java | 5bc2978ba58aab4fc314f398d40b7a3ffb7600e0 | [] | no_license | sirinath/Terracotta | https://github.com/sirinath/Terracotta | fedfc2c4f0f06c990f94b8b6c3b9c93293334345 | 00a7662b9cf530dfdb43f2dd821fa559e998c892 | refs/heads/master | 2021-01-23T05:41:52.414000 | 2015-07-02T15:21:54 | 2015-07-02T15:21:54 | 38,613,711 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* All content copyright (c) 2003-2008 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
*/
package com.tctest.statistics.retrieval.actions;
import com.tc.statistics.StatisticData;
import com.tc.statistics.StatisticRetrievalAction;
import com.tc.statistics.retrieval.actions.SRASystemProperties;
import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.Properties;
import junit.framework.TestCase;
public class SRASystemPropertiesTest extends TestCase {
public void testRetrieval() throws Exception {
StatisticRetrievalAction action = new SRASystemProperties();
Date before = new Date();
StatisticData data = action.retrieveStatisticData()[0];
Date after = new Date();
assertEquals(SRASystemProperties.ACTION_NAME, data.getName());
assertNull(data.getAgentIp());
assertNull(data.getAgentDifferentiator());
assertNull(data.getMoment());
assertNull(data.getElement());
Properties props = new Properties();
props.load(new ByteArrayInputStream(((String)data.getData()).getBytes("ISO-8859-1")));
Properties sysprops = System.getProperties();
assertEquals(props, sysprops);
}
} | UTF-8 | Java | 1,212 | java | SRASystemPropertiesTest.java | Java | [] | null | [] | /*
* All content copyright (c) 2003-2008 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
*/
package com.tctest.statistics.retrieval.actions;
import com.tc.statistics.StatisticData;
import com.tc.statistics.StatisticRetrievalAction;
import com.tc.statistics.retrieval.actions.SRASystemProperties;
import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.Properties;
import junit.framework.TestCase;
public class SRASystemPropertiesTest extends TestCase {
public void testRetrieval() throws Exception {
StatisticRetrievalAction action = new SRASystemProperties();
Date before = new Date();
StatisticData data = action.retrieveStatisticData()[0];
Date after = new Date();
assertEquals(SRASystemProperties.ACTION_NAME, data.getName());
assertNull(data.getAgentIp());
assertNull(data.getAgentDifferentiator());
assertNull(data.getMoment());
assertNull(data.getElement());
Properties props = new Properties();
props.load(new ByteArrayInputStream(((String)data.getData()).getBytes("ISO-8859-1")));
Properties sysprops = System.getProperties();
assertEquals(props, sysprops);
}
} | 1,212 | 0.759901 | 0.74835 | 34 | 34.676472 | 30.25939 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.735294 | false | false | 3 |
9846a1342de0dadbfc59d17f9811be31cb6ecaa0 | 2,345,052,156,824 | 27f54b71d2f57c300eb04fed1939eba7ee6015b6 | /Lab/StringLab/src/q1/StringBasic.java | e56c3ae38bef2e3b13a163a7e330081f76cd60dd | [
"MIT"
] | permissive | IT20643218/Java-Basic | https://github.com/IT20643218/Java-Basic | 3ef1a6c795becd42d3793dd2d96300df24eb8b42 | 06297272b78ddd5c5c67d68bd44627f5675e54d1 | refs/heads/main | 2023-08-25T02:43:56.968000 | 2021-10-08T18:30:57 | 2021-10-08T18:30:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package q1;
public class StringBasic {
public static void main(String[] args) {
String str = "Hello";
System.out.println(str);
char s[]= {'H','E'};
str = new String(s);
System.out.println(str);
String s = "Hello";
str = s;
str = new String("Hello");
str.concat("World");
System.out.println(str);
}
}
| UTF-8 | Java | 334 | java | StringBasic.java | Java | [] | null | [] | package q1;
public class StringBasic {
public static void main(String[] args) {
String str = "Hello";
System.out.println(str);
char s[]= {'H','E'};
str = new String(s);
System.out.println(str);
String s = "Hello";
str = s;
str = new String("Hello");
str.concat("World");
System.out.println(str);
}
}
| 334 | 0.595808 | 0.592814 | 21 | 14.904762 | 12.274265 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.904762 | false | false | 3 |
b09081994b1841d0003712d613e6527632255731 | 25,975,962,266,142 | faf55adee6ebf064d1abd4c0a1c7ee72126c2caa | /trunk/zhikebao-web/src/com/xyz/stock/client/model/Video.java | 7af2005445349cda29db7123a50cec732b44b289 | [] | no_license | BGCX261/zhikebao-ecom-svn-to-git | https://github.com/BGCX261/zhikebao-ecom-svn-to-git | 48ebb95d1e5883b9991ee116482eb556cd320c64 | 33616de5a809b7dd6f2c2cc98784b04004eef996 | refs/heads/master | 2019-01-20T12:40:43.882000 | 2015-08-25T15:28:09 | 2015-08-25T15:28:09 | 42,322,786 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xyz.stock.client.model;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import com.xyz.resources.client.model.BaseModel;
/**
* @author Val
* @since 1.0, 2009-8-4
*/
@Entity
public class Video extends BaseModel {
private static final long serialVersionUID = 870177203685713401L;
private String id;
private String videoId;
private String url;
private Date modified;
private Date created;
@ManyToOne
private ItemModel itemModel; //所属商品
public ItemModel getItem() {
return itemModel;
}
public void setItem(ItemModel itemModel) {
this.itemModel = itemModel;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getVideoId() {
return this.videoId;
}
public void setVideoId(String videoId) {
this.videoId = videoId;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public Date getModified() {
return this.modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
public Date getCreated() {
return this.created;
}
public void setCreated(Date created) {
this.created = created;
}
}
| UTF-8 | Java | 1,295 | java | Video.java | Java | [
{
"context": "sources.client.model.BaseModel;\r\n\r\n/**\r\n * @author Val\r\n * @since 1.0, 2009-8-4\r\n */\r\n@Entity\r\npublic cl",
"end": 209,
"score": 0.9963021278381348,
"start": 206,
"tag": "NAME",
"value": "Val"
}
] | null | [] | package com.xyz.stock.client.model;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import com.xyz.resources.client.model.BaseModel;
/**
* @author Val
* @since 1.0, 2009-8-4
*/
@Entity
public class Video extends BaseModel {
private static final long serialVersionUID = 870177203685713401L;
private String id;
private String videoId;
private String url;
private Date modified;
private Date created;
@ManyToOne
private ItemModel itemModel; //所属商品
public ItemModel getItem() {
return itemModel;
}
public void setItem(ItemModel itemModel) {
this.itemModel = itemModel;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getVideoId() {
return this.videoId;
}
public void setVideoId(String videoId) {
this.videoId = videoId;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public Date getModified() {
return this.modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
public Date getCreated() {
return this.created;
}
public void setCreated(Date created) {
this.created = created;
}
}
| 1,295 | 0.682207 | 0.662005 | 64 | 18.109375 | 15.139061 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.328125 | false | false | 3 |
884f8f946761e54207a4cae11c4ff66ae7547734 | 3,882,650,503,882 | 74c37241d8ddf09e32368e3f225d0ed8f5670619 | /univ_exe.java | 25f4e7e461a82a8427e2d5fb2ffca462ebad0a86 | [] | no_license | Mranand21/Java-Practice-Codes | https://github.com/Mranand21/Java-Practice-Codes | a7c9d4e8ef3b94b91879c8e6a74b5c6175fe1945 | 7945ddbae8730ce1669d47e706de796b8e2d1d9c | refs/heads/master | 2023-06-01T05:04:03.310000 | 2021-07-03T13:30:13 | 2021-07-03T13:30:13 | 382,614,877 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
class univexe extends Exception
{
String s;
univexe(String x)
{
s=x;
}
public String toString()
{
return "Wrong course";
}
}
class univ_exe
{
static void compare(String s) throws univexe
{
if(s.equals("java"))
System.out.println("Valid");
else
throw new univexe(s);
}
public static void main(String args[])
{
try
{
Scanner sc=new Scanner(System.in);
String course;
String uname;
System.out.println("Enter Course and University name: ");
course=sc.next();
uname=sc.next();
compare(course);
}catch(univexe e)
{
System.out.println("Error = "+e);
}
}
} | UTF-8 | Java | 600 | java | univ_exe.java | Java | [] | null | [] | import java.util.*;
class univexe extends Exception
{
String s;
univexe(String x)
{
s=x;
}
public String toString()
{
return "Wrong course";
}
}
class univ_exe
{
static void compare(String s) throws univexe
{
if(s.equals("java"))
System.out.println("Valid");
else
throw new univexe(s);
}
public static void main(String args[])
{
try
{
Scanner sc=new Scanner(System.in);
String course;
String uname;
System.out.println("Enter Course and University name: ");
course=sc.next();
uname=sc.next();
compare(course);
}catch(univexe e)
{
System.out.println("Error = "+e);
}
}
} | 600 | 0.671667 | 0.671667 | 40 | 14.025 | 14.358773 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35 | false | false | 3 |
472d91736fe50cb18cbf64745cffc3e628604411 | 11,768,210,453,806 | 8498603fe5974d4a2de938039787eafd21e98b4f | /app/src/main/java/dev/merz/plc4x_android_demo/MainActivity.java | 1a23f2a33a850f526bf04ce4ecaa7bd3d2d0c07e | [] | no_license | NiklasMerz/plc4x-android-demo | https://github.com/NiklasMerz/plc4x-android-demo | d1c100b193eb162c06854f6d096e454e14c72762 | 56483b23e1eb8592dadbd36f2e2621a42f6b7128 | refs/heads/master | 2020-12-05T17:14:17.615000 | 2020-01-07T19:52:21 | 2020-01-07T19:52:21 | 232,184,848 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dev.merz.plc4x_android_demo;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import org.apache.log4j.Level;
import org.apache.log4j.chainsaw.Main;
import org.apache.plc4x.java.PlcDriverManager;
import org.apache.plc4x.java.api.PlcConnection;
import org.apache.plc4x.java.api.messages.PlcReadResponse;
import de.mindpipe.android.logging.log4j.LogConfigurator;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
Log.d("PLC4X", "No permission");
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.INTERNET}, 1);
}
final LogConfigurator logConfigurator = new LogConfigurator();
logConfigurator.setFileName(getApplicationContext().getExternalFilesDir("log").getAbsolutePath() + "app.log");
logConfigurator.setRootLevel(Level.DEBUG);
// Set log level of a specific logger
logConfigurator.setLevel("org.apache", Level.ERROR);
logConfigurator.configure();
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
String connectionString = "s7://10.10.64.20/1/1";
try (PlcConnection plcConnection = new PlcDriverManager().getConnection(connectionString)) {
if (!plcConnection.getMetadata().canRead()) {
Log.d("PLC4X", "This connection doesn't support reading.");
return;
}
PlcReadResponse response = plcConnection.readRequestBuilder()
.addItem("item1", "%DB555.DBD0:DINT")
.build()
.execute()
.get();
Long res = response.getLong("item1");
Snackbar.make(view, res.toString(), Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
} catch (Exception e) {
Log.d("PLC4X", "PlcConnection: " + e.getMessage());
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| UTF-8 | Java | 4,149 | java | MainActivity.java | Java | [] | null | [] | package dev.merz.plc4x_android_demo;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import org.apache.log4j.Level;
import org.apache.log4j.chainsaw.Main;
import org.apache.plc4x.java.PlcDriverManager;
import org.apache.plc4x.java.api.PlcConnection;
import org.apache.plc4x.java.api.messages.PlcReadResponse;
import de.mindpipe.android.logging.log4j.LogConfigurator;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
Log.d("PLC4X", "No permission");
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.INTERNET}, 1);
}
final LogConfigurator logConfigurator = new LogConfigurator();
logConfigurator.setFileName(getApplicationContext().getExternalFilesDir("log").getAbsolutePath() + "app.log");
logConfigurator.setRootLevel(Level.DEBUG);
// Set log level of a specific logger
logConfigurator.setLevel("org.apache", Level.ERROR);
logConfigurator.configure();
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
String connectionString = "s7://10.10.64.20/1/1";
try (PlcConnection plcConnection = new PlcDriverManager().getConnection(connectionString)) {
if (!plcConnection.getMetadata().canRead()) {
Log.d("PLC4X", "This connection doesn't support reading.");
return;
}
PlcReadResponse response = plcConnection.readRequestBuilder()
.addItem("item1", "%DB555.DBD0:DINT")
.build()
.execute()
.get();
Long res = response.getLong("item1");
Snackbar.make(view, res.toString(), Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
} catch (Exception e) {
Log.d("PLC4X", "PlcConnection: " + e.getMessage());
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 4,149 | 0.647626 | 0.639913 | 108 | 37.416668 | 32.14381 | 199 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62963 | false | false | 3 |
8516058f3770a4fb868a598c85855ddb10aad029 | 2,534,030,706,393 | fcd3e8e4ac46583312ce85e29e07faa011928d80 | /src/main/java/org/fasttrackit/MonthstoPayOffaCreditCard.java | 285c1ffbb613da27434baf998da6c400ac4c6d52 | [] | no_license | BugnarGeorgeta/algorithmsparttwo | https://github.com/BugnarGeorgeta/algorithmsparttwo | 523fb9632898017af65f2ac364a4459cdb9d6f0f | db885d25fcd365d1024a7c5f706173b4092e9b6a | refs/heads/master | 2023-04-12T16:59:06.396000 | 2021-04-29T16:39:52 | 2021-04-29T16:39:52 | 362,883,409 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.fasttrackit;
//Write a program that will help you determine how many
// months it will take to pay off a credit card balance. The
// program should ask the user to enter the balance of a credit
// card and the APR of the card. The program should then
// return the number of months needed.
import java.util.InputMismatchException;
import java.util.Scanner;
public class MonthstoPayOffaCreditCard {
public double calculateMonthsUntilPaidOff() {
double months;
System.out.println("What is your balance?");
try {
Scanner scanner = new Scanner(System.in);
double balance = scanner.nextDouble();
System.out.println("What is the APR(annual percentage rate) on the card (as a percent)? ");
double apr = scanner.nextDouble() / 36500;
System.out.println("What is the monthly payment you can make?");
double pay = scanner.nextDouble();
double first = Math.log(1 + ((balance / pay) * (1 - (Math.pow((1 + apr), 30)))));
double second = Math.log(1 + apr);
months = Math.ceil(-(1.0 / 30.0) * (first / second));
System.out.println("It will take you " + months + " months to pay off this card");
} catch (InputMismatchException e) {
System.out.println("Please enter corectly information");
return calculateMonthsUntilPaidOff();
}
return months;
}
public static void main(String[] args) {
MonthstoPayOffaCreditCard monthstoPayOffaCreditCard = new MonthstoPayOffaCreditCard();
monthstoPayOffaCreditCard.calculateMonthsUntilPaidOff();
}
}
| UTF-8 | Java | 1,697 | java | MonthstoPayOffaCreditCard.java | Java | [] | null | [] | package org.fasttrackit;
//Write a program that will help you determine how many
// months it will take to pay off a credit card balance. The
// program should ask the user to enter the balance of a credit
// card and the APR of the card. The program should then
// return the number of months needed.
import java.util.InputMismatchException;
import java.util.Scanner;
public class MonthstoPayOffaCreditCard {
public double calculateMonthsUntilPaidOff() {
double months;
System.out.println("What is your balance?");
try {
Scanner scanner = new Scanner(System.in);
double balance = scanner.nextDouble();
System.out.println("What is the APR(annual percentage rate) on the card (as a percent)? ");
double apr = scanner.nextDouble() / 36500;
System.out.println("What is the monthly payment you can make?");
double pay = scanner.nextDouble();
double first = Math.log(1 + ((balance / pay) * (1 - (Math.pow((1 + apr), 30)))));
double second = Math.log(1 + apr);
months = Math.ceil(-(1.0 / 30.0) * (first / second));
System.out.println("It will take you " + months + " months to pay off this card");
} catch (InputMismatchException e) {
System.out.println("Please enter corectly information");
return calculateMonthsUntilPaidOff();
}
return months;
}
public static void main(String[] args) {
MonthstoPayOffaCreditCard monthstoPayOffaCreditCard = new MonthstoPayOffaCreditCard();
monthstoPayOffaCreditCard.calculateMonthsUntilPaidOff();
}
}
| 1,697 | 0.634649 | 0.625221 | 46 | 35.891304 | 31.101677 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.456522 | false | false | 3 |
9daf38c815b5c7435e0fcb259abd79c48f29dd08 | 24,464,133,787,091 | fddae514575b22978c4627a6e0994c29cbc44907 | /xc-framework-model/src/main/java/com/xuecheng/framework/domain/media/request/QueryMediaFileRequest.java | aadb89c61ff1ed2dca674b10ddfdd739bd7d6876 | [] | no_license | zishuimuyu/xcEduService | https://github.com/zishuimuyu/xcEduService | 4959a99f0eadc0f204f0f72ebdc815bd0a592233 | 13abf89d7a8318f9904216b93b9f41a2e73bffd5 | refs/heads/master | 2022-12-08T02:09:40.503000 | 2019-10-31T13:39:52 | 2019-10-31T13:39:52 | 172,695,909 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xuecheng.framework.domain.media.request;
import com.xuecheng.framework.model.request.RequestData;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
*
* @author:GJH
* @createDate:2019/9/28
* @company:洪荒宇宙加力蹲大学
*/
@Data
@NoArgsConstructor
public class QueryMediaFileRequest extends RequestData {
private String fileOriginalName;
private String processStatus;
private String tag;
}
| UTF-8 | Java | 442 | java | QueryMediaFileRequest.java | Java | [
{
"context": "port lombok.NoArgsConstructor;\n\n/**\n *\n * @author:GJH\n * @createDate:2019/9/28\n * @company:洪荒宇宙加力蹲大学\n *",
"end": 186,
"score": 0.9995675086975098,
"start": 183,
"tag": "USERNAME",
"value": "GJH"
}
] | null | [] | package com.xuecheng.framework.domain.media.request;
import com.xuecheng.framework.model.request.RequestData;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
*
* @author:GJH
* @createDate:2019/9/28
* @company:洪荒宇宙加力蹲大学
*/
@Data
@NoArgsConstructor
public class QueryMediaFileRequest extends RequestData {
private String fileOriginalName;
private String processStatus;
private String tag;
}
| 442 | 0.772727 | 0.755981 | 20 | 19.9 | 18.627668 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35 | false | false | 3 |
82987ede5a750f84ffc0b4ccd0c0be3049451f3a | 11,940,009,107,874 | a93753bf95927a721bce80e39581ecbfb1dabf68 | /java/tags/ifTag.java | d5810d0d714b320fb072b983dcaf4d62585880c8 | [] | no_license | cloudbearings/tradeusedbooks | https://github.com/cloudbearings/tradeusedbooks | 04896e9827c6976721be3f83818b9418cd60e599 | b30387d3f8e083754193d60f9cd6a1805f8735a1 | refs/heads/master | 2021-01-18T09:40:08.709000 | 2013-07-11T18:29:51 | 2013-07-11T18:29:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package server;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
/*
*a class that takes two parameters as selected and unselected
*with the word <void> specifying where to insert the word
*in body
*/
public class ifTag extends BodyTagSupport{
private boolean test;
public void setTest(boolean s) {
test = s;
}
public int doAfterBody() throws JspException{
BodyContent body = getBodyContent();
JspWriter out = body.getEnclosingWriter();
try{
if (test == true){
out.println(body.getString());
}
}catch (IOException e){
}
return(SKIP_BODY);
}
} | UTF-8 | Java | 606 | java | ifTag.java | Java | [] | null | [] | package server;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
/*
*a class that takes two parameters as selected and unselected
*with the word <void> specifying where to insert the word
*in body
*/
public class ifTag extends BodyTagSupport{
private boolean test;
public void setTest(boolean s) {
test = s;
}
public int doAfterBody() throws JspException{
BodyContent body = getBodyContent();
JspWriter out = body.getEnclosingWriter();
try{
if (test == true){
out.println(body.getString());
}
}catch (IOException e){
}
return(SKIP_BODY);
}
} | 606 | 0.706271 | 0.706271 | 26 | 22.346153 | 17.935659 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5 | false | false | 3 |
b2c986a90af2d770f9a05117da5e48697d742696 | 15,444,702,434,393 | f5aeace919c5f875634df49d4a1961f54d5203c5 | /easy/ChangeXY.java | b3a543b664e91ea98e7eb78eaee0da15f2df3e1d | [] | no_license | Abhikakar/recursion | https://github.com/Abhikakar/recursion | 0fcceee51c626b469f46c8906d80d0d30a221d40 | a135afc9de8afd4dca304758c41a561acd38b29c | refs/heads/master | 2023-04-21T16:53:06.248000 | 2021-05-18T07:44:23 | 2021-05-18T07:44:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
Given a string, compute recursively (no loops) a new string where all the lowercase 'x' chars have been changed to 'y' chars.
changeXY("codex") → "codey"
changeXY("xxhixx") → "yyhiyy"
changeXY("xhixhix") → "yhiyhiy"
*/
public class ChangeXY {
public static void main(String[] args) {
System.out.println(changeXY("codex"));
System.out.println(changeXY("xxhixx"));
System.out.println(changeXY("xhixx"));
}
static String changeXY(String s) {
return changeXY(s, s.length() - 1);
}
static String changeXY(String s, int n) {
// BC1: If empty string, nothing to change
if (n < 0)
return "";
// RC1: If last char is x, recurse on rest and concatenate with "y"
if (s.charAt(n) == 'x')
return changeXY(s, n - 1) + "y";
// RC2: If last char not x, recurse on rest and keep current character
else
return changeXY(s, n - 1) + s.charAt(n);
}
}
| UTF-8 | Java | 987 | java | ChangeXY.java | Java | [] | null | [] | /*
Given a string, compute recursively (no loops) a new string where all the lowercase 'x' chars have been changed to 'y' chars.
changeXY("codex") → "codey"
changeXY("xxhixx") → "yyhiyy"
changeXY("xhixhix") → "yhiyhiy"
*/
public class ChangeXY {
public static void main(String[] args) {
System.out.println(changeXY("codex"));
System.out.println(changeXY("xxhixx"));
System.out.println(changeXY("xhixx"));
}
static String changeXY(String s) {
return changeXY(s, s.length() - 1);
}
static String changeXY(String s, int n) {
// BC1: If empty string, nothing to change
if (n < 0)
return "";
// RC1: If last char is x, recurse on rest and concatenate with "y"
if (s.charAt(n) == 'x')
return changeXY(s, n - 1) + "y";
// RC2: If last char not x, recurse on rest and keep current character
else
return changeXY(s, n - 1) + s.charAt(n);
}
}
| 987 | 0.585117 | 0.577982 | 30 | 31.700001 | 28.121344 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
08f6f0a73ba8c14c2102f2877e2b4afe4e02c797 | 6,047,314,019,616 | fb7b55af620581b584815e967288d2b13bccfa35 | /src/main/java/ConcurrentDemo/LockDemo.java | 34e88e0329d2a211b865caf3576aa23f58be80bc | [] | no_license | BattingBoy/demo-in-pap | https://github.com/BattingBoy/demo-in-pap | 016560067929cf22bc07c8aebeb8ba6be523895d | 20d2cec1c90d7da2d0103ce4bb15bb71e557d8c3 | refs/heads/master | 2017-12-02T06:25:39.586000 | 2017-10-24T09:29:40 | 2017-10-24T09:29:40 | 85,051,889 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ConcurrentDemo;
import org.junit.Test;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Created by DENGZHIHONG988 on 2017/4/26.
*/
public class LockDemo {
Lock lock = new ReentrantLock();
ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
int[] iInt = {0};
int[] iiInt = {0};
@Test
public void run() {
for (int i = 0; i < 100; i++) {
new Thread(() -> {
for (int j = 0; j < 1000; j++) {
try {
Thread.sleep((long) (Math.random() * 10));
} catch (InterruptedException e) {
e.printStackTrace();
}
iInt[0]++;
}
}).start();
new Thread(() -> {
for (int j = 0; j < 1000; j++) {
try {
Thread.sleep((long) (Math.random() * 10));
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.lock();
iiInt[0]++;
lock.unlock();
}
}).start();
}
do {
} while (Thread.activeCount() > 2);
System.out.println(Thread.currentThread().getName() + " iInt " + iInt[0]);
System.out.println(Thread.currentThread().getName() + " iiInt " + iiInt[0]);
}
@Test
public void runRWLock(){
ExecutorService pool = Executors.newCachedThreadPool();
pool.execute(()->{
System.out.println("2"+rwLock.readLock().tryLock());
});
pool.execute(()->{
System.out.println("4"+rwLock.readLock().tryLock());
});
pool.execute(()->{
System.out.println("1"+rwLock.writeLock().tryLock());
});
pool.execute(()->{
System.out.println("3"+rwLock.writeLock().tryLock());
});
do {
} while (Thread.activeCount() > 1);
}
}
| UTF-8 | Java | 2,395 | java | LockDemo.java | Java | [
{
"context": "t.locks.ReentrantReadWriteLock;\n\n/**\n * Created by DENGZHIHONG988 on 2017/4/26.\n */\npublic class LockDemo {\n Loc",
"end": 488,
"score": 0.9996546506881714,
"start": 474,
"tag": "USERNAME",
"value": "DENGZHIHONG988"
}
] | null | [] | package ConcurrentDemo;
import org.junit.Test;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Created by DENGZHIHONG988 on 2017/4/26.
*/
public class LockDemo {
Lock lock = new ReentrantLock();
ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
int[] iInt = {0};
int[] iiInt = {0};
@Test
public void run() {
for (int i = 0; i < 100; i++) {
new Thread(() -> {
for (int j = 0; j < 1000; j++) {
try {
Thread.sleep((long) (Math.random() * 10));
} catch (InterruptedException e) {
e.printStackTrace();
}
iInt[0]++;
}
}).start();
new Thread(() -> {
for (int j = 0; j < 1000; j++) {
try {
Thread.sleep((long) (Math.random() * 10));
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.lock();
iiInt[0]++;
lock.unlock();
}
}).start();
}
do {
} while (Thread.activeCount() > 2);
System.out.println(Thread.currentThread().getName() + " iInt " + iInt[0]);
System.out.println(Thread.currentThread().getName() + " iiInt " + iiInt[0]);
}
@Test
public void runRWLock(){
ExecutorService pool = Executors.newCachedThreadPool();
pool.execute(()->{
System.out.println("2"+rwLock.readLock().tryLock());
});
pool.execute(()->{
System.out.println("4"+rwLock.readLock().tryLock());
});
pool.execute(()->{
System.out.println("1"+rwLock.writeLock().tryLock());
});
pool.execute(()->{
System.out.println("3"+rwLock.writeLock().tryLock());
});
do {
} while (Thread.activeCount() > 1);
}
}
| 2,395 | 0.506054 | 0.489353 | 80 | 28.9375 | 21.890833 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55 | false | false | 3 |
771f3b4019752c94dd6a1664d3a002027b587db2 | 31,121,333,059,982 | ca2970e93111f9161e52e29b4d176a53cce66e2c | /src/chapter2/WeightFormat.java | 50c1d005bee99e58c62fc05d9d33392c17a4e317 | [] | no_license | skyWY/Java8 | https://github.com/skyWY/Java8 | b1fa7ad604522e4fb4f8a517a53c06971df7f18d | 8072c2d416db80f95c6f441c3d3d54dd4b85b6fa | refs/heads/master | 2017-12-18T00:09:54.178000 | 2017-01-17T10:08:22 | 2017-01-17T10:08:22 | 77,373,384 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package chapter2;
import chapter1.Apple;
/**
* Created by wy on 2016/12/26.
*/
public class WeightFormat implements OutputFormat {
@Override
public String accept(Apple apple) {
String w=apple.getWeight()>150?"heavy":"light";
return w;
}
}
| UTF-8 | Java | 271 | java | WeightFormat.java | Java | [
{
"context": "apter2;\n\nimport chapter1.Apple;\n\n/**\n * Created by wy on 2016/12/26.\n */\npublic class WeightFormat impl",
"end": 63,
"score": 0.9881531000137329,
"start": 61,
"tag": "USERNAME",
"value": "wy"
}
] | null | [] | package chapter2;
import chapter1.Apple;
/**
* Created by wy on 2016/12/26.
*/
public class WeightFormat implements OutputFormat {
@Override
public String accept(Apple apple) {
String w=apple.getWeight()>150?"heavy":"light";
return w;
}
}
| 271 | 0.653137 | 0.605166 | 14 | 18.357143 | 18.254578 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 3 |
46045b3b5bcccbf638b5a5a600c722f4ebbecb40 | 12,962,211,321,003 | d55e8799f13b0b9aee8ff7cfa46c3047b3e435ed | /nanaclimate/src/main/java/ar/com/ada/api/nanaclimate/models/request/PostPaisRequest.java | 9d4c7be89bedb485d17d595d3fc4f333fcf941c5 | [] | no_license | KaoruH/NANA_Climate_Change | https://github.com/KaoruH/NANA_Climate_Change | 2db7ef8d446219cb13f3daac79f6e9c5dd6a65d3 | 5fb423d26c1067b8551489ddf512054c0d37d8d0 | refs/heads/master | 2022-11-29T21:52:23.184000 | 2020-08-05T23:40:34 | 2020-08-05T23:40:34 | 276,892,157 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ar.com.ada.api.nanaclimate.models.request;
public class PostPaisRequest {
private Integer paisId;
private String nombre;
public Integer getPaisId() {
return paisId;
}
public void setPaisId(Integer paisId) {
this.paisId = paisId;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
} | UTF-8 | Java | 431 | java | PostPaisRequest.java | Java | [] | null | [] | package ar.com.ada.api.nanaclimate.models.request;
public class PostPaisRequest {
private Integer paisId;
private String nombre;
public Integer getPaisId() {
return paisId;
}
public void setPaisId(Integer paisId) {
this.paisId = paisId;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
} | 431 | 0.62413 | 0.62413 | 24 | 17 | 16.116762 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.291667 | false | false | 3 |
59b8c25390d2cc658cba9d39312516ae8524ddb0 | 12,558,484,399,347 | 88a07976599a72401d8a9b0e2849f10aabae44cf | /app/src/main/java/com/aloine/resolute40/auth/register/activity/RegisterActivity.java | f8b56abd715224013ed3feb7a694ba4e3214c953 | [] | no_license | themavencoder/resolute40 | https://github.com/themavencoder/resolute40 | 96336fa2a057066439c0aa31bc142d70e4862df0 | 6474d37f64a4071836a122b4735976025e73cf0f | refs/heads/master | 2020-04-08T22:30:54.193000 | 2019-06-21T00:33:20 | 2019-06-21T00:33:20 | 159,790,166 | 2 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.aloine.resolute40.auth.register.activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.aloine.resolute40.AppInstance;
import com.aloine.resolute40.R;
import com.aloine.resolute40.auth.formalLogin.activity.FormalSignInActivity;
import com.aloine.resolute40.auth.register.contract.RegisterContract;
import com.aloine.resolute40.auth.register.database.table.Farmer;
import com.aloine.resolute40.auth.register.model.RegisterModel;
import com.aloine.resolute40.auth.register.network.ApiService;
import com.aloine.resolute40.auth.register.network.Client;
import com.aloine.resolute40.auth.register.network.RegisterResponse;
import com.aloine.resolute40.auth.register.presenter.RegisterPresenter;
import com.aloine.resolute40.auth.register.registerdialog.DialogFragment;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class RegisterActivity extends AppCompatActivity implements RegisterContract.View {
private EditText mEtName, mEtPhone, mEtCommunity, mEtPin, mEtProductType;
private Spinner mSpState;
private TextView mTvSignIn;
private Button mButtonReg;
private RegisterContract.Presenter mPresenter;
private CoordinatorLayout mCoordinatorLayout;
private ApiService mApiService;
private DialogFragment dialogFragment;
private RegisterModel model;
private Farmer farmer;
public SharedPreferences sharedPreferences;
public static final String mypreference = "mypref";
public static final String userName = "userNameKey";
public AppInstance app;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
flags();
if (Build.VERSION.SDK_INT >= 21) {
statusColor();
}
init();
register();
mPresenter = new RegisterPresenter(this);
signIn();
farmer = new Farmer();
app = AppInstance.getInstance();
sharedPreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE);
if (sharedPreferences.contains(userName)) {
app.setUsername(sharedPreferences.getString(userName,""));
}
}
private void statusColor() {
Window window = this.getWindow();
if (Build.VERSION.SDK_INT >= 21) {
window.setStatusBarColor(ContextCompat.getColor(this,R.color.colorPrimaryDark));
}
}
private void signIn() {
mTvSignIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mPresenter.loadSignInScreen();
}
});
}
private void register() {
mButtonReg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String full_name = mEtName.getText().toString();
String community = mEtCommunity.getText().toString();
String phone_number = mEtPhone.getText().toString();
String pin = mEtPin.getText().toString();
String productType = mEtProductType.getText().toString();
mPresenter.insertData(full_name, phone_number,community, pin,productType);
if (mPresenter.verifyEntries() && !mSpState.getSelectedItem().toString().equals("Select state")) {
dialogFragment.setCancelable(false);
dialogFragment.show(getSupportFragmentManager(), "my_dialog");
model = new RegisterModel(full_name, mSpState.getSelectedItem().toString(),phone_number,community, productType,pin, "null", "Farmer" );
sendUserData(model);
} else {
Snackbar snackbar = inCompleteDetails();
snackbar.show();
}
}
});
}
@NonNull
private Snackbar inCompleteDetails() {
Snackbar snackbar = Snackbar.make(mCoordinatorLayout, "Some details are missing!", Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
snackbar.setActionTextColor(Color.WHITE);
View sbView = snackbar.getView();
sbView.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(getResources().getColor(R.color.white));
return snackbar;
}
private void flags() {
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
);
}
private void init() {
mSpState = findViewById(R.id.spin_status);
mSpState.getBackground().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
mEtName = findViewById(R.id.edit_full_name);
mEtPhone = findViewById(R.id.edit_phone_number);
mEtCommunity = findViewById(R.id.edit_community);
mEtPin = findViewById(R.id.edit_pin);
mEtProductType = findViewById(R.id.edit_product_type);
mTvSignIn = findViewById(R.id.text_sign_in);
mButtonReg = findViewById(R.id.button_register);
mCoordinatorLayout = findViewById(R.id.coordinatorLayout);
dialogFragment = new DialogFragment();
ArrayAdapter<CharSequence> statusAdapter = ArrayAdapter.createFromResource(this, R.array.Status, R.layout.spinner_item);
statusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpState.setAdapter(statusAdapter);
}
@Override
public void navigateToNextScreen() {
startActivity(new Intent(RegisterActivity.this, FormalSignInActivity.class));
}
@Override
public void navigateToSignInScreen() {
startActivity(new Intent(RegisterActivity.this, FormalSignInActivity.class));
}
private void sendUserData(RegisterModel registerModel) {
mApiService = Client.getClient().create(ApiService.class);
Call<RegisterResponse> call = mApiService.registerUser(registerModel);
call.enqueue(new Callback<RegisterResponse>() {
@Override
public void onResponse(Call<RegisterResponse> call, Response<RegisterResponse> response) {
if (response.body().getResponse().equals("success")) {
dialogFragment.dismiss();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(userName,mEtPhone.getText().toString());
editor.commit();
farmer.setId(1);
farmer.setPhone_number(mEtPhone.getText().toString());
farmer.save();
app.setUsername(mEtPhone.getText().toString());
Toast.makeText(RegisterActivity.this, "Registration status:" + response.body().getResponse(), Toast.LENGTH_SHORT).show();
mPresenter.loadNextScreen();
}
if (response.body().getResponse().equals("Failure")) {
Toast.makeText(RegisterActivity.this, "Registration status:" + response.body().getResponse(), Toast.LENGTH_SHORT).show();
registerFailure();
}
if (response.body().getMessage().equals("Phone number exists")) {
dialogFragment.dismiss();
Toast.makeText(RegisterActivity.this, "This phone number has been registered by another user.", Toast.LENGTH_SHORT).show();
return;
}
else {
dialogFragment.dismiss();
Toast.makeText(RegisterActivity.this, "Registration status:" + response.body().getResponse(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<RegisterResponse> call, Throwable t) {
dialogFragment.dismiss();
Snackbar snackbar = errorFailure("Unable to connect to the server");
snackbar.show();
}
});
}
@NonNull
private Snackbar errorFailure(String s) {
Snackbar snackbar = Snackbar.make(mCoordinatorLayout, s, Snackbar.LENGTH_LONG)
.setAction("TRY AGAIN", new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mPresenter.verifyEntries()) {
dialogFragment.setCancelable(false);
dialogFragment.show(getSupportFragmentManager(), "my_dialog");
sendUserData(model);
}
}
});
snackbar.setActionTextColor(Color.WHITE);
View sbView = snackbar.getView();
sbView.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(getResources().getColor(R.color.white));
return snackbar;
}
private void registerFailure() {
Snackbar snackbar = errorFailure("Unable to process registration, Try again");
snackbar.show();
}
}
| UTF-8 | Java | 10,276 | java | RegisterActivity.java | Java | [
{
"context": "pref\";\n public static final String userName = \"userNameKey\";\n public AppInstance app;\n\n @Override\n ",
"end": 2229,
"score": 0.9871957302093506,
"start": 2218,
"tag": "USERNAME",
"value": "userNameKey"
},
{
"context": "phone_number,community, productT... | null | [] | package com.aloine.resolute40.auth.register.activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.aloine.resolute40.AppInstance;
import com.aloine.resolute40.R;
import com.aloine.resolute40.auth.formalLogin.activity.FormalSignInActivity;
import com.aloine.resolute40.auth.register.contract.RegisterContract;
import com.aloine.resolute40.auth.register.database.table.Farmer;
import com.aloine.resolute40.auth.register.model.RegisterModel;
import com.aloine.resolute40.auth.register.network.ApiService;
import com.aloine.resolute40.auth.register.network.Client;
import com.aloine.resolute40.auth.register.network.RegisterResponse;
import com.aloine.resolute40.auth.register.presenter.RegisterPresenter;
import com.aloine.resolute40.auth.register.registerdialog.DialogFragment;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class RegisterActivity extends AppCompatActivity implements RegisterContract.View {
private EditText mEtName, mEtPhone, mEtCommunity, mEtPin, mEtProductType;
private Spinner mSpState;
private TextView mTvSignIn;
private Button mButtonReg;
private RegisterContract.Presenter mPresenter;
private CoordinatorLayout mCoordinatorLayout;
private ApiService mApiService;
private DialogFragment dialogFragment;
private RegisterModel model;
private Farmer farmer;
public SharedPreferences sharedPreferences;
public static final String mypreference = "mypref";
public static final String userName = "userNameKey";
public AppInstance app;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
flags();
if (Build.VERSION.SDK_INT >= 21) {
statusColor();
}
init();
register();
mPresenter = new RegisterPresenter(this);
signIn();
farmer = new Farmer();
app = AppInstance.getInstance();
sharedPreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE);
if (sharedPreferences.contains(userName)) {
app.setUsername(sharedPreferences.getString(userName,""));
}
}
private void statusColor() {
Window window = this.getWindow();
if (Build.VERSION.SDK_INT >= 21) {
window.setStatusBarColor(ContextCompat.getColor(this,R.color.colorPrimaryDark));
}
}
private void signIn() {
mTvSignIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mPresenter.loadSignInScreen();
}
});
}
private void register() {
mButtonReg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String full_name = mEtName.getText().toString();
String community = mEtCommunity.getText().toString();
String phone_number = mEtPhone.getText().toString();
String pin = mEtPin.getText().toString();
String productType = mEtProductType.getText().toString();
mPresenter.insertData(full_name, phone_number,community, pin,productType);
if (mPresenter.verifyEntries() && !mSpState.getSelectedItem().toString().equals("Select state")) {
dialogFragment.setCancelable(false);
dialogFragment.show(getSupportFragmentManager(), "my_dialog");
model = new RegisterModel(full_name, mSpState.getSelectedItem().toString(),phone_number,community, productType,pin, "null", "Farmer" );
sendUserData(model);
} else {
Snackbar snackbar = inCompleteDetails();
snackbar.show();
}
}
});
}
@NonNull
private Snackbar inCompleteDetails() {
Snackbar snackbar = Snackbar.make(mCoordinatorLayout, "Some details are missing!", Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
snackbar.setActionTextColor(Color.WHITE);
View sbView = snackbar.getView();
sbView.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(getResources().getColor(R.color.white));
return snackbar;
}
private void flags() {
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
);
}
private void init() {
mSpState = findViewById(R.id.spin_status);
mSpState.getBackground().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
mEtName = findViewById(R.id.edit_full_name);
mEtPhone = findViewById(R.id.edit_phone_number);
mEtCommunity = findViewById(R.id.edit_community);
mEtPin = findViewById(R.id.edit_pin);
mEtProductType = findViewById(R.id.edit_product_type);
mTvSignIn = findViewById(R.id.text_sign_in);
mButtonReg = findViewById(R.id.button_register);
mCoordinatorLayout = findViewById(R.id.coordinatorLayout);
dialogFragment = new DialogFragment();
ArrayAdapter<CharSequence> statusAdapter = ArrayAdapter.createFromResource(this, R.array.Status, R.layout.spinner_item);
statusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpState.setAdapter(statusAdapter);
}
@Override
public void navigateToNextScreen() {
startActivity(new Intent(RegisterActivity.this, FormalSignInActivity.class));
}
@Override
public void navigateToSignInScreen() {
startActivity(new Intent(RegisterActivity.this, FormalSignInActivity.class));
}
private void sendUserData(RegisterModel registerModel) {
mApiService = Client.getClient().create(ApiService.class);
Call<RegisterResponse> call = mApiService.registerUser(registerModel);
call.enqueue(new Callback<RegisterResponse>() {
@Override
public void onResponse(Call<RegisterResponse> call, Response<RegisterResponse> response) {
if (response.body().getResponse().equals("success")) {
dialogFragment.dismiss();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(userName,mEtPhone.getText().toString());
editor.commit();
farmer.setId(1);
farmer.setPhone_number(mEtPhone.getText().toString());
farmer.save();
app.setUsername(mEtPhone.getText().toString());
Toast.makeText(RegisterActivity.this, "Registration status:" + response.body().getResponse(), Toast.LENGTH_SHORT).show();
mPresenter.loadNextScreen();
}
if (response.body().getResponse().equals("Failure")) {
Toast.makeText(RegisterActivity.this, "Registration status:" + response.body().getResponse(), Toast.LENGTH_SHORT).show();
registerFailure();
}
if (response.body().getMessage().equals("Phone number exists")) {
dialogFragment.dismiss();
Toast.makeText(RegisterActivity.this, "This phone number has been registered by another user.", Toast.LENGTH_SHORT).show();
return;
}
else {
dialogFragment.dismiss();
Toast.makeText(RegisterActivity.this, "Registration status:" + response.body().getResponse(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<RegisterResponse> call, Throwable t) {
dialogFragment.dismiss();
Snackbar snackbar = errorFailure("Unable to connect to the server");
snackbar.show();
}
});
}
@NonNull
private Snackbar errorFailure(String s) {
Snackbar snackbar = Snackbar.make(mCoordinatorLayout, s, Snackbar.LENGTH_LONG)
.setAction("TRY AGAIN", new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mPresenter.verifyEntries()) {
dialogFragment.setCancelable(false);
dialogFragment.show(getSupportFragmentManager(), "my_dialog");
sendUserData(model);
}
}
});
snackbar.setActionTextColor(Color.WHITE);
View sbView = snackbar.getView();
sbView.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(getResources().getColor(R.color.white));
return snackbar;
}
private void registerFailure() {
Snackbar snackbar = errorFailure("Unable to process registration, Try again");
snackbar.show();
}
}
| 10,276 | 0.644998 | 0.641689 | 264 | 37.924244 | 32.424885 | 156 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.689394 | false | false | 3 |
b27b0fcbbc4becbf25a376d2eb9b528942be0c5b | 11,321,533,800,316 | 755cd8f80adc00d22309c444366ba4535410d661 | /src/main/java/ru/job4j/array/AndArray.java | 46c098bb8d0c1409bf31a3588a258ce62e0f69d3 | [] | no_license | timurvvolkov/job4j_elementary | https://github.com/timurvvolkov/job4j_elementary | 6702fe0887db02368e5e0156f60ff111d5cc4166 | 8b16b3ca0a9e75fc654ef92f34f99a6e4e4ce89e | refs/heads/master | 2022-12-24T18:03:56.760000 | 2022-12-18T23:22:05 | 2022-12-18T23:22:05 | 247,971,216 | 0 | 0 | null | true | 2020-03-17T13:03:56 | 2020-03-17T13:03:55 | 2020-02-26T08:00:46 | 2020-02-26T08:00:44 | 545 | 0 | 0 | 0 | null | false | false | package ru.job4j.array;
import java.util.Arrays;
public class AndArray {
public static int[] and(int[] left, int[] right) {
if (left.length >= right.length) {
return makeArray(left, right);
} else {
return makeArray(right, left);
}
}
private static int[] makeArray(int[] master, int[] slave) {
int[] rsl = new int[slave.length];
int count = 0;
for (int i = 0; i < master.length; i++) {
for (int j = 0; j < slave.length; j++) {
if (master[i] == slave[j]) {
rsl[count++] = master[i];
break;
}
}
}
return Arrays.copyOf(rsl, count);
}
}
| UTF-8 | Java | 736 | java | AndArray.java | Java | [] | null | [] | package ru.job4j.array;
import java.util.Arrays;
public class AndArray {
public static int[] and(int[] left, int[] right) {
if (left.length >= right.length) {
return makeArray(left, right);
} else {
return makeArray(right, left);
}
}
private static int[] makeArray(int[] master, int[] slave) {
int[] rsl = new int[slave.length];
int count = 0;
for (int i = 0; i < master.length; i++) {
for (int j = 0; j < slave.length; j++) {
if (master[i] == slave[j]) {
rsl[count++] = master[i];
break;
}
}
}
return Arrays.copyOf(rsl, count);
}
}
| 736 | 0.467391 | 0.461957 | 27 | 26.25926 | 19.043016 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 3 |
f056220b0878a2188b2a08be2468322eed562bbd | 12,876,311,962,545 | d6171b61c1565417ecf30f124f18ec9bf725c87b | /BSTre/src/no/hvl/dat102/KjedetBSTre.java | 47702b746d30c7dc7b04cc143274f96c10900cac | [] | no_license | 587851/dat102 | https://github.com/587851/dat102 | 3ef80c2c697adb1335a8881feb2f81ec2675def3 | e678d87360c949b214006d5622892fc8eee9047b | refs/heads/master | 2023-04-08T01:04:09.345000 | 2021-03-23T22:01:09 | 2021-03-23T22:01:09 | 328,928,657 | 0 | 0 | null | true | 2021-03-09T11:13:56 | 2021-01-12T09:03:26 | 2021-03-09T11:09:53 | 2021-03-09T11:09:50 | 371 | 0 | 0 | 0 | Java | false | false | package no.hvl.dat102;
import java.util.Iterator;
import no.hvl.dat102.adt.BSTreADT;
//********************************************************************
// KjedetBinærSøkeTre.java
//
//********************************************************************
public class KjedetBSTre<T extends Comparable<T>> implements BSTreADT<T>,Iterable<T> {
private int antall;
/**
* @return the rot
*/
public BinaerTreNode<T> getRot() {
return rot;
}
/**
* @param rot the rot to set
*/
public void setRot(BinaerTreNode<T> rot) {
this.rot = rot;
}
private BinaerTreNode<T> rot;
/******************************************************************
* Oppretter et tomt binært søketre.
******************************************************************/
public KjedetBSTre() {
antall = 0;
rot = null;
}
/******************************************************************
* Oppretter et binært søketre med en node..
******************************************************************/
public KjedetBSTre(T element) {
rot = new BinaerTreNode<T>(element);
antall = 1;
}
@Override
public int antall() {
return antall;
}
@Override
public boolean erTom() {
return (antall == 0);
}
@Override
public void leggTil(T element) {
rot = leggTilRek(rot, element);
antall++;
}
private BinaerTreNode<T> leggTilRek(BinaerTreNode<T> p, T element) {
if (p == null)
return new BinaerTreNode<T>(element);
if (p.getElement().compareTo(element) > 0) {
p.setVenstre(leggTilRek(p.getVenstre(), element));
return p;
}else
p.setHoyre(leggTilRek(p.getHoyre(), element));
return p;
}
/******************************************************************
* Legger det spesifiserte elementet på passende plass i dette binære søketreet.
* Like elementer blir lagt til høyre.
******************************************************************/
public void leggTil2(T element) {
//
}
/******************************************************************
* Fjerner noden med minste verdi fra dette binære søketreet.
*********************************************************************/
@Override
public T fjernMin() {
T element = null;
if (rot == null)
return null;
if (rot.getVenstre() == null) {
element = rot.getElement();
rot = rot.getHoyre();
}
else {
BinaerTreNode<T> prev = rot;
BinaerTreNode<T> el = rot.getVenstre();
while(el.getVenstre() != null) {
prev = el;
el = el.getVenstre();
}
element = el.getElement();
prev.setVenstre(el.getHoyre());
}
antall--;
return element;
}//
/******************************************************************
* Fjerner noden med største verdi fra dette binære søketreet.
******************************************************************/
@Override
public T fjernMaks() {
T element = null;
if (rot == null)
return null;
if (rot.getHoyre() == null) {
element = rot.getElement();
rot = rot.getVenstre();
}
else {
BinaerTreNode<T> prev = rot;
BinaerTreNode<T> el = rot.getHoyre();
while(el.getHoyre() != null) {
prev = el;
el = el.getHoyre();
}
element = el.getElement();
prev.setHoyre(el.getVenstre());
}
antall--;
return element;
}//
/******************************************************************
* Returnerer det minste elementet i dette binære søketreet.
******************************************************************/
@Override
public T finnMin() {
T element = null;
if (rot == null)
return null;
else {
BinaerTreNode<T> el = rot;
while(el.getVenstre() != null) {
el = el.getVenstre();
}
element = el.getElement();
}
return element;
}//
/******************************************************************
* Returnerer det største elementet i dette binære søketreet.
******************************************************************/
@Override
public T finnMaks() {
T element = null;
if (rot == null)
return null;
else {
BinaerTreNode<T> el = rot;
while(el.getHoyre() != null) {
el = el.getHoyre();
}
element = el.getElement();
}
return element;
}//
/*******************************************************************************
* Returnerer en referanse til det spesifiserte elementet hvis det finst i dette
* BS-treet, null ellers. Bruk av rekursjon /
******************************************************************************/
@Override
public T finn(T element) {
// Søk med rekursiv hjelpemetode
return finnRek(element, rot);
}
private T finnRek(T element, BinaerTreNode<T> t) {
if (t == null)
return null;
if (t.getElement().compareTo(element) > 0)
return finnRek(element, t.getVenstre());
else if (t.getElement().compareTo(element) < 0) {
return finnRek(element, t.getHoyre());
}
return t.getElement();
}
/************************************************************************
* Returnerer en referanse til det spesifiserte elementet hvis det fins i dette
* BS-treet, null ellers. Uten bruk av rekursjon. /
************************************************************************/
public T finn2(T element) {
if (rot == null)
return null;
BinaerTreNode<T> t = rot;
boolean kanFinnes = true;
while(t.getElement().compareTo(element) != 0 && kanFinnes) {
if(t.getElement().compareTo(element) < 0) {
if (t.getHoyre() != null)
t = t.getHoyre();
else
kanFinnes = false;
}
else if(t.getElement().compareTo(element) > 0) {
if (t.getVenstre() != null)
t = t.getVenstre();
else
kanFinnes = false;
}
}
if (!kanFinnes)
return null;
return t.getElement();
}
public void visInorden() {
visInorden(rot);
System.out.println();
}
private void visInorden(BinaerTreNode<T> p) {
if (p != null) {
visInorden(p.getVenstre());
System.out.print(" " + p.getElement());
visInorden(p.getHoyre());
}
}
@Override
public Iterator<T> iterator() {
return new InordenIterator<T>(rot);
}
public int hoyde() {
return hoydeRek(rot);
}
private int hoydeRek(BinaerTreNode<T> t) {
if(t == null)
return -1;
return (int)Math.max(hoydeRek(t.getVenstre()), hoydeRek(t.getHoyre())) + 1;
}
public void skrivVerdier(T nedre, T ovre) {
skrivVerdierRek(rot, nedre, ovre);
}
private void skrivVerdierRek(BinaerTreNode<T> t, T min, T maks) {
if(t != null) {
if (t.getElement().compareTo(min) >= 0)
skrivVerdierRek(t.getVenstre(), min, maks);
if((t.getElement().compareTo(min) >= 0) && (t.getElement().compareTo(maks) <= 0)){
System.out.println(t.getElement() + " ");
}
if (t.getElement().compareTo(maks) <= 0)
skrivVerdierRek(t.getHoyre(), min, maks);
}
}
}// class
| ISO-8859-15 | Java | 6,764 | java | KjedetBSTre.java | Java | [] | null | [] | package no.hvl.dat102;
import java.util.Iterator;
import no.hvl.dat102.adt.BSTreADT;
//********************************************************************
// KjedetBinærSøkeTre.java
//
//********************************************************************
public class KjedetBSTre<T extends Comparable<T>> implements BSTreADT<T>,Iterable<T> {
private int antall;
/**
* @return the rot
*/
public BinaerTreNode<T> getRot() {
return rot;
}
/**
* @param rot the rot to set
*/
public void setRot(BinaerTreNode<T> rot) {
this.rot = rot;
}
private BinaerTreNode<T> rot;
/******************************************************************
* Oppretter et tomt binært søketre.
******************************************************************/
public KjedetBSTre() {
antall = 0;
rot = null;
}
/******************************************************************
* Oppretter et binært søketre med en node..
******************************************************************/
public KjedetBSTre(T element) {
rot = new BinaerTreNode<T>(element);
antall = 1;
}
@Override
public int antall() {
return antall;
}
@Override
public boolean erTom() {
return (antall == 0);
}
@Override
public void leggTil(T element) {
rot = leggTilRek(rot, element);
antall++;
}
private BinaerTreNode<T> leggTilRek(BinaerTreNode<T> p, T element) {
if (p == null)
return new BinaerTreNode<T>(element);
if (p.getElement().compareTo(element) > 0) {
p.setVenstre(leggTilRek(p.getVenstre(), element));
return p;
}else
p.setHoyre(leggTilRek(p.getHoyre(), element));
return p;
}
/******************************************************************
* Legger det spesifiserte elementet på passende plass i dette binære søketreet.
* Like elementer blir lagt til høyre.
******************************************************************/
public void leggTil2(T element) {
//
}
/******************************************************************
* Fjerner noden med minste verdi fra dette binære søketreet.
*********************************************************************/
@Override
public T fjernMin() {
T element = null;
if (rot == null)
return null;
if (rot.getVenstre() == null) {
element = rot.getElement();
rot = rot.getHoyre();
}
else {
BinaerTreNode<T> prev = rot;
BinaerTreNode<T> el = rot.getVenstre();
while(el.getVenstre() != null) {
prev = el;
el = el.getVenstre();
}
element = el.getElement();
prev.setVenstre(el.getHoyre());
}
antall--;
return element;
}//
/******************************************************************
* Fjerner noden med største verdi fra dette binære søketreet.
******************************************************************/
@Override
public T fjernMaks() {
T element = null;
if (rot == null)
return null;
if (rot.getHoyre() == null) {
element = rot.getElement();
rot = rot.getVenstre();
}
else {
BinaerTreNode<T> prev = rot;
BinaerTreNode<T> el = rot.getHoyre();
while(el.getHoyre() != null) {
prev = el;
el = el.getHoyre();
}
element = el.getElement();
prev.setHoyre(el.getVenstre());
}
antall--;
return element;
}//
/******************************************************************
* Returnerer det minste elementet i dette binære søketreet.
******************************************************************/
@Override
public T finnMin() {
T element = null;
if (rot == null)
return null;
else {
BinaerTreNode<T> el = rot;
while(el.getVenstre() != null) {
el = el.getVenstre();
}
element = el.getElement();
}
return element;
}//
/******************************************************************
* Returnerer det største elementet i dette binære søketreet.
******************************************************************/
@Override
public T finnMaks() {
T element = null;
if (rot == null)
return null;
else {
BinaerTreNode<T> el = rot;
while(el.getHoyre() != null) {
el = el.getHoyre();
}
element = el.getElement();
}
return element;
}//
/*******************************************************************************
* Returnerer en referanse til det spesifiserte elementet hvis det finst i dette
* BS-treet, null ellers. Bruk av rekursjon /
******************************************************************************/
@Override
public T finn(T element) {
// Søk med rekursiv hjelpemetode
return finnRek(element, rot);
}
private T finnRek(T element, BinaerTreNode<T> t) {
if (t == null)
return null;
if (t.getElement().compareTo(element) > 0)
return finnRek(element, t.getVenstre());
else if (t.getElement().compareTo(element) < 0) {
return finnRek(element, t.getHoyre());
}
return t.getElement();
}
/************************************************************************
* Returnerer en referanse til det spesifiserte elementet hvis det fins i dette
* BS-treet, null ellers. Uten bruk av rekursjon. /
************************************************************************/
public T finn2(T element) {
if (rot == null)
return null;
BinaerTreNode<T> t = rot;
boolean kanFinnes = true;
while(t.getElement().compareTo(element) != 0 && kanFinnes) {
if(t.getElement().compareTo(element) < 0) {
if (t.getHoyre() != null)
t = t.getHoyre();
else
kanFinnes = false;
}
else if(t.getElement().compareTo(element) > 0) {
if (t.getVenstre() != null)
t = t.getVenstre();
else
kanFinnes = false;
}
}
if (!kanFinnes)
return null;
return t.getElement();
}
public void visInorden() {
visInorden(rot);
System.out.println();
}
private void visInorden(BinaerTreNode<T> p) {
if (p != null) {
visInorden(p.getVenstre());
System.out.print(" " + p.getElement());
visInorden(p.getHoyre());
}
}
@Override
public Iterator<T> iterator() {
return new InordenIterator<T>(rot);
}
public int hoyde() {
return hoydeRek(rot);
}
private int hoydeRek(BinaerTreNode<T> t) {
if(t == null)
return -1;
return (int)Math.max(hoydeRek(t.getVenstre()), hoydeRek(t.getHoyre())) + 1;
}
public void skrivVerdier(T nedre, T ovre) {
skrivVerdierRek(rot, nedre, ovre);
}
private void skrivVerdierRek(BinaerTreNode<T> t, T min, T maks) {
if(t != null) {
if (t.getElement().compareTo(min) >= 0)
skrivVerdierRek(t.getVenstre(), min, maks);
if((t.getElement().compareTo(min) >= 0) && (t.getElement().compareTo(maks) <= 0)){
System.out.println(t.getElement() + " ");
}
if (t.getElement().compareTo(maks) <= 0)
skrivVerdierRek(t.getHoyre(), min, maks);
}
}
}// class
| 6,764 | 0.501112 | 0.497701 | 266 | 24.349625 | 22.619314 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.067669 | false | false | 3 |
5c9b7520a58a17253fbf32bdbf3406e11e43eeaf | 15,238,543,972,715 | 264827fcfa3e954d57452fb269e225d7ffdd0166 | /src/test/java/com/worker/RedisTest.java | bffb0607e56953318670b57ba7a442f0d7e57201 | [] | no_license | 17391929083/fksbworker | https://github.com/17391929083/fksbworker | d5ea0ba80fc551693cc00ee466e09de7cbc72868 | be6e952d019ca92311cf5fd3ce8d6c26dd613e59 | refs/heads/master | 2023-04-15T05:28:56.056000 | 2021-04-29T02:08:13 | 2021-04-29T02:08:13 | 334,823,555 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.worker;
import com.fksb.fksbenrol.service.FksbEnrolService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.Map;
import java.util.Set;
/*
*@Author 常胜杰 QQ1209939478
*@Slogin 致敬大师 致敬未来的你
*/
public class RedisTest {
ClassPathXmlApplicationContext ioc;
private RedisTemplate redisTemplate;
@Before
public void before(){
// 加载spring容器
//ApplicationContext spring的顶层核心接口
// ClassPathXmlApplicationContext 根据项目路径的xml配置来实例化spring容器
// FileSystemXmlApplicationContext 根据磁盘路径的xml配置来实例化spring容器
// AnnotationConfigApplicationContext 根据javaconfig 来配置实例化spring容器
// 在容器实例化的时候 就会加载所有的bean
ioc=new ClassPathXmlApplicationContext("spring-redis.xml");
redisTemplate = ioc.getBean("redisTemplate", RedisTemplate.class);
}
@Test
public void testDirect(){
// Set<String> keys = redisTemplate.keys("*");
// redisTemplate.delete(keys);
//2.发送消息
//redisTemplate.opsForHash().put("ruleOrgcd","610113010",0);
System.out.println(redisTemplate.opsForHash().entries("equuidTompcd"));
}
@Autowired
private FksbEnrolService fksbEnrolService;
}
| UTF-8 | Java | 1,578 | java | RedisTest.java | Java | [
{
"context": "ava.util.Map;\nimport java.util.Set;\n\n/*\n *@Author 常胜杰 QQ1209939478\n *@Slogin 致敬大师 致敬未来的你\n */\npublic c",
"end": 379,
"score": 0.9540019035339355,
"start": 376,
"tag": "USERNAME",
"value": "常胜杰"
}
] | null | [] | package com.worker;
import com.fksb.fksbenrol.service.FksbEnrolService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.Map;
import java.util.Set;
/*
*@Author 常胜杰 QQ1209939478
*@Slogin 致敬大师 致敬未来的你
*/
public class RedisTest {
ClassPathXmlApplicationContext ioc;
private RedisTemplate redisTemplate;
@Before
public void before(){
// 加载spring容器
//ApplicationContext spring的顶层核心接口
// ClassPathXmlApplicationContext 根据项目路径的xml配置来实例化spring容器
// FileSystemXmlApplicationContext 根据磁盘路径的xml配置来实例化spring容器
// AnnotationConfigApplicationContext 根据javaconfig 来配置实例化spring容器
// 在容器实例化的时候 就会加载所有的bean
ioc=new ClassPathXmlApplicationContext("spring-redis.xml");
redisTemplate = ioc.getBean("redisTemplate", RedisTemplate.class);
}
@Test
public void testDirect(){
// Set<String> keys = redisTemplate.keys("*");
// redisTemplate.delete(keys);
//2.发送消息
//redisTemplate.opsForHash().put("ruleOrgcd","610113010",0);
System.out.println(redisTemplate.opsForHash().entries("equuidTompcd"));
}
@Autowired
private FksbEnrolService fksbEnrolService;
}
| 1,578 | 0.721986 | 0.707092 | 54 | 25.111111 | 25.542025 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false | 3 |
142c2773e291facf982de226b170c5bac0ed3d9f | 15,238,543,971,363 | 54fc75b55242f6cfb43513548347131779fd19cd | /src/main/java/com/hassler/kardex/persistence/DetailSaleDAO.java | 0d6e30c7f7f7391d531717faca4cbb9050a88ee2 | [] | no_license | HasslerYahir/kardex | https://github.com/HasslerYahir/kardex | 16050325269b69a9918777253581f12495733f34 | 2509304250c586f90028aec23003ed5c31a229c0 | refs/heads/master | 2020-12-22T17:23:06.673000 | 2020-02-03T19:27:24 | 2020-02-03T19:27:24 | 236,873,547 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hassler.kardex.persistence;
import org.springframework.data.jpa.repository.JpaRepository;
import com.hassler.kardex.model.DetailSale;
public interface DetailSaleDAO extends JpaRepository<DetailSale, Long>{
}
| UTF-8 | Java | 225 | java | DetailSaleDAO.java | Java | [] | null | [] | package com.hassler.kardex.persistence;
import org.springframework.data.jpa.repository.JpaRepository;
import com.hassler.kardex.model.DetailSale;
public interface DetailSaleDAO extends JpaRepository<DetailSale, Long>{
}
| 225 | 0.831111 | 0.831111 | 9 | 24 | 27.788887 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 3 |
232b87126a3ebf006673c0187882a265c445a8e2 | 17,008,070,497,505 | 6463d9ed10ce055f58790dccdef7f4a781082840 | /GUI/src/Interface/frame.java | ef715bb24b4074405fe1bc29e1a529e72a8a3384 | [] | no_license | phuocnhatfabulous/Learn_Java | https://github.com/phuocnhatfabulous/Learn_Java | fc2ed8ded096bd05b931a432a38855983f8b5fb4 | f111ebdff3243d2ab11e450db3b02e8f45507ada | refs/heads/master | 2023-04-28T22:02:27.930000 | 2021-05-11T02:24:30 | 2021-05-11T02:24:30 | 344,401,979 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.awt.Color;
import javax.swing.JFrame; //Declare java frame library
import javax.swing.ImageIcon;
public class frame {
public static void main(String[] args) {
JFrame frame = new JFrame(); //Create a frame
frame.setTitle("JFrame title goes here "); //Set title of frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); //Exit out of application
frame.setResizable(false); //Prevent frame from being resize
frame.setSize(420,420); //Sets the x-dimension, and y-dimension of frame
frame.setVisible(true); //Make frame visible
ImageIcon image = new ImageIcon("bame.png"); //Create an image
frame.setIconImage(image.getImage()); //Change icon frame
frame.setContentPane().setBackground(new Color(0,0,6)); //Change color of background
}
}
| UTF-8 | Java | 784 | java | frame.java | Java | [] | null | [] |
import java.awt.Color;
import javax.swing.JFrame; //Declare java frame library
import javax.swing.ImageIcon;
public class frame {
public static void main(String[] args) {
JFrame frame = new JFrame(); //Create a frame
frame.setTitle("JFrame title goes here "); //Set title of frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); //Exit out of application
frame.setResizable(false); //Prevent frame from being resize
frame.setSize(420,420); //Sets the x-dimension, and y-dimension of frame
frame.setVisible(true); //Make frame visible
ImageIcon image = new ImageIcon("bame.png"); //Create an image
frame.setIconImage(image.getImage()); //Change icon frame
frame.setContentPane().setBackground(new Color(0,0,6)); //Change color of background
}
}
| 784 | 0.733418 | 0.721939 | 21 | 36.285713 | 29.661812 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false | 3 |
1763b88eeeb8a8ea54813da999342d21d9632822 | 17,643,725,657,162 | f9c48857adbf7177f19154441dd3d218d003e6ba | /src/main/java/org/kleber/settings/geral/GeralController.java | a0c1845bc68ec47c174b4641adbd93d611d5d15f | [] | no_license | klebermo/store | https://github.com/klebermo/store | 658dbf03f45bf17a7d5d1982b5afe94b943570ba | 0579e208ad32806b05635e3288f051c1519ccc69 | refs/heads/master | 2018-02-08T22:22:23.589000 | 2018-02-01T12:47:19 | 2018-02-01T12:47:19 | 81,083,921 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.kleber.settings.geral;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import javax.validation.Valid;
import org.springframework.validation.BindingResult;
@Controller
@RequestMapping("geral")
public class GeralController extends org.kleber.model.Controller<Geral> {
@Autowired
private GeralService serv;
public GeralController() {
super(Geral.class);
}
@RequestMapping(value = "/get")
public String get(Model model) {
model.addAttribute("setting", this.serv.get());
return "admin";
}
@RequestMapping(value = "/set", method=RequestMethod.POST)
@ResponseBody
public void set(@Valid Geral object, BindingResult result) {
this.serv.set(object);
}
}
| UTF-8 | Java | 971 | java | GeralController.java | Java | [] | null | [] | package org.kleber.settings.geral;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import javax.validation.Valid;
import org.springframework.validation.BindingResult;
@Controller
@RequestMapping("geral")
public class GeralController extends org.kleber.model.Controller<Geral> {
@Autowired
private GeralService serv;
public GeralController() {
super(Geral.class);
}
@RequestMapping(value = "/get")
public String get(Model model) {
model.addAttribute("setting", this.serv.get());
return "admin";
}
@RequestMapping(value = "/set", method=RequestMethod.POST)
@ResponseBody
public void set(@Valid Geral object, BindingResult result) {
this.serv.set(object);
}
}
| 971 | 0.790937 | 0.790937 | 35 | 26.742857 | 23.464676 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.028571 | false | false | 3 |
a42ffdfa2ede996371b233eab4908c6807c4e845 | 876,173,340,995 | e682fa3667adce9277ecdedb40d4d01a785b3912 | /internal/fischer/mangf/A064565.java | 364ed0d8cc3e0f74fb9a8a173b0258d9e8187714 | [
"Apache-2.0"
] | permissive | gfis/joeis-lite | https://github.com/gfis/joeis-lite | 859158cb8fc3608febf39ba71ab5e72360b32cb4 | 7185a0b62d54735dc3d43d8fb5be677734f99101 | refs/heads/master | 2023-08-31T00:23:51.216000 | 2023-08-29T21:11:31 | 2023-08-29T21:11:31 | 179,938,034 | 4 | 1 | Apache-2.0 | false | 2022-06-25T22:47:19 | 2019-04-07T08:35:01 | 2022-03-26T06:04:12 | 2022-06-25T22:47:18 | 8,156 | 3 | 0 | 1 | Roff | false | false | package irvine.oeis.a064;
// Generated by gen_seq4.pl build/parm4 at 2023-02-21 22:23
import irvine.math.z.Z;
import irvine.oeis.a064.A064560;
/**
* A064565 Reciprocal of n terminates with an infinite repetition of digit 6. Multiples of 10 are omitted.
* @author Georg Fischer
*/
public class A064565 extends A064560 {
/** Construct the sequence. */
public A064565() {
super(0, i -> Z.ONE.shiftLeft(2*i + 1).multiply(Z.THREE), i -> Z.FIVE.pow(2*i + 1).multiply(Z.THREE));
}
}
| UTF-8 | Java | 491 | java | A064565.java | Java | [
{
"context": "f digit 6. Multiples of 10 are omitted.\n * @author Georg Fischer\n */\npublic class A064565 extends A064560 {\n\n /**",
"end": 279,
"score": 0.9998615980148315,
"start": 266,
"tag": "NAME",
"value": "Georg Fischer"
}
] | null | [] | package irvine.oeis.a064;
// Generated by gen_seq4.pl build/parm4 at 2023-02-21 22:23
import irvine.math.z.Z;
import irvine.oeis.a064.A064560;
/**
* A064565 Reciprocal of n terminates with an infinite repetition of digit 6. Multiples of 10 are omitted.
* @author <NAME>
*/
public class A064565 extends A064560 {
/** Construct the sequence. */
public A064565() {
super(0, i -> Z.ONE.shiftLeft(2*i + 1).multiply(Z.THREE), i -> Z.FIVE.pow(2*i + 1).multiply(Z.THREE));
}
}
| 484 | 0.694501 | 0.576375 | 16 | 29.6875 | 33.07325 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 3 |
a5c8bce1231ffa191323028e709e8defdd97a1e8 | 24,086,176,665,492 | 627da11d85a4ed307df8272dbfad9053c2d2d327 | /FredBoat/src/main/java/fredboat/audio/queue/SimpleTrackProvider.java | 5e38fdee77d56818fe50d41c57a270e81c338155 | [
"MIT"
] | permissive | kophop/Hest | https://github.com/kophop/Hest | bbd04ccb4db2f10a7d66d4bd38997dd80e539744 | 4b7911f2e1ecc30fa7fff51b94f3d4cf482cbee5 | refs/heads/master | 2021-04-30T15:59:41.048000 | 2016-12-20T10:14:53 | 2016-12-20T10:14:53 | 76,968,403 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* The MIT License (MIT)
* Copyright (c) 2016 Frederik Mikkelsen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package fredboat.audio.queue;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;
public class SimpleTrackProvider extends AbstractTrackProvider {
private volatile ConcurrentLinkedQueue<AudioTrack> queue = new ConcurrentLinkedQueue<>();
private AudioTrack lastTrack = null;
@Override
public AudioTrack getNext() {
return queue.peek();
}
@Override
public AudioTrack provideAudioTrack(boolean skipped) {
if (isRepeat() && !skipped && lastTrack != null) {
return lastTrack.makeClone();
}
if (isShuffle()) {
//Get random int from queue, remove it and then return it
List<Object> list = Arrays.asList(queue.toArray());
if (list.isEmpty()) {
return null;
}
lastTrack = (AudioTrack) list.get(new Random().nextInt(list.size()));
queue.remove(lastTrack);
return lastTrack;
} else {
lastTrack = queue.poll();
return lastTrack;
}
}
@Override
public AudioTrack removeAt(int i) {
if(queue.size() < i){
return null;
} else {
int i2 = 0;
for(Object obj : Arrays.asList(queue.toArray())){
if(i == i2){
//noinspection SuspiciousMethodCalls
queue.remove(obj);
return (AudioTrack) obj;
}
i2++;
}
}
return null;
}
@Override
public List<AudioTrack> getAsList() {
return new ArrayList<>(queue);
}
@Override
public boolean isEmpty() {
return queue.isEmpty();
}
@Override
public void add(AudioTrack track) {
queue.add(track);
}
@Override
public void clear() {
queue.clear();
}
}
| UTF-8 | Java | 3,160 | java | SimpleTrackProvider.java | Java | [
{
"context": "/*\n * The MIT License (MIT)\n * Copyright (c) 2016 Frederik Mikkelsen\n *\n * Permission is hereby granted, free of charg",
"end": 68,
"score": 0.9998197555541992,
"start": 50,
"tag": "NAME",
"value": "Frederik Mikkelsen"
}
] | null | [] | /*
* The MIT License (MIT)
* Copyright (c) 2016 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package fredboat.audio.queue;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;
public class SimpleTrackProvider extends AbstractTrackProvider {
private volatile ConcurrentLinkedQueue<AudioTrack> queue = new ConcurrentLinkedQueue<>();
private AudioTrack lastTrack = null;
@Override
public AudioTrack getNext() {
return queue.peek();
}
@Override
public AudioTrack provideAudioTrack(boolean skipped) {
if (isRepeat() && !skipped && lastTrack != null) {
return lastTrack.makeClone();
}
if (isShuffle()) {
//Get random int from queue, remove it and then return it
List<Object> list = Arrays.asList(queue.toArray());
if (list.isEmpty()) {
return null;
}
lastTrack = (AudioTrack) list.get(new Random().nextInt(list.size()));
queue.remove(lastTrack);
return lastTrack;
} else {
lastTrack = queue.poll();
return lastTrack;
}
}
@Override
public AudioTrack removeAt(int i) {
if(queue.size() < i){
return null;
} else {
int i2 = 0;
for(Object obj : Arrays.asList(queue.toArray())){
if(i == i2){
//noinspection SuspiciousMethodCalls
queue.remove(obj);
return (AudioTrack) obj;
}
i2++;
}
}
return null;
}
@Override
public List<AudioTrack> getAsList() {
return new ArrayList<>(queue);
}
@Override
public boolean isEmpty() {
return queue.isEmpty();
}
@Override
public void add(AudioTrack track) {
queue.add(track);
}
@Override
public void clear() {
queue.clear();
}
}
| 3,148 | 0.634494 | 0.631962 | 92 | 33.347828 | 66.143196 | 463 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.554348 | false | false | 3 |
135e8a542e9f055c9daa9b5d2911eeafa6bc63a4 | 18,605,798,341,027 | ce1e2ff0c4d9e7421762e0313b44e0a31a5a6fe2 | /center-modules/center-admin/src/main/java/com/zorkdata/center/admin/entity/SuperEntity.java | 902c1a38c82c98f2ee8536d55c34a1ad2b13fd9d | [] | no_license | fx524913413/smartoms-admin | https://github.com/fx524913413/smartoms-admin | 5f3d4fdc3627b967f5df9e099a2b77354e6fd960 | c945107413878146d00ec3c244bdb792a4c8c3b3 | refs/heads/master | 2020-03-29T01:10:55.083000 | 2018-09-19T01:45:22 | 2018-09-19T01:45:22 | 149,375,295 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zorkdata.center.admin.entity;
import java.util.TreeMap;
/**
* 万能实体类,可用于任何数据的封装
*/
public class SuperEntity extends TreeMap<String, Object> {
public SuperEntity setProperty(String key, Object value) {
this.put(key, value);
return this;
}
}
| UTF-8 | Java | 314 | java | SuperEntity.java | Java | [] | null | [] | package com.zorkdata.center.admin.entity;
import java.util.TreeMap;
/**
* 万能实体类,可用于任何数据的封装
*/
public class SuperEntity extends TreeMap<String, Object> {
public SuperEntity setProperty(String key, Object value) {
this.put(key, value);
return this;
}
}
| 314 | 0.680851 | 0.680851 | 16 | 16.625 | 20.52095 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false | 3 |
4b53ae8d950cf04eebda07ca936153f30bf4d3d0 | 19,043,885,010,766 | 5a028162ee43c4d0e99c4023a2acf4e8644a1080 | /supplier-api/src/main/java/com/channelsharing/hongqu/supplier/api/controller/supplier/SupplierUserAddRequestEntity.java | 4547d826770a1b540a519affb2e6aaf1e4c4226a | [
"Apache-2.0"
] | permissive | Gradven/platform-api | https://github.com/Gradven/platform-api | fb9f67e4a2a513370b3f6175e23dcf07d1cdee9e | 2f3740df0591e95e368713b0bb502e122d9ff650 | refs/heads/master | 2023-04-29T12:39:46.385000 | 2021-05-08T09:51:04 | 2021-05-08T09:51:04 | 365,476,378 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright © 2016-2022 liuhangjun All rights reserved.
*/
package com.channelsharing.hongqu.supplier.api.controller.supplier;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotNull;
/**
* 供应商用户Entity
*
* @author liuhangjun
* @version 2018-02-02
*/
@Data
public class SupplierUserAddRequestEntity {
@Length(min = 0, max = 32, message = "供应商用户姓名长度必须介于 0 和 32 之间")
public String name; // 供应商用户姓名
@Length(min = 1, max = 512, message = "登录密码长度必须介于 1 和 512 之间")
public String password; // 登录密码
public Integer age; // 年龄
@Length(min = 1, max = 50, message = "登录名长度必须介于 1 和 50 之间")
public String account; // 登录名
@Length(min = 0, max = 20, message = "手机号码长度必须介于 0 和 20 之间")
public String mobile; // 手机号码
@Length(min = 0, max = 128, message = "邮箱长度必须介于 0 和 128 之间")
public String email; // 邮箱
public Integer status; // 用户状态
@NotNull(message = "所属供应商不能为空")
public Integer supplierId; // 所属供应商
@Length(min = 0, max = 64, message = "备注号长度必须介于 0 和 64 之间")
public String remark; // 备注
}
| UTF-8 | Java | 1,443 | java | SupplierUserAddRequestEntity.java | Java | [
{
"context": "/**\n * Copyright © 2016-2022 liuhangjun All rights reserved.\n */\npackage com.chan",
"end": 36,
"score": 0.6354480385780334,
"start": 34,
"tag": "USERNAME",
"value": "li"
},
{
"context": "/**\n * Copyright © 2016-2022 liuhangjun All rights reserved.\n */\npa... | null | [] | /**
* Copyright © 2016-2022 liuhangjun All rights reserved.
*/
package com.channelsharing.hongqu.supplier.api.controller.supplier;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotNull;
/**
* 供应商用户Entity
*
* @author liuhangjun
* @version 2018-02-02
*/
@Data
public class SupplierUserAddRequestEntity {
@Length(min = 0, max = 32, message = "供应商用户姓名长度必须介于 0 和 32 之间")
public String name; // 供应商用户姓名
@Length(min = 1, max = 512, message = "登录密码长度必须介于 1 和 512 之间")
public String password; // 登录密码
public Integer age; // 年龄
@Length(min = 1, max = 50, message = "登录名长度必须介于 1 和 50 之间")
public String account; // 登录名
@Length(min = 0, max = 20, message = "手机号码长度必须介于 0 和 20 之间")
public String mobile; // 手机号码
@Length(min = 0, max = 128, message = "邮箱长度必须介于 0 和 128 之间")
public String email; // 邮箱
public Integer status; // 用户状态
@NotNull(message = "所属供应商不能为空")
public Integer supplierId; // 所属供应商
@Length(min = 0, max = 64, message = "备注号长度必须介于 0 和 64 之间")
public String remark; // 备注
}
| 1,443 | 0.622594 | 0.575732 | 47 | 24.425531 | 24.740993 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.553191 | false | false | 3 |
28b859cdf32f286175d7bb6324af8ca9d197d94d | 15,573,551,420,148 | d8de49cab5d03328f9fcbe8a203e48cde2491088 | /src/test/java/io/fake/utils/JSUtils.java | 8d7b167dcf6cd2bcf9cb6a48d084f687b1b69515 | [] | no_license | nbdnnm/web_tests | https://github.com/nbdnnm/web_tests | 0d996b6252788b036c82cc82b7dc5738f1356dd6 | e84a11ece5fc9519a7f7ce2546d186b901f57bc9 | refs/heads/master | 2020-03-23T02:09:53.055000 | 2019-02-22T14:23:38 | 2019-02-22T14:23:38 | 140,959,740 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.fake.utils;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class JSUtils {
public static void waitPageToBeReady(WebDriver driver) {
(new WebDriverWait(driver, 5000)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
JavascriptExecutor js = (JavascriptExecutor) d;
return js.executeScript("return document.readyState").equals("complete");
}
});
}
}
| UTF-8 | Java | 624 | java | JSUtils.java | Java | [] | null | [] | package io.fake.utils;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class JSUtils {
public static void waitPageToBeReady(WebDriver driver) {
(new WebDriverWait(driver, 5000)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
JavascriptExecutor js = (JavascriptExecutor) d;
return js.executeScript("return document.readyState").equals("complete");
}
});
}
}
| 624 | 0.697115 | 0.690705 | 18 | 33.666668 | 28.509258 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
caeb1736abcdde4f193eb8b5a1217ed43dd73ac9 | 24,352,464,576,996 | 0c7effb90311bfa0678498360309d12ad8f1ff59 | /App.java | 75ac8f2336e4e9c4c6797ed036d7e7439b369dd5 | [] | no_license | Ntshembo-Hlongwane1/Assesment | https://github.com/Ntshembo-Hlongwane1/Assesment | 81a7ad120f9f930df2f1dfda0828af26a1f1eb87 | 732f5e5a6e7dc0c96990abddf2cde553c73d5a97 | refs/heads/master | 2023-08-29T14:08:26.053000 | 2021-10-12T21:02:02 | 2021-10-12T21:02:02 | 416,474,946 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
// DO NOT EDIT UNLESS SPECIFIED TO DO SO!
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.stream.Stream;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
// https://www.tutorialspoint.com/json_simple/json_simple_quick_guide.htm
public class App {
public static void main(String[] args) throws Exception {
System.out.println("Hello, Student!\n");
Graph bellman = null;
Graph djikstra = null;
// Add code for handling Json file here
JSONParser parser = new JSONParser();
try (Reader reader = new FileReader("graphs.json")) {
JSONObject jsonObject = (JSONObject) parser.parse(reader);
JSONObject obj = (JSONObject) jsonObject.get("Graph_2");
int end = Integer.parseInt(obj.get("end").toString());
ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>();
ArrayList<ArrayList<Integer>> matrix = (ArrayList<ArrayList<Integer>>) obj.get("graph");
for (int i=0; i<end+1; i++) {
graph.add(matrix.get(i));
}
graph = truncateElements(graph, 0, end+1);
char[] possible_vertices = {'A', 'B', 'C', 'D', 'E','F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S','T', 'U', 'V', 'W','X', 'Y', 'Z'};
//Vertices
ArrayList<Character> vertices = new ArrayList<Character>();
for (int i=0; i<end+1; i++) {
vertices.add(possible_vertices[i]);
}
//Edges
ArrayList<ArrayList<Character>> edges = new ArrayList<ArrayList<Character>>();
for (int i=0; i<end+1; i++) {
for (int j=0; j<end+1; j++) {
ArrayList<Integer>current_array = graph.get(i);
long current_value = ((Number)current_array.get(j)).longValue();
if (current_value > 0) {
edges.add(new ArrayList<Character>(Arrays.asList(vertices.get(i), vertices.get(j))));
}
}
}
//Weights
ArrayList<Integer> weights = new ArrayList<Integer>();
for (int i=0; i<end+1; i++) {
for (int j=0; j<end+1; j++) {
ArrayList<Integer>current_array = graph.get(i);
long current_value = ((Number)current_array.get(j)).longValue();
if (current_value > 0) {
weights.add((int) current_value);
}
}
}
int [] update_weight_array = convertWeightArrayList(weights);
String[] update_vertices_array = convertVerticesArrayList(vertices);
String[][] update_edges_array = convertEdgesArrayList(edges);
Graph new_graph = new Graph(update_vertices_array, update_edges_array, update_weight_array);
// Declare graph build
bellman = new Graph(update_vertices_array, update_edges_array, update_weight_array);
bellman.buildGraph();
djikstra = new Graph(update_vertices_array, update_edges_array, update_weight_array);
djikstra.buildGraph();
Djikstra dj = new Djikstra(new_graph);
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
Scanner scanner = new Scanner(System.in);
while (true) {
String[] options = { "1", "2", "3", "4", "5", "6" };
List<String> _options = new ArrayList<>(Arrays.asList(options));
System.out.println("Choose option to display: \n" + "[1] Provided Bellman graph information.\n"
+ "[2] Provided Djikstra graph information.\n" + "[3] Bellman solution.\n"
+ "[4] Djikstra solution.\n" + "[5] Test Bellman solution on other graph.\n"
+ "[6] Test Djikstra Solution on other graph.\n" + "Any other button to exit.\n");
String s = scanner.nextLine();
switch (s) {
case "1":
bellman.printGraphInfo();
break;
case "2":
djikstra.printGraphInfo();
break;
case "3":
// Now we call the bellman algo
new Bellman(bellman).run();
break;
case "4":
// Now we call the djikstra algo
new Djikstra(djikstra).run();
break;
case "5":
System.out.println("Student completes this section!");
// jsonGraph(jsonObject, true);
break;
case "6":
// System.out.println("Student completes this section!");
// jsonGraph(jsonObject, false);
break;
}
if (!_options.contains(s)) {
scanner.close();
break;
}
}
}
private static String[][] convertEdgesArrayList(ArrayList<ArrayList<Character>> edges){
String[][] updated_edges_array = new String[edges.size()][2];
for (int i=0; i<edges.size(); i++) {
String[] temp = new String[2];
for(int j=0; j<2; j++) {
temp[j] = edges.get(i).get(j).toString();
}
updated_edges_array[i] = temp;
}
return updated_edges_array;
}
private static String[] convertVerticesArrayList(ArrayList<Character> vertices) {
String[] update_vertices_array = new String[vertices.size()];
for (int i=0; i<vertices.size(); i++) {
update_vertices_array[i] = vertices.get(i).toString();
}
return update_vertices_array;
}
private static int[] convertWeightArrayList(ArrayList<Integer> weights) {
int [] new_weights = new int[weights.size()];
for (int i=0; i<weights.size(); i++) {
new_weights[i] = weights.get(i);
}
return new_weights;
}
private static ArrayList<ArrayList<Integer>> truncateElements(ArrayList<ArrayList<Integer>> graph, int start, int end) {
for (int i=0; i<end; i++) {
graph.set(i, new ArrayList(graph.get(i).subList(start, end)));
}
return graph;
}
// Modify the section below to use graph data from json file
/*
* public static void jsonGraph(JSONObject obj, boolean flag){
*
* // Add your code here //
*
* // Do not edit below! if (flag){ Bellman(null, adj_matrix).run(); }else{
* Djikstra(null, adj_matrix).run(); }
*
*
* }
*/
// public static void jsonGraph(JSONObject obj, boolean flag) {
// int end = Integer.parseInt(obj.get("end").toString());
// ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>();
// ArrayList<ArrayList<Integer>> matrix = (ArrayList<ArrayList<Integer>>) obj.get("graph");
//
//
// for (int i=0; i<end+1; i++) {
// graph.add(matrix.get(i));
// }
//
// graph = truncateElements(graph, 0, end+1);
// char[] possible_vertices = {'A', 'B', 'C', 'D', 'E','F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S','T', 'U', 'V', 'W','X', 'Y', 'Z'};
//
// //Vertices
// ArrayList<Character> vertices = new ArrayList<Character>();
// for (int i=0; i<end+1; i++) {
// vertices.add(possible_vertices[i]);
// }
//
// //Edges
// ArrayList<ArrayList<Character>> edges = new ArrayList<ArrayList<Character>>();
// for (int i=0; i<end+1; i++) {
// for (int j=0; j<end+1; j++) {
// ArrayList<Integer>current_array = graph.get(i);
// long current_value = ((Number)current_array.get(j)).longValue();
//
// if (current_value > 0) {
// edges.add(new ArrayList<Character>(Arrays.asList(vertices.get(i), vertices.get(j))));
// }
// }
// }
//
// //Weights
// ArrayList<Integer> weights = new ArrayList<Integer>();
// for (int i=0; i<end+1; i++) {
// for (int j=0; j<end+1; j++) {
// ArrayList<Integer>current_array = graph.get(i);
// long current_value = ((Number)current_array.get(j)).longValue();
//
// if (current_value > 0) {
// weights.add((int) current_value);
// }
// }
// }
//
//
// int [] update_weight_array = convertWeightArrayList(weights);
// String[] update_vertices_array = convertVerticesArrayList(vertices);
// String[][] update_edges_array = convertEdgesArrayList(edges);
//
// Graph new_graph = new Graph(update_vertices_array, update_edges_array, update_weight_array);
// new_graph.buildGraph();
//
// Djikstra dj = new Djikstra(new_graph);
// dj.run();
// }
}
| UTF-8 | Java | 9,459 | java | App.java | Java | [] | null | [] |
// DO NOT EDIT UNLESS SPECIFIED TO DO SO!
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.stream.Stream;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
// https://www.tutorialspoint.com/json_simple/json_simple_quick_guide.htm
public class App {
public static void main(String[] args) throws Exception {
System.out.println("Hello, Student!\n");
Graph bellman = null;
Graph djikstra = null;
// Add code for handling Json file here
JSONParser parser = new JSONParser();
try (Reader reader = new FileReader("graphs.json")) {
JSONObject jsonObject = (JSONObject) parser.parse(reader);
JSONObject obj = (JSONObject) jsonObject.get("Graph_2");
int end = Integer.parseInt(obj.get("end").toString());
ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>();
ArrayList<ArrayList<Integer>> matrix = (ArrayList<ArrayList<Integer>>) obj.get("graph");
for (int i=0; i<end+1; i++) {
graph.add(matrix.get(i));
}
graph = truncateElements(graph, 0, end+1);
char[] possible_vertices = {'A', 'B', 'C', 'D', 'E','F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S','T', 'U', 'V', 'W','X', 'Y', 'Z'};
//Vertices
ArrayList<Character> vertices = new ArrayList<Character>();
for (int i=0; i<end+1; i++) {
vertices.add(possible_vertices[i]);
}
//Edges
ArrayList<ArrayList<Character>> edges = new ArrayList<ArrayList<Character>>();
for (int i=0; i<end+1; i++) {
for (int j=0; j<end+1; j++) {
ArrayList<Integer>current_array = graph.get(i);
long current_value = ((Number)current_array.get(j)).longValue();
if (current_value > 0) {
edges.add(new ArrayList<Character>(Arrays.asList(vertices.get(i), vertices.get(j))));
}
}
}
//Weights
ArrayList<Integer> weights = new ArrayList<Integer>();
for (int i=0; i<end+1; i++) {
for (int j=0; j<end+1; j++) {
ArrayList<Integer>current_array = graph.get(i);
long current_value = ((Number)current_array.get(j)).longValue();
if (current_value > 0) {
weights.add((int) current_value);
}
}
}
int [] update_weight_array = convertWeightArrayList(weights);
String[] update_vertices_array = convertVerticesArrayList(vertices);
String[][] update_edges_array = convertEdgesArrayList(edges);
Graph new_graph = new Graph(update_vertices_array, update_edges_array, update_weight_array);
// Declare graph build
bellman = new Graph(update_vertices_array, update_edges_array, update_weight_array);
bellman.buildGraph();
djikstra = new Graph(update_vertices_array, update_edges_array, update_weight_array);
djikstra.buildGraph();
Djikstra dj = new Djikstra(new_graph);
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
Scanner scanner = new Scanner(System.in);
while (true) {
String[] options = { "1", "2", "3", "4", "5", "6" };
List<String> _options = new ArrayList<>(Arrays.asList(options));
System.out.println("Choose option to display: \n" + "[1] Provided Bellman graph information.\n"
+ "[2] Provided Djikstra graph information.\n" + "[3] Bellman solution.\n"
+ "[4] Djikstra solution.\n" + "[5] Test Bellman solution on other graph.\n"
+ "[6] Test Djikstra Solution on other graph.\n" + "Any other button to exit.\n");
String s = scanner.nextLine();
switch (s) {
case "1":
bellman.printGraphInfo();
break;
case "2":
djikstra.printGraphInfo();
break;
case "3":
// Now we call the bellman algo
new Bellman(bellman).run();
break;
case "4":
// Now we call the djikstra algo
new Djikstra(djikstra).run();
break;
case "5":
System.out.println("Student completes this section!");
// jsonGraph(jsonObject, true);
break;
case "6":
// System.out.println("Student completes this section!");
// jsonGraph(jsonObject, false);
break;
}
if (!_options.contains(s)) {
scanner.close();
break;
}
}
}
private static String[][] convertEdgesArrayList(ArrayList<ArrayList<Character>> edges){
String[][] updated_edges_array = new String[edges.size()][2];
for (int i=0; i<edges.size(); i++) {
String[] temp = new String[2];
for(int j=0; j<2; j++) {
temp[j] = edges.get(i).get(j).toString();
}
updated_edges_array[i] = temp;
}
return updated_edges_array;
}
private static String[] convertVerticesArrayList(ArrayList<Character> vertices) {
String[] update_vertices_array = new String[vertices.size()];
for (int i=0; i<vertices.size(); i++) {
update_vertices_array[i] = vertices.get(i).toString();
}
return update_vertices_array;
}
private static int[] convertWeightArrayList(ArrayList<Integer> weights) {
int [] new_weights = new int[weights.size()];
for (int i=0; i<weights.size(); i++) {
new_weights[i] = weights.get(i);
}
return new_weights;
}
private static ArrayList<ArrayList<Integer>> truncateElements(ArrayList<ArrayList<Integer>> graph, int start, int end) {
for (int i=0; i<end; i++) {
graph.set(i, new ArrayList(graph.get(i).subList(start, end)));
}
return graph;
}
// Modify the section below to use graph data from json file
/*
* public static void jsonGraph(JSONObject obj, boolean flag){
*
* // Add your code here //
*
* // Do not edit below! if (flag){ Bellman(null, adj_matrix).run(); }else{
* Djikstra(null, adj_matrix).run(); }
*
*
* }
*/
// public static void jsonGraph(JSONObject obj, boolean flag) {
// int end = Integer.parseInt(obj.get("end").toString());
// ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>();
// ArrayList<ArrayList<Integer>> matrix = (ArrayList<ArrayList<Integer>>) obj.get("graph");
//
//
// for (int i=0; i<end+1; i++) {
// graph.add(matrix.get(i));
// }
//
// graph = truncateElements(graph, 0, end+1);
// char[] possible_vertices = {'A', 'B', 'C', 'D', 'E','F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S','T', 'U', 'V', 'W','X', 'Y', 'Z'};
//
// //Vertices
// ArrayList<Character> vertices = new ArrayList<Character>();
// for (int i=0; i<end+1; i++) {
// vertices.add(possible_vertices[i]);
// }
//
// //Edges
// ArrayList<ArrayList<Character>> edges = new ArrayList<ArrayList<Character>>();
// for (int i=0; i<end+1; i++) {
// for (int j=0; j<end+1; j++) {
// ArrayList<Integer>current_array = graph.get(i);
// long current_value = ((Number)current_array.get(j)).longValue();
//
// if (current_value > 0) {
// edges.add(new ArrayList<Character>(Arrays.asList(vertices.get(i), vertices.get(j))));
// }
// }
// }
//
// //Weights
// ArrayList<Integer> weights = new ArrayList<Integer>();
// for (int i=0; i<end+1; i++) {
// for (int j=0; j<end+1; j++) {
// ArrayList<Integer>current_array = graph.get(i);
// long current_value = ((Number)current_array.get(j)).longValue();
//
// if (current_value > 0) {
// weights.add((int) current_value);
// }
// }
// }
//
//
// int [] update_weight_array = convertWeightArrayList(weights);
// String[] update_vertices_array = convertVerticesArrayList(vertices);
// String[][] update_edges_array = convertEdgesArrayList(edges);
//
// Graph new_graph = new Graph(update_vertices_array, update_edges_array, update_weight_array);
// new_graph.buildGraph();
//
// Djikstra dj = new Djikstra(new_graph);
// dj.run();
// }
}
| 9,459 | 0.513056 | 0.506819 | 254 | 36.236221 | 30.868647 | 167 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.283465 | false | false | 3 |
bfde2f4d04617add33e6f35c77bb536c47f39fae | 21,268,678,113,006 | 6baf1fe00541560788e78de5244ae17a7a2b375a | /hollywood/com.oculus.socialplatform-base/sources/com/oculus/panelapp/people/FBLinkedStatus.java | e8ef8656fdf482c06327696e86977dd67ad375d5 | [] | no_license | phwd/quest-tracker | https://github.com/phwd/quest-tracker | 286e605644fc05f00f4904e51f73d77444a78003 | 3d46fbb467ba11bee5827f7cae7dfeabeb1fd2ba | refs/heads/main | 2023-03-29T20:33:10.959000 | 2021-04-10T22:14:11 | 2021-04-10T22:14:11 | 357,185,040 | 4 | 2 | null | true | 2021-04-12T12:28:09 | 2021-04-12T12:28:08 | 2021-04-10T22:15:44 | 2021-04-10T22:15:39 | 116,441 | 0 | 0 | 0 | null | false | false | package com.oculus.panelapp.people;
public enum FBLinkedStatus {
LINKED,
NOT_LINKED,
NOT_READY,
ERROR
}
| UTF-8 | Java | 121 | java | FBLinkedStatus.java | Java | [] | null | [] | package com.oculus.panelapp.people;
public enum FBLinkedStatus {
LINKED,
NOT_LINKED,
NOT_READY,
ERROR
}
| 121 | 0.677686 | 0.677686 | 8 | 14.125 | 11.384611 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
6b6a60f4e418dba1773012431e601a31265c75fe | 10,505,490,013,792 | 8a030385a54403884235f0c8d05619b90b32a264 | /app/src/main/java/com/alextinekov/socialcontacts/socialcallbacks/AuthCallbacks.java | 56eb49ae9c0a4b1a3e620fd3f47b1c619e85758f | [] | no_license | Tamplier/SocialContacts | https://github.com/Tamplier/SocialContacts | b903731a4731238d876dd55f7bb50c27ec67a86c | 78531f58e066d660cf4d64ad407a9ca21be360f2 | refs/heads/master | 2021-01-17T16:30:03.245000 | 2016-07-17T14:38:03 | 2016-07-17T14:38:03 | 63,535,796 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.alextinekov.socialcontacts.socialcallbacks;
import android.content.Context;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginResult;
import com.vk.sdk.VKAccessToken;
import com.vk.sdk.VKCallback;
import com.vk.sdk.api.VKError;
/**
* Created by Alex Tinekov on 14.07.2016.
*/
public class AuthCallbacks implements VKCallback<VKAccessToken>, FacebookCallback<LoginResult> {
public enum NETWORKS {VK, FB};
private AuthCallbacksListener listener;
public AuthCallbacks(){
}
public void setCalbacksListeer(AuthCallbacksListener listener){
this.listener = listener;
}
@Override
public void onResult(VKAccessToken res) {
if(listener != null) listener.onSuccess(NETWORKS.VK);
}
@Override
public void onError(VKError error) {
if(listener != null) listener.onError(error.errorMessage);
}
@Override
public void onSuccess(LoginResult loginResult) {
if(listener != null) listener.onSuccess(NETWORKS.FB);
}
@Override
public void onCancel() {
if(listener != null) listener.onError("");
}
@Override
public void onError(FacebookException error) {
if(listener != null) listener.onError(error.getMessage());
}
}
| UTF-8 | Java | 1,307 | java | AuthCallbacks.java | Java | [
{
"context": "\nimport com.vk.sdk.api.VKError;\n\n/**\n * Created by Alex Tinekov on 14.07.2016.\n */\npublic class AuthCallbacks imp",
"end": 331,
"score": 0.9997903108596802,
"start": 319,
"tag": "NAME",
"value": "Alex Tinekov"
}
] | null | [] | package com.alextinekov.socialcontacts.socialcallbacks;
import android.content.Context;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginResult;
import com.vk.sdk.VKAccessToken;
import com.vk.sdk.VKCallback;
import com.vk.sdk.api.VKError;
/**
* Created by <NAME> on 14.07.2016.
*/
public class AuthCallbacks implements VKCallback<VKAccessToken>, FacebookCallback<LoginResult> {
public enum NETWORKS {VK, FB};
private AuthCallbacksListener listener;
public AuthCallbacks(){
}
public void setCalbacksListeer(AuthCallbacksListener listener){
this.listener = listener;
}
@Override
public void onResult(VKAccessToken res) {
if(listener != null) listener.onSuccess(NETWORKS.VK);
}
@Override
public void onError(VKError error) {
if(listener != null) listener.onError(error.errorMessage);
}
@Override
public void onSuccess(LoginResult loginResult) {
if(listener != null) listener.onSuccess(NETWORKS.FB);
}
@Override
public void onCancel() {
if(listener != null) listener.onError("");
}
@Override
public void onError(FacebookException error) {
if(listener != null) listener.onError(error.getMessage());
}
}
| 1,301 | 0.705432 | 0.699311 | 50 | 25.139999 | 24.050789 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.36 | false | false | 3 |
cb6254456c2d771b44cf7fc27e451b1213003725 | 28,475,633,236,008 | 5aa4d7fc917e9f5dbff52827e989c710f7ab2ed9 | /app/src/main/java/cn/yiya/shiji/activity/SearchForwardedGoodsActivity.java | 4c11003546538559a62e91b9c7236a2848066c41 | [] | no_license | muaijuan/demoApp | https://github.com/muaijuan/demoApp | 945e171341bb95e57a0428adc07f7b5ae44e859e | fc1d4e2341e0a503015bc0d5b5e9380167b41dd5 | refs/heads/master | 2017-08-02T23:10:05.863000 | 2017-02-10T16:33:25 | 2017-02-10T16:33:25 | 81,564,200 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.yiya.shiji.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import cn.yiya.shiji.R;
import cn.yiya.shiji.adapter.ForwardedGoodsAdapter;
import cn.yiya.shiji.business.ApiRequest;
import cn.yiya.shiji.business.HttpMessage;
import cn.yiya.shiji.business.MsgCallBack;
import cn.yiya.shiji.business.RetrofitRequest;
import cn.yiya.shiji.entity.MallGoodsDetailObject;
/**
* Created by Tom on 2016/12/5.
*/
public class SearchForwardedGoodsActivity extends BaseAppCompatActivity implements View.OnClickListener {
private TextView tvCancle;
private EditText etSearch;
private RecyclerView rycvForwarded;
private ForwardedGoodsAdapter mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_forwarded_goods);
initViews();
initEvents();
init();
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tv_cancel:
onBackPressed();
break;
case R.id.tv_reload:
searchGoods(etSearch.getText().toString());
break;
}
}
@Override
protected void initViews() {
tvCancle = (TextView) findViewById(R.id.tv_cancel);
etSearch = (EditText) findViewById(R.id.tv_search);
rycvForwarded = (RecyclerView) findViewById(R.id.rycv_forwarded);
rycvForwarded.setItemAnimator(new DefaultItemAnimator());
rycvForwarded.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new ForwardedGoodsAdapter(this);
rycvForwarded.setAdapter(mAdapter);
addDefaultNullView();
initDefaultNullView(R.mipmap.zanwusousuojieguo, "暂无结果", this);
}
@Override
protected void initEvents() {
tvCancle.setOnClickListener(this);
etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT){
searchGoods(etSearch.getText().toString());
return true;
}
return false;
}
});
}
// 查询搜索结果
private void searchGoods(String s) {
if(TextUtils.isEmpty(s)){
showTips("请输入搜索内容");
return;
}
// // TODO: 2016/12/5
getGoodsList();
}
private void getGoodsList() {
new RetrofitRequest<MallGoodsDetailObject>(ApiRequest.getApiShiji().getWishGoods()).handRequest(new MsgCallBack() {
@Override
public void onResult(HttpMessage msg) {
if (msg.isSuccess()) {
MallGoodsDetailObject object = (MallGoodsDetailObject) msg.obj;
if (object.getList() != null && object.getList().size() > 0) {
mAdapter.setmList(object.getList());
mAdapter.notifyDataSetChanged();
setSuccessView(rycvForwarded);
}else {
setNullView(rycvForwarded);
}
}else {
setOffNetView(rycvForwarded);
}
}
});
}
@Override
protected void init() {
}
}
| UTF-8 | Java | 3,997 | java | SearchForwardedGoodsActivity.java | Java | [
{
"context": "ntity.MallGoodsDetailObject;\r\n\r\n/**\r\n * Created by Tom on 2016/12/5.\r\n */\r\n\r\npublic class SearchForwarde",
"end": 788,
"score": 0.9465661644935608,
"start": 785,
"tag": "NAME",
"value": "Tom"
}
] | null | [] | package cn.yiya.shiji.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import cn.yiya.shiji.R;
import cn.yiya.shiji.adapter.ForwardedGoodsAdapter;
import cn.yiya.shiji.business.ApiRequest;
import cn.yiya.shiji.business.HttpMessage;
import cn.yiya.shiji.business.MsgCallBack;
import cn.yiya.shiji.business.RetrofitRequest;
import cn.yiya.shiji.entity.MallGoodsDetailObject;
/**
* Created by Tom on 2016/12/5.
*/
public class SearchForwardedGoodsActivity extends BaseAppCompatActivity implements View.OnClickListener {
private TextView tvCancle;
private EditText etSearch;
private RecyclerView rycvForwarded;
private ForwardedGoodsAdapter mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_forwarded_goods);
initViews();
initEvents();
init();
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tv_cancel:
onBackPressed();
break;
case R.id.tv_reload:
searchGoods(etSearch.getText().toString());
break;
}
}
@Override
protected void initViews() {
tvCancle = (TextView) findViewById(R.id.tv_cancel);
etSearch = (EditText) findViewById(R.id.tv_search);
rycvForwarded = (RecyclerView) findViewById(R.id.rycv_forwarded);
rycvForwarded.setItemAnimator(new DefaultItemAnimator());
rycvForwarded.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new ForwardedGoodsAdapter(this);
rycvForwarded.setAdapter(mAdapter);
addDefaultNullView();
initDefaultNullView(R.mipmap.zanwusousuojieguo, "暂无结果", this);
}
@Override
protected void initEvents() {
tvCancle.setOnClickListener(this);
etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT){
searchGoods(etSearch.getText().toString());
return true;
}
return false;
}
});
}
// 查询搜索结果
private void searchGoods(String s) {
if(TextUtils.isEmpty(s)){
showTips("请输入搜索内容");
return;
}
// // TODO: 2016/12/5
getGoodsList();
}
private void getGoodsList() {
new RetrofitRequest<MallGoodsDetailObject>(ApiRequest.getApiShiji().getWishGoods()).handRequest(new MsgCallBack() {
@Override
public void onResult(HttpMessage msg) {
if (msg.isSuccess()) {
MallGoodsDetailObject object = (MallGoodsDetailObject) msg.obj;
if (object.getList() != null && object.getList().size() > 0) {
mAdapter.setmList(object.getList());
mAdapter.notifyDataSetChanged();
setSuccessView(rycvForwarded);
}else {
setNullView(rycvForwarded);
}
}else {
setOffNetView(rycvForwarded);
}
}
});
}
@Override
protected void init() {
}
}
| 3,997 | 0.601564 | 0.597022 | 120 | 31.025 | 25.121193 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.516667 | false | false | 3 |
ea6a5e4c191b481dd27ec37f1113e540db95210b | 10,342,281,306,343 | ab9f2f08a2a74193568838d8d856b4d824ff90f6 | /src/main/java/com/alexpark/rest/OrderController.java | a1c690b79eafb9efb6547cd3af68dec6d21c8418 | [] | no_license | SumithraMounika/shopping-cart | https://github.com/SumithraMounika/shopping-cart | 3f208369898364b4bfb061c8193735f483314003 | cddbcc52f7ce89df1b33286114bcfa36744c822d | refs/heads/master | 2020-07-22T16:13:33.637000 | 2018-04-14T04:59:20 | 2018-04-14T04:59:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.alexpark.rest;
import com.alexpark.order.model.Order;
import com.alexpark.order.service.IOrderService;
import com.alexpark.product.model.Product;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.Optional;
/**
* @author Alex Park
*/
@RestController
@RequestMapping(value = "/api/orders")
@CrossOrigin(origins = "*")
@Api(value = "The Shopping Shop")
public class OrderController {
@Autowired
private IOrderService orderService;
@GetMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
@ApiOperation(value = "Get All Orders", response = Order.class)
public List<Order> getOrderList() {
return orderService.listAll();
}
@GetMapping(value="/{orderId}", produces = {MediaType.APPLICATION_JSON_VALUE})
@ApiOperation(value = "Get A Order By {orderId}", response = Order.class)
public Order getOrder(@PathVariable String orderId) {
return orderService.getById(orderId);
}
@PostMapping()
@ApiOperation(value = "Insert New Order")
public ResponseEntity<String> saveProduct(@RequestBody @Valid Order order) {
orderService.save(order);
return new ResponseEntity<>(HttpStatus.CREATED);
}
}
| UTF-8 | Java | 1,537 | java | OrderController.java | Java | [
{
"context": "l.List;\nimport java.util.Optional;\n\n/**\n * @author Alex Park\n */\n@RestController\n@RequestMapping(value = \"/api",
"end": 593,
"score": 0.9998208284378052,
"start": 584,
"tag": "NAME",
"value": "Alex Park"
}
] | null | [] | package com.alexpark.rest;
import com.alexpark.order.model.Order;
import com.alexpark.order.service.IOrderService;
import com.alexpark.product.model.Product;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.Optional;
/**
* @author <NAME>
*/
@RestController
@RequestMapping(value = "/api/orders")
@CrossOrigin(origins = "*")
@Api(value = "The Shopping Shop")
public class OrderController {
@Autowired
private IOrderService orderService;
@GetMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
@ApiOperation(value = "Get All Orders", response = Order.class)
public List<Order> getOrderList() {
return orderService.listAll();
}
@GetMapping(value="/{orderId}", produces = {MediaType.APPLICATION_JSON_VALUE})
@ApiOperation(value = "Get A Order By {orderId}", response = Order.class)
public Order getOrder(@PathVariable String orderId) {
return orderService.getById(orderId);
}
@PostMapping()
@ApiOperation(value = "Insert New Order")
public ResponseEntity<String> saveProduct(@RequestBody @Valid Order order) {
orderService.save(order);
return new ResponseEntity<>(HttpStatus.CREATED);
}
}
| 1,534 | 0.743006 | 0.743006 | 48 | 31.020834 | 23.241028 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458333 | false | false | 3 |
331ccc88ccefe22509634765d9fc6892f8f6cfb7 | 13,675,175,941,999 | bc4a18346128a28fd37b1044e97508dc9e3d5871 | /app/com/linkedin/drelephant/analysis/HadoopSystemContext.java | 0d1a37f1c61dbe2c7c4832dd77cdae724135b667 | [
"Apache-2.0",
"MIT",
"BSD-3-Clause",
"GPL-2.0-only"
] | permissive | shahrukhkhan489/dr-elephant | https://github.com/shahrukhkhan489/dr-elephant | 2dce27432dc5d2432dda8e10db019a20c53bc46d | 88256b629d82dc145e09c00ad16c4a9c11b95725 | refs/heads/master | 2021-05-15T11:38:17.505000 | 2019-01-02T10:33:09 | 2019-01-02T10:33:09 | 108,264,908 | 2 | 0 | Apache-2.0 | true | 2018-11-07T08:42:54 | 2017-10-25T12:10:28 | 2017-11-28T01:34:26 | 2018-11-07T08:42:53 | 10,718 | 1 | 0 | 0 | Java | false | null | /*
* Copyright 2016 LinkedIn Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.linkedin.drelephant.analysis;
import org.apache.hadoop.conf.Configuration;
/**
* Hadoop System Information
*/
public final class HadoopSystemContext {
private static final String MAPREDUCE_FRAMEWORK_NAME_PROP = "mapreduce.framework.name";
private static final String YARN = "yarn";
/**
* Detect if the current Hadoop environment is 2.x
*
* @return true if it is Hadoop 2 env, else false
*/
public static boolean isHadoop2Env() {
Configuration hadoopConf = new Configuration();
String hadoopVersion = hadoopConf.get(MAPREDUCE_FRAMEWORK_NAME_PROP);
return hadoopVersion != null && hadoopVersion.equals(YARN);
}
/**
* Check if a Hadoop version matches the current Hadoop environment
*
* @param majorVersion the major version number of hadoop
* @return true if we have a major version match else false
*/
public static boolean matchCurrentHadoopVersion(int majorVersion) {
return majorVersion == 2 && isHadoop2Env();
}
}
| UTF-8 | Java | 1,591 | java | HadoopSystemContext.java | Java | [] | null | [] | /*
* Copyright 2016 LinkedIn Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.linkedin.drelephant.analysis;
import org.apache.hadoop.conf.Configuration;
/**
* Hadoop System Information
*/
public final class HadoopSystemContext {
private static final String MAPREDUCE_FRAMEWORK_NAME_PROP = "mapreduce.framework.name";
private static final String YARN = "yarn";
/**
* Detect if the current Hadoop environment is 2.x
*
* @return true if it is Hadoop 2 env, else false
*/
public static boolean isHadoop2Env() {
Configuration hadoopConf = new Configuration();
String hadoopVersion = hadoopConf.get(MAPREDUCE_FRAMEWORK_NAME_PROP);
return hadoopVersion != null && hadoopVersion.equals(YARN);
}
/**
* Check if a Hadoop version matches the current Hadoop environment
*
* @param majorVersion the major version number of hadoop
* @return true if we have a major version match else false
*/
public static boolean matchCurrentHadoopVersion(int majorVersion) {
return majorVersion == 2 && isHadoop2Env();
}
}
| 1,591 | 0.72973 | 0.721559 | 50 | 30.82 | 30.014456 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.28 | false | false | 3 |
7d80f4bda506b03050ea356c52a383ba0823adad | 34,694,745,818,174 | 3a6370ae55e1e8c5ff6fb939161c00f8463e466c | /core2/src/main/java/com/consultoraestrategia/ss_crmeducativo/dao/tareasDao/TareasRecursoDaoImpl.java | 1bd1b6b72fb711419c08ea9c56cbe2d709cd5c94 | [] | no_license | consultorasystemstrategy/SS_crmeducativo_v2_1 | https://github.com/consultorasystemstrategy/SS_crmeducativo_v2_1 | d25bb86e6f10b131194dcab9d2790bc96376158c | 58905cb56d70a257aedbddeb41c9d82e6775da01 | refs/heads/master | 2019-06-17T04:25:44.468000 | 2019-04-25T02:05:31 | 2019-04-25T02:05:31 | 99,705,205 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.consultoraestrategia.ss_crmeducativo.dao.tareasDao;
import com.consultoraestrategia.ss_crmeducativo.dao.baseDao.BaseDaoImpl;
import com.consultoraestrategia.ss_crmeducativo.entities.TareasRecursosC;
import com.consultoraestrategia.ss_crmeducativo.entities.TareasRecursosC_Table;
/**
* Created by @stevecampos on 18/04/2018.
*/
public class TareasRecursoDaoImpl extends BaseDaoImpl<TareasRecursosC, TareasRecursosC_Table> implements TareasRecursoDao {
private static TareasRecursoDao mInstance;
private TareasRecursoDaoImpl() {
}
public static TareasRecursoDao getInstance() {
if (mInstance == null) {
mInstance = new TareasRecursoDaoImpl();
}
return mInstance;
}
@Override
protected Class<TareasRecursosC> getEntityClass() {
return TareasRecursosC.class;
}
@Override
protected Class<TareasRecursosC_Table> getTableclass() {
return TareasRecursosC_Table.class;
}
}
| UTF-8 | Java | 985 | java | TareasRecursoDaoImpl.java | Java | [
{
"context": "entities.TareasRecursosC_Table;\n\n/**\n * Created by @stevecampos on 18/04/2018.\n */\n\npublic class TareasRecursoDao",
"end": 323,
"score": 0.999657154083252,
"start": 311,
"tag": "USERNAME",
"value": "@stevecampos"
}
] | null | [] | package com.consultoraestrategia.ss_crmeducativo.dao.tareasDao;
import com.consultoraestrategia.ss_crmeducativo.dao.baseDao.BaseDaoImpl;
import com.consultoraestrategia.ss_crmeducativo.entities.TareasRecursosC;
import com.consultoraestrategia.ss_crmeducativo.entities.TareasRecursosC_Table;
/**
* Created by @stevecampos on 18/04/2018.
*/
public class TareasRecursoDaoImpl extends BaseDaoImpl<TareasRecursosC, TareasRecursosC_Table> implements TareasRecursoDao {
private static TareasRecursoDao mInstance;
private TareasRecursoDaoImpl() {
}
public static TareasRecursoDao getInstance() {
if (mInstance == null) {
mInstance = new TareasRecursoDaoImpl();
}
return mInstance;
}
@Override
protected Class<TareasRecursosC> getEntityClass() {
return TareasRecursosC.class;
}
@Override
protected Class<TareasRecursosC_Table> getTableclass() {
return TareasRecursosC_Table.class;
}
}
| 985 | 0.737056 | 0.728934 | 37 | 25.621622 | 30.218441 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.27027 | false | false | 3 |
2abb8e5a83037ad51ce92fa5e3abd5ac4ef7135f | 33,956,011,445,970 | 1c9e746af17358b77e7a97664498eff9c404fa34 | /src/main/java/com/gestionProduit/repository/Etudiant_Matiere_ClasseRepository.java | a51077f6de939bb63e1392be39fbd46043d49ce9 | [] | no_license | ZaghdoudiBaha/Absence-Management | https://github.com/ZaghdoudiBaha/Absence-Management | 8ccf0be334712c770749df11289f6aa1c472e7c0 | be16d8f7ac2968e1e91352e1cd29943ae4d57151 | refs/heads/master | 2020-12-12T16:16:20.494000 | 2020-01-15T21:14:22 | 2020-01-15T21:14:22 | 234,171,874 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gestionProduit.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.gestionProduit.Model.Etudiant;
import com.gestionProduit.Model.Etudiant_Matiere_Classe;
public interface Etudiant_Matiere_ClasseRepository extends JpaRepository<Etudiant_Matiere_Classe, Long> {
@Query("select sum(e.nbr_seance * 1.5) from emc e where etudiant.matricule = :x and matiere.id = :y")
public Float calculerAbsenceParMatiere(@Param("x")Long matricule , @Param("y") Long id);
@Query("select sum(e.nbr_seance * 1.5) from emc e where matiere.id = :x")
public Float calculerAbsenceGroupeParMatiere(@Param("x") Long id);
@Query("select distinct etudiant from emc" )
public List<Etudiant> tousLesEtudiantAbsent();
}
| UTF-8 | Java | 881 | java | Etudiant_Matiere_ClasseRepository.java | Java | [] | null | [] | package com.gestionProduit.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.gestionProduit.Model.Etudiant;
import com.gestionProduit.Model.Etudiant_Matiere_Classe;
public interface Etudiant_Matiere_ClasseRepository extends JpaRepository<Etudiant_Matiere_Classe, Long> {
@Query("select sum(e.nbr_seance * 1.5) from emc e where etudiant.matricule = :x and matiere.id = :y")
public Float calculerAbsenceParMatiere(@Param("x")Long matricule , @Param("y") Long id);
@Query("select sum(e.nbr_seance * 1.5) from emc e where matiere.id = :x")
public Float calculerAbsenceGroupeParMatiere(@Param("x") Long id);
@Query("select distinct etudiant from emc" )
public List<Etudiant> tousLesEtudiantAbsent();
}
| 881 | 0.782066 | 0.777526 | 23 | 37.304348 | 34.794346 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.869565 | false | false | 3 |
d93a3b74b5e497b07d76dec2a799380b7604aa80 | 34,024,730,924,377 | 7ab910fe04f8b20f7f290c96addb3ebf5b75e012 | /b2b2c/src/main/java/com/rbt/service/IMemberreportService.java | 88447731eb4bc4a408e025d03b993752d9774ffa | [] | no_license | stranger2008/rbtb2b | https://github.com/stranger2008/rbtb2b | 6cbf1bf8977dc6655b8ace5b67fb8abd872a86b3 | 6b4e0c3b378fd3c7013e121d822bd1c535492241 | refs/heads/master | 2021-01-10T03:26:55.270000 | 2016-01-06T09:04:37 | 2016-01-06T09:04:37 | 49,122,713 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* ISConsole Copyright 2011 ruibaotong COMPANY, Co.ltd .
* All rights reserved.
* Package:com.rbt.servie
* FileName: IMemberreportService.java
*/
package com.rbt.service;
import java.util.List;
import java.util.Map;
import com.rbt.model.Memberreport;
/**
* @function 功能 会员举报信息表Service层业务接口实现类
* @author 创建人 蔡毅存
* @date 创建日期 Wed Nov 30 14:19:40 CST 2011
*/
public interface IMemberreportService extends IGenericService<Memberreport,String>{
}
| UTF-8 | Java | 518 | java | IMemberreportService.java | Java | [
{
"context": "unction 功能 会员举报信息表Service层业务接口实现类\n * @author 创建人 蔡毅存\n * @date 创建日期 Wed Nov 30 14:19:40 CST 2011\n */\n\n",
"end": 325,
"score": 0.9998106956481934,
"start": 322,
"tag": "NAME",
"value": "蔡毅存"
}
] | null | [] | /*
* ISConsole Copyright 2011 ruibaotong COMPANY, Co.ltd .
* All rights reserved.
* Package:com.rbt.servie
* FileName: IMemberreportService.java
*/
package com.rbt.service;
import java.util.List;
import java.util.Map;
import com.rbt.model.Memberreport;
/**
* @function 功能 会员举报信息表Service层业务接口实现类
* @author 创建人 蔡毅存
* @date 创建日期 Wed Nov 30 14:19:40 CST 2011
*/
public interface IMemberreportService extends IGenericService<Memberreport,String>{
}
| 518 | 0.741379 | 0.706897 | 22 | 20.045454 | 21.655312 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.318182 | false | false | 3 |
336e42128ca7830636cd3cf312c068f502faacd8 | 19,928,648,264,412 | 230f9dfb4b228caec0e2efe1d9c2c0af9f58aa98 | /app/src/main/java/com/duokaile/yifa/yuan/yifa/view/WheelViewBottomDialog.java | 604986af13a74e45ab8b61d6e27fcfde22cf07f4 | [
"Apache-2.0"
] | permissive | yuanpeigen/YIFa | https://github.com/yuanpeigen/YIFa | 5edc3644a52a0fdf3599e0aa1fabe77c9a0e6d95 | 20d6ecbea16c3dfbaa57f8b985993cd033a864ff | refs/heads/master | 2019-01-17T03:45:07.967000 | 2016-11-10T09:47:35 | 2016-11-10T09:47:35 | 73,364,658 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.duokaile.yifa.yuan.yifa.view;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.duokaile.yifa.yuan.yifa.R;
import com.wx.wheelview.adapter.ArrayWheelAdapter;
import com.wx.wheelview.widget.WheelView;
import java.util.List;
public class WheelViewBottomDialog extends Dialog {
private Context mContext;
private Handler mHandler;
private RelativeLayout rlDialogBg;
private TextView tvCancel;
private TextView tvDone;
private TextView tvTitle;
private View viewBg;
private int whatMsg;
private WheelView wheelView;
private void init() {
Window window = this.getWindow();
window.requestFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.bottom_dialog_view);
tvCancel = ((TextView) findViewById(R.id.tvCancel));
tvDone = ((TextView) findViewById(R.id.tvDone));
tvTitle = ((TextView) findViewById(R.id.tvTitle));
viewBg = findViewById(R.id.viewBg);
rlDialogBg = ((RelativeLayout) findViewById(R.id.rlDialogBg));
wheelView = ((WheelView) findViewById(R.id.wheelView));
tvCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View paramAnonymousView) {
dismiss();
}
});
viewBg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View paramAnonymousView) {
dismiss();
}
});
wheelView.setSkin(WheelView.Skin.Holo);
wheelView.setWheelAdapter(new ArrayWheelAdapter(mContext));
// window.getDecorView().setPadding(0, 0, 0, 0);
// WindowManager.LayoutParams lp = window.getAttributes();
// lp.width = WindowManager.LayoutParams.MATCH_PARENT;
// lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
// lp.gravity = Gravity.BOTTOM;
// window.setAttributes(lp);
}
public WheelViewBottomDialog(Context paramContext) {
super(paramContext);
this.mContext = paramContext;
init();
setTitle("选取账套号");
show();
}
public WheelViewBottomDialog(Context paramContext, int paramInt) {
super(paramContext, paramInt);
this.mContext = paramContext;
show();
}
// @Override
// public void dismiss() {
// Animation localAnimation = AnimationUtils.loadAnimation(this.mContext, R.anim.fade_in);
// localAnimation.setAnimationListener(new Animation.AnimationListener() {
// @Override
// public void onAnimationStart(Animation animation) {
//
// }
//
// @Override
// public void onAnimationEnd(Animation paramAnonymousAnimation) {
// WheelViewBottomDialog.this.viewBg.setVisibility(View.INVISIBLE);
// WheelViewBottomDialog.this.rlDialogBg.setVisibility(View.INVISIBLE);
// if ((WheelViewBottomDialog.this.mHandler != null) && (WheelViewBottomDialog.this.whatMsg != 0)) {
// Message msg = new Message();
// msg.what = WheelViewBottomDialog.this.whatMsg;
// WheelViewBottomDialog.this.mHandler.sendMessage(msg);
// }
// WheelViewBottomDialog.this.dismiss();
// }
//
// @Override
// public void onAnimationRepeat(Animation animation) {
//
// }
// });
// viewBg.startAnimation(localAnimation);
// rlDialogBg.startAnimation(AnimationUtils.loadAnimation(this.mContext, R.anim.slide_out_bottom));
// }
public void dismissDialog(int paramInt, Handler paramHandler) {
this.mHandler = paramHandler;
this.whatMsg = paramInt;
dismiss();
}
@Override
protected void onStart() {
super.onStart();
this.viewBg.startAnimation(AnimationUtils.loadAnimation(this.mContext, R.anim.fade_out));
this.rlDialogBg.startAnimation(AnimationUtils.loadAnimation(this.mContext, R.anim.slide_in_up));
}
public void setIndex(int paramInt) {
this.wheelView.setSelection(paramInt);
}
public void setOkBtnClickListener(final View.OnClickListener paramOnClickListener) {
if (this.tvDone != null) {
this.tvDone.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView) {
if (paramOnClickListener != null) {
paramOnClickListener.onClick(paramAnonymousView);
}
WheelViewBottomDialog.this.dismiss();
}
});
}
}
public void setOnWheelItemSelectedListener(WheelView.OnWheelItemSelectedListener paramOnWheelItemSelectedListener) {
this.wheelView.setOnWheelItemSelectedListener(paramOnWheelItemSelectedListener);
}
public void setTitle(int paramInt) {
if (this.tvTitle != null) {
this.tvTitle.setText(paramInt);
}
}
public void setTitle(String paramString) {
if (this.tvTitle != null) {
this.tvTitle.setText(paramString);
}
}
public void setWheelData(List<String> paramList) {
this.wheelView.setWheelData(paramList);
}
}
| UTF-8 | Java | 5,509 | java | WheelViewBottomDialog.java | Java | [] | null | [] | package com.duokaile.yifa.yuan.yifa.view;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.duokaile.yifa.yuan.yifa.R;
import com.wx.wheelview.adapter.ArrayWheelAdapter;
import com.wx.wheelview.widget.WheelView;
import java.util.List;
public class WheelViewBottomDialog extends Dialog {
private Context mContext;
private Handler mHandler;
private RelativeLayout rlDialogBg;
private TextView tvCancel;
private TextView tvDone;
private TextView tvTitle;
private View viewBg;
private int whatMsg;
private WheelView wheelView;
private void init() {
Window window = this.getWindow();
window.requestFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.bottom_dialog_view);
tvCancel = ((TextView) findViewById(R.id.tvCancel));
tvDone = ((TextView) findViewById(R.id.tvDone));
tvTitle = ((TextView) findViewById(R.id.tvTitle));
viewBg = findViewById(R.id.viewBg);
rlDialogBg = ((RelativeLayout) findViewById(R.id.rlDialogBg));
wheelView = ((WheelView) findViewById(R.id.wheelView));
tvCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View paramAnonymousView) {
dismiss();
}
});
viewBg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View paramAnonymousView) {
dismiss();
}
});
wheelView.setSkin(WheelView.Skin.Holo);
wheelView.setWheelAdapter(new ArrayWheelAdapter(mContext));
// window.getDecorView().setPadding(0, 0, 0, 0);
// WindowManager.LayoutParams lp = window.getAttributes();
// lp.width = WindowManager.LayoutParams.MATCH_PARENT;
// lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
// lp.gravity = Gravity.BOTTOM;
// window.setAttributes(lp);
}
public WheelViewBottomDialog(Context paramContext) {
super(paramContext);
this.mContext = paramContext;
init();
setTitle("选取账套号");
show();
}
public WheelViewBottomDialog(Context paramContext, int paramInt) {
super(paramContext, paramInt);
this.mContext = paramContext;
show();
}
// @Override
// public void dismiss() {
// Animation localAnimation = AnimationUtils.loadAnimation(this.mContext, R.anim.fade_in);
// localAnimation.setAnimationListener(new Animation.AnimationListener() {
// @Override
// public void onAnimationStart(Animation animation) {
//
// }
//
// @Override
// public void onAnimationEnd(Animation paramAnonymousAnimation) {
// WheelViewBottomDialog.this.viewBg.setVisibility(View.INVISIBLE);
// WheelViewBottomDialog.this.rlDialogBg.setVisibility(View.INVISIBLE);
// if ((WheelViewBottomDialog.this.mHandler != null) && (WheelViewBottomDialog.this.whatMsg != 0)) {
// Message msg = new Message();
// msg.what = WheelViewBottomDialog.this.whatMsg;
// WheelViewBottomDialog.this.mHandler.sendMessage(msg);
// }
// WheelViewBottomDialog.this.dismiss();
// }
//
// @Override
// public void onAnimationRepeat(Animation animation) {
//
// }
// });
// viewBg.startAnimation(localAnimation);
// rlDialogBg.startAnimation(AnimationUtils.loadAnimation(this.mContext, R.anim.slide_out_bottom));
// }
public void dismissDialog(int paramInt, Handler paramHandler) {
this.mHandler = paramHandler;
this.whatMsg = paramInt;
dismiss();
}
@Override
protected void onStart() {
super.onStart();
this.viewBg.startAnimation(AnimationUtils.loadAnimation(this.mContext, R.anim.fade_out));
this.rlDialogBg.startAnimation(AnimationUtils.loadAnimation(this.mContext, R.anim.slide_in_up));
}
public void setIndex(int paramInt) {
this.wheelView.setSelection(paramInt);
}
public void setOkBtnClickListener(final View.OnClickListener paramOnClickListener) {
if (this.tvDone != null) {
this.tvDone.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView) {
if (paramOnClickListener != null) {
paramOnClickListener.onClick(paramAnonymousView);
}
WheelViewBottomDialog.this.dismiss();
}
});
}
}
public void setOnWheelItemSelectedListener(WheelView.OnWheelItemSelectedListener paramOnWheelItemSelectedListener) {
this.wheelView.setOnWheelItemSelectedListener(paramOnWheelItemSelectedListener);
}
public void setTitle(int paramInt) {
if (this.tvTitle != null) {
this.tvTitle.setText(paramInt);
}
}
public void setTitle(String paramString) {
if (this.tvTitle != null) {
this.tvTitle.setText(paramString);
}
}
public void setWheelData(List<String> paramList) {
this.wheelView.setWheelData(paramList);
}
}
| 5,509 | 0.638116 | 0.637207 | 157 | 34.019108 | 27.813637 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.541401 | false | false | 3 |
8a8fd184bf294fb3d8ad54cf46a5fb4937a4dabf | 25,640,954,804,818 | f6e13275d11c03acc5fea5c4d380b2b1232f6318 | /app/src/main/java/cn/lovexiaoai/androidcodingdemo/base/BaseFragment.java | 437b189d0837fba7e4c51d4d31189b6d93abeec8 | [] | no_license | qianxiaoai/AndroidCodingDemo | https://github.com/qianxiaoai/AndroidCodingDemo | 17a3dba3fd86e965c139876dbc2e409840aba933 | d5cb4a2528fae532f901aeabea464fdd43e9acf0 | refs/heads/master | 2020-03-26T07:32:52.859000 | 2018-08-15T03:38:47 | 2018-08-15T03:38:47 | 144,659,662 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.lovexiaoai.androidcodingdemo.base;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
import cn.lovexiaoai.androidcodingdemo.utils.LogUtil;
/**
* Created by tangh on 14-4-21.
*/
public abstract class BaseFragment extends Fragment {
/**
* 全局activity
*/
protected FragmentActivity mContext;
protected FragmentManager mFragmentManager;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = getActivity();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFragmentManager = getChildFragmentManager();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (getContentView() != 0) {
return inflater.inflate(getContentView(), container, false);
}
return getContentLayout();
}
/**
* 沉浸式颜色
* @param color
*/
public void setStatusBarColorRes(@ColorRes int color){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
setStatusBarColor(getResources().getColor(color));
}
/**
* 沉浸式颜色
* @param color
*/
public void setStatusBarColor(@ColorInt int color){
if (mContext != null &&Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mContext.getWindow().setStatusBarColor(color);
}
}
public abstract int getContentView();
public View getContentLayout() {
return null;
}
@Override
public void onPause() {
super.onPause();
LogUtil.d(((Object) this).getClass().getSimpleName(),"onPause");
}
@Override
public void onResume() {
super.onResume();
LogUtil.d(((Object) this).getClass().getSimpleName(),"onResume");
}
@Override
public void onStart() {
super.onStart();
LogUtil.d(((Object) this).getClass().getSimpleName(),"onStart");
}
@Override
public void onDetach() {
super.onDetach();
LogUtil.d(((Object) this).getClass().getSimpleName(),"onDetach");
}
@Override
public void onStop() {
super.onStop();
LogUtil.d(((Object) this).getClass().getSimpleName(),"onStop");
}
@Override
public void onDestroy() {
super.onDestroy();
LogUtil.d(((Object) this).getClass().getSimpleName(),"onDestroy");
}
@Override
public void onDestroyView() {
super.onDestroyView();
LogUtil.d(((Object) this).getClass().getSimpleName(),"onDestroyView");
}
/**
* 将resid布局替换成fragment
*
* @param resid
* @param fragment
*/
public void replace(int resid, Fragment fragment) {
mFragmentManager.beginTransaction().replace(resid, fragment).commitAllowingStateLoss();
}
/**
* @param resid
* @param fragment
*/
public void add(int resid, Fragment fragment) {
mFragmentManager.beginTransaction().add(resid, fragment).commitAllowingStateLoss();
}
/**
* @param resid
* @param fragment
*/
public void add(int resid, Fragment fragment, String tag) {
mFragmentManager.beginTransaction().add(resid, fragment, tag).commitAllowingStateLoss();
}
/**
* 显示fragment
*
* @param fragment
*/
public void show(Fragment fragment) {
mFragmentManager.beginTransaction().show(fragment).commitAllowingStateLoss();
}
/**
* 隐藏fragment
*
* @param fragment
*/
public void hide(Fragment fragment) {
mFragmentManager.beginTransaction().hide(fragment).commitAllowingStateLoss();
}
/**
* 显示fragment(带动画)
*
* @param fragment
*/
public void showWithAnim(Fragment fragment, int enter, int exit) {
mFragmentManager.beginTransaction().setCustomAnimations(enter, exit).show(fragment).commitAllowingStateLoss();
}
/**
* 隐藏fragment(带动画)
*
* @param fragment
*/
public void hideWithAnim(Fragment fragment, int enter, int exit) {
mFragmentManager.beginTransaction().setCustomAnimations(enter, exit).hide(fragment).commitAllowingStateLoss();
}
/**
* 异步Task访问资源前判断Fragment是否存在,且处于可交互状态
* 避免:java.lang.IllegalStateException: Fragment XXX not attached to Activity
*
* @return
*/
protected boolean isUIStateLost() {
return getActivity() == null || isRemoving() || isDetached();
}
/**
* 返回当前展示的fragment 用于页面承载ViewPager
* @param list
* @param position
* @return
*/
public BaseFragment getCurPagerFragment(List<Fragment> list, int position) {
if (list != null && !list.isEmpty()) {
Fragment fragment = list.get(position);
if (fragment != null && fragment instanceof BaseFragment) {
return (BaseFragment) fragment;
}
}
return null;
}
}
| UTF-8 | Java | 4,940 | java | BaseFragment.java | Java | [
{
"context": "ndroidcodingdemo.utils.LogUtil;\n\n/**\n * Created by tangh on 14-4-21.\n */\npublic abstract class BaseFragmen",
"end": 547,
"score": 0.9991273880004883,
"start": 542,
"tag": "USERNAME",
"value": "tangh"
}
] | null | [] | package cn.lovexiaoai.androidcodingdemo.base;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
import cn.lovexiaoai.androidcodingdemo.utils.LogUtil;
/**
* Created by tangh on 14-4-21.
*/
public abstract class BaseFragment extends Fragment {
/**
* 全局activity
*/
protected FragmentActivity mContext;
protected FragmentManager mFragmentManager;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = getActivity();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFragmentManager = getChildFragmentManager();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (getContentView() != 0) {
return inflater.inflate(getContentView(), container, false);
}
return getContentLayout();
}
/**
* 沉浸式颜色
* @param color
*/
public void setStatusBarColorRes(@ColorRes int color){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
setStatusBarColor(getResources().getColor(color));
}
/**
* 沉浸式颜色
* @param color
*/
public void setStatusBarColor(@ColorInt int color){
if (mContext != null &&Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mContext.getWindow().setStatusBarColor(color);
}
}
public abstract int getContentView();
public View getContentLayout() {
return null;
}
@Override
public void onPause() {
super.onPause();
LogUtil.d(((Object) this).getClass().getSimpleName(),"onPause");
}
@Override
public void onResume() {
super.onResume();
LogUtil.d(((Object) this).getClass().getSimpleName(),"onResume");
}
@Override
public void onStart() {
super.onStart();
LogUtil.d(((Object) this).getClass().getSimpleName(),"onStart");
}
@Override
public void onDetach() {
super.onDetach();
LogUtil.d(((Object) this).getClass().getSimpleName(),"onDetach");
}
@Override
public void onStop() {
super.onStop();
LogUtil.d(((Object) this).getClass().getSimpleName(),"onStop");
}
@Override
public void onDestroy() {
super.onDestroy();
LogUtil.d(((Object) this).getClass().getSimpleName(),"onDestroy");
}
@Override
public void onDestroyView() {
super.onDestroyView();
LogUtil.d(((Object) this).getClass().getSimpleName(),"onDestroyView");
}
/**
* 将resid布局替换成fragment
*
* @param resid
* @param fragment
*/
public void replace(int resid, Fragment fragment) {
mFragmentManager.beginTransaction().replace(resid, fragment).commitAllowingStateLoss();
}
/**
* @param resid
* @param fragment
*/
public void add(int resid, Fragment fragment) {
mFragmentManager.beginTransaction().add(resid, fragment).commitAllowingStateLoss();
}
/**
* @param resid
* @param fragment
*/
public void add(int resid, Fragment fragment, String tag) {
mFragmentManager.beginTransaction().add(resid, fragment, tag).commitAllowingStateLoss();
}
/**
* 显示fragment
*
* @param fragment
*/
public void show(Fragment fragment) {
mFragmentManager.beginTransaction().show(fragment).commitAllowingStateLoss();
}
/**
* 隐藏fragment
*
* @param fragment
*/
public void hide(Fragment fragment) {
mFragmentManager.beginTransaction().hide(fragment).commitAllowingStateLoss();
}
/**
* 显示fragment(带动画)
*
* @param fragment
*/
public void showWithAnim(Fragment fragment, int enter, int exit) {
mFragmentManager.beginTransaction().setCustomAnimations(enter, exit).show(fragment).commitAllowingStateLoss();
}
/**
* 隐藏fragment(带动画)
*
* @param fragment
*/
public void hideWithAnim(Fragment fragment, int enter, int exit) {
mFragmentManager.beginTransaction().setCustomAnimations(enter, exit).hide(fragment).commitAllowingStateLoss();
}
/**
* 异步Task访问资源前判断Fragment是否存在,且处于可交互状态
* 避免:java.lang.IllegalStateException: Fragment XXX not attached to Activity
*
* @return
*/
protected boolean isUIStateLost() {
return getActivity() == null || isRemoving() || isDetached();
}
/**
* 返回当前展示的fragment 用于页面承载ViewPager
* @param list
* @param position
* @return
*/
public BaseFragment getCurPagerFragment(List<Fragment> list, int position) {
if (list != null && !list.isEmpty()) {
Fragment fragment = list.get(position);
if (fragment != null && fragment instanceof BaseFragment) {
return (BaseFragment) fragment;
}
}
return null;
}
}
| 4,940 | 0.707292 | 0.705417 | 207 | 22.188406 | 25.376741 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.31401 | false | false | 3 |
c3d1a2a12ac3bb9bc38ef54424ed5595a5cfa8d3 | 17,282,948,400,743 | bd97431b1bcbfd66314710932783882f397ac37d | /evento-war/src/main/java/controller/MyProfileController.java | 7604432daa45c6eae65b5d8a5cf2e3e0708e217b | [] | no_license | sharifahmed/evento | https://github.com/sharifahmed/evento | 1f3b980f6b7d6f7910edc37bd44af534703b3733 | 373234e8ca42deda66332b49f0269ce72000d4e5 | refs/heads/master | 2016-09-06T00:20:57.596000 | 2013-07-29T09:02:39 | 2013-07-29T09:02:39 | 8,668,390 | 1 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controller;
import entities.User;
import service.UserService;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpSession;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* Author: sahmed
* Date: 3/13/13
* Time: 4:39 PM
*/
@Named
@RequestScoped
public class MyProfileController {
@EJB
private UserService userService;
private User user;
private Integer userId;
private FacesContext facesContext;
private HttpSession session;
@PostConstruct
public void startUp() {
facesContext = FacesContext.getCurrentInstance();
session = (HttpSession) facesContext.getExternalContext().getSession(false);
userId = (Integer) session.getAttribute("userId");
user = userService.getUserById(userId);
}
public String updateProfile() {
userService.updateUserInfo(user);
return "my_profile.xhtml?faces-redirect=true";
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
}
| UTF-8 | Java | 1,347 | java | MyProfileController.java | Java | [
{
"context": "ap;\n\n/**\n * Created with IntelliJ IDEA.\n * Author: sahmed\n * Date: 3/13/13\n * Time: 4:39 PM\n */\n\n@Named\n@Re",
"end": 362,
"score": 0.9989632964134216,
"start": 356,
"tag": "USERNAME",
"value": "sahmed"
}
] | null | [] | package controller;
import entities.User;
import service.UserService;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpSession;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* Author: sahmed
* Date: 3/13/13
* Time: 4:39 PM
*/
@Named
@RequestScoped
public class MyProfileController {
@EJB
private UserService userService;
private User user;
private Integer userId;
private FacesContext facesContext;
private HttpSession session;
@PostConstruct
public void startUp() {
facesContext = FacesContext.getCurrentInstance();
session = (HttpSession) facesContext.getExternalContext().getSession(false);
userId = (Integer) session.getAttribute("userId");
user = userService.getUserById(userId);
}
public String updateProfile() {
userService.updateUserInfo(user);
return "my_profile.xhtml?faces-redirect=true";
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
}
| 1,347 | 0.685969 | 0.68003 | 62 | 20.725807 | 18.561293 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.403226 | false | false | 3 |
406946421dbf351771cb59d2e43576ce4ee98386 | 24,910,810,366,148 | ba5fbe84538bd39ab27755a565c882d467bb33fb | /src/main/java/com/tayani/app/util/StringUtility.java | ed2b89ded43847a4c4c49bbf1e5f76793592047f | [] | no_license | dsabhrawal/tayani-app | https://github.com/dsabhrawal/tayani-app | a3f885930fd7c3d60e6af1c3b913259541b1e37e | 44b8fdfa4bcccf7ac6a97864832c9dd2e349fa61 | refs/heads/master | 2021-01-10T12:21:44.656000 | 2016-04-03T17:37:10 | 2016-04-03T17:37:10 | 55,358,282 | 2 | 0 | null | false | 2016-04-03T17:37:10 | 2016-04-03T17:10:04 | 2016-04-03T17:14:59 | 2016-04-03T17:37:10 | 127 | 1 | 0 | 0 | Java | null | null | package com.tayani.app.util;
public final class StringUtility {
public static String emptyString = "";
}
| UTF-8 | Java | 114 | java | StringUtility.java | Java | [] | null | [] | package com.tayani.app.util;
public final class StringUtility {
public static String emptyString = "";
}
| 114 | 0.710526 | 0.710526 | 9 | 11.666667 | 15.776213 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 3 |
98991972ffeaa79b590a39a156bfb1b3407097fd | 1,503,238,556,347 | db173b5180789c71b6aff3f2b87f60daf29401a1 | /cpj/src/main/java/chapter4/DualOutputPushStage.java | 33113e0b2398290d9e4c3f925c2687031883abe8 | [] | no_license | xiaozhiliaoo/concurrency-practice | https://github.com/xiaozhiliaoo/concurrency-practice | 0f584d4b3e95559e22581d9a42e32c770e3cead8 | a9b8809c7e1488fa2a4c5a981e5d12d3bfae85d0 | refs/heads/master | 2023-04-29T09:12:25.172000 | 2022-11-24T06:09:47 | 2022-11-24T06:09:47 | 248,147,420 | 5 | 4 | null | false | 2022-12-06T00:50:14 | 2020-03-18T05:36:40 | 2022-08-30T02:52:45 | 2022-12-06T00:50:13 | 411,180 | 3 | 3 | 2 | Java | false | false | package chapter4;
/**
* @author lili
* @date 2022/6/19 10:39
*/
public class DualOutputPushStage extends SingleOutputPushStage {
private PushStage next2 = null;
protected synchronized PushStage next2() {
return next2;
}
public synchronized void attach2(PushStage s) {
next2 = s;
}
}
| UTF-8 | Java | 325 | java | DualOutputPushStage.java | Java | [
{
"context": "package chapter4;\n\n/**\n * @author lili\n * @date 2022/6/19 10:39\n */\npublic class DualOut",
"end": 38,
"score": 0.8561974167823792,
"start": 34,
"tag": "USERNAME",
"value": "lili"
}
] | null | [] | package chapter4;
/**
* @author lili
* @date 2022/6/19 10:39
*/
public class DualOutputPushStage extends SingleOutputPushStage {
private PushStage next2 = null;
protected synchronized PushStage next2() {
return next2;
}
public synchronized void attach2(PushStage s) {
next2 = s;
}
}
| 325 | 0.658462 | 0.606154 | 17 | 18.117647 | 19.375189 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.235294 | false | false | 3 |
1dbff39789f8ea8dbb6d7380f466a920ecf7bb3d | 20,736,102,148,199 | e45b54ac2c009b230e866dbb51ad1c7edee3bdbe | /src/main/java/http/response/HttpStatus.java | 35aa56500036a5e913ac7b0b673cbec05030f0de | [] | no_license | yk1028/jwp-was | https://github.com/yk1028/jwp-was | 65174d0457b48de31695cb2496f71aea54e2c804 | 7a07a9088c05c22a55ef2aafce897ac1c7b8e163 | refs/heads/yk1028 | 2022-02-22T16:20:14.856000 | 2019-09-23T13:08:00 | 2019-09-23T13:08:00 | 208,954,164 | 0 | 0 | null | true | 2019-09-21T10:59:46 | 2019-09-17T03:47:44 | 2019-09-21T10:59:45 | 2019-09-21T10:59:43 | 287 | 0 | 0 | 0 | Java | false | false | package http.response;
public enum HttpStatus {
OK(200, "OK"),
CREATED(201, "Created"),
ACCEPTED(202, "Accepted"),
MOVED_PERMANENTLY(301, "Moved Permanently"),
FOUND(302, "Found"),
BAD_REQUEST(400, "Bad Request"),
NOT_FOUND(404, "Not Found"),
METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
INTERNAL_SERVER_ERROR(500, "Internal Sever Error"),
NOT_IMPLEMENTED(501, "Not Implemented");
private Integer code;
private String message;
HttpStatus(Integer code, String message) {
this.code = code;
this.message = message;
}
public String getMessage() {
return code + " " + message;
}
public boolean match(HttpStatus httpStatus) {
return this == httpStatus;
}
}
| UTF-8 | Java | 762 | java | HttpStatus.java | Java | [] | null | [] | package http.response;
public enum HttpStatus {
OK(200, "OK"),
CREATED(201, "Created"),
ACCEPTED(202, "Accepted"),
MOVED_PERMANENTLY(301, "Moved Permanently"),
FOUND(302, "Found"),
BAD_REQUEST(400, "Bad Request"),
NOT_FOUND(404, "Not Found"),
METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
INTERNAL_SERVER_ERROR(500, "Internal Sever Error"),
NOT_IMPLEMENTED(501, "Not Implemented");
private Integer code;
private String message;
HttpStatus(Integer code, String message) {
this.code = code;
this.message = message;
}
public String getMessage() {
return code + " " + message;
}
public boolean match(HttpStatus httpStatus) {
return this == httpStatus;
}
}
| 762 | 0.625984 | 0.586614 | 30 | 24.4 | 17.201939 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.933333 | false | false | 3 |
e7bd4c73d95d3e3db427cb8077fe6464d017c266 | 27,358,941,731,300 | a3a4efab31a98e8c25e1a7c393644ab691fb89f7 | /src/test/java/ca/craigthomas/yacoco3e/listeners/LoadVirtualDiskMenuItemListenerTest.java | c15f884331d74b3dc46041209e9ab7b84b98244e | [
"GPL-2.0-only",
"MIT",
"Classpath-exception-2.0"
] | permissive | craigthomas/CoCo3Java | https://github.com/craigthomas/CoCo3Java | 24a72a915e4dec4e51a9e97a10cef56e66e59026 | 6a884561dc70cf9401d53286040e77631d6862d9 | refs/heads/main | 2023-08-31T08:21:12.782000 | 2023-08-04T18:00:30 | 2023-08-04T18:00:30 | 97,992,316 | 16 | 5 | MIT | false | 2023-09-10T14:26:42 | 2017-07-21T22:56:24 | 2023-08-05T04:50:17 | 2023-09-10T14:26:41 | 592 | 12 | 3 | 4 | Java | false | false | /*
* Copyright (C) 2017-2019 Craig Thomas
* This project uses an MIT style license - see LICENSE for details.
*/
package ca.craigthomas.yacoco3e.listeners;
import ca.craigthomas.yacoco3e.components.Emulator;
import org.junit.Before;
import org.junit.Test;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import static org.mockito.Mockito.*;
public class LoadVirtualDiskMenuItemListenerTest
{
private LoadVirtualDiskMenuItemActionListener listener0spy;
private LoadVirtualDiskMenuItemActionListener listener1spy;
private ActionEvent mockItemEvent;
private JFileChooser fileChooser;
@Before
public void setUp() {
Emulator emulator = mock(Emulator.class);
fileChooser = mock(JFileChooser.class);
when(fileChooser.getSelectedFile()).thenReturn(new File(""));
LoadVirtualDiskMenuItemActionListener listener0 = new LoadVirtualDiskMenuItemActionListener(0, emulator);
LoadVirtualDiskMenuItemActionListener listener1 = new LoadVirtualDiskMenuItemActionListener(1, emulator);
listener0spy = spy(listener0);
listener1spy = spy(listener1);
ButtonModel buttonModel = mock(ButtonModel.class);
when(buttonModel.isSelected()).thenReturn(true);
AbstractButton button = mock(AbstractButton.class);
when(button.getModel()).thenReturn(buttonModel);
mockItemEvent = mock(ActionEvent.class);
when(mockItemEvent.getSource()).thenReturn(button);
when(listener0spy.createFileChooser()).thenReturn(fileChooser);
when(listener1spy.createFileChooser()).thenReturn(fileChooser);
}
@Test
public void testLoadVirtualDiskDialogShowsWhenClicked() {
listener0spy.actionPerformed(mockItemEvent);
listener0spy.actionPerformed(mockItemEvent);
listener1spy.actionPerformed(mockItemEvent);
verify(listener0spy, times(2)).createFileChooser();
verify(listener1spy, times(1)).createFileChooser();
verify(fileChooser, times(3)).showOpenDialog(any());
}
}
| UTF-8 | Java | 2,061 | java | LoadVirtualDiskMenuItemListenerTest.java | Java | [
{
"context": "/*\n * Copyright (C) 2017-2019 Craig Thomas\n * This project uses an MIT style license - see L",
"end": 42,
"score": 0.999613344669342,
"start": 30,
"tag": "NAME",
"value": "Craig Thomas"
}
] | null | [] | /*
* Copyright (C) 2017-2019 <NAME>
* This project uses an MIT style license - see LICENSE for details.
*/
package ca.craigthomas.yacoco3e.listeners;
import ca.craigthomas.yacoco3e.components.Emulator;
import org.junit.Before;
import org.junit.Test;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import static org.mockito.Mockito.*;
public class LoadVirtualDiskMenuItemListenerTest
{
private LoadVirtualDiskMenuItemActionListener listener0spy;
private LoadVirtualDiskMenuItemActionListener listener1spy;
private ActionEvent mockItemEvent;
private JFileChooser fileChooser;
@Before
public void setUp() {
Emulator emulator = mock(Emulator.class);
fileChooser = mock(JFileChooser.class);
when(fileChooser.getSelectedFile()).thenReturn(new File(""));
LoadVirtualDiskMenuItemActionListener listener0 = new LoadVirtualDiskMenuItemActionListener(0, emulator);
LoadVirtualDiskMenuItemActionListener listener1 = new LoadVirtualDiskMenuItemActionListener(1, emulator);
listener0spy = spy(listener0);
listener1spy = spy(listener1);
ButtonModel buttonModel = mock(ButtonModel.class);
when(buttonModel.isSelected()).thenReturn(true);
AbstractButton button = mock(AbstractButton.class);
when(button.getModel()).thenReturn(buttonModel);
mockItemEvent = mock(ActionEvent.class);
when(mockItemEvent.getSource()).thenReturn(button);
when(listener0spy.createFileChooser()).thenReturn(fileChooser);
when(listener1spy.createFileChooser()).thenReturn(fileChooser);
}
@Test
public void testLoadVirtualDiskDialogShowsWhenClicked() {
listener0spy.actionPerformed(mockItemEvent);
listener0spy.actionPerformed(mockItemEvent);
listener1spy.actionPerformed(mockItemEvent);
verify(listener0spy, times(2)).createFileChooser();
verify(listener1spy, times(1)).createFileChooser();
verify(fileChooser, times(3)).showOpenDialog(any());
}
}
| 2,055 | 0.739447 | 0.724891 | 53 | 37.886791 | 28.120132 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.716981 | false | false | 3 |
fef798cd99024e2b3e8ac9e4193b5e648006853a | 14,413,910,289,603 | 522cc78a62c65e53a7d97f113a2272dc5968036e | /src/ParseException.java | 2aeccaa6c76aa58757bc408e3882fef00529d01f | [] | no_license | tnagorra/BOBS-Sim | https://github.com/tnagorra/BOBS-Sim | 7d82577b20db17ce2f8df82cf3449fcbf3ab8ad4 | d6083789c2252d14dddfc85b3291d9ece52bfac6 | refs/heads/master | 2021-01-10T19:49:58.838000 | 2015-03-23T16:04:28 | 2015-03-23T16:04:28 | 31,963,443 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class ParseException extends Exception {
// Some shit about serialization
private static final long serialVersionUID =83232;
public ParseException(){
super();
}
public ParseException(String message){
super(message);
}
}
| UTF-8 | Java | 270 | java | ParseException.java | Java | [] | null | [] | public class ParseException extends Exception {
// Some shit about serialization
private static final long serialVersionUID =83232;
public ParseException(){
super();
}
public ParseException(String message){
super(message);
}
}
| 270 | 0.666667 | 0.648148 | 13 | 19.76923 | 19.063271 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 3 |
f318d96f1077b32639f792b7a043a61792e75378 | 30,640,296,737,827 | eaf857e2934488842ea0ee1b0f3e230ea5224e29 | /src/important/backtrack/MinCostUsingTrain.java | 4ac97b598d2e98971e654f035766b5df1eae4842 | [] | no_license | arnabs542/leetcode-48 | https://github.com/arnabs542/leetcode-48 | d73d92765eccdfa9544efab3d3445bf1c0d485e9 | b882881fab2a542911a5fc769c052a95af530fbb | refs/heads/master | 2023-03-18T19:35:34.904000 | 2018-05-25T17:53:32 | 2018-05-25T17:53:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package important.backtrack;
/**
* / This function returns the smallest possible cost to
// reach station N-1 from station 0.
int minCost(int cost[][N])
{
// dist[i] stores minimum cost to reach station i
// from station 0.
int dist[N];
for (int i=0; i<N; i++)
dist[i] = INF;
dist[0] = 0;
// Go through every station and check if using it
// as an intermediate station gives better path
for (int i=0; i<N; i++)
for (int j=i+1; j<N; j++)
if (dist[j] > dist[i] + cost[i][j])
dist[j] = dist[i] + cost[i][j];
return dist[N-1];
}
// Driver program to test above function
int main()
{
int cost[N][N] = { {0, 15, 80, 90},
{INF, 0, 40, 50},
{INF, INF, 0, 70},
{INF, INF, INF, 0}
};
cout << "The Minimum cost to reach station "
<< N << " is " << minCost(cost);
return 0;
}
* @author het
*
*/
public class MinCostUsingTrain {
private int cost[][] = { {0, 15, 80, 90},{-1, 0, 40, 50},{-1, -1, 0, 70},{-1, -1, -1, 0}};
public int minCost(){
int stationLength = cost.length;
int [] dist = new int[stationLength];
for(int i = 0;i<stationLength;i+=1){
dist[i] = Integer.MAX_VALUE;
}
dist[0] = 0;
for(int i = 1;i<stationLength;i+=1){
for(int j = 0; j<i;j+=1){
dist[i] = Math.min(dist[i], dist[j]+cost[j][i]);
}
}
return dist[stationLength-1];
}
public static void main(String[] args) {
System.out.println(new MinCostUsingTrain().minCost());
System.out.println(new MinCostUsingTrain().maxCost());
System.out.println(new MinCostUsingTrain().count(3, 6));
}
public static int count(int n, int sum){
if(sum < 0 || n <=0) return 0;
int [] cache = new int [sum+1];
for(int i=0;i<=sum&& i<=9;i+=1){
cache[i] = 1;
}
if(n == 1){
if(sum >=0 && sum<=9) {
return 1;
}else{
return 0;
}
}
int [] current = new int[sum+1];
for( int i=1;i<n;i+=1){
for(int j=0;j<=sum;j+=1){
current[j] = 0;
int digit = (i== n-1)? 1: 0;
for(;digit <10;digit+=1){
current[j]+= j-digit <0 ? 0: cache[j-digit];
}
}
for(int index=0;index<=sum;index++){
cache[index] =current[index];
}
}
return cache[sum];
}
public int maxCost(){
int stationLength = cost.length;
int [] dist = new int[stationLength];
for(int i = 0;i<stationLength;i+=1){
dist[i] = Integer.MIN_VALUE;
}
dist[0] = 0;
for(int i = 1;i<stationLength;i+=1){
for(int j = 0; j<i;j+=1){
dist[i] = Math.max(dist[i], dist[j]+cost[j][i]);
}
}
return dist[stationLength-1];
}
}
| UTF-8 | Java | 3,318 | java | MinCostUsingTrain.java | Java | [
{
"context": "is \" << minCost(cost);\n return 0;\n}\n\n * @author het\n *\n */\npublic class MinCostUsingTrain {\n\tprivate ",
"end": 967,
"score": 0.9922305941581726,
"start": 964,
"tag": "USERNAME",
"value": "het"
}
] | null | [] | package important.backtrack;
/**
* / This function returns the smallest possible cost to
// reach station N-1 from station 0.
int minCost(int cost[][N])
{
// dist[i] stores minimum cost to reach station i
// from station 0.
int dist[N];
for (int i=0; i<N; i++)
dist[i] = INF;
dist[0] = 0;
// Go through every station and check if using it
// as an intermediate station gives better path
for (int i=0; i<N; i++)
for (int j=i+1; j<N; j++)
if (dist[j] > dist[i] + cost[i][j])
dist[j] = dist[i] + cost[i][j];
return dist[N-1];
}
// Driver program to test above function
int main()
{
int cost[N][N] = { {0, 15, 80, 90},
{INF, 0, 40, 50},
{INF, INF, 0, 70},
{INF, INF, INF, 0}
};
cout << "The Minimum cost to reach station "
<< N << " is " << minCost(cost);
return 0;
}
* @author het
*
*/
public class MinCostUsingTrain {
private int cost[][] = { {0, 15, 80, 90},{-1, 0, 40, 50},{-1, -1, 0, 70},{-1, -1, -1, 0}};
public int minCost(){
int stationLength = cost.length;
int [] dist = new int[stationLength];
for(int i = 0;i<stationLength;i+=1){
dist[i] = Integer.MAX_VALUE;
}
dist[0] = 0;
for(int i = 1;i<stationLength;i+=1){
for(int j = 0; j<i;j+=1){
dist[i] = Math.min(dist[i], dist[j]+cost[j][i]);
}
}
return dist[stationLength-1];
}
public static void main(String[] args) {
System.out.println(new MinCostUsingTrain().minCost());
System.out.println(new MinCostUsingTrain().maxCost());
System.out.println(new MinCostUsingTrain().count(3, 6));
}
public static int count(int n, int sum){
if(sum < 0 || n <=0) return 0;
int [] cache = new int [sum+1];
for(int i=0;i<=sum&& i<=9;i+=1){
cache[i] = 1;
}
if(n == 1){
if(sum >=0 && sum<=9) {
return 1;
}else{
return 0;
}
}
int [] current = new int[sum+1];
for( int i=1;i<n;i+=1){
for(int j=0;j<=sum;j+=1){
current[j] = 0;
int digit = (i== n-1)? 1: 0;
for(;digit <10;digit+=1){
current[j]+= j-digit <0 ? 0: cache[j-digit];
}
}
for(int index=0;index<=sum;index++){
cache[index] =current[index];
}
}
return cache[sum];
}
public int maxCost(){
int stationLength = cost.length;
int [] dist = new int[stationLength];
for(int i = 0;i<stationLength;i+=1){
dist[i] = Integer.MIN_VALUE;
}
dist[0] = 0;
for(int i = 1;i<stationLength;i+=1){
for(int j = 0; j<i;j+=1){
dist[i] = Math.max(dist[i], dist[j]+cost[j][i]);
}
}
return dist[stationLength-1];
}
}
| 3,318 | 0.449585 | 0.418953 | 114 | 26.491228 | 19.505396 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.438596 | false | false | 3 |
b5f5a6286aa0475065832618533dc2444031318b | 16,501,264,355,182 | 7b95f6ff0dfe666a1adb11e81f272916569bff73 | /第八章/src/set/TreeSetDemo.java | 9eb290b08c0f951afbf130ebc3b879da53473a38 | [] | no_license | jzhnice/chor7 | https://github.com/jzhnice/chor7 | d7b2e59d69acdee0dfda11ec849f9eedf2c50258 | 3a80e08ca883f3744f65817b7c8ccb562f515cbf | refs/heads/master | 2023-05-04T16:57:29.839000 | 2021-05-15T12:04:37 | 2021-05-15T12:04:37 | 364,912,996 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package set;
import java.util.TreeSet;
/**
* @version 1.0
* @author: jiazhihao
* @date: 2021-05-08 09:26
*/
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<String> set =new TreeSet<>();
set.add("111");
set.add("222");
set.add("地理");
set.add("历史");
set.add("asdd");
set.add("ASDD");
System.out.println(set);
}
}
| UTF-8 | Java | 450 | java | TreeSetDemo.java | Java | [
{
"context": "util.TreeSet;\r\n\r\n/**\r\n * @version 1.0\r\n * @author: jiazhihao\r\n * @date: 2021-05-08 09:26\r\n */\r\npublic class Tr",
"end": 88,
"score": 0.9626070261001587,
"start": 79,
"tag": "NAME",
"value": "jiazhihao"
}
] | null | [] | package set;
import java.util.TreeSet;
/**
* @version 1.0
* @author: jiazhihao
* @date: 2021-05-08 09:26
*/
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<String> set =new TreeSet<>();
set.add("111");
set.add("222");
set.add("地理");
set.add("历史");
set.add("asdd");
set.add("ASDD");
System.out.println(set);
}
}
| 450 | 0.502262 | 0.457014 | 23 | 17.217392 | 13.474474 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false | 3 |
a59206bd0bc881c67a88be2602e8be5f7c916e04 | 19,679,540,214,801 | b2cc38b38b9eb14bafb23c69d6a733fe670a4043 | /Dayone/src/dayone/selenium/EnqFormPropFile.java | af107bf727435a26bbb1234048a293bfa52dec5e | [] | no_license | Jeganath86automation/gitdemo | https://github.com/Jeganath86automation/gitdemo | 14d68f3c3bdb11453fa7f192c4d0509e68904c7e | ac2c3d883f17af52b882f4fa154652337bf63161 | refs/heads/master | 2023-06-28T04:29:58.551000 | 2021-08-03T06:59:30 | 2021-08-03T06:59:30 | 376,458,726 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dayone.selenium;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
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.io.FileHandler;
import org.openqa.selenium.support.ui.Select;
public class EnqFormPropFile {
static WebDriver driver;
public static void main(String[] args) throws IOException, InterruptedException {
Properties prop=new Properties();
FileInputStream fis=new FileInputStream("D:/Automation Scripts/Dayone/src/dayone/selenium/Testdata.properties");
prop.load(fis);
String browserName=prop.getProperty("browser");
String url=prop.getProperty("url");
if(browserName.equals("chrome")){
System.setProperty("webdriver.chrome.driver", "D:\\Automation Scripts\\Selenium\\chromedriver_win32\\chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
}else if(browserName.equals("firefox")){
System.setProperty("webdriver.gecko.driver", "D:\\Automation Scripts\\Selenium\\geckodriver-v0.29.1-win64\\geckodriver.exe");
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
}
driver.get(url);
Thread.sleep(3000);
String pagetitle=driver.getTitle();
if(pagetitle.equalsIgnoreCase(prop.getProperty("pagetitle")))
{
DateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy h-m-s");
Date date = new Date();
System.out.println("Page is redirected to 404 page");
File src=((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileHandler.copy(src, new File("D:/Automation Scripts/Dayone/src/dayone/selenium/404error "+dateFormat.format(date)+".jpg" ));
driver.close();
}else
{
System.out.println("Page is loaded fine");
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.xpath(prop.getProperty("topnvalenicon_xpath"))).click();
driver.findElement(By.xpath(prop.getProperty("topnavsrch_xpath"))).sendKeys(prop.getProperty("topnavsearch"));
driver.findElement(By.xpath("//ul[@id='topNvUnivUl']//li//a//descendant::span[@id='univ_0']")).click();
driver.findElement(By.xpath(prop.getProperty("cibutton_xpath"))).click();
Thread.sleep(5000);
driver.findElement(By.xpath(prop.getProperty("allwall_xpath"))).click();
Thread.sleep(4000);
driver.findElement(By.xpath(prop.getProperty("enqfirstname_xpath"))).sendKeys(prop.getProperty("enqfirstname"));
driver.findElement(By.xpath(prop.getProperty("enqlasttname_xpath"))).sendKeys(prop.getProperty("enqlastname"));
driver.findElement(By.xpath(prop.getProperty("enqemailaddress_xpath"))).sendKeys(prop.getProperty("enqemailaddress"));
Thread.sleep(2000);
WebElement countryofresidence=driver.findElement(By.xpath(prop.getProperty("cor_xpath")));
JavascriptExecutor js=((JavascriptExecutor)driver);
js.executeScript("arguments[0].scrollIntoView(true);", countryofresidence);
Thread.sleep(3000);
Select corval=new Select(driver.findElement(By.xpath(prop.getProperty("cor_xpath"))));
corval.selectByVisibleText("Cambodia");
driver.findElement(By.xpath(prop.getProperty("coc_xpath"))).click();
Select phonetype=new Select(driver.findElement(By.xpath(prop.getProperty("phonetype_xpath"))));
phonetype.selectByIndex(1);
Thread.sleep(3000);
driver.findElement(By.xpath(prop.getProperty("mobnumber_xpath"))).click();
driver.findElement(By.xpath(prop.getProperty("mobnumber_xpath"))).sendKeys("1234567890");
Select stdlvl=new Select(driver.findElement(By.xpath(prop.getProperty("studylevl_xapth"))));
stdlvl.selectByVisibleText("Undergraduate");
//driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
Select subj=new Select(driver.findElement(By.xpath(prop.getProperty("subject_xpath"))));
subj.selectByVisibleText("Agriculture");
Select year=new Select(driver.findElement(By.xpath(prop.getProperty("startyear_xpath"))));
year.selectByVisibleText("2021");
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
Select month=new Select(driver.findElement(By.xpath(prop.getProperty("startmonth_xpath"))));
month.selectByVisibleText("December");
}
}
| UTF-8 | Java | 4,787 | java | EnqFormPropFile.java | Java | [
{
"context": "h(prop.getProperty(\"mobnumber_xpath\"))).sendKeys(\"1234567890\");\r\n\t\tSelect stdlvl=new Select(driver.findElement",
"end": 4077,
"score": 0.7179079651832581,
"start": 4067,
"tag": "PASSWORD",
"value": "1234567890"
}
] | null | [] | package dayone.selenium;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
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.io.FileHandler;
import org.openqa.selenium.support.ui.Select;
public class EnqFormPropFile {
static WebDriver driver;
public static void main(String[] args) throws IOException, InterruptedException {
Properties prop=new Properties();
FileInputStream fis=new FileInputStream("D:/Automation Scripts/Dayone/src/dayone/selenium/Testdata.properties");
prop.load(fis);
String browserName=prop.getProperty("browser");
String url=prop.getProperty("url");
if(browserName.equals("chrome")){
System.setProperty("webdriver.chrome.driver", "D:\\Automation Scripts\\Selenium\\chromedriver_win32\\chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
}else if(browserName.equals("firefox")){
System.setProperty("webdriver.gecko.driver", "D:\\Automation Scripts\\Selenium\\geckodriver-v0.29.1-win64\\geckodriver.exe");
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
}
driver.get(url);
Thread.sleep(3000);
String pagetitle=driver.getTitle();
if(pagetitle.equalsIgnoreCase(prop.getProperty("pagetitle")))
{
DateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy h-m-s");
Date date = new Date();
System.out.println("Page is redirected to 404 page");
File src=((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileHandler.copy(src, new File("D:/Automation Scripts/Dayone/src/dayone/selenium/404error "+dateFormat.format(date)+".jpg" ));
driver.close();
}else
{
System.out.println("Page is loaded fine");
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.xpath(prop.getProperty("topnvalenicon_xpath"))).click();
driver.findElement(By.xpath(prop.getProperty("topnavsrch_xpath"))).sendKeys(prop.getProperty("topnavsearch"));
driver.findElement(By.xpath("//ul[@id='topNvUnivUl']//li//a//descendant::span[@id='univ_0']")).click();
driver.findElement(By.xpath(prop.getProperty("cibutton_xpath"))).click();
Thread.sleep(5000);
driver.findElement(By.xpath(prop.getProperty("allwall_xpath"))).click();
Thread.sleep(4000);
driver.findElement(By.xpath(prop.getProperty("enqfirstname_xpath"))).sendKeys(prop.getProperty("enqfirstname"));
driver.findElement(By.xpath(prop.getProperty("enqlasttname_xpath"))).sendKeys(prop.getProperty("enqlastname"));
driver.findElement(By.xpath(prop.getProperty("enqemailaddress_xpath"))).sendKeys(prop.getProperty("enqemailaddress"));
Thread.sleep(2000);
WebElement countryofresidence=driver.findElement(By.xpath(prop.getProperty("cor_xpath")));
JavascriptExecutor js=((JavascriptExecutor)driver);
js.executeScript("arguments[0].scrollIntoView(true);", countryofresidence);
Thread.sleep(3000);
Select corval=new Select(driver.findElement(By.xpath(prop.getProperty("cor_xpath"))));
corval.selectByVisibleText("Cambodia");
driver.findElement(By.xpath(prop.getProperty("coc_xpath"))).click();
Select phonetype=new Select(driver.findElement(By.xpath(prop.getProperty("phonetype_xpath"))));
phonetype.selectByIndex(1);
Thread.sleep(3000);
driver.findElement(By.xpath(prop.getProperty("mobnumber_xpath"))).click();
driver.findElement(By.xpath(prop.getProperty("mobnumber_xpath"))).sendKeys("<PASSWORD>");
Select stdlvl=new Select(driver.findElement(By.xpath(prop.getProperty("studylevl_xapth"))));
stdlvl.selectByVisibleText("Undergraduate");
//driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
Select subj=new Select(driver.findElement(By.xpath(prop.getProperty("subject_xpath"))));
subj.selectByVisibleText("Agriculture");
Select year=new Select(driver.findElement(By.xpath(prop.getProperty("startyear_xpath"))));
year.selectByVisibleText("2021");
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
Select month=new Select(driver.findElement(By.xpath(prop.getProperty("startmonth_xpath"))));
month.selectByVisibleText("December");
}
}
| 4,787 | 0.742427 | 0.730102 | 101 | 45.396038 | 34.467972 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.524752 | false | false | 3 |
d874c969c1fa8a4c1b24237ea0cabb57091c3dde | 19,164,144,139,955 | 56406bf903df36d2cf29e9c1fac9a872bcab3f3c | /src/memsys/ui/options/ElectricianAdd.java | 0bb38cf24af95774d218787eae48582710c4496a | [] | no_license | lcadiz/MemSys | https://github.com/lcadiz/MemSys | bee8ba7fdc0a02b1be57f16ecad33cf541a58c33 | 6f298bb90ae06c61901fe4f277078d9598c4bc66 | refs/heads/master | 2021-03-17T06:04:28.709000 | 2020-03-13T02:14:00 | 2020-03-13T02:14:11 | 246,968,786 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package memsys.ui.options;
import memsys.global.DBConn.MainDBConn;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
public class ElectricianAdd extends javax.swing.JDialog {
public static ElectricianManage frmParent;
static Statement stmt;
public static int areaCode;
static int typeid;
public ElectricianAdd(ElectricianManage parent, boolean modal) {
this.frmParent = parent;
this.setModal(modal);
initComponents();
setLocationRelativeTo(this);
getRootPane().setDefaultButton(cmdadd);
populateType();
}
public static void Add(int code, String name) {
Connection conn = MainDBConn.getConnection();
String createString;
createString = "INSERT INTO electricianTBL"
+ "("
+ "areacode,"
+ "name,"
+ "type "
+ ") "
+ "VALUES "
+ "('" + code + "','" + name + "',"+typeid+")";
try {
stmt = conn.createStatement();
stmt.executeUpdate(createString);
stmt.close();
conn.close();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
public void populateType() {
//Populate Combo Area
Connection conn = MainDBConn.getConnection();
String createString;
createString = "SELECT type, typedesc FROM electricianTypeTBL";
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(createString);
while (rs.next()) {
cmbType.addItem(new Item2(rs.getInt(1), rs.getString(2)));
}
stmt.close();
conn.close();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Error RSQuery/004: Query Select All Areas!");
}
}
class Item2 {
private int id;
private String description;
public Item2(int id, String description) {
this.id = id;
this.description = description;
}
public int getId() {
return id;
}
public String getDescription() {
return description;
}
public String toString() {
return description;
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel7 = new javax.swing.JLabel();
cmdExit = new javax.swing.JButton();
cmdadd = new javax.swing.JButton();
txtname = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
cmbType = new javax.swing.JComboBox();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Add New Electrician");
setResizable(false);
jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel7.setText("Electrician Name:");
cmdExit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/exit.png"))); // NOI18N
cmdExit.setMnemonic('C');
cmdExit.setText("Cancel");
cmdExit.setToolTipText("Cancel and exit window");
cmdExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdExitActionPerformed(evt);
}
});
cmdadd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/add.png"))); // NOI18N
cmdadd.setMnemonic('A');
cmdadd.setText("Add");
cmdadd.setToolTipText("Create new schedule");
cmdadd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdaddActionPerformed(evt);
}
});
cmdadd.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
cmdaddKeyPressed(evt);
}
});
txtname.setToolTipText("Specific Address: Ex. Bulod, Bindoy Negros Oriental ");
jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel8.setText("Type:");
cmbType.setForeground(new java.awt.Color(102, 102, 102));
cmbType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "-SELECT-" }));
cmbType.setToolTipText("");
cmbType.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
cmbType.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmbTypeActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(cmdadd)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cmdExit))
.addComponent(cmbType, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtname, javax.swing.GroupLayout.PREFERRED_SIZE, 329, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(35, 35, 35))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtname, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cmbType, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cmdadd)
.addComponent(cmdExit))
.addContainerGap(38, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void cmdExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdExitActionPerformed
this.dispose();
}//GEN-LAST:event_cmdExitActionPerformed
private void cmdaddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdaddActionPerformed
if (txtname.getText().isEmpty() == true) {
JOptionPane.showMessageDialog(this, "Please fill-up all the required fields!");
} else {
Add(areaCode, txtname.getText().toUpperCase());
frmParent.populateTBL();
this.dispose();
JOptionPane.showMessageDialog(this, "Added succesfully!");
}
}//GEN-LAST:event_cmdaddActionPerformed
private void cmdaddKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cmdaddKeyPressed
// add();
}//GEN-LAST:event_cmdaddKeyPressed
private void cmbTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbTypeActionPerformed
try {
Item2 item = (Item2) cmbType.getSelectedItem();
typeid =item.getId();
} catch (Exception e) {
}
}//GEN-LAST:event_cmbTypeActionPerformed
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
ElectricianAdd dialog = new ElectricianAdd(frmParent, true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox cmbType;
private javax.swing.JButton cmdExit;
private javax.swing.JButton cmdadd;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JTextField txtname;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 9,930 | java | ElectricianAdd.java | Java | [] | null | [] | package memsys.ui.options;
import memsys.global.DBConn.MainDBConn;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
public class ElectricianAdd extends javax.swing.JDialog {
public static ElectricianManage frmParent;
static Statement stmt;
public static int areaCode;
static int typeid;
public ElectricianAdd(ElectricianManage parent, boolean modal) {
this.frmParent = parent;
this.setModal(modal);
initComponents();
setLocationRelativeTo(this);
getRootPane().setDefaultButton(cmdadd);
populateType();
}
public static void Add(int code, String name) {
Connection conn = MainDBConn.getConnection();
String createString;
createString = "INSERT INTO electricianTBL"
+ "("
+ "areacode,"
+ "name,"
+ "type "
+ ") "
+ "VALUES "
+ "('" + code + "','" + name + "',"+typeid+")";
try {
stmt = conn.createStatement();
stmt.executeUpdate(createString);
stmt.close();
conn.close();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
public void populateType() {
//Populate Combo Area
Connection conn = MainDBConn.getConnection();
String createString;
createString = "SELECT type, typedesc FROM electricianTypeTBL";
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(createString);
while (rs.next()) {
cmbType.addItem(new Item2(rs.getInt(1), rs.getString(2)));
}
stmt.close();
conn.close();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Error RSQuery/004: Query Select All Areas!");
}
}
class Item2 {
private int id;
private String description;
public Item2(int id, String description) {
this.id = id;
this.description = description;
}
public int getId() {
return id;
}
public String getDescription() {
return description;
}
public String toString() {
return description;
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel7 = new javax.swing.JLabel();
cmdExit = new javax.swing.JButton();
cmdadd = new javax.swing.JButton();
txtname = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
cmbType = new javax.swing.JComboBox();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Add New Electrician");
setResizable(false);
jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel7.setText("Electrician Name:");
cmdExit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/exit.png"))); // NOI18N
cmdExit.setMnemonic('C');
cmdExit.setText("Cancel");
cmdExit.setToolTipText("Cancel and exit window");
cmdExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdExitActionPerformed(evt);
}
});
cmdadd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/add.png"))); // NOI18N
cmdadd.setMnemonic('A');
cmdadd.setText("Add");
cmdadd.setToolTipText("Create new schedule");
cmdadd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdaddActionPerformed(evt);
}
});
cmdadd.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
cmdaddKeyPressed(evt);
}
});
txtname.setToolTipText("Specific Address: Ex. Bulod, Bindoy Negros Oriental ");
jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel8.setText("Type:");
cmbType.setForeground(new java.awt.Color(102, 102, 102));
cmbType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "-SELECT-" }));
cmbType.setToolTipText("");
cmbType.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
cmbType.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmbTypeActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(cmdadd)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cmdExit))
.addComponent(cmbType, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtname, javax.swing.GroupLayout.PREFERRED_SIZE, 329, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(35, 35, 35))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtname, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cmbType, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cmdadd)
.addComponent(cmdExit))
.addContainerGap(38, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void cmdExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdExitActionPerformed
this.dispose();
}//GEN-LAST:event_cmdExitActionPerformed
private void cmdaddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdaddActionPerformed
if (txtname.getText().isEmpty() == true) {
JOptionPane.showMessageDialog(this, "Please fill-up all the required fields!");
} else {
Add(areaCode, txtname.getText().toUpperCase());
frmParent.populateTBL();
this.dispose();
JOptionPane.showMessageDialog(this, "Added succesfully!");
}
}//GEN-LAST:event_cmdaddActionPerformed
private void cmdaddKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cmdaddKeyPressed
// add();
}//GEN-LAST:event_cmdaddKeyPressed
private void cmbTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbTypeActionPerformed
try {
Item2 item = (Item2) cmbType.getSelectedItem();
typeid =item.getId();
} catch (Exception e) {
}
}//GEN-LAST:event_cmbTypeActionPerformed
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
ElectricianAdd dialog = new ElectricianAdd(frmParent, true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox cmbType;
private javax.swing.JButton cmdExit;
private javax.swing.JButton cmdadd;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JTextField txtname;
// End of variables declaration//GEN-END:variables
}
| 9,930 | 0.623162 | 0.61571 | 244 | 39.69672 | 32.668327 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.627049 | false | false | 3 |
22581edf22ded9c73df6c40ef6a584b1f2939aa7 | 21,706,764,766,707 | d685d4f1cea60efbd1780a97c8f06fd2c39d9e6e | /src/jike/ssm/service/PhotoManager.java | ab015882e4192f3919daccd7415c7b6142967b53 | [] | no_license | 18128862785/Task14 | https://github.com/18128862785/Task14 | 8ca35c01cec60e640adc92917868f3b96b6364f4 | d48515a0be22a5d3878ab09a48adf8aa3a2680d2 | refs/heads/master | 2018-01-04T23:07:23.064000 | 2016-10-14T09:35:33 | 2016-10-14T09:35:33 | 70,895,591 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jike.ssm.service;
public interface PhotoManager {
}
| UTF-8 | Java | 67 | java | PhotoManager.java | Java | [] | null | [] | package jike.ssm.service;
public interface PhotoManager {
}
| 67 | 0.716418 | 0.716418 | 5 | 11.4 | 13.690873 | 31 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 3 |
4cba29e97e32c6885e5f85acb87b9b15759d97a6 | 33,526,514,770,899 | b4ab76595c036218cb7fc7adda83ee3dcbaaef3d | /ibzou/ibzou-core/src/main/java/cn/ibizlab/core/ou/service/logic/impl/SysEmployeesaveDeptMemberLogicImpl.java | 22c80103f94a9a2c8da9df7bf2fc65ec99e605d6 | [
"Apache-2.0"
] | permissive | bellmit/ibizlab-runtime | https://github.com/bellmit/ibizlab-runtime | a1c342e38f332d7de3e0bbfcbc980002245e0b6e | 1ad216e76800763c9c10ecfd27d92a017af6576c | refs/heads/master | 2023-06-03T10:56:34.322000 | 2021-04-02T10:53:05 | 2021-04-02T10:53:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.ibizlab.core.ou.service.logic.impl;
@Deprecated
public class SysEmployeesaveDeptMemberLogicImpl{
}
| UTF-8 | Java | 112 | java | SysEmployeesaveDeptMemberLogicImpl.java | Java | [] | null | [] | package cn.ibizlab.core.ou.service.logic.impl;
@Deprecated
public class SysEmployeesaveDeptMemberLogicImpl{
}
| 112 | 0.830357 | 0.830357 | 6 | 17.666666 | 21.09239 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 3 |
8d8ae2f5508f8b61fa6ec8a4675542b0dae86b6c | 35,914,516,547,566 | 74626d8d96e8c207e6affcb454ae4e30451e40e6 | /src/main/java/io/github/lucaseasedup/logit/command/LogItTabCompleter.java | 10af07b4d1783e41da59699778ab2ba8313e4cfe | [
"CC-PDDC",
"LicenseRef-scancode-public-domain"
] | permissive | nicku1/LogIt | https://github.com/nicku1/LogIt | bcdc3f253fb6d9dc117b2d558077a86a8a79b358 | 36a9052cd1fa952bd2c26f45a3787764e8bafaf4 | refs/heads/master | 2022-11-22T14:23:55.636000 | 2017-06-10T08:24:22 | 2017-06-10T08:24:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.github.lucaseasedup.logit.command;
import io.github.lucaseasedup.logit.LogItCoreObject;
import io.github.lucaseasedup.logit.account.Account;
import io.github.lucaseasedup.logit.command.hub.HubCommand;
import io.github.lucaseasedup.logit.command.hub.HubCommands;
import io.github.lucaseasedup.logit.storage.Infix;
import io.github.lucaseasedup.logit.storage.SelectorCondition;
import io.github.lucaseasedup.logit.util.Utils;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public final class LogItTabCompleter extends LogItCoreObject
{
public List<String> completeHubCommand(String stub)
{
if (stub == null)
throw new IllegalArgumentException();
List<String> suggestions = new ArrayList<>();
Iterator<HubCommand> commandIt = HubCommands.iterator();
while (commandIt.hasNext() && suggestions.size() < MAX_SUGGESTIONS)
{
HubCommand command = commandIt.next();
if (command.getSubcommand().startsWith(stub))
{
String[] stubWords = Utils.getWords(stub);
String[] commandWords = Utils.getWords(command.getSubcommand());
String suggestion;
// Complete next word.
if (stubWords.length == 0 || stub.endsWith(" "))
{
suggestion = commandWords[stubWords.length];
}
// Complete current word.
else
{
suggestion = commandWords[stubWords.length - 1];
}
if (!suggestions.contains(suggestion))
{
suggestions.add(suggestion);
}
}
}
return suggestions;
}
public List<String> completeUsername(String stub)
{
if (stub == null)
throw new IllegalArgumentException();
List<Account> accounts = getAccountManager().selectAccounts(
Arrays.asList(keys().username()),
new SelectorCondition(
keys().username(),
Infix.STARTS_WITH,
stub
)
);
if (accounts == null)
return null;
List<String> suggestions = new ArrayList<>();
for (Account account : accounts)
{
suggestions.add(account.getUsername());
}
Collections.sort(suggestions);
return suggestions.subList(0,
(suggestions.size() < MAX_SUGGESTIONS)
? suggestions.size() : MAX_SUGGESTIONS);
}
public List<String> completeBackupFilename(String stub)
{
if (stub == null)
throw new IllegalArgumentException();
File[] backups = getBackupManager().getBackups();
List<String> suggestions = new ArrayList<>();
for (File backup : backups)
{
if (backup.getName().startsWith(stub))
{
suggestions.add(backup.getName());
}
if (suggestions.size() >= MAX_SUGGESTIONS)
{
break;
}
}
return suggestions;
}
public List<String> completeConfigProperty(String stub)
{
if (stub == null)
throw new IllegalArgumentException();
List<String> suggestions = new ArrayList<>();
for (String property : getConfig("config.yml").getProperties().keySet())
{
if (property.startsWith(stub))
{
suggestions.add(property);
if (suggestions.size() >= MAX_SUGGESTIONS)
{
break;
}
}
}
return suggestions;
}
private static final int MAX_SUGGESTIONS = 16;
}
| UTF-8 | Java | 4,298 | java | LogItTabCompleter.java | Java | [
{
"context": "package io.github.lucaseasedup.logit.command;\r\n\r\nimport io.github.lucaseasedup.l",
"end": 30,
"score": 0.9987941384315491,
"start": 18,
"tag": "USERNAME",
"value": "lucaseasedup"
},
{
"context": "b.lucaseasedup.logit.command;\r\n\r\nimport io.github.lucaseasedup.log... | null | [] | package io.github.lucaseasedup.logit.command;
import io.github.lucaseasedup.logit.LogItCoreObject;
import io.github.lucaseasedup.logit.account.Account;
import io.github.lucaseasedup.logit.command.hub.HubCommand;
import io.github.lucaseasedup.logit.command.hub.HubCommands;
import io.github.lucaseasedup.logit.storage.Infix;
import io.github.lucaseasedup.logit.storage.SelectorCondition;
import io.github.lucaseasedup.logit.util.Utils;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public final class LogItTabCompleter extends LogItCoreObject
{
public List<String> completeHubCommand(String stub)
{
if (stub == null)
throw new IllegalArgumentException();
List<String> suggestions = new ArrayList<>();
Iterator<HubCommand> commandIt = HubCommands.iterator();
while (commandIt.hasNext() && suggestions.size() < MAX_SUGGESTIONS)
{
HubCommand command = commandIt.next();
if (command.getSubcommand().startsWith(stub))
{
String[] stubWords = Utils.getWords(stub);
String[] commandWords = Utils.getWords(command.getSubcommand());
String suggestion;
// Complete next word.
if (stubWords.length == 0 || stub.endsWith(" "))
{
suggestion = commandWords[stubWords.length];
}
// Complete current word.
else
{
suggestion = commandWords[stubWords.length - 1];
}
if (!suggestions.contains(suggestion))
{
suggestions.add(suggestion);
}
}
}
return suggestions;
}
public List<String> completeUsername(String stub)
{
if (stub == null)
throw new IllegalArgumentException();
List<Account> accounts = getAccountManager().selectAccounts(
Arrays.asList(keys().username()),
new SelectorCondition(
keys().username(),
Infix.STARTS_WITH,
stub
)
);
if (accounts == null)
return null;
List<String> suggestions = new ArrayList<>();
for (Account account : accounts)
{
suggestions.add(account.getUsername());
}
Collections.sort(suggestions);
return suggestions.subList(0,
(suggestions.size() < MAX_SUGGESTIONS)
? suggestions.size() : MAX_SUGGESTIONS);
}
public List<String> completeBackupFilename(String stub)
{
if (stub == null)
throw new IllegalArgumentException();
File[] backups = getBackupManager().getBackups();
List<String> suggestions = new ArrayList<>();
for (File backup : backups)
{
if (backup.getName().startsWith(stub))
{
suggestions.add(backup.getName());
}
if (suggestions.size() >= MAX_SUGGESTIONS)
{
break;
}
}
return suggestions;
}
public List<String> completeConfigProperty(String stub)
{
if (stub == null)
throw new IllegalArgumentException();
List<String> suggestions = new ArrayList<>();
for (String property : getConfig("config.yml").getProperties().keySet())
{
if (property.startsWith(stub))
{
suggestions.add(property);
if (suggestions.size() >= MAX_SUGGESTIONS)
{
break;
}
}
}
return suggestions;
}
private static final int MAX_SUGGESTIONS = 16;
}
| 4,298 | 0.507213 | 0.506049 | 137 | 29.372263 | 21.44455 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.364964 | false | false | 3 |
7b1fd44254c4c04734eefd17647cd484ab986131 | 9,380,208,636,580 | 9033c25436aac58f9630f44fa1d7078817fb5ce3 | /src/main/java/com/zhd/basics/javabase/suanfa/MainSolution.java | 95ccdc26c30b161e2059eb3982e909cc17214b3d | [] | no_license | zhanghaodong2017/basics | https://github.com/zhanghaodong2017/basics | 3d30bf68d539adc63d2e6b3b208ec33c11f06f46 | 2c508bbb530b075fa2426b49ba8b0f233af496b0 | refs/heads/master | 2020-04-05T11:41:09.939000 | 2019-03-09T03:04:05 | 2019-03-09T03:04:05 | 156,844,665 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zhd.basics.javabase.suanfa;
import java.time.LocalDate;
/**
* @Author: zhanghaodong
* @Description
* @Date: 2019-03-05 16:38
*/
public class MainSolution {
public static ListNode rotateRight(ListNode head, int k) {
if (head == null) {
return head;
}
int lenth = 1;
ListNode end = head;
ListNode nextNode = null;
while ((nextNode = end.next) != null) {
end = nextNode;
lenth++;
}
System.out.println("链表长度:" + lenth);
System.out.println("链表尾部值:" + end.val);
k = k % lenth;
System.out.println("K=" + k);
if (k == 0) {
return head;
}
int n = lenth - k - 1;
int i = 0;
ListNode pointN = head;
while (i++ < n) {
pointN = pointN.next;
}
System.out.println("pointN=" + pointN.val);
end.next = head;
head = pointN.next;
pointN.next = null;
return head;
}
public static ListNode rotateRight2(ListNode head, int k) {
if (head == null || head.next == null || k <= 0) {//链表为空或者只有一个元素或k为0
return head;
}
for (int i = 0; i < k; i++) {
}
int lenth = 1;
ListNode end = head;
ListNode nextNode = null;
while ((nextNode = end.next) != null) {
end = nextNode;
lenth++;
}
System.out.println("链表长度:" + lenth);
System.out.println("链表尾部值:" + end.val);
k = k % lenth;
System.out.println("K=" + k);
if (k == 0) {
return head;
}
int n = lenth - k - 1;
int i = 0;
ListNode pointN = head;
while (i++ < n) {
pointN = pointN.next;
}
System.out.println("pointN=" + pointN.val);
end.next = head;
head = pointN.next;
pointN.next = null;
return head;
}
public static void main(String[] args) {
ListNode listNode5 = new ListNode(5);
ListNode listNode4 = new ListNode(4, listNode5);
ListNode listNode3 = new ListNode(3, listNode4);
ListNode listNode2 = new ListNode(2, listNode3);
ListNode head = new ListNode(1, listNode2);
print(head);
ListNode result = rotateRight2(head, 7);
print(result);
System.out.println();
// System.out.println(LocalDate.now());
}
public static void print(ListNode head) {
if (head == null) {
return;
}
while (head.next != null) {
System.out.print(head.val);
System.out.print(" -> ");
head = head.next;
}
System.out.print(head.val);
}
}
| UTF-8 | Java | 2,833 | java | MainSolution.java | Java | [
{
"context": "nfa;\n\nimport java.time.LocalDate;\n\n/**\n * @Author: zhanghaodong\n * @Description\n * @Date: 2019-03-05 1",
"end": 87,
"score": 0.5751394033432007,
"start": 86,
"tag": "NAME",
"value": "z"
},
{
"context": "a;\n\nimport java.time.LocalDate;\n\n/**\n * @Author: zhangh... | null | [] | package com.zhd.basics.javabase.suanfa;
import java.time.LocalDate;
/**
* @Author: zhanghaodong
* @Description
* @Date: 2019-03-05 16:38
*/
public class MainSolution {
public static ListNode rotateRight(ListNode head, int k) {
if (head == null) {
return head;
}
int lenth = 1;
ListNode end = head;
ListNode nextNode = null;
while ((nextNode = end.next) != null) {
end = nextNode;
lenth++;
}
System.out.println("链表长度:" + lenth);
System.out.println("链表尾部值:" + end.val);
k = k % lenth;
System.out.println("K=" + k);
if (k == 0) {
return head;
}
int n = lenth - k - 1;
int i = 0;
ListNode pointN = head;
while (i++ < n) {
pointN = pointN.next;
}
System.out.println("pointN=" + pointN.val);
end.next = head;
head = pointN.next;
pointN.next = null;
return head;
}
public static ListNode rotateRight2(ListNode head, int k) {
if (head == null || head.next == null || k <= 0) {//链表为空或者只有一个元素或k为0
return head;
}
for (int i = 0; i < k; i++) {
}
int lenth = 1;
ListNode end = head;
ListNode nextNode = null;
while ((nextNode = end.next) != null) {
end = nextNode;
lenth++;
}
System.out.println("链表长度:" + lenth);
System.out.println("链表尾部值:" + end.val);
k = k % lenth;
System.out.println("K=" + k);
if (k == 0) {
return head;
}
int n = lenth - k - 1;
int i = 0;
ListNode pointN = head;
while (i++ < n) {
pointN = pointN.next;
}
System.out.println("pointN=" + pointN.val);
end.next = head;
head = pointN.next;
pointN.next = null;
return head;
}
public static void main(String[] args) {
ListNode listNode5 = new ListNode(5);
ListNode listNode4 = new ListNode(4, listNode5);
ListNode listNode3 = new ListNode(3, listNode4);
ListNode listNode2 = new ListNode(2, listNode3);
ListNode head = new ListNode(1, listNode2);
print(head);
ListNode result = rotateRight2(head, 7);
print(result);
System.out.println();
// System.out.println(LocalDate.now());
}
public static void print(ListNode head) {
if (head == null) {
return;
}
while (head.next != null) {
System.out.print(head.val);
System.out.print(" -> ");
head = head.next;
}
System.out.print(head.val);
}
}
| 2,833 | 0.492213 | 0.478088 | 109 | 24.330275 | 17.262175 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.642202 | false | false | 3 |
1ffcd4b334c7009902d24ca6bf143c2839bd45d6 | 38,053,410,243,300 | 9211928622e628dee37697da3ebb268a0a5ef566 | /src/Addons/Help.java | 8d085bf1a25386bdb87dd9404f76d68dfc3c9a64 | [] | no_license | rivizoft/vktelegrambot | https://github.com/rivizoft/vktelegrambot | 7c85ac6e99892c8ffde04e72c497040d7fb107bc | c01971f11812cb9d51e8b74f901f3b7e8c13cc06 | refs/heads/master | 2022-03-20T07:15:28.140000 | 2019-12-16T09:54:31 | 2019-12-16T09:54:31 | 210,298,394 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Addons;
import Functions.Function;
import Users.User;
public class Help implements Function {
@Override
public String getCommand() {
return "/help";
}
@Override
public String getText(User user) {
return "Привет, " + user.getName() + ". Я бот Бит. Со мной можно поиграть в разные игры: \n" +
"Набери /start1 и я с тобой сыграю в игру \"Угадай число\"\n" +
"Набери /start2 и я с тобой сыграю в игру \"21\"\n" +
"Набери /start3 и я с тобой сыграю в математическую игру\n" +
"/top - посмотреть ТОП игроков\n" +
"/stat - посмотреть свою статистику\n";
}
}
| UTF-8 | Java | 892 | java | Help.java | Java | [] | null | [] | package Addons;
import Functions.Function;
import Users.User;
public class Help implements Function {
@Override
public String getCommand() {
return "/help";
}
@Override
public String getText(User user) {
return "Привет, " + user.getName() + ". Я бот Бит. Со мной можно поиграть в разные игры: \n" +
"Набери /start1 и я с тобой сыграю в игру \"Угадай число\"\n" +
"Набери /start2 и я с тобой сыграю в игру \"21\"\n" +
"Набери /start3 и я с тобой сыграю в математическую игру\n" +
"/top - посмотреть ТОП игроков\n" +
"/stat - посмотреть свою статистику\n";
}
}
| 892 | 0.561702 | 0.55461 | 22 | 30.045454 | 29.567299 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 3 |
540ab63b63cfb1a9dc83f8ca00bf1775cce6b011 | 35,940,286,360,593 | d375d9d0e82e1f195ab4f56eb93780810faa7e56 | /Fuente_Distribuidos/src/distri/TCPDirectorio.java | f9d5d32018e87a549e835551c7c614d3cd689328 | [] | no_license | orozcojuan1998/Sistema-distribuido-de-votaci-n-de-proyectos-gubernamentales | https://github.com/orozcojuan1998/Sistema-distribuido-de-votaci-n-de-proyectos-gubernamentales | 40ad57b6cd6b6bf8437816390ab7cec5ffb30b70 | 1c840e05a2c68912bc44da01e09c164bb1d40b83 | refs/heads/master | 2020-07-23T01:56:53.358000 | 2019-09-09T21:42:39 | 2019-09-09T21:42:39 | 207,408,736 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package distri;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
import javax.annotation.processing.SupportedSourceVersion;
public class TCPDirectorio extends Thread {
private Fuente fuente;
private DataInputStream in;
private DataOutputStream out;
private Socket s;
private String ipDirectorio= "10.192.101.21";
private int port = 8002;
public TCPDirectorio(Fuente fuente) {
this.fuente = fuente;
s = null;
try{
s = new Socket(ipDirectorio, port);
in = new DataInputStream(s.getInputStream());
out =new DataOutputStream(s.getOutputStream());
}catch (UnknownHostException e){
System.out.println("Socket:"+e.getMessage());
}catch (EOFException e){
System.out.println("EOF:"+e.getMessage());
}catch (IOException e){
System.out.println("readline:"+e.getMessage());
}
}
public void obtenerProxies() {
String data="";
try{
out.writeUTF("\\REQUEST_PROXIES--");
data = in.readUTF();
while(!data.contains("\\FIN")) {
String[] resp = data.split("--");
String ip = resp[1];
String port = resp[2];
Proxy p = new Proxy(ip,Integer.parseInt(port) );
fuente.getProxies().add(p);
data = in.readUTF();
}
}catch (UnknownHostException e){
System.out.println("Socket:"+e.getMessage());
}catch (EOFException e){
System.out.println("EOF:"+e.getMessage());
}catch (IOException e){
System.out.println("readline:"+e.getMessage());
} finally {if(s!=null) try { s.close(); }catch (IOException e){
System.out.println("close:"+e.getMessage());}}
}
} | UTF-8 | Java | 1,905 | java | TCPDirectorio.java | Java | [
{
"context": "vate Socket s;\r\n\t\r\n\tprivate String ipDirectorio= \"10.192.101.21\";\r\n\tprivate int port = 8002;\r\n\r\n\tpublic TCPDirect",
"end": 574,
"score": 0.9997482299804688,
"start": 561,
"tag": "IP_ADDRESS",
"value": "10.192.101.21"
}
] | null | [] | package distri;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
import javax.annotation.processing.SupportedSourceVersion;
public class TCPDirectorio extends Thread {
private Fuente fuente;
private DataInputStream in;
private DataOutputStream out;
private Socket s;
private String ipDirectorio= "10.192.101.21";
private int port = 8002;
public TCPDirectorio(Fuente fuente) {
this.fuente = fuente;
s = null;
try{
s = new Socket(ipDirectorio, port);
in = new DataInputStream(s.getInputStream());
out =new DataOutputStream(s.getOutputStream());
}catch (UnknownHostException e){
System.out.println("Socket:"+e.getMessage());
}catch (EOFException e){
System.out.println("EOF:"+e.getMessage());
}catch (IOException e){
System.out.println("readline:"+e.getMessage());
}
}
public void obtenerProxies() {
String data="";
try{
out.writeUTF("\\REQUEST_PROXIES--");
data = in.readUTF();
while(!data.contains("\\FIN")) {
String[] resp = data.split("--");
String ip = resp[1];
String port = resp[2];
Proxy p = new Proxy(ip,Integer.parseInt(port) );
fuente.getProxies().add(p);
data = in.readUTF();
}
}catch (UnknownHostException e){
System.out.println("Socket:"+e.getMessage());
}catch (EOFException e){
System.out.println("EOF:"+e.getMessage());
}catch (IOException e){
System.out.println("readline:"+e.getMessage());
} finally {if(s!=null) try { s.close(); }catch (IOException e){
System.out.println("close:"+e.getMessage());}}
}
} | 1,905 | 0.64042 | 0.632021 | 82 | 21.256098 | 18.369389 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.329268 | false | false | 3 |
1063f3ee78db69bca655ba68a78ae83fcebfd9f1 | 16,544,214,080,614 | 5aa183a883ecf289dd1f068ae613359b71175d3e | /src/edu/cmu/cs/hcii/cogtool/ui/DefaultUI.java | e35444396a0e376d5641aada11eab7bd59ce3682 | [] | no_license | hyyuan/cogtool_plus | https://github.com/hyyuan/cogtool_plus | 9971e12bf8f95b84048642414e29b930395f419f | 0b5d04e3eb1cc6ca5aa3fa135a85fef505604c6c | refs/heads/master | 2021-06-07T22:58:21.085000 | 2021-04-20T13:57:26 | 2021-04-20T13:57:26 | 130,874,565 | 6 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*******************************************************************************
* CogTool Copyright Notice and Distribution Terms
* CogTool 1.3, Copyright (c) 2005-2013 Carnegie Mellon University
* This software is distributed under the terms of the FSF Lesser
* Gnu Public License (see LGPL.txt).
*
* CogTool is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* CogTool is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CogTool; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* CogTool makes use of several third-party components, with the
* following notices:
*
* Eclipse SWT version 3.448
* Eclipse GEF Draw2D version 3.2.1
*
* Unless otherwise indicated, all Content made available by the Eclipse
* Foundation is provided to you under the terms and conditions of the Eclipse
* Public License Version 1.0 ("EPL"). A copy of the EPL is provided with this
* Content and is also available at http://www.eclipse.org/legal/epl-v10.html.
*
* CLISP version 2.38
*
* Copyright (c) Sam Steingold, Bruno Haible 2001-2006
* This software is distributed under the terms of the FSF Gnu Public License.
* See COPYRIGHT file in clisp installation folder for more information.
*
* ACT-R 6.0
*
* Copyright (c) 1998-2007 Dan Bothell, Mike Byrne, Christian Lebiere &
* John R Anderson.
* This software is distributed under the terms of the FSF Lesser
* Gnu Public License (see LGPL.txt).
*
* Apache Jakarta Commons-Lang 2.1
*
* This product contains software developed by the Apache Software Foundation
* (http://www.apache.org/)
*
* jopt-simple version 1.0
*
* Copyright (c) 2004-2013 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Mozilla XULRunner 1.9.0.5
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (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.mozilla.org/MPL/.
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* The J2SE(TM) Java Runtime Environment version 5.0
*
* Copyright 2009 Sun Microsystems, Inc., 4150
* Network Circle, Santa Clara, California 95054, U.S.A. All
* rights reserved. U.S.
* See the LICENSE file in the jre folder for more information.
******************************************************************************/
package edu.cmu.cs.hcii.cogtool.ui;
import java.util.EventObject;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import edu.cmu.cs.hcii.cogtool.CogTool;
import edu.cmu.cs.hcii.cogtool.CogToolClipboard;
import edu.cmu.cs.hcii.cogtool.CogToolLID;
import edu.cmu.cs.hcii.cogtool.controller.Controller;
import edu.cmu.cs.hcii.cogtool.controller.ControllerRegistry;
import edu.cmu.cs.hcii.cogtool.controller.DesignEditorController;
import edu.cmu.cs.hcii.cogtool.controller.ProjectController;
import edu.cmu.cs.hcii.cogtool.model.Design;
import edu.cmu.cs.hcii.cogtool.model.Project;
import edu.cmu.cs.hcii.cogtool.util.AlertHandler;
import edu.cmu.cs.hcii.cogtool.util.IUndoableEdit;
import edu.cmu.cs.hcii.cogtool.util.L10N;
import edu.cmu.cs.hcii.cogtool.util.ListenerIdentifier;
import edu.cmu.cs.hcii.cogtool.util.ListenerIdentifierMap;
import edu.cmu.cs.hcii.cogtool.util.ManagedText;
import edu.cmu.cs.hcii.cogtool.util.MenuUtil;
import edu.cmu.cs.hcii.cogtool.util.NameChangeAlert;
import edu.cmu.cs.hcii.cogtool.util.UndoManager;
import edu.cmu.cs.hcii.cogtool.util.WindowUtil;
import edu.cmu.cs.hcii.cogtool.util.MenuUtil.MenuItemDefinition;
import edu.cmu.cs.hcii.cogtool.util.MenuUtil.SimpleMenuItemDefinition;
import edu.cmu.cs.hcii.cogtool.view.MenuFactory;
import edu.cmu.cs.hcii.cogtool.view.UndoManagerView;
/**
* Default implementation of UI functionality shared by the views
* for all CogTool model objects.
*
* @author mlh
*/
public abstract class DefaultUI extends UI
implements MenuFactory.ILeadItemUpdater
{
/**
* Specialized listener ID indicating that the window for the
* given project or design should be restored (that is, given the focus
* if it still exists, or re-created otherwise).
* <p>
* Actual restoration occurs in <code>getParameters</code>. The restored
* window is then returned by <code>getParameters</code> in case
* any further semantic action might wish to operate on the window.
* Generally, restoration of the window is all that is expected,
* so controllers do not assign any actions to instances of
* this listener ID subclass.
*
* @author mlh
*/
public static class RestoreParentControllerLID extends ListenerIdentifier
{
public final Project project;
public final Design design; // can be null
/**
* Initialize the ID; if the given design is not <code>null</code>,
* then a <code>DesignEditorController</code> will be restored.
* Otherwise, a <code>ProjectController</code> will be restored.
*
* @param p the project either to restore or as the parent of the
* given design
* @param d the design either to restore or <code>null</code> if
* restoring the project's window
* @author mlh
*/
public RestoreParentControllerLID(Project p, Design d)
{
project = p;
design = d;
}
/**
* Used by <code>getParameters</code> to restore the desired
* window. Returned by <code>getParameters</code> in case
* any further semantic action might wish to operate on the window.
* <p>
* Generally, restoration of the window is all that is expected,
* so controllers do not assign any actions to instances of
* this listener ID subclass.
*
* @return the controller restored
* @author mlh
*/
public Controller restoreWindow()
{
Controller window = null;
// Project controller if design is null
if (design == null) {
boolean notModified;
try {
notModified =
UndoManager.isAtSavePoint(project);
}
catch (IllegalStateException ex) {
System.err.println("Ignoring that isAtSavePoint failed.");
notModified = false;
}
// Presume registered -- registering twice is problematic!
window =
ProjectController.openController(project,
false,
notModified);
}
else {
// Design controller
window =
DesignEditorController.openController(design,
project);
}
return window;
}
}
/**
* All UI subclasses require access to the project that contains
* the model object being edited.
*/
protected Project project;
/**
* Marker string reflecting whether the associated project
* is modified since its last save; suitable for use in constructing
* window titles.
*/
protected String modificationFlag;
/**
* The undo manager itself. Created in the controller, held onto here.
* Mostly used for the connection to the undoManagerview.
*/
protected UndoManager undoManager; // needed in dispose
protected UndoManagerView.UndoAlertHandler undoMgrViewHandler;
/**
* Delegates closing a window to performAction in the corresponding
* Controller object.
*/
protected ShellAdapter closeListener = new ShellAdapter()
{
/**
* Handler for shellClosed -- delegates to performAction
*/
@Override
public void shellClosed(ShellEvent e)
{
CogTool.controllerNexus.saveWindowLocation(project,
getModelObject(),
getShell().getBounds());
/**
* Don't let other listeners progress if save canceled.
*/
e.doit = performAction(CogToolLID.CloseWindow, null, false);
}
};;
/**
* Definition of the "Window" menu for this window.
*/
protected MenuFactory.IWindowMenuData<Project> menuData = null;
/**
* How to react to alerts raised when save points change in any undo
* manager. Updates the window titles, reflecting modification status.
* TODO: Should we reflect modification status in "Window" menu entries?
* If so, do here!
*/
protected AlertHandler undoMgrTitleHandler =
new AlertHandler() {
public void handleAlert(EventObject evt)
{
UndoManager.SavePointChange chg =
(UndoManager.SavePointChange) evt;
updateModificationFlag(chg.nowAtSavePoint);
updateTitle();
}
};
/**
* How to react to alerts that a model object has been renamed.
* Updates window titles and "Window" menu entries.
*/
protected AlertHandler renameHandler =
new AlertHandler() {
public void handleAlert(EventObject evt)
{
updateTitle();
updateWindowMenus();
}
};
protected static final String OPEN_PROJECT_LABEL =
L10N.get("MI.OpenProject", "Display Project");
protected static final String OPEN_DESIGN_LABEL =
L10N.get("MI.OpenDesign", "Display Design");
/**
* Support for creating the lead items for the Window menu.
*
* @param p the project either to restore or as the parent of the
* given design
* @param d the design either to restore or <code>null</code> if
* restoring the project's window
* @author mlh
*/
protected static MenuItemDefinition[] buildLeadItems(Project p, Design d)
{
ListenerIdentifier openProjectLID = null;
ListenerIdentifier openDesignLID = null;
boolean openProjectEnabled = MenuUtil.DISABLED;
boolean openDesignEnabled = MenuUtil.DISABLED;
String openProjectLabel = OPEN_PROJECT_LABEL;
String openDesignLabel = OPEN_DESIGN_LABEL;
// Check to create standard LID's for opening design & project
if (p != null) {
openProjectLID = new RestoreParentControllerLID(p, null);
openProjectEnabled = MenuUtil.ENABLED;
openProjectLabel = openProjectLabel + ": " + p.getName();
if (d != null) {
openDesignLID = new RestoreParentControllerLID(p, d);
openDesignEnabled = MenuUtil.ENABLED;
openDesignLabel = openDesignLabel + ": " + d.getName();
}
}
return new MenuItemDefinition[]
{ new SimpleMenuItemDefinition(openProjectLabel,
openProjectLID,
openProjectEnabled),
new SimpleMenuItemDefinition(openDesignLabel,
openDesignLID,
openDesignEnabled),
MenuUtil.SEPARATOR };
}
// Suitable for a Design window
protected static MenuItemDefinition[] buildLeadItems(Project p)
{
return buildLeadItems(p, null);
}
// Suitable for a Project window
protected static MenuItemDefinition[] buildLeadItems()
{
return buildLeadItems(null, null);
}
/**
* All CogTool model editing views keep track of the <code>Project</code>
* instance that contains (or is) the model object being edited.
*
* @param proj the Project instance that is or contains the model
* object being edited
* @param windowMenuLabel the label for this window's entry in the
* window menu
* @param leadItems the lead menu items for the window menu of this window
* @author mlh
*/
public DefaultUI(Project proj,
String windowMenuLabel,
MenuItemDefinition[] leadItems,
UndoManager undoMgr)
{
super();
project = proj;
// Manage current project modification state and future changes
// to that state and model object names.
if (project != null) {
try {
updateModificationFlag(UndoManager.isAtSavePoint(project));
}
catch (IllegalStateException ex) {
System.err.println("Ignoring that isAtSavePoint failed.");
updateModificationFlag(false);
}
project.addHandler(this,
NameChangeAlert.class,
renameHandler);
try {
UndoManager.addSavePointChangeHandler(project,
undoMgrTitleHandler);
}
catch (IllegalStateException ex) {
System.err.println("Ignoring fact that addSavePointChangeHandler failed.");
}
}
undoManager = undoMgr;
// Create the undo manager view handler,
// resetting the undo view handler to represent any values currently in
// the undo manager. IE: remember undo.
if (undoManager != null) {
undoMgrViewHandler =
new UndoManagerView.UndoAlertHandler(undoManager,
lIDMap,
CogToolLID.Undo,
CogToolLID.Redo);
undoManager.addHandler(this,
UndoManager.UndoRedoEvent.class,
undoMgrViewHandler);
}
menuData = new DefaultWindowMenuData(this,
windowMenuLabel,
leadItems);
}
/**
* Return the UI's Project instance
*/
public Project getProject()
{
return project;
}
@Override
protected int canIDCauseSelection(ListenerIdentifier lid)
{
if (undoManager != null) {
IUndoableEdit edit = null;
if (lid == CogToolLID.Undo) {
edit = undoManager.editToBeUndone();
}
else if (lid == CogToolLID.Redo) {
edit = undoManager.editToBeRedone();
}
if (edit != null) {
lid = edit.getLID();
}
// else not undo/redo; query lid directly
}
return super.canIDCauseSelection(lid);
}
@Override
protected boolean doesIDCommitChanges(ListenerIdentifier lid)
{
if (undoManager != null) {
if (lid == CogToolLID.Undo) {
return idCommitsChanges(undoManager.editToBeUndone().getLID());
}
if (lid == CogToolLID.Redo) {
return idCommitsChanges(undoManager.editToBeRedone().getLID());
}
}
if (lid == CogToolLID.Paste) {
return CogToolClipboard.hasNonTextPasteContent();
}
// Not undo/redo; query lid directly
return super.doesIDCommitChanges(lid);
}
protected static final String operationCanceled =
L10N.get("DEFINT.OperationCanceled",
"The requested operation was canceled due to the following error:");
@Override
public boolean performAction(ListenerIdentifier id)
{
if ((undoManager != null) && doesIDCommitChanges(id)) {
Text textWithFocus = WindowUtil.getFocusedText();
if (textWithFocus != null) {
if (textWithFocus instanceof ManagedText) {
ManagedText performText = (ManagedText) textWithFocus;
if (! performText.confirm(ManagedText.LOSE_FOCUS)) {
getStandardInteraction().setStatusMessage(operationCanceled);
return false;
}
}
}
}
return super.performAction(id);
}
/**
* Return the primary model object this view/ui is responsible for
* editing.
*
* @return the primary model object this view/ui is responsible for
* editing
* @author mlh
*/
protected abstract Object getModelObject();
/**
* Based on the given modification state, recompute the modification
* marker string used in window titles.
*
* @param atSavePoint true if modification state means "saved";
* false if the associated project or any of its
* components were modified since the last save
* @author mlh
*/
protected void updateModificationFlag(boolean atSavePoint)
{
modificationFlag = atSavePoint ? "" : "* ";
}
/**
* Update the window title for this view/ui; we expect subclasses
* to override.
*
* @author mlh
*/
protected void updateTitle()
{
// subclasses may override
}
/**
* Subclasses should override to construct the string for the window
* menu's item label corresponding to this window.
*/
protected abstract String buildWindowMenuLabel();
/**
* Update the given lead item if necessary.
*
* @param leadItem the lead menu item to update
* @param position the 0-based index of the item in the Window menu
*/
public void updateLeadItem(MenuItem leadItem, int position)
{
Object itemData = leadItem.getData();
if ((itemData != null) &&
(itemData instanceof RestoreParentControllerLID))
{
RestoreParentControllerLID lid =
(RestoreParentControllerLID) itemData;
if (lid.design != null) {
leadItem.setText(OPEN_DESIGN_LABEL + ": "
+ lid.design.getName());
}
else if (lid.project != null) {
leadItem.setText(OPEN_PROJECT_LABEL + ": "
+ lid.project.getName());
}
}
}
/**
* Updates all "Window" menus based on the current information
* for the associated model object.
* <p>
* Subclasses should override to fix their IWindowMenuData,
* then they should invoke super.updateWindowMenus()
*
* @author mlh
*/
protected void updateWindowMenus()
{
menuData.setEntryLabel(buildWindowMenuLabel());
// The subclass has updated the associated "Window" definition;
// reflect those changes in all "Window" menus.
MenuFactory.updateMenuLabels(menuData, this);
}
/**
* Sets the "always-enabled" widgets;
* call this at the end of the subclass constructor!
* <p>
* All model editing windows support:
* Paste, SaveProject, SaveProjectAs, and CloseWindow
* <p>
* Take this opportunity to interpose a listener when the
* associated SWT window is closed by the user without using
* a CogTool menu item. This listener will also save the window's
* location in case a new window is restored for the associated
* model object.
*
* @author mlh
*/
@Override
protected void setInitiallyEnabled(boolean forConstruction)
{
super.setInitiallyEnabled(forConstruction);
if (undoMgrViewHandler != null) {
undoMgrViewHandler.resetView(undoManager);
}
setEnabled(CogToolLID.Paste,
ListenerIdentifierMap.ALL,
MenuUtil.ENABLED);
setEnabled(CogToolLID.SaveProject,
ListenerIdentifierMap.ALL,
MenuUtil.ENABLED);
setEnabled(CogToolLID.SaveProjectAs,
ListenerIdentifierMap.ALL,
MenuUtil.ENABLED);
setEnabled(CogToolLID.CloseWindow,
ListenerIdentifierMap.ALL,
MenuUtil.ENABLED);
setEnabled(CogToolLID.CloseProject,
ListenerIdentifierMap.ALL,
MenuUtil.ENABLED);
setEnabled(CogToolLID.Properties,
ListenerIdentifierMap.ALL,
MenuUtil.ENABLED);
Shell window = getShell();
if (forConstruction && (window != null)) {
window.removeShellListener(closeListener);
window.addShellListener(closeListener);
}
}
/**
* Fetches the parameters needed by any <code>performAction</code>
* invoked for the "specialized" <code>ListenerIdentifier</code>.
* In some cases, the determination of the parameters requires
* information from the original "general" LID subclass instance
* (see, for example, SEDemoLID).
* <p>
* If the given "general" LID is actually an instance of
* <code>RestoreParentControllerLID</code>, then the request is actually
* to restore the window of either the containing project or design.
*
* May return UNSET if no value computed; it is then the responsibility
* of the subclass to return something valid (i.e., not UNSET).
*
* @param originalLID the general LID value returned from a menu command
* @param transmutedLID the specific value representing an actual,
* concrete application function returned by
* a call to <code>specialize()</code>
* @param isContextSelection true if we should parameterize based on
* the current contextual selection;
* false to use the standard selection
* @return the parameters the <code>IListenerAction</code> may require
* to perform the requested semantic action
* @author mlh
*/
@Override
public Object getParameters(ListenerIdentifier originalLID,
ListenerIdentifier transmutedLID,
boolean isContextSelection)
{
Object parameters = super.getParameters(originalLID,
transmutedLID,
isContextSelection);
if (parameters != UNSET) {
return parameters;
}
if (originalLID instanceof RestoreParentControllerLID) {
return ((RestoreParentControllerLID) originalLID).restoreWindow();
}
return UNSET;
}
/**
* Recover any system resources being used to support the view being
* used by this UI instance.
* <p>
* At this point, we must remove alert handlers and the interposed
* listener on the associated SWT Shell object.
*
* @author mlh
*/
@Override
public void dispose()
{
if (undoManager != null) {
undoManager.removeAllHandlers(this);
}
project.removeAllHandlers(this);
try {
UndoManager.removeSavePointChangeHandler(project,
undoMgrTitleHandler);
}
catch (IllegalStateException ex) {
System.err.println("Ignoring fact that removeSavePointChangeHandler failed.");
}
Shell window = getShell();
CogTool.controllerNexus.saveWindowLocation(project,
getModelObject(),
window.getBounds());
if (window != null) {
if (closeListener != null) {
window.removeShellListener(closeListener);
}
}
super.dispose();
}
/**
* Retrieves a saved window location for the associated model object.
* <p>
* Convenience function for subclasses that passes request through to
* the ControllerNexus.
*
* @param model the model object being edited in the window
* @return the location Rectangle previously saved for this model
*/
public Rectangle getWindowLocation()
{
return CogTool.controllerNexus.getWindowLocation(project,
getModelObject());
}
/**
* Returns a saved window zoom level for a previously-edited model object.
* Recall that the map stores the zoom factor in a <code>Double</code>
* instance.
* <p>
* Convenience function for subclasses that passes request through to
* the ControllerNexus.
*
* @param model the model object being edited in the window
* @return the zoom level previously saved for this model
*/
public double getWindowZoom(Object model)
{
return CogTool.controllerNexus.getWindowZoom(project, model);
}
/**
* Saves a window zoom level associated with a particular model object.
* <p>
* Convenience function for subclasses that passes request through to
* the ControllerNexus.
*
* @param model the model object being edited in the window
* @param loc the zoom level for the window
*/
public void saveWindowZoom(Object model, double zoom)
{
CogTool.controllerNexus.saveWindowZoom(project, model, zoom);
}
/**
* Close the registered open controller for the associated model object.
* Used when the object or an ancestor has been removed from the model.
*
* @author mlh
*/
protected void closeOpenController()
{
// MLH TODO: Be nice if we didn't have to import ControllerRegistry
// because of its interface use of DefaultController!
Controller c =
ControllerRegistry.ONLY.findOpenController(getModelObject());
if (c != null) {
c.dispose();
}
}
}
| UTF-8 | Java | 28,392 | java | DefaultUI.java | Java | [
{
"context": "ml.\n * \n * CLISP version 2.38\n * \n * Copyright (c) Sam Steingold, Bruno Haible 2001-2006\n * This software is distr",
"end": 1570,
"score": 0.999871015548706,
"start": 1557,
"tag": "NAME",
"value": "Sam Steingold"
},
{
"context": "P version 2.38\n * \n * Copyright (... | null | [] | /*******************************************************************************
* CogTool Copyright Notice and Distribution Terms
* CogTool 1.3, Copyright (c) 2005-2013 Carnegie Mellon University
* This software is distributed under the terms of the FSF Lesser
* Gnu Public License (see LGPL.txt).
*
* CogTool is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* CogTool is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CogTool; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* CogTool makes use of several third-party components, with the
* following notices:
*
* Eclipse SWT version 3.448
* Eclipse GEF Draw2D version 3.2.1
*
* Unless otherwise indicated, all Content made available by the Eclipse
* Foundation is provided to you under the terms and conditions of the Eclipse
* Public License Version 1.0 ("EPL"). A copy of the EPL is provided with this
* Content and is also available at http://www.eclipse.org/legal/epl-v10.html.
*
* CLISP version 2.38
*
* Copyright (c) <NAME>, <NAME> 2001-2006
* This software is distributed under the terms of the FSF Gnu Public License.
* See COPYRIGHT file in clisp installation folder for more information.
*
* ACT-R 6.0
*
* Copyright (c) 1998-2007 <NAME>, <NAME>, <NAME> &
* <NAME>.
* This software is distributed under the terms of the FSF Lesser
* Gnu Public License (see LGPL.txt).
*
* Apache Jakarta Commons-Lang 2.1
*
* This product contains software developed by the Apache Software Foundation
* (http://www.apache.org/)
*
* jopt-simple version 1.0
*
* Copyright (c) 2004-2013 <NAME>, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Mozilla XULRunner 1.9.0.5
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (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.mozilla.org/MPL/.
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* The J2SE(TM) Java Runtime Environment version 5.0
*
* Copyright 2009 Sun Microsystems, Inc., 4150
* Network Circle, Santa Clara, California 95054, U.S.A. All
* rights reserved. U.S.
* See the LICENSE file in the jre folder for more information.
******************************************************************************/
package edu.cmu.cs.hcii.cogtool.ui;
import java.util.EventObject;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import edu.cmu.cs.hcii.cogtool.CogTool;
import edu.cmu.cs.hcii.cogtool.CogToolClipboard;
import edu.cmu.cs.hcii.cogtool.CogToolLID;
import edu.cmu.cs.hcii.cogtool.controller.Controller;
import edu.cmu.cs.hcii.cogtool.controller.ControllerRegistry;
import edu.cmu.cs.hcii.cogtool.controller.DesignEditorController;
import edu.cmu.cs.hcii.cogtool.controller.ProjectController;
import edu.cmu.cs.hcii.cogtool.model.Design;
import edu.cmu.cs.hcii.cogtool.model.Project;
import edu.cmu.cs.hcii.cogtool.util.AlertHandler;
import edu.cmu.cs.hcii.cogtool.util.IUndoableEdit;
import edu.cmu.cs.hcii.cogtool.util.L10N;
import edu.cmu.cs.hcii.cogtool.util.ListenerIdentifier;
import edu.cmu.cs.hcii.cogtool.util.ListenerIdentifierMap;
import edu.cmu.cs.hcii.cogtool.util.ManagedText;
import edu.cmu.cs.hcii.cogtool.util.MenuUtil;
import edu.cmu.cs.hcii.cogtool.util.NameChangeAlert;
import edu.cmu.cs.hcii.cogtool.util.UndoManager;
import edu.cmu.cs.hcii.cogtool.util.WindowUtil;
import edu.cmu.cs.hcii.cogtool.util.MenuUtil.MenuItemDefinition;
import edu.cmu.cs.hcii.cogtool.util.MenuUtil.SimpleMenuItemDefinition;
import edu.cmu.cs.hcii.cogtool.view.MenuFactory;
import edu.cmu.cs.hcii.cogtool.view.UndoManagerView;
/**
* Default implementation of UI functionality shared by the views
* for all CogTool model objects.
*
* @author mlh
*/
public abstract class DefaultUI extends UI
implements MenuFactory.ILeadItemUpdater
{
/**
* Specialized listener ID indicating that the window for the
* given project or design should be restored (that is, given the focus
* if it still exists, or re-created otherwise).
* <p>
* Actual restoration occurs in <code>getParameters</code>. The restored
* window is then returned by <code>getParameters</code> in case
* any further semantic action might wish to operate on the window.
* Generally, restoration of the window is all that is expected,
* so controllers do not assign any actions to instances of
* this listener ID subclass.
*
* @author mlh
*/
public static class RestoreParentControllerLID extends ListenerIdentifier
{
public final Project project;
public final Design design; // can be null
/**
* Initialize the ID; if the given design is not <code>null</code>,
* then a <code>DesignEditorController</code> will be restored.
* Otherwise, a <code>ProjectController</code> will be restored.
*
* @param p the project either to restore or as the parent of the
* given design
* @param d the design either to restore or <code>null</code> if
* restoring the project's window
* @author mlh
*/
public RestoreParentControllerLID(Project p, Design d)
{
project = p;
design = d;
}
/**
* Used by <code>getParameters</code> to restore the desired
* window. Returned by <code>getParameters</code> in case
* any further semantic action might wish to operate on the window.
* <p>
* Generally, restoration of the window is all that is expected,
* so controllers do not assign any actions to instances of
* this listener ID subclass.
*
* @return the controller restored
* @author mlh
*/
public Controller restoreWindow()
{
Controller window = null;
// Project controller if design is null
if (design == null) {
boolean notModified;
try {
notModified =
UndoManager.isAtSavePoint(project);
}
catch (IllegalStateException ex) {
System.err.println("Ignoring that isAtSavePoint failed.");
notModified = false;
}
// Presume registered -- registering twice is problematic!
window =
ProjectController.openController(project,
false,
notModified);
}
else {
// Design controller
window =
DesignEditorController.openController(design,
project);
}
return window;
}
}
/**
* All UI subclasses require access to the project that contains
* the model object being edited.
*/
protected Project project;
/**
* Marker string reflecting whether the associated project
* is modified since its last save; suitable for use in constructing
* window titles.
*/
protected String modificationFlag;
/**
* The undo manager itself. Created in the controller, held onto here.
* Mostly used for the connection to the undoManagerview.
*/
protected UndoManager undoManager; // needed in dispose
protected UndoManagerView.UndoAlertHandler undoMgrViewHandler;
/**
* Delegates closing a window to performAction in the corresponding
* Controller object.
*/
protected ShellAdapter closeListener = new ShellAdapter()
{
/**
* Handler for shellClosed -- delegates to performAction
*/
@Override
public void shellClosed(ShellEvent e)
{
CogTool.controllerNexus.saveWindowLocation(project,
getModelObject(),
getShell().getBounds());
/**
* Don't let other listeners progress if save canceled.
*/
e.doit = performAction(CogToolLID.CloseWindow, null, false);
}
};;
/**
* Definition of the "Window" menu for this window.
*/
protected MenuFactory.IWindowMenuData<Project> menuData = null;
/**
* How to react to alerts raised when save points change in any undo
* manager. Updates the window titles, reflecting modification status.
* TODO: Should we reflect modification status in "Window" menu entries?
* If so, do here!
*/
protected AlertHandler undoMgrTitleHandler =
new AlertHandler() {
public void handleAlert(EventObject evt)
{
UndoManager.SavePointChange chg =
(UndoManager.SavePointChange) evt;
updateModificationFlag(chg.nowAtSavePoint);
updateTitle();
}
};
/**
* How to react to alerts that a model object has been renamed.
* Updates window titles and "Window" menu entries.
*/
protected AlertHandler renameHandler =
new AlertHandler() {
public void handleAlert(EventObject evt)
{
updateTitle();
updateWindowMenus();
}
};
protected static final String OPEN_PROJECT_LABEL =
L10N.get("MI.OpenProject", "Display Project");
protected static final String OPEN_DESIGN_LABEL =
L10N.get("MI.OpenDesign", "Display Design");
/**
* Support for creating the lead items for the Window menu.
*
* @param p the project either to restore or as the parent of the
* given design
* @param d the design either to restore or <code>null</code> if
* restoring the project's window
* @author mlh
*/
protected static MenuItemDefinition[] buildLeadItems(Project p, Design d)
{
ListenerIdentifier openProjectLID = null;
ListenerIdentifier openDesignLID = null;
boolean openProjectEnabled = MenuUtil.DISABLED;
boolean openDesignEnabled = MenuUtil.DISABLED;
String openProjectLabel = OPEN_PROJECT_LABEL;
String openDesignLabel = OPEN_DESIGN_LABEL;
// Check to create standard LID's for opening design & project
if (p != null) {
openProjectLID = new RestoreParentControllerLID(p, null);
openProjectEnabled = MenuUtil.ENABLED;
openProjectLabel = openProjectLabel + ": " + p.getName();
if (d != null) {
openDesignLID = new RestoreParentControllerLID(p, d);
openDesignEnabled = MenuUtil.ENABLED;
openDesignLabel = openDesignLabel + ": " + d.getName();
}
}
return new MenuItemDefinition[]
{ new SimpleMenuItemDefinition(openProjectLabel,
openProjectLID,
openProjectEnabled),
new SimpleMenuItemDefinition(openDesignLabel,
openDesignLID,
openDesignEnabled),
MenuUtil.SEPARATOR };
}
// Suitable for a Design window
protected static MenuItemDefinition[] buildLeadItems(Project p)
{
return buildLeadItems(p, null);
}
// Suitable for a Project window
protected static MenuItemDefinition[] buildLeadItems()
{
return buildLeadItems(null, null);
}
/**
* All CogTool model editing views keep track of the <code>Project</code>
* instance that contains (or is) the model object being edited.
*
* @param proj the Project instance that is or contains the model
* object being edited
* @param windowMenuLabel the label for this window's entry in the
* window menu
* @param leadItems the lead menu items for the window menu of this window
* @author mlh
*/
public DefaultUI(Project proj,
String windowMenuLabel,
MenuItemDefinition[] leadItems,
UndoManager undoMgr)
{
super();
project = proj;
// Manage current project modification state and future changes
// to that state and model object names.
if (project != null) {
try {
updateModificationFlag(UndoManager.isAtSavePoint(project));
}
catch (IllegalStateException ex) {
System.err.println("Ignoring that isAtSavePoint failed.");
updateModificationFlag(false);
}
project.addHandler(this,
NameChangeAlert.class,
renameHandler);
try {
UndoManager.addSavePointChangeHandler(project,
undoMgrTitleHandler);
}
catch (IllegalStateException ex) {
System.err.println("Ignoring fact that addSavePointChangeHandler failed.");
}
}
undoManager = undoMgr;
// Create the undo manager view handler,
// resetting the undo view handler to represent any values currently in
// the undo manager. IE: remember undo.
if (undoManager != null) {
undoMgrViewHandler =
new UndoManagerView.UndoAlertHandler(undoManager,
lIDMap,
CogToolLID.Undo,
CogToolLID.Redo);
undoManager.addHandler(this,
UndoManager.UndoRedoEvent.class,
undoMgrViewHandler);
}
menuData = new DefaultWindowMenuData(this,
windowMenuLabel,
leadItems);
}
/**
* Return the UI's Project instance
*/
public Project getProject()
{
return project;
}
@Override
protected int canIDCauseSelection(ListenerIdentifier lid)
{
if (undoManager != null) {
IUndoableEdit edit = null;
if (lid == CogToolLID.Undo) {
edit = undoManager.editToBeUndone();
}
else if (lid == CogToolLID.Redo) {
edit = undoManager.editToBeRedone();
}
if (edit != null) {
lid = edit.getLID();
}
// else not undo/redo; query lid directly
}
return super.canIDCauseSelection(lid);
}
@Override
protected boolean doesIDCommitChanges(ListenerIdentifier lid)
{
if (undoManager != null) {
if (lid == CogToolLID.Undo) {
return idCommitsChanges(undoManager.editToBeUndone().getLID());
}
if (lid == CogToolLID.Redo) {
return idCommitsChanges(undoManager.editToBeRedone().getLID());
}
}
if (lid == CogToolLID.Paste) {
return CogToolClipboard.hasNonTextPasteContent();
}
// Not undo/redo; query lid directly
return super.doesIDCommitChanges(lid);
}
protected static final String operationCanceled =
L10N.get("DEFINT.OperationCanceled",
"The requested operation was canceled due to the following error:");
@Override
public boolean performAction(ListenerIdentifier id)
{
if ((undoManager != null) && doesIDCommitChanges(id)) {
Text textWithFocus = WindowUtil.getFocusedText();
if (textWithFocus != null) {
if (textWithFocus instanceof ManagedText) {
ManagedText performText = (ManagedText) textWithFocus;
if (! performText.confirm(ManagedText.LOSE_FOCUS)) {
getStandardInteraction().setStatusMessage(operationCanceled);
return false;
}
}
}
}
return super.performAction(id);
}
/**
* Return the primary model object this view/ui is responsible for
* editing.
*
* @return the primary model object this view/ui is responsible for
* editing
* @author mlh
*/
protected abstract Object getModelObject();
/**
* Based on the given modification state, recompute the modification
* marker string used in window titles.
*
* @param atSavePoint true if modification state means "saved";
* false if the associated project or any of its
* components were modified since the last save
* @author mlh
*/
protected void updateModificationFlag(boolean atSavePoint)
{
modificationFlag = atSavePoint ? "" : "* ";
}
/**
* Update the window title for this view/ui; we expect subclasses
* to override.
*
* @author mlh
*/
protected void updateTitle()
{
// subclasses may override
}
/**
* Subclasses should override to construct the string for the window
* menu's item label corresponding to this window.
*/
protected abstract String buildWindowMenuLabel();
/**
* Update the given lead item if necessary.
*
* @param leadItem the lead menu item to update
* @param position the 0-based index of the item in the Window menu
*/
public void updateLeadItem(MenuItem leadItem, int position)
{
Object itemData = leadItem.getData();
if ((itemData != null) &&
(itemData instanceof RestoreParentControllerLID))
{
RestoreParentControllerLID lid =
(RestoreParentControllerLID) itemData;
if (lid.design != null) {
leadItem.setText(OPEN_DESIGN_LABEL + ": "
+ lid.design.getName());
}
else if (lid.project != null) {
leadItem.setText(OPEN_PROJECT_LABEL + ": "
+ lid.project.getName());
}
}
}
/**
* Updates all "Window" menus based on the current information
* for the associated model object.
* <p>
* Subclasses should override to fix their IWindowMenuData,
* then they should invoke super.updateWindowMenus()
*
* @author mlh
*/
protected void updateWindowMenus()
{
menuData.setEntryLabel(buildWindowMenuLabel());
// The subclass has updated the associated "Window" definition;
// reflect those changes in all "Window" menus.
MenuFactory.updateMenuLabels(menuData, this);
}
/**
* Sets the "always-enabled" widgets;
* call this at the end of the subclass constructor!
* <p>
* All model editing windows support:
* Paste, SaveProject, SaveProjectAs, and CloseWindow
* <p>
* Take this opportunity to interpose a listener when the
* associated SWT window is closed by the user without using
* a CogTool menu item. This listener will also save the window's
* location in case a new window is restored for the associated
* model object.
*
* @author mlh
*/
@Override
protected void setInitiallyEnabled(boolean forConstruction)
{
super.setInitiallyEnabled(forConstruction);
if (undoMgrViewHandler != null) {
undoMgrViewHandler.resetView(undoManager);
}
setEnabled(CogToolLID.Paste,
ListenerIdentifierMap.ALL,
MenuUtil.ENABLED);
setEnabled(CogToolLID.SaveProject,
ListenerIdentifierMap.ALL,
MenuUtil.ENABLED);
setEnabled(CogToolLID.SaveProjectAs,
ListenerIdentifierMap.ALL,
MenuUtil.ENABLED);
setEnabled(CogToolLID.CloseWindow,
ListenerIdentifierMap.ALL,
MenuUtil.ENABLED);
setEnabled(CogToolLID.CloseProject,
ListenerIdentifierMap.ALL,
MenuUtil.ENABLED);
setEnabled(CogToolLID.Properties,
ListenerIdentifierMap.ALL,
MenuUtil.ENABLED);
Shell window = getShell();
if (forConstruction && (window != null)) {
window.removeShellListener(closeListener);
window.addShellListener(closeListener);
}
}
/**
* Fetches the parameters needed by any <code>performAction</code>
* invoked for the "specialized" <code>ListenerIdentifier</code>.
* In some cases, the determination of the parameters requires
* information from the original "general" LID subclass instance
* (see, for example, SEDemoLID).
* <p>
* If the given "general" LID is actually an instance of
* <code>RestoreParentControllerLID</code>, then the request is actually
* to restore the window of either the containing project or design.
*
* May return UNSET if no value computed; it is then the responsibility
* of the subclass to return something valid (i.e., not UNSET).
*
* @param originalLID the general LID value returned from a menu command
* @param transmutedLID the specific value representing an actual,
* concrete application function returned by
* a call to <code>specialize()</code>
* @param isContextSelection true if we should parameterize based on
* the current contextual selection;
* false to use the standard selection
* @return the parameters the <code>IListenerAction</code> may require
* to perform the requested semantic action
* @author mlh
*/
@Override
public Object getParameters(ListenerIdentifier originalLID,
ListenerIdentifier transmutedLID,
boolean isContextSelection)
{
Object parameters = super.getParameters(originalLID,
transmutedLID,
isContextSelection);
if (parameters != UNSET) {
return parameters;
}
if (originalLID instanceof RestoreParentControllerLID) {
return ((RestoreParentControllerLID) originalLID).restoreWindow();
}
return UNSET;
}
/**
* Recover any system resources being used to support the view being
* used by this UI instance.
* <p>
* At this point, we must remove alert handlers and the interposed
* listener on the associated SWT Shell object.
*
* @author mlh
*/
@Override
public void dispose()
{
if (undoManager != null) {
undoManager.removeAllHandlers(this);
}
project.removeAllHandlers(this);
try {
UndoManager.removeSavePointChangeHandler(project,
undoMgrTitleHandler);
}
catch (IllegalStateException ex) {
System.err.println("Ignoring fact that removeSavePointChangeHandler failed.");
}
Shell window = getShell();
CogTool.controllerNexus.saveWindowLocation(project,
getModelObject(),
window.getBounds());
if (window != null) {
if (closeListener != null) {
window.removeShellListener(closeListener);
}
}
super.dispose();
}
/**
* Retrieves a saved window location for the associated model object.
* <p>
* Convenience function for subclasses that passes request through to
* the ControllerNexus.
*
* @param model the model object being edited in the window
* @return the location Rectangle previously saved for this model
*/
public Rectangle getWindowLocation()
{
return CogTool.controllerNexus.getWindowLocation(project,
getModelObject());
}
/**
* Returns a saved window zoom level for a previously-edited model object.
* Recall that the map stores the zoom factor in a <code>Double</code>
* instance.
* <p>
* Convenience function for subclasses that passes request through to
* the ControllerNexus.
*
* @param model the model object being edited in the window
* @return the zoom level previously saved for this model
*/
public double getWindowZoom(Object model)
{
return CogTool.controllerNexus.getWindowZoom(project, model);
}
/**
* Saves a window zoom level associated with a particular model object.
* <p>
* Convenience function for subclasses that passes request through to
* the ControllerNexus.
*
* @param model the model object being edited in the window
* @param loc the zoom level for the window
*/
public void saveWindowZoom(Object model, double zoom)
{
CogTool.controllerNexus.saveWindowZoom(project, model, zoom);
}
/**
* Close the registered open controller for the associated model object.
* Used when the object or an ancestor has been removed from the model.
*
* @author mlh
*/
protected void closeOpenController()
{
// MLH TODO: Be nice if we didn't have to import ControllerRegistry
// because of its interface use of DefaultController!
Controller c =
ControllerRegistry.ONLY.findOpenController(getModelObject());
if (c != null) {
c.dispose();
}
}
}
| 28,342 | 0.599429 | 0.595942 | 793 | 34.80328 | 27.107866 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.359395 | false | false | 3 |
7dbf8119dc30c39d899997b57b9d74e02dbbe879 | 38,019,050,513,961 | 4cda0167e50f192c88b7dfebbfb8af920d37f57d | /src/main/java/com/trekiz/admin/modules/hotel/input/PriceDifferenceInput.java | c8f5f7bc298556b6a4c03a8bfbb51ce639c98daa | [] | no_license | cckmit/CustomerInfo | https://github.com/cckmit/CustomerInfo | 1e7e685a8f96ba56af7e4e624b1ec23029682e85 | 15ee744e47236557ed33d24ced09b6b5f37f9a9c | refs/heads/master | 2023-03-15T10:09:47.938000 | 2017-08-17T05:57:46 | 2017-08-17T06:23:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.trekiz.admin.modules.hotel.input;
/**
* 单房差类
* @author wangxv
*
*/
public class PriceDifferenceInput {
private String price;
private UnitInput unit;
private CurrencyInput currency;
/*private String currency;// UUID
private String currencyText;// 币种符号
private String unit;// 单房差单位id
private String unitText;// 名称
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getCurrencyText() {
return currencyText;
}
public void setCurrencyText(String currencyText) {
this.currencyText = currencyText;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public String getUnitText() {
return unitText;
}
public void setUnitText(String unitText) {
this.unitText = unitText;
}*/
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public UnitInput getUnit() {
return unit;
}
public void setUnit(UnitInput unit) {
this.unit = unit;
}
public CurrencyInput getCurrency() {
return currency;
}
public void setCurrency(CurrencyInput currency) {
this.currency = currency;
}
}
| UTF-8 | Java | 1,255 | java | PriceDifferenceInput.java | Java | [
{
"context": ".admin.modules.hotel.input;\n/**\n * 单房差类\n * @author wangxv\n *\n */\npublic class PriceDifferenceInput {\n\t\n\t\n\tp",
"end": 75,
"score": 0.9996614456176758,
"start": 69,
"tag": "USERNAME",
"value": "wangxv"
}
] | null | [] | package com.trekiz.admin.modules.hotel.input;
/**
* 单房差类
* @author wangxv
*
*/
public class PriceDifferenceInput {
private String price;
private UnitInput unit;
private CurrencyInput currency;
/*private String currency;// UUID
private String currencyText;// 币种符号
private String unit;// 单房差单位id
private String unitText;// 名称
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getCurrencyText() {
return currencyText;
}
public void setCurrencyText(String currencyText) {
this.currencyText = currencyText;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public String getUnitText() {
return unitText;
}
public void setUnitText(String unitText) {
this.unitText = unitText;
}*/
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public UnitInput getUnit() {
return unit;
}
public void setUnit(UnitInput unit) {
this.unit = unit;
}
public CurrencyInput getCurrency() {
return currency;
}
public void setCurrency(CurrencyInput currency) {
this.currency = currency;
}
}
| 1,255 | 0.713469 | 0.713469 | 63 | 18.444445 | 15.278138 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.444444 | false | false | 3 |
36e694868b84deee158582e8d5340341a062f637 | 36,627,481,121,544 | 2deb74d5bf569bdbe637846d93fac47c01b278a4 | /android/util/Xml.java | abf25bc6f91e259a1873c03e574a6c74f6b5fb2e | [] | no_license | isabella232/android-sdk-sources-for-api-level-11 | https://github.com/isabella232/android-sdk-sources-for-api-level-11 | 8aefeff38cbc0bbe7cfbbd04a940f8c4aa319772 | d772b816a1e388a5f8022d4bc47adc9016195600 | refs/heads/master | 2023-03-16T14:08:07.661000 | 2015-07-03T11:17:32 | 2015-07-03T11:17:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* */ package android.util;
/* */
/* */ import java.io.IOException;
/* */ import java.io.InputStream;
/* */ import java.io.Reader;
/* */ import java.io.UnsupportedEncodingException;
/* */ import org.xml.sax.ContentHandler;
/* */ import org.xml.sax.SAXException;
/* */ import org.xmlpull.v1.XmlPullParser;
/* */ import org.xmlpull.v1.XmlSerializer;
/* */
/* */ public class Xml
/* */ {
/* */ public static String FEATURE_RELAXED;
/* */
/* */ public Xml()
/* */ {
/* 11 */ throw new RuntimeException("Stub!"); }
/* 12 */ public static void parse(String xml, ContentHandler contentHandler) throws SAXException { throw new RuntimeException("Stub!"); }
/* 13 */ public static void parse(Reader in, ContentHandler contentHandler) throws IOException, SAXException { throw new RuntimeException("Stub!"); }
/* 14 */ public static void parse(InputStream in, Encoding encoding, ContentHandler contentHandler) throws IOException, SAXException { throw new RuntimeException("Stub!"); }
/* 15 */ public static XmlPullParser newPullParser() { throw new RuntimeException("Stub!"); }
/* 16 */ public static XmlSerializer newSerializer() { throw new RuntimeException("Stub!"); }
/* 17 */ public static Encoding findEncodingByName(String encodingName) throws UnsupportedEncodingException { throw new RuntimeException("Stub!"); }
/* 18 */ public static AttributeSet asAttributeSet(XmlPullParser parser) { throw new RuntimeException("Stub!");
/* */ }
/* */
/* */ public static enum Encoding
/* */ {
/* 6 */ ISO_8859_1,
/* 7 */ US_ASCII,
/* 8 */ UTF_16,
/* 9 */ UTF_8;
/* */ }
/* */ }
/* Location: D:\xyh\Android_3.0\android.jar
* Qualified Name: android.util.Xml
* JD-Core Version: 0.6.0
*/ | UTF-8 | Java | 1,824 | java | Xml.java | Java | [] | null | [] | /* */ package android.util;
/* */
/* */ import java.io.IOException;
/* */ import java.io.InputStream;
/* */ import java.io.Reader;
/* */ import java.io.UnsupportedEncodingException;
/* */ import org.xml.sax.ContentHandler;
/* */ import org.xml.sax.SAXException;
/* */ import org.xmlpull.v1.XmlPullParser;
/* */ import org.xmlpull.v1.XmlSerializer;
/* */
/* */ public class Xml
/* */ {
/* */ public static String FEATURE_RELAXED;
/* */
/* */ public Xml()
/* */ {
/* 11 */ throw new RuntimeException("Stub!"); }
/* 12 */ public static void parse(String xml, ContentHandler contentHandler) throws SAXException { throw new RuntimeException("Stub!"); }
/* 13 */ public static void parse(Reader in, ContentHandler contentHandler) throws IOException, SAXException { throw new RuntimeException("Stub!"); }
/* 14 */ public static void parse(InputStream in, Encoding encoding, ContentHandler contentHandler) throws IOException, SAXException { throw new RuntimeException("Stub!"); }
/* 15 */ public static XmlPullParser newPullParser() { throw new RuntimeException("Stub!"); }
/* 16 */ public static XmlSerializer newSerializer() { throw new RuntimeException("Stub!"); }
/* 17 */ public static Encoding findEncodingByName(String encodingName) throws UnsupportedEncodingException { throw new RuntimeException("Stub!"); }
/* 18 */ public static AttributeSet asAttributeSet(XmlPullParser parser) { throw new RuntimeException("Stub!");
/* */ }
/* */
/* */ public static enum Encoding
/* */ {
/* 6 */ ISO_8859_1,
/* 7 */ US_ASCII,
/* 8 */ UTF_16,
/* 9 */ UTF_8;
/* */ }
/* */ }
/* Location: D:\xyh\Android_3.0\android.jar
* Qualified Name: android.util.Xml
* JD-Core Version: 0.6.0
*/ | 1,824 | 0.632127 | 0.612939 | 40 | 44.625 | 44.343369 | 176 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7 | false | false | 3 |
9b8cac19badab3a9986dc24721097a613a512e4a | 20,014,547,639,165 | 01a23639a4edfe7ffb5330894d553de52368debe | /src/main/java/com/finlabs/finexa/service/FinexaSubscriptionService.java | 61ea6ad7946ad6458e4a45a4d4fae0b1fb1ba9d2 | [] | no_license | kaustubh-walokar/ClientService | https://github.com/kaustubh-walokar/ClientService | 47943e419482524127abf536f7a293cffb9af90d | 579d8fc89b1df1f1101a75f98c92f6e5cf08f0de | refs/heads/master | 2021-05-24T16:36:28.919000 | 2020-02-28T12:53:43 | 2020-02-28T12:53:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.finlabs.finexa.service;
import java.util.List;
import com.finlabs.finexa.dto.FinexaSubscriptionDTO;
public interface FinexaSubscriptionService {
public FinexaSubscriptionDTO save(FinexaSubscriptionDTO finexaSubscriptionDTO) throws RuntimeException;
List<FinexaSubscriptionDTO> getAllSubscriptionByAdvisor(int advisorId) throws RuntimeException;
public FinexaSubscriptionDTO getSubscriptionById(int subId) throws RuntimeException;
}
| UTF-8 | Java | 470 | java | FinexaSubscriptionService.java | Java | [] | null | [] | package com.finlabs.finexa.service;
import java.util.List;
import com.finlabs.finexa.dto.FinexaSubscriptionDTO;
public interface FinexaSubscriptionService {
public FinexaSubscriptionDTO save(FinexaSubscriptionDTO finexaSubscriptionDTO) throws RuntimeException;
List<FinexaSubscriptionDTO> getAllSubscriptionByAdvisor(int advisorId) throws RuntimeException;
public FinexaSubscriptionDTO getSubscriptionById(int subId) throws RuntimeException;
}
| 470 | 0.831915 | 0.831915 | 15 | 29.333334 | 37.149548 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 3 |
02d478c3d75d984e4de8f2f8af5dffedc900bf38 | 4,011,499,469,797 | 6eb65d37e01aa1ab1515a82ce246996262479e41 | /CJ_30_Incapsulamento_e_ereditarieta/src/I_e_E.java | 067cd8d660b7ed49016e551f29dc458d3855595e | [] | no_license | rootan/CJ | https://github.com/rootan/CJ | bf13812c26c34ed75cde5d58bf933614250a7129 | 6e15909aec4b5b1d51f8895777861bddac103083 | refs/heads/master | 2019-05-26T16:56:08.467000 | 2017-07-01T11:52:45 | 2017-07-01T11:52:45 | 84,651,299 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**7 marzo 2017
* Che cosa provoca l'utilizzo combianto sia dell'incapsulamento che dell'ereditarietà?
*
* Ovvero cosa si eredita da una classe incapsulata?
* *estendere una classe significa ereditarne i membri non privati
* *quindi gli attributi privati della superclasse non si erediteranno
* *ma i metodi set e get che lavorano su questi attributi si essendo loro
* dichiarati public
* Concludendo anche se una classe ereditata non possiede esplicitamente le variabili
* private della superclasse, può comunque usufruirne tramite l'incapsulamento. In
* pratica è come se le possedesse.
*
* Quindi non è necessario dichiarare una variabile protected per ereditarla nelle
* sottoclassi. Anzi dichiarare una variabile d'istanza protetta protetta significa
* renderla pubblica a tutte le classi dello stesso package (e quindi non sarà
* veramente incapsulata).
*/
public class I_e_E
{
public static void main(String[] args)
{
System.out.println("Incapsualmento usato assieme all'ereditarietà.");
}
}
| UTF-8 | Java | 1,060 | java | I_e_E.java | Java | [] | null | [] | /**7 marzo 2017
* Che cosa provoca l'utilizzo combianto sia dell'incapsulamento che dell'ereditarietà?
*
* Ovvero cosa si eredita da una classe incapsulata?
* *estendere una classe significa ereditarne i membri non privati
* *quindi gli attributi privati della superclasse non si erediteranno
* *ma i metodi set e get che lavorano su questi attributi si essendo loro
* dichiarati public
* Concludendo anche se una classe ereditata non possiede esplicitamente le variabili
* private della superclasse, può comunque usufruirne tramite l'incapsulamento. In
* pratica è come se le possedesse.
*
* Quindi non è necessario dichiarare una variabile protected per ereditarla nelle
* sottoclassi. Anzi dichiarare una variabile d'istanza protetta protetta significa
* renderla pubblica a tutte le classi dello stesso package (e quindi non sarà
* veramente incapsulata).
*/
public class I_e_E
{
public static void main(String[] args)
{
System.out.println("Incapsualmento usato assieme all'ereditarietà.");
}
}
| 1,060 | 0.755218 | 0.750474 | 25 | 41.16 | 34.309975 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.28 | false | false | 3 |
e8881aa9ed8d5ff94b7dab2c62f74b071a022ba2 | 5,566,277,624,423 | 7f3d2a07b2615843e2dadb9966f9b3995f22a9e6 | /src/org/smram/stats/LongSummaryStats.java | eaebd49eff9d86957e8c9ed59e952d8e5d0fbca8 | [] | no_license | smram/range-partition | https://github.com/smram/range-partition | 25dc8cd908895f0cf03c9d93a01d50a250e57b16 | 2fdae8fae3ca4a8e4b776fb94346d0e08081fc8c | refs/heads/master | 2021-01-20T07:48:57.485000 | 2015-06-21T22:57:58 | 2015-06-21T22:57:58 | 37,426,994 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.smram.stats;
/**
* Running Statistics for long objects.
*
* This class is not thread-safe because the update() method is not synchronized
*
* This is my test implementation; normally Apache Commons Math has one I'd use
* @author smram
*/
public class LongSummaryStats {
//public final static double FP_COMPARE_EPSILON = 1e-6;
private long num;
private double mean;
private double moment2;
private long min;
private long max;
public LongSummaryStats() {
clear();
}
public void update(long val)
{
num++;
double oldMean = mean;
// I could compute mean after moment2 and avoid caching oldMean, but
// this code is clearer to me...
// Also: Apache Math initializes mean specially (mean=x_1) for first
// data point... mathematically with oldMean=0 and num=1 its the same.
// but perhaps Apache Math avoids loss of precision due to div by 1.0?
// TODO test it
// computing mean by maintaining sum: sum may overflow. Do this instead
mean += (val - oldMean)/((double)num);
// John Cook's blog uses mean_now and mean_{now-1}. See Apache Math code
// for equivalent formula using mean_{now-1} which I found simpler
moment2 += (val - oldMean)*(val - oldMean)*(num-1)/(double)num;
if (val < min)
min = val;
if (val > max)
max = val;
}
public long getNumPoints() {
return num;
}
public double getMean() {
return mean;
}
/**
* References:
* http://www.johndcook.com/blog/2008/09/26/comparing-three-methods-of-computing-standard-deviation/
*
* Apache Commons Math uses this implementation too, see source of
* org/apache/commons/math3/stat/descriptive/moment/SecondMoment.html
* org/apache/commons/math3/stat/descriptive/moment/Variance.html
* org/apache/commons/math3/stat/descriptive/SummaryStatistics.html
*
* @return bias-corrected variance
*/
public double getVar() {
return moment2/((double)(getNumPoints()-1));
// this obvious impl can have severe loss of precision when data points
// are large and their variance is small
// See http://www.johndcook.com/blog/standard_deviation/
//return (sum*sum - sumSq)/((double)(num - 1));
}
public long getMin() {
return min;
}
public long getMax() {
return max;
}
/**
* Resets internal state to start state
*/
public void clear() {
num = 0;
mean = 0;
moment2 = 0;
max = Long.MIN_VALUE;
min = Long.MAX_VALUE;
}
@Override
public String toString()
{
return String.format("num=%d, avg=%f, sd=%f, min=%d, max=%d",
getNumPoints(), getMean(), Math.sqrt(getVar()), getMin(), getMax());
}
} | UTF-8 | Java | 2,600 | java | LongSummaryStats.java | Java | [
{
"context": "lly Apache Commons Math has one I'd use\n * @author smram\n */\npublic class LongSummaryStats {\n\t//public fin",
"end": 255,
"score": 0.9995385408401489,
"start": 250,
"tag": "USERNAME",
"value": "smram"
}
] | null | [] | package org.smram.stats;
/**
* Running Statistics for long objects.
*
* This class is not thread-safe because the update() method is not synchronized
*
* This is my test implementation; normally Apache Commons Math has one I'd use
* @author smram
*/
public class LongSummaryStats {
//public final static double FP_COMPARE_EPSILON = 1e-6;
private long num;
private double mean;
private double moment2;
private long min;
private long max;
public LongSummaryStats() {
clear();
}
public void update(long val)
{
num++;
double oldMean = mean;
// I could compute mean after moment2 and avoid caching oldMean, but
// this code is clearer to me...
// Also: Apache Math initializes mean specially (mean=x_1) for first
// data point... mathematically with oldMean=0 and num=1 its the same.
// but perhaps Apache Math avoids loss of precision due to div by 1.0?
// TODO test it
// computing mean by maintaining sum: sum may overflow. Do this instead
mean += (val - oldMean)/((double)num);
// John Cook's blog uses mean_now and mean_{now-1}. See Apache Math code
// for equivalent formula using mean_{now-1} which I found simpler
moment2 += (val - oldMean)*(val - oldMean)*(num-1)/(double)num;
if (val < min)
min = val;
if (val > max)
max = val;
}
public long getNumPoints() {
return num;
}
public double getMean() {
return mean;
}
/**
* References:
* http://www.johndcook.com/blog/2008/09/26/comparing-three-methods-of-computing-standard-deviation/
*
* Apache Commons Math uses this implementation too, see source of
* org/apache/commons/math3/stat/descriptive/moment/SecondMoment.html
* org/apache/commons/math3/stat/descriptive/moment/Variance.html
* org/apache/commons/math3/stat/descriptive/SummaryStatistics.html
*
* @return bias-corrected variance
*/
public double getVar() {
return moment2/((double)(getNumPoints()-1));
// this obvious impl can have severe loss of precision when data points
// are large and their variance is small
// See http://www.johndcook.com/blog/standard_deviation/
//return (sum*sum - sumSq)/((double)(num - 1));
}
public long getMin() {
return min;
}
public long getMax() {
return max;
}
/**
* Resets internal state to start state
*/
public void clear() {
num = 0;
mean = 0;
moment2 = 0;
max = Long.MIN_VALUE;
min = Long.MAX_VALUE;
}
@Override
public String toString()
{
return String.format("num=%d, avg=%f, sd=%f, min=%d, max=%d",
getNumPoints(), getMean(), Math.sqrt(getVar()), getMin(), getMax());
}
} | 2,600 | 0.675769 | 0.663846 | 101 | 24.752476 | 25.970816 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.683168 | false | false | 3 |
b079e1b304c06ea8d4564c6afa2ea16736667f8e | 5,566,277,623,391 | 38a535b02821443773cbb778b501fd1eff9538ee | /JDBC/src/Connect.java | 1cfc775989db6ffaaa3df59e66eba8a6d6f8720c | [] | no_license | V-Modder/DbiBenchmark | https://github.com/V-Modder/DbiBenchmark | 2570ea930fffd545bc1de50666a9fdaf2336b70e | e10fa0bc83a63c8c7ae85ed5d62c9edb32c28593 | refs/heads/master | 2016-09-10T03:17:04.929000 | 2013-12-19T18:14:03 | 2013-12-19T18:14:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Random;
import java.util.Scanner;
public class Connect
{
public static void delete_tables(java.sql.Statement stmt) throws SQLException
{
stmt.execute("TRUNCATE TABLE history");
stmt.execute("SET FOREIGN_KEY_CHECKS = 0;");
stmt.execute("SET UNIQUE_CHECKS = 0;");
stmt.execute("SET sql_log_bin = 0");
}
public static int Kontostand_TX(java.sql.Statement stmt, int ACCID) throws SQLException
{
ResultSet rs = stmt.executeQuery("select balance from accounts where accid="+ACCID+";");
rs.first();
return rs.getInt(1);
}
public static int Einzahlungs_TX(java.sql.Statement stmt, int ACCID, int TELLERID, int BRANCHID, int DELTA) throws SQLException
{
//stmt.executeUpdate("update branches set balance=balance+"+DELTA+" where branchid="+BRANCHID+";");
//stmt.executeUpdate("update tellers set balance=balance+"+DELTA+" where tellerid="+TELLERID+";");
//stmt.executeUpdate("update accounts set balance=balance+"+DELTA+" where accid="+ACCID+";");
//DBMS^
//ResultSet rs = stmt.executeQuery("select balance from accounts where accid="+ACCID+";");
//rs.first();
//int newbalance = rs.getInt(1) + DELTA;
//stmt.executeUpdate("insert into history values ("+ ACCID +","+ TELLERID +","+ DELTA +","+ BRANCHID +","+ newbalance +",'Einzahlung')");
//return newbalance;
//stmt.setQueryTimeout(998493834);
stmt.execute("CALL Einzahlungs_TX("+ACCID+","+TELLERID+","+BRANCHID+","+DELTA+");");
return 0;
}
public static int Analyse_TX(java.sql.Statement stmt, int DELTA) throws SQLException
{
ResultSet rs = stmt.executeQuery("select count(accid) from benchmark.history where delta="+ DELTA +";");
rs.first();
return rs.getInt(1);
}
private static int rand()
{
Random rnd = new Random();
int x = rnd.nextInt(100) + 1;
if(x<= 50)
return 1;
if(x<=85)
return 2;
return 3;
}
public static void main(String[] args) throws SQLException
{
int iTxCount = 0;
int iPercent = 0;
long tnow, tend, tbeg;
java.sql.Statement stmt = null;
Scanner scr = new Scanner(System.in);
final int iGesamtZeit = 60000;
final int iEinschwingZeit = 24000;
final int iAusschwingZeit = 54000;
String user = "dbi";
String pass = "janbe2013";
String DB = "benchmark";
System.out.print("DB-Server: ");
String ConnectionName = "jdbc:mysql://"+scr.nextLine()+"/" + DB;
scr.close();
Connection con = DriverManager.getConnection(ConnectionName, user, pass);
stmt = con.createStatement();
//Commit der Datenbank erst am Ende der Operationen
//con.setAutoCommit(false);
//create_table(stmt);
delete_tables(stmt);
Random r = new Random();
System.out.print("|1%_____________________50%____________________100%|\n|");
tend = System.currentTimeMillis() + iGesamtZeit;
tnow = System.currentTimeMillis();
tbeg = tnow;
while(tnow < tend )
{
tnow = System.currentTimeMillis();
switch(rand())
{
case 1:
Kontostand_TX(stmt, r.nextInt(10000)+1);
break;
case 2:
Einzahlungs_TX(stmt, r.nextInt(10000)+1, r.nextInt(10000)+1, r.nextInt(10000)+1, r.nextInt(10000)+1);
break;
case 3:
Analyse_TX(stmt, r.nextInt(10000)+1);
break;
}
if((tnow - tbeg) > iEinschwingZeit && (tnow - tbeg) < iAusschwingZeit)
iTxCount++;
int xx = (iGesamtZeit - (int)(tend-tnow))*100/iGesamtZeit;
if(xx > iPercent)
{
if(xx%2 == 0)
System.out.print("=");
iPercent = xx;
}
try {
Thread.sleep(50);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("|\n\n");
System.out.println("Tx : " + iTxCount);
System.out.println("TxPS: "+ (double)((double)iTxCount/((double)(iAusschwingZeit-iEinschwingZeit)/1000)));
stmt.close();
con.close();
}
}
| UTF-8 | Java | 3,882 | java | Connect.java | Java | [
{
"context": "nal int iAusschwingZeit = 54000;\n\t\tString user = \"dbi\";\n\t\tString pass = \"janbe2013\";\n\t\tString DB = \"ben",
"end": 2309,
"score": 0.9993272423744202,
"start": 2306,
"tag": "USERNAME",
"value": "dbi"
},
{
"context": " = 54000;\n\t\tString user = \"dbi\";\n\t\... | null | [] | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Random;
import java.util.Scanner;
public class Connect
{
public static void delete_tables(java.sql.Statement stmt) throws SQLException
{
stmt.execute("TRUNCATE TABLE history");
stmt.execute("SET FOREIGN_KEY_CHECKS = 0;");
stmt.execute("SET UNIQUE_CHECKS = 0;");
stmt.execute("SET sql_log_bin = 0");
}
public static int Kontostand_TX(java.sql.Statement stmt, int ACCID) throws SQLException
{
ResultSet rs = stmt.executeQuery("select balance from accounts where accid="+ACCID+";");
rs.first();
return rs.getInt(1);
}
public static int Einzahlungs_TX(java.sql.Statement stmt, int ACCID, int TELLERID, int BRANCHID, int DELTA) throws SQLException
{
//stmt.executeUpdate("update branches set balance=balance+"+DELTA+" where branchid="+BRANCHID+";");
//stmt.executeUpdate("update tellers set balance=balance+"+DELTA+" where tellerid="+TELLERID+";");
//stmt.executeUpdate("update accounts set balance=balance+"+DELTA+" where accid="+ACCID+";");
//DBMS^
//ResultSet rs = stmt.executeQuery("select balance from accounts where accid="+ACCID+";");
//rs.first();
//int newbalance = rs.getInt(1) + DELTA;
//stmt.executeUpdate("insert into history values ("+ ACCID +","+ TELLERID +","+ DELTA +","+ BRANCHID +","+ newbalance +",'Einzahlung')");
//return newbalance;
//stmt.setQueryTimeout(998493834);
stmt.execute("CALL Einzahlungs_TX("+ACCID+","+TELLERID+","+BRANCHID+","+DELTA+");");
return 0;
}
public static int Analyse_TX(java.sql.Statement stmt, int DELTA) throws SQLException
{
ResultSet rs = stmt.executeQuery("select count(accid) from benchmark.history where delta="+ DELTA +";");
rs.first();
return rs.getInt(1);
}
private static int rand()
{
Random rnd = new Random();
int x = rnd.nextInt(100) + 1;
if(x<= 50)
return 1;
if(x<=85)
return 2;
return 3;
}
public static void main(String[] args) throws SQLException
{
int iTxCount = 0;
int iPercent = 0;
long tnow, tend, tbeg;
java.sql.Statement stmt = null;
Scanner scr = new Scanner(System.in);
final int iGesamtZeit = 60000;
final int iEinschwingZeit = 24000;
final int iAusschwingZeit = 54000;
String user = "dbi";
String pass = "<PASSWORD>";
String DB = "benchmark";
System.out.print("DB-Server: ");
String ConnectionName = "jdbc:mysql://"+scr.nextLine()+"/" + DB;
scr.close();
Connection con = DriverManager.getConnection(ConnectionName, user, pass);
stmt = con.createStatement();
//Commit der Datenbank erst am Ende der Operationen
//con.setAutoCommit(false);
//create_table(stmt);
delete_tables(stmt);
Random r = new Random();
System.out.print("|1%_____________________50%____________________100%|\n|");
tend = System.currentTimeMillis() + iGesamtZeit;
tnow = System.currentTimeMillis();
tbeg = tnow;
while(tnow < tend )
{
tnow = System.currentTimeMillis();
switch(rand())
{
case 1:
Kontostand_TX(stmt, r.nextInt(10000)+1);
break;
case 2:
Einzahlungs_TX(stmt, r.nextInt(10000)+1, r.nextInt(10000)+1, r.nextInt(10000)+1, r.nextInt(10000)+1);
break;
case 3:
Analyse_TX(stmt, r.nextInt(10000)+1);
break;
}
if((tnow - tbeg) > iEinschwingZeit && (tnow - tbeg) < iAusschwingZeit)
iTxCount++;
int xx = (iGesamtZeit - (int)(tend-tnow))*100/iGesamtZeit;
if(xx > iPercent)
{
if(xx%2 == 0)
System.out.print("=");
iPercent = xx;
}
try {
Thread.sleep(50);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("|\n\n");
System.out.println("Tx : " + iTxCount);
System.out.println("TxPS: "+ (double)((double)iTxCount/((double)(iAusschwingZeit-iEinschwingZeit)/1000)));
stmt.close();
con.close();
}
}
| 3,883 | 0.655332 | 0.628542 | 132 | 28.40909 | 30.349468 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.909091 | false | false | 3 |
3d41dee3b366efd1862d2f0fb65a1ea4bfefdb10 | 11,828,339,977,248 | 386419a2c777c4a7af547da99ab0a3fd91d7859c | /app/src/main/java/vn/com/duan1/coffeemanagement/Staff_item/AccountLoginFragment.java | 2004209f02057c1fd1c8b120ee4cbe8e6f3e3658 | [] | no_license | cauhuyso0/DuAnCoffee | https://github.com/cauhuyso0/DuAnCoffee | dd91fa54ab12352407d4a11afa13b372f1cf20c6 | 4196eca4ab8cf3f750995233f476cdfe12311afc | refs/heads/main | 2023-01-01T10:29:39.486000 | 2020-10-29T01:57:55 | 2020-10-29T01:57:55 | 308,189,430 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package vn.com.duan1.coffeemanagement.Staff_item;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import vn.com.duan1.coffeemanagement.Adapter.NguoiDungAdapter;
import vn.com.duan1.coffeemanagement.DAO.NguoiDungDAO;
import vn.com.duan1.coffeemanagement.DataModel.NguoiDung;
import vn.com.duan1.coffeemanagement.R;
import static vn.com.duan1.coffeemanagement.MainActivity.idAfterLogin;
import static vn.com.duan1.coffeemanagement.Staff_item.StaffManagementFragment.nhanViens;
import static vn.com.duan1.coffeemanagement.Staff_item.StaffManagementFragment.quanLys;
import static vn.com.duan1.coffeemanagement.Staff_item.StaffManagementFragment.sttNhanVien;
import static vn.com.duan1.coffeemanagement.Staff_item.StaffManagementFragment.sttQuanLy;
public class AccountLoginFragment extends Fragment {
RecyclerView rvAccountManager;
FloatingActionButton fl;
NguoiDungDAO nguoiDungDAO;
NguoiDungAdapter nguoiDungAdapter;
public AccountLoginFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_account_login, null);
rvAccountManager = view.findViewById(R.id.rvAccountManager);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(view.getRootView().getContext());
rvAccountManager.setLayoutManager(linearLayoutManager);
nguoiDungAdapter = new NguoiDungAdapter(view.getRootView().getContext(),quanLys);
rvAccountManager.setAdapter(nguoiDungAdapter);
fl = view.findViewById(R.id.addStaffAcount);
nguoiDungDAO = new NguoiDungDAO(getContext());
if (idAfterLogin.contains("ql")) {
fl.setEnabled(true);
fl.setVisibility(View.VISIBLE);
} else {
fl.setEnabled(false);
fl.setVisibility(View.GONE);
}
capnhatgiaodien();
if (fl.isEnabled()) {
fl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
themTaiKhoanB1();
}
});
}
return view;
}
public void capnhatgiaodien() {
}
String begin;
int flagQL = 0;
int flagNV = 0;
public void themTaiKhoanB1() {
sttQuanLy++;
sttNhanVien++;
AlertDialog.Builder builder1 = new AlertDialog.Builder(getContext());
LayoutInflater inf = getLayoutInflater();
View viewdialog1 = inf.inflate(R.layout.dialog_add_account_login, null);
builder1.setView(viewdialog1);
final Spinner spinner = viewdialog1.findViewById(R.id.spinnerChucVu);
final EditText edtSTT = viewdialog1.findViewById(R.id.edtSTT);
final EditText edtAddPassword = viewdialog1.findViewById(R.id.edtAddPassword);
ArrayList<String> chucVu = new ArrayList<>();
chucVu.add("Quản lý - ql");
chucVu.add("Nhân viên - nv");
ArrayAdapter arrayAdapter = new ArrayAdapter(viewdialog1.getContext(), android.R.layout.simple_spinner_item, chucVu);
spinner.setAdapter(arrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String chucVuNguoiDung = adapterView.getItemAtPosition(i).toString();
if (chucVuNguoiDung.contains("ql")) {
flagQL = 1;
flagNV = 0;
begin = "ql";
edtSTT.setText(sttQuanLy + "");
} else if (chucVuNguoiDung.contains("nv")) {
flagQL = 0;
flagNV = 1;
begin = "nv";
edtSTT.setText(sttNhanVien + "");
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
builder1.setPositiveButton("Bước 2", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String userID = "";
String password = edtAddPassword.getText().toString();
userID = begin + edtSTT.getText().toString();
if(TextUtils.isEmpty(password)){
Toast.makeText(getContext(), "Mật khẩu không được trống!", Toast.LENGTH_SHORT).show();
sttQuanLy--;
sttNhanVien--;
}else {
NguoiDung nguoiDungMoi = new NguoiDung(userID, password);
themTaiKhoanB2(nguoiDungMoi);
if (flagQL == 1 && flagNV == 0) {
sttNhanVien--;
} else if (flagQL == 0 && flagNV == 1) {
sttQuanLy--;
}
}
}
});
builder1.setNegativeButton("Hủy", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sttQuanLy--;
sttNhanVien--;
dialog.cancel();
}
});
builder1.show();
}
public void themTaiKhoanB2(final NguoiDung nguoiDung) {
AlertDialog.Builder builder2 = new AlertDialog.Builder(getContext());
LayoutInflater inf = getLayoutInflater();
View viewdialog2 = inf.inflate(R.layout.dialog_add_staff, null);
builder2.setView(viewdialog2);
final EditText edtTen = viewdialog2.findViewById(R.id.edtTen);
final EditText edtCMND = viewdialog2.findViewById(R.id.edtCMND);
final EditText edtsdt = viewdialog2.findViewById(R.id.edtsdt);
builder2.setPositiveButton("Hoàn tất", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
nguoiDung.setTen(edtTen.getText().toString());
nguoiDung.setCMND(edtCMND.getText().toString());
nguoiDung.setSdt(edtsdt.getText().toString());
nguoiDungDAO.inserNguoiDung(nguoiDung);
nguoiDungAdapter.notifyDataSetChanged();
}
}).setNegativeButton("Hủy", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder2.show();
}
}
| UTF-8 | Java | 7,335 | java | AccountLoginFragment.java | Java | [
{
"context": "ing userID = \"\";\n String password = edtAddPassword.getText().toString();\n\n userID = begin + edtSTT.getTe",
"end": 4994,
"score": 0.8974034786224365,
"start": 4961,
"tag": "PASSWORD",
"value": "edtAddPassword.getText().toString"
}
] | null | [] | package vn.com.duan1.coffeemanagement.Staff_item;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import vn.com.duan1.coffeemanagement.Adapter.NguoiDungAdapter;
import vn.com.duan1.coffeemanagement.DAO.NguoiDungDAO;
import vn.com.duan1.coffeemanagement.DataModel.NguoiDung;
import vn.com.duan1.coffeemanagement.R;
import static vn.com.duan1.coffeemanagement.MainActivity.idAfterLogin;
import static vn.com.duan1.coffeemanagement.Staff_item.StaffManagementFragment.nhanViens;
import static vn.com.duan1.coffeemanagement.Staff_item.StaffManagementFragment.quanLys;
import static vn.com.duan1.coffeemanagement.Staff_item.StaffManagementFragment.sttNhanVien;
import static vn.com.duan1.coffeemanagement.Staff_item.StaffManagementFragment.sttQuanLy;
public class AccountLoginFragment extends Fragment {
RecyclerView rvAccountManager;
FloatingActionButton fl;
NguoiDungDAO nguoiDungDAO;
NguoiDungAdapter nguoiDungAdapter;
public AccountLoginFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_account_login, null);
rvAccountManager = view.findViewById(R.id.rvAccountManager);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(view.getRootView().getContext());
rvAccountManager.setLayoutManager(linearLayoutManager);
nguoiDungAdapter = new NguoiDungAdapter(view.getRootView().getContext(),quanLys);
rvAccountManager.setAdapter(nguoiDungAdapter);
fl = view.findViewById(R.id.addStaffAcount);
nguoiDungDAO = new NguoiDungDAO(getContext());
if (idAfterLogin.contains("ql")) {
fl.setEnabled(true);
fl.setVisibility(View.VISIBLE);
} else {
fl.setEnabled(false);
fl.setVisibility(View.GONE);
}
capnhatgiaodien();
if (fl.isEnabled()) {
fl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
themTaiKhoanB1();
}
});
}
return view;
}
public void capnhatgiaodien() {
}
String begin;
int flagQL = 0;
int flagNV = 0;
public void themTaiKhoanB1() {
sttQuanLy++;
sttNhanVien++;
AlertDialog.Builder builder1 = new AlertDialog.Builder(getContext());
LayoutInflater inf = getLayoutInflater();
View viewdialog1 = inf.inflate(R.layout.dialog_add_account_login, null);
builder1.setView(viewdialog1);
final Spinner spinner = viewdialog1.findViewById(R.id.spinnerChucVu);
final EditText edtSTT = viewdialog1.findViewById(R.id.edtSTT);
final EditText edtAddPassword = viewdialog1.findViewById(R.id.edtAddPassword);
ArrayList<String> chucVu = new ArrayList<>();
chucVu.add("Quản lý - ql");
chucVu.add("Nhân viên - nv");
ArrayAdapter arrayAdapter = new ArrayAdapter(viewdialog1.getContext(), android.R.layout.simple_spinner_item, chucVu);
spinner.setAdapter(arrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String chucVuNguoiDung = adapterView.getItemAtPosition(i).toString();
if (chucVuNguoiDung.contains("ql")) {
flagQL = 1;
flagNV = 0;
begin = "ql";
edtSTT.setText(sttQuanLy + "");
} else if (chucVuNguoiDung.contains("nv")) {
flagQL = 0;
flagNV = 1;
begin = "nv";
edtSTT.setText(sttNhanVien + "");
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
builder1.setPositiveButton("Bước 2", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String userID = "";
String password = <PASSWORD>();
userID = begin + edtSTT.getText().toString();
if(TextUtils.isEmpty(password)){
Toast.makeText(getContext(), "Mật khẩu không được trống!", Toast.LENGTH_SHORT).show();
sttQuanLy--;
sttNhanVien--;
}else {
NguoiDung nguoiDungMoi = new NguoiDung(userID, password);
themTaiKhoanB2(nguoiDungMoi);
if (flagQL == 1 && flagNV == 0) {
sttNhanVien--;
} else if (flagQL == 0 && flagNV == 1) {
sttQuanLy--;
}
}
}
});
builder1.setNegativeButton("Hủy", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sttQuanLy--;
sttNhanVien--;
dialog.cancel();
}
});
builder1.show();
}
public void themTaiKhoanB2(final NguoiDung nguoiDung) {
AlertDialog.Builder builder2 = new AlertDialog.Builder(getContext());
LayoutInflater inf = getLayoutInflater();
View viewdialog2 = inf.inflate(R.layout.dialog_add_staff, null);
builder2.setView(viewdialog2);
final EditText edtTen = viewdialog2.findViewById(R.id.edtTen);
final EditText edtCMND = viewdialog2.findViewById(R.id.edtCMND);
final EditText edtsdt = viewdialog2.findViewById(R.id.edtsdt);
builder2.setPositiveButton("Hoàn tất", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
nguoiDung.setTen(edtTen.getText().toString());
nguoiDung.setCMND(edtCMND.getText().toString());
nguoiDung.setSdt(edtsdt.getText().toString());
nguoiDungDAO.inserNguoiDung(nguoiDung);
nguoiDungAdapter.notifyDataSetChanged();
}
}).setNegativeButton("Hủy", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder2.show();
}
}
| 7,312 | 0.629908 | 0.623752 | 185 | 38.508106 | 27.723757 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.691892 | false | false | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.