blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
listlengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d815e13ad678b445f82e05909cf741d31e6a2a8e | aa38b9cc9c6adea0253708268d53879d144e68a0 | /CS-643-Project-master/src/main/java/edu/njit/cs643/group3/mappers/AllHourlyStatisticsMapper.java | 93e69cc5bcb0a0d1a17f93c0e7dcae5ed3a1e97c | []
| no_license | Maharshimdj7/NYC-Taxi-Limousine-Commission-Trip-Explorer | 25a0471e0ebce488999166bbd5ffcfa74997ceac | c7bd63f31b1509eedc75dab705c801548a242887 | refs/heads/main | 2023-02-07T05:58:35.923302 | 2021-01-03T23:00:07 | 2021-01-03T23:00:07 | 326,516,738 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,855 | java | package edu.njit.cs643.group3.mappers;
import edu.njit.cs643.group3.utils.Constants;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class AllHourlyStatisticsMapper extends Mapper<LongWritable, Text, Text, MapWritable> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String[] parts = value.toString().split(",");
try {
Integer.parseInt(parts[7]);
Integer.parseInt(parts[8]);
} catch (NumberFormatException e) {
return;
}
//
// Generate the hour-of-day string.
//
int pickupHour = LocalDateTime.parse(parts[1], Constants.TIMESTAMP_FORMAT).getHour();
String pickupTime = LocalTime.of(pickupHour, 0).format(Constants.TIME_FORMAT);
MapWritable result = new MapWritable();
try {
int passengerCount = Integer.parseInt(parts[3]);
float tripDistance = Float.parseFloat(parts[4]);
float fareAmount = Float.parseFloat(parts[10]);
float tipAmount = Float.parseFloat(parts[13]);
float totalAmount = Float.parseFloat(parts[16]);
result.put(new Text("passenger_count"), new IntWritable(passengerCount));
result.put(new Text("trip_distance"), new FloatWritable(tripDistance));
result.put(new Text("fare_amount"), new FloatWritable(fareAmount));
result.put(new Text("tip_amount"), new FloatWritable(tipAmount));
result.put(new Text("total_amount"), new FloatWritable(totalAmount));
context.write(new Text(pickupTime), result);
} catch (Exception e) {
// Do nothing.
}
}
}
| [
"[email protected]"
]
| |
f28b4c56aa844bd75692c7801dac8cf0f9f13504 | eed6f178e71e10ab6237b22a79eaaaa8c40b6dca | /demoDruidMulti/src/main/java/com/wuti/demo/param/PageParam.java | 9ef523585299187cc882f20aa1205542891c1ffe | []
| no_license | developthinking/springboot-project | 76ad9c37d9c0fa82a06ca2248e62c4071912e378 | 7c58b6d044ab714cbb4dd12fe4913f433b4902d1 | refs/heads/master | 2018-10-05T15:47:26.156874 | 2018-06-08T08:20:32 | 2018-06-08T08:20:32 | 109,335,676 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 722 | java | package com.wuti.demo.param;
import org.apache.commons.lang3.builder.ToStringBuilder;
public class PageParam {
private int beginLine; // 起始行
private Integer pageSize = 5;
private Integer currentPage = 0; // 当前页
public int getBeginLine() {
return pageSize*currentPage;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
| [
"[email protected]"
]
| |
86b74dc6897937a4c2bdcaa099094e3b9a09151d | 76c3cae55f0fcd7b307746d64fcc1f8b7a8de60a | /src/test/java/utilities/PropertyFileReader.java | 94cf72af4401d1c353dc5b7a5fb479cc59724123 | []
| no_license | adi4848/FrameworkBdd | 175e39ccd2604a148ff7ab423e3c1502512ac19a | e26f3888e0bc35c212423c0768c2423c22823e0b | refs/heads/master | 2023-08-31T02:39:13.646845 | 2021-09-28T18:08:28 | 2021-09-28T18:08:28 | 411,378,924 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 350 | java | package utilities;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertyFileReader {
public static Properties loadFile() throws IOException {
Properties prop = new Properties();
FileInputStream fis = new FileInputStream(".\\config.properties");
prop.load(fis);
return prop;
}
}
| [
"[email protected]"
]
| |
0392c7d1dc1f4e9a745dcb9b7acfa3710cac1fa0 | 31019a00a143a893d5a61a2ea0d1177589151b86 | /SpringFramework/j01/src/main/java/com/zerock/myapp/HomeController.java | f532779ea5c5e57e7ae36c9b50e9a2a41917be54 | []
| no_license | cksql96/SpringFramework | bde4bff8967bc3613e14cb531f8c650d67b2ec70 | 5f3d4e9b7df9e31def64c988f9f05956f789fadf | refs/heads/main | 2023-01-22T10:20:00.916339 | 2020-12-08T02:15:59 | 2020-12-08T02:15:59 | 313,158,151 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,078 | java | package com.zerock.myapp;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
}
}
| [
"[email protected]"
]
| |
04d41b1b0755f224f7c6c1e616c55c929f39216a | 85e491f462b9f76213c68e971f84ff4b14d2f9b6 | /src/db.java | 333226b26de552d62b7147329104eb8f3e12b600 | []
| no_license | chhavi02/Hotel-Management-System_Course-Project | 7fcd1ce6a724cf1bf1153b344260d461df1ee9ae | 7ba260d817cb036e5e5cdef1c9ee796f17b5f9f8 | refs/heads/master | 2020-03-22T02:08:43.630133 | 2018-07-01T18:31:29 | 2018-07-01T18:31:29 | 139,352,233 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,916 | java | import java.sql.*;
import static java.sql.DriverManager.getConnection;
public class db {
private static final String dbClassName = "com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql://localhost:3306/";
static ResultSet rs=null;
static Statement stmt;
static Connection con;
static PreparedStatement pstmt;
static PreparedStatement pstmt2;
static PreparedStatement pstmt3;
static int rcount=0;
static int avail=0;
public static void startDatabase() throws ClassNotFoundException, SQLException {
Class.forName(dbClassName);
con=getConnection(url,"root","2020");
System.out.println("successfully connected to MySQL Database");
stmt=con.createStatement();
pstmt=con.prepareStatement("insert into customer values(?,?,?,?,?,?)");
pstmt2=con.prepareStatement("insert into room values(?,?,?,?,?)");
pstmt3=con.prepareStatement("insert into booking values(?,?,?,?,?)");
}
public static boolean use(String name) throws SQLException {
if (stmt.execute("use "+name)) return true;
else {
return false;
}
}
public static void close() throws SQLException {
stmt.close();
con.close();
System.out.println("database connection closed successfully");
}
public static boolean createDatabase(String name) throws SQLException
{
if (stmt.execute("create database "+name)) {
return true;
}
else return false;
}
public static boolean dropDatabase(String name) throws SQLException {
if (stmt.execute("drop database "+name)) return true;
else {
return false;
}
}
public static boolean createTable(String q) throws SQLException
{
if (stmt.execute(q)) return true;
else {
return false;
}
}
}
| [
"[email protected]"
]
| |
46622a6a44c31c7a95cfba26d6a2fcc76d629d4a | fc160694094b89ab09e5c9a0f03db80437eabc93 | /java-enterpriseknowledgegraph/samples/snippets/generated/com/google/cloud/enterpriseknowledgegraph/v1/enterpriseknowledgegraphservice/deleteentityreconciliationjob/SyncDeleteEntityReconciliationJob.java | a8051bd0ea70725091e518a4de35d4a279168ceb | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | googleapis/google-cloud-java | 4f4d97a145e0310db142ecbc3340ce3a2a444e5e | 6e23c3a406e19af410a1a1dd0d0487329875040e | refs/heads/main | 2023-09-04T09:09:02.481897 | 2023-08-31T20:45:11 | 2023-08-31T20:45:11 | 26,181,278 | 1,122 | 685 | Apache-2.0 | 2023-09-13T21:21:23 | 2014-11-04T17:57:16 | Java | UTF-8 | Java | false | false | 2,403 | java | /*
* Copyright 2023 Google LLC
*
* 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
*
* https://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.google.cloud.enterpriseknowledgegraph.v1.samples;
// [START enterpriseknowledgegraph_v1_generated_EnterpriseKnowledgeGraphService_DeleteEntityReconciliationJob_sync]
import com.google.cloud.enterpriseknowledgegraph.v1.DeleteEntityReconciliationJobRequest;
import com.google.cloud.enterpriseknowledgegraph.v1.EnterpriseKnowledgeGraphServiceClient;
import com.google.cloud.enterpriseknowledgegraph.v1.EntityReconciliationJobName;
import com.google.protobuf.Empty;
public class SyncDeleteEntityReconciliationJob {
public static void main(String[] args) throws Exception {
syncDeleteEntityReconciliationJob();
}
public static void syncDeleteEntityReconciliationJob() throws Exception {
// This snippet has been automatically generated and should be regarded as a code template only.
// It will require modifications to work:
// - It may require correct/in-range values for request initialization.
// - It may require specifying regional endpoints when creating the service client as shown in
// https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
try (EnterpriseKnowledgeGraphServiceClient enterpriseKnowledgeGraphServiceClient =
EnterpriseKnowledgeGraphServiceClient.create()) {
DeleteEntityReconciliationJobRequest request =
DeleteEntityReconciliationJobRequest.newBuilder()
.setName(
EntityReconciliationJobName.of(
"[PROJECT]", "[LOCATION]", "[ENTITY_RECONCILIATION_JOB]")
.toString())
.build();
enterpriseKnowledgeGraphServiceClient.deleteEntityReconciliationJob(request);
}
}
}
// [END enterpriseknowledgegraph_v1_generated_EnterpriseKnowledgeGraphService_DeleteEntityReconciliationJob_sync]
| [
"[email protected]"
]
| |
0c51568b0b7d1ebbebd0cc6f8e7d78506ef641d1 | d34ecbeeeafb871c6462c7ffe7fdc9fe62be9036 | /service/manager/src/main/java/cn/fintecher/manager/model/UserLoginResponse.java | f027e03a8ca40e7dac719c0710589335257a5269 | []
| no_license | gulangcoder/customer | a4b95b1350a22602eba8fbf5cf85ece392424b72 | c460b22fb0c5616ad64f672f7938c589fca8eba9 | refs/heads/master | 2020-04-02T04:16:41.933919 | 2018-10-21T13:32:16 | 2018-10-21T13:32:16 | 154,009,219 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 351 | java | package cn.fintecher.manager.model;
import cn.fintecher.common.userinfo.UserInfo;
import lombok.Data;
import java.util.Map;
/**
* Created by ChenChang on 2017/3/7.
*/
@Data
public class UserLoginResponse {
String token;
boolean reset; //true是需要修改密码
String regDay;
UserInfo userInfo;
Map<String,Object> data;
}
| [
"[email protected]"
]
| |
c31f21d502dd545c4b860aa9ea5c418e3a15911a | e64c2201c1cf2adf9197c77aab2676670de9bf4c | /src/com/Snippet.java | 13a8dff5721288afa6bfcba04e4c282dd158af8f | []
| no_license | zengxianbing/JavaStudy | 45016f3910606988403f16bd1b5f0e60d52de7b2 | 9a4593cf4b6f79ada4677bdd87a045ff04ee721a | refs/heads/master | 2020-04-06T04:29:17.203382 | 2016-07-04T01:11:47 | 2016-07-04T01:11:47 | 62,491,476 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 96 | java | package com;
public class Snippet {
public static void main(String[] args) {
}
}
| [
"[email protected]"
]
| |
01ef894cb2112762c2bd0ea3954140145b13b914 | e3109a079793c5a66891aebef6dd7c2a44f8d360 | /base/java/e/c/a/b/a/b.java | 08b272a16b6a1e1e7be992a35e335cdf825363a3 | []
| no_license | msorland/no.simula.smittestopp | d5a317b432e8a37c547fc9f2403f25db78ffd871 | f5eeba1cc4b1cad98b8174315bb2b0b388d14be9 | refs/heads/master | 2022-04-17T12:50:10.853188 | 2020-04-17T10:14:01 | 2020-04-17T10:14:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,412 | java | package e.c.a.b.a;
import android.animation.TypeEvaluator;
public class b implements TypeEvaluator<Integer> {
public static final b a = new b();
public Object evaluate(float f2, Object obj, Object obj2) {
int intValue = ((Integer) obj).intValue();
float f3 = ((float) ((intValue >> 24) & 255)) / 255.0f;
int intValue2 = ((Integer) obj2).intValue();
float pow = (float) Math.pow((double) (((float) ((intValue >> 16) & 255)) / 255.0f), 2.2d);
float pow2 = (float) Math.pow((double) (((float) ((intValue >> 8) & 255)) / 255.0f), 2.2d);
float pow3 = (float) Math.pow((double) (((float) (intValue & 255)) / 255.0f), 2.2d);
float pow4 = (float) Math.pow((double) (((float) ((intValue2 >> 16) & 255)) / 255.0f), 2.2d);
float pow5 = ((((float) Math.pow((double) (((float) (intValue2 & 255)) / 255.0f), 2.2d)) - pow3) * f2) + pow3;
return Integer.valueOf((Math.round(((float) Math.pow((double) (((pow4 - pow) * f2) + pow), 0.45454545454545453d)) * 255.0f) << 16) | (Math.round(((((((float) ((intValue2 >> 24) & 255)) / 255.0f) - f3) * f2) + f3) * 255.0f) << 24) | (Math.round(((float) Math.pow((double) (((((float) Math.pow((double) (((float) ((intValue2 >> 8) & 255)) / 255.0f), 2.2d)) - pow2) * f2) + pow2), 0.45454545454545453d)) * 255.0f) << 8) | Math.round(((float) Math.pow((double) pow5, 0.45454545454545453d)) * 255.0f));
}
}
| [
"[email protected]"
]
| |
a243298ff1f20086a46495e90537496fdf070710 | 8ae7f77025e87afb783abc3a36192772be050f4e | /Design1/src/design1/Design.java | fa635d00f9d9db28fb7ea5ab6e3d9c31bba970d4 | []
| no_license | Shohanurcsevu/NeatBeanProject | 915c64c72e1c1b2fdb58188ebe6e8e6660b20990 | 7e924555385045c7613dbf936f44d0b570f1aff9 | refs/heads/master | 2021-01-10T15:43:20.675980 | 2016-03-28T02:04:53 | 2016-03-28T02:04:53 | 54,858,420 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,887 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package design1;
/**
*
* @author SHOHANUR PC
*/
public class Design extends javax.swing.JFrame {
/**
* Creates new form Design
*/
public Design() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel3 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jComboBox1 = new javax.swing.JComboBox();
jLabel4 = new javax.swing.JLabel();
jTextField3 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
getContentPane().setLayout(null);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(339, 0, 283, 93);
jLabel3.setBackground(new java.awt.Color(255, 0, 204));
jLabel3.setIcon(new javax.swing.ImageIcon("C:\\Users\\SHOHANUR PC\\Desktop\\Cata.JPG")); // NOI18N
jLabel3.setText("Catagory:");
getContentPane().add(jLabel3);
jLabel3.setBounds(10, 50, 90, 21);
jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});
getContentPane().add(jTextField2);
jTextField2.setBounds(130, 10, 87, 20);
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
getContentPane().add(jComboBox1);
jComboBox1.setBounds(130, 50, 87, 20);
jLabel4.setIcon(new javax.swing.ImageIcon("C:\\Users\\SHOHANUR PC\\Desktop\\price1.JPG")); // NOI18N
jLabel4.setText("Price: ");
getContentPane().add(jLabel4);
jLabel4.setBounds(0, 90, 100, 24);
getContentPane().add(jTextField3);
jTextField3.setBounds(130, 90, 87, 30);
jButton1.setText("Save");
getContentPane().add(jButton1);
jButton1.setBounds(10, 150, 70, 23);
jButton2.setText("Update");
getContentPane().add(jButton2);
jButton2.setBounds(90, 150, 100, 23);
jButton3.setText("Delete");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
getContentPane().add(jButton3);
jButton3.setBounds(200, 150, 63, 23);
jLabel2.setBackground(new java.awt.Color(51, 102, 0));
jLabel2.setIcon(new javax.swing.ImageIcon("C:\\Users\\SHOHANUR PC\\Desktop\\PN.JPG")); // NOI18N
jLabel2.setText("Product Name: ");
getContentPane().add(jLabel2);
jLabel2.setBounds(0, 11, 120, 22);
jLabel1.setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\SHOHANUR PC\\Downloads\\316701.jpg")); // NOI18N
getContentPane().add(jLabel1);
jLabel1.setBounds(0, 0, 630, 410);
jLabel5.setText("jLabel5");
getContentPane().add(jLabel5);
jLabel5.setBounds(330, 220, 100, 40);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField2ActionPerformed
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox1ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton3ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Design.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Design.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Design.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Design.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Design().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
// End of variables declaration//GEN-END:variables
}
| [
"[email protected]"
]
| |
22605867c7d80664e4e313debe4f4d4a689ac669 | 17f2e00af0730621df33158eb6a2a1ae3c4da733 | /NetworkChatClient/src/main/java/ru/gb/java2/chat/client/ViewController.java | 80d2c82859c69d3d1f5a0bbf232b5fcbc68f63ad | []
| no_license | TrishinIN/Java2_2021_05_17 | 7147258b91c4550028cdc94b1064d51d239461ab | ed7553e2aff0f3aecf7bec7f40cdf73f1812d13b | refs/heads/master | 2023-05-24T05:13:48.219248 | 2021-06-18T19:23:11 | 2021-06-18T19:23:11 | 378,246,333 | 0 | 0 | null | 2021-06-18T20:06:08 | 2021-06-18T19:22:59 | Java | UTF-8 | Java | false | false | 3,014 | java | package NetworkChatClient.src.main.java.ru.gb.java2.chat.client;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javax.swing.text.html.ListView;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
public class ViewController {
@FXML
public ListView<String> usersList;
@FXML
private Button sendButton;
@FXML
private TextArea chatHistory;
@FXML
private TextArea messageTextArea;
private ClientChat application;
@FXML
public void initialize() {
usersList.setItems(FXCollections.observableArrayList(ClientChat.USERS_TEST_DATA));
}
@FXML
private void sendMessage() {
String message = messageTextArea.getText().trim();
if (message.isEmpty()) {
messageTextArea.clear();
return;
}
String sender = null;
if (!usersList.getSelectionModel().isEmpty()) {
sender = usersList.getSelectionModel().getSelectedItem();
}
try {
message = sender != null ? String.join(": ", sender, message) : message; // sender + ": " + message
Network.getInstance().sendMessage(message);
} catch (IOException e) {
application.showNetworkErrorDialog("Ошибка передачи данных по сети", "Не удалось отправить сообщение!");
}
appendMessageToChat("Я", message);
}
private void appendMessageToChat(String sender, String message) {
chatHistory.appendText(DateFormat.getDateTimeInstance().format(new Date()));
chatHistory.appendText(System.lineSeparator());
if (sender != null) {
chatHistory.appendText(sender + ":");
chatHistory.appendText(System.lineSeparator());
}
chatHistory.appendText(message);
chatHistory.appendText(System.lineSeparator());
chatHistory.appendText(System.lineSeparator());
messageTextArea.clear();
}
@FXML
public void sendTextAreaMessage(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
event.consume(); // otherwise a new line will be added to the textArea after the sendFunction() call
if (event.isShiftDown()) {
messageTextArea.appendText(System.lineSeparator());
} else {
sendMessage();
}
}
}
public void initMessageHandler() {
Network.getInstance().waitMessages(message -> Platform.runLater(() -> {
ViewController.this.appendMessageToChat("Server", message);
}));
}
public void setApplication(ClientChat application) {
this.application = application;
}
} | [
"[email protected]"
]
| |
7cfd58cc7a46e9871b7feeb61d7c35d6fdece0e5 | 56be2045b9463945d45fb64be234359226ac2ab5 | /src/main/java/com/markevich/task1/comparator/employee/EmployeeComparatorBySalary.java | c0ebaa9b8089765a0e0a7fd3f64f60bc184113d0 | []
| no_license | HeatLee/JWD-Task1 | 5e80399c6648408409d296243e29377500111c5e | 59875199c7efd7af02824463142cbc563b089287 | refs/heads/master | 2020-12-28T07:10:13.973642 | 2020-02-07T20:58:39 | 2020-02-07T20:58:39 | 238,223,477 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 329 | java | package com.markevich.task1.comparator.employee;
import com.markevich.task1.entity.Employee;
import java.util.Comparator;
public class EmployeeComparatorBySalary implements Comparator<Employee> {
@Override
public int compare(Employee o1, Employee o2) {
return o1.getSalary().compareTo(o2.getSalary());
}
}
| [
"[email protected]"
]
| |
924d8343cd1e38245594669762800e27b9152151 | d9988fd6d2cf910f0d4aaaf952e021696d144c6c | /ProjetoRecrutamentoBackEnd/src/main/java/br/com/recrutamento/brasilia/model/Job.java | ab073187465790a77ae8aa9d598ee47f29d797c5 | []
| no_license | matheus-henr/ProjetoRecrutamento | cb42fb3c1f291752d305c580995bde80aabd719d | c9b0797a73ab08f0e7684e371a9490b0ad373534 | refs/heads/master | 2023-01-09T18:48:10.826148 | 2019-08-07T04:00:54 | 2019-08-07T04:00:54 | 200,901,985 | 0 | 0 | null | 2023-01-01T10:00:32 | 2019-08-06T18:12:52 | Java | UTF-8 | Java | false | false | 2,096 | java | package br.com.recrutamento.brasilia.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.validation.constraints.NotEmpty;
@Entity
public class Job implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotEmpty(message = "O atributo não pode ser nulo ou vazio")
@Column(unique=true)
private String name;
private boolean active;
@OneToOne
private Job parentJob;
@OneToMany(mappedBy = "job", targetEntity = Task.class, fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<Task> tasks;
public Job() {}
public Job(int id, String name, boolean active, Job parentJob) {
this.id = id;
this.name = name;
this.active = active;
this.parentJob = parentJob;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Job getParentJob() {
return parentJob;
}
public void setParentJob(Job parentJob) {
this.parentJob = parentJob;
}
public List<Task> getTasks() {
return tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Job other = (Job) obj;
if (id != other.id)
return false;
return true;
}
}
| [
"[email protected]"
]
| |
c361277613989c1a90f997673b40038d54d6b09f | 616db74c740950862f8144b9d5d2ad4abfbf84da | /src/main/java/nx/domain/tcc/converters/clock/ClockConverter.java | f912ca401cde6624c958b2d27785e8b272ac4797 | [
"Apache-2.0"
]
| permissive | tnakagome/TextConversionChain | 553eea71c9d0157837ffe34f8de7ffe1b18d689f | 2d7b431df61b1237f0a1618f0a40a4080e904458 | refs/heads/master | 2021-06-18T04:06:24.565192 | 2020-10-17T09:06:23 | 2020-10-17T09:06:23 | 90,106,770 | 1 | 0 | Apache-2.0 | 2020-10-17T09:06:24 | 2017-05-03T04:04:08 | Java | UTF-8 | Java | false | false | 731 | java | package nx.domain.tcc.converters.clock;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import nx.domain.tcc.AbstractConverter;
public abstract class ClockConverter extends AbstractConverter {
protected static final String UTC_ZONENAME = "UTC";
protected static final String LOCAL_ZONENAME = "Local";
protected ZoneId timezone;
public ClockConverter(final String signature, final String zoneName, final String displayString) {
super(signature, displayString);
if (zoneName.equals(UTC_ZONENAME))
this.timezone = ZoneOffset.UTC;
else
this.timezone = ZonedDateTime.now().getZone();
}
}
| [
"[email protected]"
]
| |
5eb45f937cc238182f6d81878551779ba54339d7 | 15fb46ab2d0dfa973f91ff82cdc2da35b2916700 | /src/main/java/com/herokuapp/tassistant/service/email/EmailService.java | d3265a502aa821738f1a5bc02ba869bb62eade0e | []
| no_license | maskrz/TrainerAssistant | e3958556084041bc3913c86abc08a096368a3509 | a0d13b10c53bedf69a74acfcfa645096b2c0e425 | refs/heads/master | 2016-09-12T07:31:11.904739 | 2016-05-26T19:59:33 | 2016-05-26T19:59:33 | 55,355,103 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 196 | java | package com.herokuapp.tassistant.service.email;
import com.herokuapp.tassistant.database.entity.User;
public interface EmailService {
public void sendConfirmationEmail(User user);
}
| [
"[email protected]"
]
| |
55fc6b8507dce4ca459a4b2305426b8f84cce86a | 83380915dc4355ea4ea05307222c88f3077f83ab | /services/distribution/src/main/java/app/coronawarn/server/services/distribution/dgc/dsc/CloudDscFeignClientConfiguration.java | 3786274a486199a187c2f4bbf75fe6902945fce8 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-unknown"
]
| permissive | corona-warn-app/cwa-server | d1c4f25f44f5c2970c4351cf663d599dc4549a83 | c61d55f6f83b6d005cb6aca9e9b455afac572d72 | refs/heads/main | 2023-08-07T14:50:25.777087 | 2023-05-10T07:59:47 | 2023-05-10T07:59:47 | 260,712,390 | 2,174 | 497 | Apache-2.0 | 2023-05-10T07:59:48 | 2020-05-02T15:07:31 | Java | UTF-8 | Java | false | false | 1,838 | java | package app.coronawarn.server.services.distribution.dgc.dsc;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
import feign.Client;
import feign.Retryer;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
@EnableFeignClients
@Profile("!revocation")
public class CloudDscFeignClientConfiguration {
private static final Logger logger = LoggerFactory.getLogger(CloudDscFeignClientConfiguration.class);
private final CloudDscFeignHttpClientProvider feignClientProvider;
private final DistributionServiceConfig.Client clientConfig;
/**
* Create an instance.
*/
public CloudDscFeignClientConfiguration(CloudDscFeignHttpClientProvider feignClientProvider,
DistributionServiceConfig distributionServiceConfig) {
logger.debug("Creating Cloud DSC Feign Client Configuration");
this.feignClientProvider = feignClientProvider;
this.clientConfig = distributionServiceConfig.getDigitalGreenCertificate().getDscClient();
}
@Bean
@Profile("!revocation")
public Client dscFeignClient() {
return feignClientProvider.createDscFeignClient();
}
/**
* Retrier configuration for Feign DSC client.
*/
@Bean
@Profile("!revocation")
public Retryer dscRetryer() {
long retryPeriod = TimeUnit.SECONDS.toMillis(clientConfig.getRetryPeriod());
long maxRetryPeriod = TimeUnit.SECONDS.toMillis(clientConfig.getMaxRetryPeriod());
int maxAttempts = clientConfig.getMaxRetryAttempts();
return new Retryer.Default(retryPeriod, maxRetryPeriod, maxAttempts);
}
}
| [
"[email protected]"
]
| |
93afb080742417cf93c7f7cb80edb0a446d6f2f4 | c37d77786ad3ffe05b85c43958a614464f1af106 | /src/main/java/com/cloud/study/entity/Hr.java | 6d6980336c08a5c480c40dbdec7f07bd48ea7e53 | []
| no_license | dengqiquan/cloud-user-service | 5a1bb07164233359b2ac8bde9074c5f4988b98c9 | 508d664085466cae09ae5b90551629a722eb2818 | refs/heads/master | 2023-02-09T21:21:20.415311 | 2021-01-04T08:46:54 | 2021-01-04T08:46:54 | 299,547,953 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,382 | java | package com.cloud.study.entity;
import java.io.Serializable;
import lombok.Data;
@Data
public class Hr implements Serializable {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column hr.id
*
* @mbg.generated
*/
private Integer id;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column hr.name
*
* @mbg.generated
*/
private String name;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column hr.phone
*
* @mbg.generated
*/
private String phone;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column hr.telephone
*
* @mbg.generated
*/
private String telephone;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column hr.address
*
* @mbg.generated
*/
private String address;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column hr.enabled
*
* @mbg.generated
*/
private Boolean enabled;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column hr.username
*
* @mbg.generated
*/
private String username;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column hr.password
*
* @mbg.generated
*/
private String password;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column hr.userface
*
* @mbg.generated
*/
private String userface;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column hr.remark
*
* @mbg.generated
*/
private String remark;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table hr
*
* @mbg.generated
*/
private static final long serialVersionUID = 1L;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column hr.id
*
* @return the value of hr.id
*
* @mbg.generated
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column hr.id
*
* @param id the value for hr.id
*
* @mbg.generated
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column hr.name
*
* @return the value of hr.name
*
* @mbg.generated
*/
public String getName() {
return name;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column hr.name
*
* @param name the value for hr.name
*
* @mbg.generated
*/
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column hr.phone
*
* @return the value of hr.phone
*
* @mbg.generated
*/
public String getPhone() {
return phone;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column hr.phone
*
* @param phone the value for hr.phone
*
* @mbg.generated
*/
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column hr.telephone
*
* @return the value of hr.telephone
*
* @mbg.generated
*/
public String getTelephone() {
return telephone;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column hr.telephone
*
* @param telephone the value for hr.telephone
*
* @mbg.generated
*/
public void setTelephone(String telephone) {
this.telephone = telephone == null ? null : telephone.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column hr.address
*
* @return the value of hr.address
*
* @mbg.generated
*/
public String getAddress() {
return address;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column hr.address
*
* @param address the value for hr.address
*
* @mbg.generated
*/
public void setAddress(String address) {
this.address = address == null ? null : address.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column hr.enabled
*
* @return the value of hr.enabled
*
* @mbg.generated
*/
public Boolean getEnabled() {
return enabled;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column hr.enabled
*
* @param enabled the value for hr.enabled
*
* @mbg.generated
*/
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column hr.username
*
* @return the value of hr.username
*
* @mbg.generated
*/
public String getUsername() {
return username;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column hr.username
*
* @param username the value for hr.username
*
* @mbg.generated
*/
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column hr.password
*
* @return the value of hr.password
*
* @mbg.generated
*/
public String getPassword() {
return password;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column hr.password
*
* @param password the value for hr.password
*
* @mbg.generated
*/
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column hr.userface
*
* @return the value of hr.userface
*
* @mbg.generated
*/
public String getUserface() {
return userface;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column hr.userface
*
* @param userface the value for hr.userface
*
* @mbg.generated
*/
public void setUserface(String userface) {
this.userface = userface == null ? null : userface.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column hr.remark
*
* @return the value of hr.remark
*
* @mbg.generated
*/
public String getRemark() {
return remark;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column hr.remark
*
* @param remark the value for hr.remark
*
* @mbg.generated
*/
public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
} | [
"deng@2019"
]
| deng@2019 |
bc18c670119f95009f0c2aa680ea24da146f94fb | 16852261dc19de19f392b1b181ba1efc34b8f691 | /src/java/servlets/user/verifySession.java | 3111325ee5bd2493e9ae74595dd86fed302f048d | []
| no_license | CristianR98/JNxpress-back | 25550cae1452ee2e5f9cd62416f125451adc9042 | 50323e3e319717221b23140bdf95684d34e5297f | refs/heads/master | 2020-08-21T00:59:58.596189 | 2019-11-01T16:49:13 | 2019-11-01T16:49:13 | 216,084,095 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,432 | java | package servlets.user;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import response.JWTAuth;
import response.Respuesta;
@WebServlet(name = "verifySession", urlPatterns = {"/verifySession"})
public class verifySession extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/json;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Gson json = new Gson();
String token = request.getParameter("token");
Respuesta respuesta = JWTAuth.verifyToken(token);
if (respuesta.isOk()) {
}
out.println(json.toJson(respuesta));
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| [
"[email protected]"
]
| |
af3cdb13bf7531ddc58b1476fefd95bfbaa6fac5 | 54b102372ff46f69cc2c2171e12c4fffa9211d95 | /app/src/androidTest/java/com/example/mario/laborwerteapp/ExampleInstrumentedTest.java | b7f1845f622e6252f0143850e6092c814dc78224 | []
| no_license | raabmario/LaborwerteApp | 8bbc9a9d7a486f8e5bb4b619504ec08940729b84 | 6083952956e6f8bfa7d4572ac2337ed72a1969cc | refs/heads/master | 2020-04-10T16:59:17.173092 | 2018-12-14T13:45:10 | 2018-12-14T13:45:10 | 161,161,316 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 746 | java | package com.example.mario.laborwerteapp;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.mario.laborwerteapp", appContext.getPackageName());
}
}
| [
"[email protected]"
]
| |
3ba6670a6807d74abba078e207705cefbbe68cfe | 8d96720bd331d7743dca7fcabd921b2b34a6acfc | /1107 QuickSort/src/QuickSort.java | 3098fd769d7c29f0bd637b93475809e912eda2ca | []
| no_license | lilyz622/cus1126-intro-to-data-structures | da846e3a1c812597e44b0e199f1f88869b57194b | 4b7b7ea870047e7a7b077f736119542645ac52dc | refs/heads/master | 2020-12-08T22:48:46.412742 | 2016-12-05T15:32:31 | 2016-12-05T15:32:31 | 67,937,135 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,401 | java | import java.util.Arrays;
public class QuickSort {
public static void main(String[] args){
int[] even = {63, 40, 35, 77, 95, 77, 25, 25, 40, 35, 15, 24, 68, 69, 58, 37, 4, 29, 14, 90, 48, 53, 95, 79, 22,
6, 94, 31, 66, 74, 16, 7, 12, 30, 68, 14, 17, 90, 53, 61, 91, 69, 41, 2};
quickSort(even,0, even.length-1);
System.out.println(Arrays.toString(even));
}
public static void quickSort(int[] input, int start, int end){
if (start >= end){
return;
}
int pivot = input[end];
int left = 0;
int right = 0;
int pointer = start;
while (pointer <end){
if (input[pointer] > pivot){
right++;
} else {
if (right > 0){
int temp = input[left+start];
input[left+start] = input[pointer];
input[pointer]= temp;
}
left++;
}
pointer++;
}
int temp = input[left+start];
input[left+start]= pivot;
input[end]= temp;
// System.out.println(Arrays.toString(input));
// int[] leftArray = Arrays.copyOfRange(input, 0,left);
// int[] rightArray = Arrays.copyOfRange(input, left+1, input.length);
// System.out.println("Left Array:"+Arrays.toString(leftArray));
// System.out.println("Right Array:"+Arrays.toString(rightArray));
System.out.println("Pivot:"+(start+left)+"\tLeft:["+start+","+(start+left-1)+"]\tRight:["+(start+left+1)+","+end+"]");
quickSort(input,start,start+left-1);
quickSort(input,start+left+1,end);
}
}
| [
"[email protected]"
]
| |
d1034c66bc1e4eedbb0162dfa4f951029c7e5814 | e15453b90c1a195efbd5eeb4d07224857baabfc7 | /sih_forest_app (copy)/app/src/main/java/com/example/forest/TaskActivity.java | 4c7e0aacf6e404ff22f010699176664fa3a78411 | []
| no_license | learner-pratik/test_forest | d4df6915e45294a23bc721157a9a06c19bd49319 | a46f54513042211a73ee09b77d9b0f49d8c96fc2 | refs/heads/master | 2022-11-25T09:46:00.777830 | 2020-07-27T13:24:59 | 2020-07-27T13:24:59 | 282,833,836 | 0 | 0 | null | 2020-07-27T08:08:29 | 2020-07-27T08:08:28 | null | UTF-8 | Java | false | false | 16,299 | java | package com.example.forest;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.forest.Connectivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.JsonArray;
import com.hudomju.swipe.SwipeToDismissTouchListener;
import com.hudomju.swipe.adapter.ListViewAdapter;
import com.hudomju.swipe.adapter.RecyclerViewAdapter;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import static android.widget.Toast.LENGTH_SHORT;
import static androidx.recyclerview.widget.ItemTouchHelper.LEFT;
//Volley
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
//JSON
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class TaskActivity extends AppCompatActivity {
private ListView lv;
public Adapter adapter;
public ArrayList<Model> modelArrayList;
public JSONArray data_array=new JSONArray();
public JSONArray cache=new JSONArray();
public int flag=0,flag1=0;
Connectivity con=new Connectivity();
private String urlJsonArry = "https://forestweb.herokuapp.com/apptask";
private String urltask = "https://forestweb.herokuapp.com/gettask";
private static String TAG = MainActivity.class.getSimpleName();
private String jsonResponse;
private String[] myList = new String[]{"Benz", "Bike",
"Car","Carrera"
,"Ferrari","Harly",
"Lamborghini","Silver"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
lv = (ListView) findViewById(R.id.listview);
modelArrayList=populateList();
Log.d("before",modelArrayList.toString());
Log.d("internet",String.valueOf(con.isConnected(this)));
if(con.isConnected(this))
{
new CountDownTimer(3000,1000){
//send tasks from cache
@Override
public void onTick(long millisUntilFinished) {
try {
if(flag1==0) {
String data = readFromFile("cache.txt");
Log.d("cache data", data);
if (data.length() != 0) {
cache = new JSONArray(data);
JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST, urlJsonArry, cache,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
Appcontroller.getInstance().addToRequestQueue(req);
}
}
flag1=1;
}catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFinish() {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("cache.txt", MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
new CountDownTimer(3000, 1000) {
//get new task
public void onTick(long millisUntilFinished) {
if (flag==0){
Log.d("wait","wait function");
Log.d("wait","wait function continue");
try {
modelArrayList=makeJsonArrayRequest();
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("hello",modelArrayList.toString());
}
flag=1;
}
public void onFinish() {
// adapter = new Adapter(this,modelArrayList);
// lv.setAdapter(adapter);
next();
}
}.start();
}
}.start();
}
else{
//Offline
String data=readFromFile("tasks.txt");
final ArrayList<Model> list = new ArrayList<>();
Log.d("from cache",data);
try {
JSONArray tasks = new JSONArray(data);
Log.d("list",tasks.toString());
for(int i = 0; i < tasks.length(); i++){
Model model = new Model();
JSONObject curr = tasks.getJSONObject(i);
model.setName(curr.getString("task_info"));
list.add(model);
}
Log.d("add list",list.toString());
data_array=tasks;
modelArrayList=list;
}
catch(JSONException e){
e.printStackTrace();
}
next();
}
// adapter = new Adapter(this,modelArrayList);
// lv.setAdapter(adapter);
//
// final SwipeToDismissTouchListener<ListViewAdapter> touchListener =
// new SwipeToDismissTouchListener<>(
// new ListViewAdapter(lv),
// new SwipeToDismissTouchListener.DismissCallbacks<ListViewAdapter>() {
// @Override
// public boolean canDismiss(int position) {
// return true;
// }
//
// @Override
// public void onDismiss(ListViewAdapter view, int position) {
// adapter.remove(position);
// }
// });
//
// lv.setOnTouchListener(touchListener);
// lv.setOnScrollListener((AbsListView.OnScrollListener) touchListener.makeScrollListener());
// lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// if (touchListener.existPendingDismisses()) {
// touchListener.undoPendingDismiss();
// } else {
// Toast.makeText(TaskActivity.this, "Position " + position, LENGTH_SHORT).show();
// }
// }
// });
}
public void next(){
Log.d("check list",modelArrayList.toString());
//if list is empty display no task
try {
adapter = new Adapter(this,modelArrayList);
lv.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "No Task" , LENGTH_SHORT).show();
}
final SwipeToDismissTouchListener<ListViewAdapter> touchListener =
new SwipeToDismissTouchListener<>(
new ListViewAdapter(lv),
new SwipeToDismissTouchListener.DismissCallbacks<ListViewAdapter>() {
@Override
public boolean canDismiss(int position) {
return true;
}
@Override
public void onDismiss(ListViewAdapter view, int position) {
adapter.remove(position);
try {
sendrequest(position);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
lv.setOnTouchListener(touchListener);
lv.setOnScrollListener((AbsListView.OnScrollListener) touchListener.makeScrollListener());
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (touchListener.existPendingDismisses()) {
touchListener.undoPendingDismiss();
} else {
Toast.makeText(TaskActivity.this, "Position " + position, LENGTH_SHORT).show();
}
}
});
}
private ArrayList<Model> populateList(){
ArrayList<Model> list = new ArrayList<>();
for(int i = 0; i < myList.length; i++){
Model model = new Model();
model.setName(myList[i]);
list.add(model);
}
return list;
}
//server request
private ArrayList<Model> makeJsonArrayRequest() throws JSONException {
// showpDialog();
final ArrayList<Model> list = new ArrayList<>();
String temp = "";
FileInputStream fin = null;
try {
fin = openFileInput("mytextfile.txt");
int c;
while ((c = fin.read()) != -1) {
temp = temp + Character.toString((char) c);
}
fin.close();
}catch (Exception e) {
e.printStackTrace();
}
JSONObject d=new JSONObject();
d.put("id",temp);
JSONArray xyz=new JSONArray();
xyz.put(temp);
JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST,urltask,xyz,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d("json array", response.toString());
try {
// JSONObject jsonObject = new JSONObject();
// jsonObject.put("task", response.toString());
writeToFile(response.toString());
JSONArray tasks = new JSONArray(response.toString());
Log.d("list",tasks.toString());
for(int i = 0; i < tasks.length(); i++){
Model model = new Model();
JSONObject curr = tasks.getJSONObject(i);
model.setName(curr.getString("task_info"));
list.add(model);
}
Log.d("add list",list.toString());
data_array=tasks;
// return(list);
}
catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to request queue
Appcontroller.getInstance().addToRequestQueue(req);
Log.d("function",list.toString());
return list;
}
private void sendrequest(int i) throws JSONException {
if(con.isConnected(this)) {
JSONObject rem = (JSONObject) data_array.get(i);
rem.remove("status");
rem.put("status", "complete");
JsonObjectRequest req = new JsonObjectRequest(urlJsonArry, rem,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject data) {
Log.d("response", data.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hidepDialog();
}
});
// Adding request to request queue
Appcontroller.getInstance().addToRequestQueue(req);
}
Connectivity con=new Connectivity();
if(!con.isConnected(this))
{
JSONObject rem = (JSONObject) data_array.get(i);
rem.remove("status");
rem.put("status", "complete");
cache.put(rem);
writeToFilecache(cache.toString());
}
int len=data_array.length();
JSONArray temp=new JSONArray();
for (int x=0;x<len;x++)
{
//Excluding the item at position
if (x != i)
{
temp.put(data_array.get(x));
}
}
data_array=temp;
writeToFile(data_array.toString());
Log.d("function",modelArrayList.toString());
}
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("tasks.txt", MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private void writeToFilecache(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("cache.txt", MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String readFromFile(String file) {
String ret = "";
try {
InputStream inputStream = openFileInput(file);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
}
| [
"[email protected]"
]
| |
a3dbf4545e1fe838731ab7d67cbb3aa59a59a7f3 | d1c6b49b98c6627e299a5936eba648d5140923a1 | /board2/src/main/java/com/ktds/dojun/board/web/ViewModifyServlet.java | 0b1dd79e5043297d4b73c9f50860585e30fe6c0b | []
| no_license | hondaas/sts | 3f797c102fa8543d9bae380469d113d9607675d2 | f878db2fe3a5724b7bf01b28db52f7c12c6fe298 | refs/heads/master | 2021-06-14T15:05:47.434547 | 2017-03-22T09:11:15 | 2017-03-22T09:11:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,565 | java | package com.ktds.dojun.board.web;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ktds.dojun.board.biz.BoardBiz;
import com.ktds.dojun.board.biz.BoardBizImpl;
import com.ktds.dojun.board.vo.BoardVO;
/**
* Servlet implementation class ViewModifyServlet
*/
public class ViewModifyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private BoardBiz boardBiz;
public ViewModifyServlet() {
boardBiz = new BoardBizImpl();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String boardIdString = request.getParameter("boardId");
int boardId = 0;
try {
boardId = Integer.parseInt(boardIdString);
} catch (NumberFormatException e) {
throw new RuntimeException("존재하지 않는 게시글이거나 잘못된 접근");
}
BoardVO boardVO = boardBiz.getOneArticle(boardId);
String content = boardVO.getContent();
content = content.replaceAll("<br/>", "\n");
boardVO.setContent(content);
request.setAttribute("board", boardVO);
RequestDispatcher dispatcher = request.getRequestDispatcher("/modify.jsp");
dispatcher.forward(request, response);
}
}
| [
"[email protected]"
]
| |
bf65770616f7ddeae8be8c50e666831e7e3d127a | c160d3dba2febfd6572a9df3641a790580edc188 | /src/main/java/com/example/strategy_pattern/demo3/LanguageBook.java | 1873161c315961882bdfd2cfc42aa6d84f6e762a | []
| no_license | wangwei216/design-patterns | ae33c4fca5e2ea6b70f3c5eea69df7bbc4b981b2 | 5502b7431cc5fe75b1d3b696d8bd9adf0e76e9ba | refs/heads/master | 2020-03-28T20:19:38.630411 | 2019-04-04T02:49:20 | 2019-04-04T02:49:20 | 149,059,990 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 273 | java | package com.example.strategy_pattern.demo3;
public class LanguageBook implements Discount {
@Override
public double BookDiscount(int pirce) {
double sum = pirce - 2;
System.out.println("LanguageBook单价为:" + sum);
return sum;
}
}
| [
"[email protected]"
]
| |
bca54b6e65cc90e6817f41141c8d11fa5c1ea270 | 4e2311e57c1a47a3194c4228ae1c96cd00f0e687 | /corejavatraining/src/com/vm/training/java/Exceptions/BalanceLow.java | 17d47c58be50c77f61be47ebd82e160c337da7fd | []
| no_license | prembattineni/core-java-Training | 0f9f9066c7a15673f64b151fe59cb71dfe4549ca | 532cd529b522f6cee84356e131ce85dbb7b66d82 | refs/heads/master | 2023-05-27T09:06:01.294927 | 2021-06-17T11:41:41 | 2021-06-17T11:41:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 226 | java | package com.vm.training.java.Exceptions;
public class BalanceLow extends Exception{
String message;
BalanceLow(String message)
{
this.message=message;
}
@Override
public String toString() {
return message;
}
}
| [
"[email protected]"
]
| |
9792fa2e6b48ce4a40539361c37ab96abc027085 | adbbec77dac4c016e5d9467d75924e60cdc2c6ea | /src/com/company/structural/proxy/ServiceInterface.java | a1955d483f69643594201881bfe9289a1b448153 | []
| no_license | Kid72/Test2 | b292e6d05ab10add4ac5b474245146d0cda9adb3 | 5a098fe873a3b2e40f08b732f0846ae9bf34d1fb | refs/heads/master | 2023-04-01T02:13:28.358858 | 2021-03-11T10:09:33 | 2021-03-11T10:09:33 | 345,728,754 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 99 | java | package com.company.structural.proxy;
public interface ServiceInterface {
void operation();
}
| [
"[email protected]"
]
| |
06b9134d302ee93c1cc24757f295c9cb59933482 | d60e287543a95a20350c2caeabafbec517cabe75 | /LACCPlus/HBase/3020_1.java | 127ee7e9ddf575037d59797050c14680c9ae1b41 | [
"MIT"
]
| permissive | sgholamian/log-aware-clone-detection | 242067df2db6fd056f8d917cfbc143615c558b2c | 9993cb081c420413c231d1807bfff342c39aa69a | refs/heads/main | 2023-07-20T09:32:19.757643 | 2021-08-27T15:02:50 | 2021-08-27T15:02:50 | 337,837,827 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,572 | java | //,temp,THBaseService.java,7101,7128,temp,THBaseService.java,6581,6608
//,2
public class xxx {
public void onError(java.lang.Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TSerializable msg;
isTableAvailableWithSplit_result result = new isTableAvailableWithSplit_result();
if (e instanceof TIOError) {
result.io = (TIOError) e;
result.setIoIsSet(true);
msg = result;
} else if (e instanceof org.apache.thrift.transport.TTransportException) {
_LOGGER.error("TTransportException inside handler", e);
fb.close();
return;
} else if (e instanceof org.apache.thrift.TApplicationException) {
_LOGGER.error("TApplicationException inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TApplicationException)e;
} else {
_LOGGER.error("Exception inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
} catch (java.lang.Exception ex) {
_LOGGER.error("Exception writing to internal frame buffer", ex);
fb.close();
}
}
}; | [
"[email protected]"
]
| |
1441e5dfb19a931fd03cc5abaff6bf9b98db1580 | 8196d31e59f4185d03fc7dbeb632f30d79c85b62 | /warehouse/src/main/java/com/gin/wms/warehouse/operator/Picking/PickingTaskActivity.java | c25a972c715808969165265dbab5652d899d381b | []
| no_license | kelvinks777/WMS_Android | 5cc274ea121ec2734057b9530e2ad5d3106dd51b | bb0e06ed87ec0e754cb1b6c285eb88a2761006b0 | refs/heads/master | 2020-05-02T02:31:45.331488 | 2019-03-26T03:22:48 | 2019-03-26T03:22:48 | 177,706,363 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 28,800 | java | package com.gin.wms.warehouse.operator.Picking;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.bosnet.ngemart.libgen.DateUtil;
import com.bosnet.ngemart.libgen.barcode_scanner.integration.IntentIntegrator;
import com.bosnet.ngemart.libgen.barcode_scanner.integration.IntentResult;
import com.gin.wms.manager.PickingTaskManager;
import com.gin.wms.manager.db.data.CompUomData;
import com.gin.wms.manager.db.data.PickingTaskData;
import com.gin.wms.manager.db.data.PickingTaskDestItemData;
import com.gin.wms.manager.db.data.PickingTaskSourceItemData;
import com.gin.wms.manager.db.data.enums.TaskStatusEnum;
import com.gin.wms.warehouse.R;
import com.gin.wms.warehouse.base.WarehouseActivity;
import com.gin.wms.warehouse.component.CompUomInterpreter;
import com.gin.wms.warehouse.component.SingleInputDialogFragment;
import com.gin.wms.warehouse.operator.TaskSwitcherActivity;
import com.gin.wms.warehouse.warehouseProblem.WarehouseProblemReportActivity;
import java.text.MessageFormat;
import java.util.List;
public class PickingTaskActivity extends WarehouseActivity
implements View.OnClickListener,
SingleInputDialogFragment.InputManualInterface{
private PickingTaskManager pickingTaskManager;
private PickingTaskData pickingTaskData;
private EditText txtId, txtBarcode, txtPalletNumber, txtProductName, txtExpiredDate;
private TextView tvToolbarTitle, tvToolbarCounter, tvLocation;
private ProgressBar spinnerPickingTask;
private Button btnStartPicking, btnNextPicking, btnFinishPicking, btnReport;
private CardView cardExpDate;
private CompUomInterpreter compUomInterpreter;
private static int SCAN_PICKING_ID_CODE = 1001;
private String currentAction;
private boolean alreadyStartTask;
private double actualSourcePickingQty = 0;
private double actualDestPickingQty = 0;
private static int DIALOG_FRAGMENT_TYPE_CODE_FOR_PALLET = 999;
private static int DIALOG_FRAGMENT_TYPE_CODE_FOR_BARCODE = 666;
public static String PICKING_TASK_ID = "pickingTaskId";
private enum CurrentActionEnum {
PICKING_FROM_SOURCE("PICKING_FROM_SOURCE"),
PICKING_TO_DEST("PICKING_TO_DEST");
private String action;
CurrentActionEnum(String action) {
this.action = action;
}
public String getAction() {
return action;
}
}
//region Override function
@Override
protected void onCreate(Bundle savedInstanceState) {
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picking_task);
initObject();
initComponent();
initToolbar();
getBundle();
getPickingTaskDataThread();
}catch (Exception ex){
showErrorDialog(ex);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imgBtnBarcode:
if (alreadyStartTask)
LaunchBarcodeScanner(SCAN_PICKING_ID_CODE);
else
showInfoDialog(getResources().getString(R.string.info), getResources().getString(R.string.info_must_start_task));
break;
case R.id.btnNextPicking:
showNextItemToUi();
break;
case R.id.btnStartPicking:
showAskDialog(getResources().getString(R.string.start_picking), getResources().getString(R.string.ask_start_task),
(dialog, which) -> startPickingThread(),
(dialog, which) -> dialog.dismiss()
);
break;
case R.id.btnReport:
Intent intent = new Intent(this, WarehouseProblemReportActivity.class);
startActivity(intent);
break;
case R.id.btnFinishPicking:
finishTask();
break;
case R.id.txtBarcode:
if (alreadyStartTask)
showInputBarcodeDialog();
else
showInfoDialog(getResources().getString(R.string.info), getResources().getString(R.string.info_must_start_task));
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try{
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (resultCode == Activity.RESULT_OK && (requestCode == SCAN_PICKING_ID_CODE))
validateLocationId(result.getContents());
}
}catch (Exception ex){
showErrorDialog(ex);
}
}
@Override
public void onBackPressed() {
if(currentAction.equals(CurrentActionEnum.PICKING_FROM_SOURCE.getAction())){
showInfoSnackBar(getResources().getString(R.string.exit_warning));
}else if(currentAction.equals(CurrentActionEnum.PICKING_TO_DEST.getAction())){
if((DescLocationHelper.currentIndex >= pickingTaskData.destBin.size()-1) && DescLocationHelper.hasCorrectLocation){
super.onBackPressed();
finish();
}else{
showInfoSnackBar(getResources().getString(R.string.exit_warning));
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
showInfoSnackBar(getResources().getString(R.string.exit_warning));
break;
}
return true;
}
@Override
public void onTextInput(int typeCode, String inputText) {
try{
if(typeCode == DIALOG_FRAGMENT_TYPE_CODE_FOR_PALLET){
showAskDialog(getResources().getString(R.string.update_pallet_number),
MessageFormat.format(getString(R.string.ask_to_update_pallet_number), inputText),
(dialog, which) -> UpdatePalletNumberThread(inputText),
(dialog, which) -> dialog.dismiss()
);
}else if(typeCode == DIALOG_FRAGMENT_TYPE_CODE_FOR_BARCODE){
validateLocationId(inputText);
}else{
throw new ClassNotFoundException("typeCode is not match !");
}
}catch (Exception e){
showErrorDialog(e);
}
}
//endregion
//region Init
private void initToolbar(){
tvToolbarTitle.setText(getResources().getString(R.string.picking_task_title));
}
private void initComponent(){
ImageButton imgBtnBarcode = findViewById(R.id.imgBtnBarcode);
txtId = findViewById(R.id.txtId);
txtBarcode = findViewById(R.id.txtBarcode);
txtPalletNumber = findViewById(R.id.txtPalletNumber);
txtExpiredDate = findViewById(R.id.txtExpiredDate);
txtProductName = findViewById(R.id.txtProductName);
compUomInterpreter = findViewById(R.id.compUomInterpreter);
spinnerPickingTask = findViewById(R.id.spinnerPickingTask);
btnStartPicking = findViewById(R.id.btnStartPicking);
btnNextPicking = findViewById(R.id.btnNextPicking);
btnFinishPicking = findViewById(R.id.btnFinishPicking);
btnReport = findViewById(R.id.btnReport);
cardExpDate = findViewById(R.id.cardExpDate);
tvToolbarTitle = findViewById(R.id.tvToolbarTitle);
tvToolbarCounter = findViewById(R.id.tvToolbarCounter);
tvLocation = findViewById(R.id.tvLocation);
imgBtnBarcode.setOnClickListener(this);
txtBarcode.setOnClickListener(this);
btnStartPicking.setOnClickListener(this);
btnNextPicking.setOnClickListener(this);
btnFinishPicking.setOnClickListener(this);
btnReport.setOnClickListener(this);
clearUi();
setCardExpDateVisibility(true);
}
private void initObject()throws Exception{
pickingTaskManager = new PickingTaskManager(getApplicationContext());
}
private void setSpinnerVisibility(boolean needToShow){
if(needToShow){
if(spinnerPickingTask.getVisibility() == View.GONE)
spinnerPickingTask.setVisibility(View.VISIBLE);
}else {
if(spinnerPickingTask.getVisibility() == View.VISIBLE)
spinnerPickingTask.setVisibility(View.GONE);
}
}
//endregion
//region Ui
private void getBundle(){
if(getIntent().getExtras() != null)
this.pickingTaskData = (PickingTaskData)getIntent().getSerializableExtra(PICKING_TASK_ID);
}
private void showInputPalletDialog(){
String customTitle = "Masukkan Nomor Pallet Tujuan Sebelum Memulai Task Ini";
DialogFragment dialogFragment;
dialogFragment = SingleInputDialogFragment.newInstanceWithCustomTitle(DIALOG_FRAGMENT_TYPE_CODE_FOR_PALLET, customTitle, "");
dialogFragment.setCancelable(false);
dialogFragment.show(getSupportFragmentManager(), "");
}
private void showInputBarcodeDialog(){
DialogFragment dialogFragment;
dialogFragment = SingleInputDialogFragment.newInstance(DIALOG_FRAGMENT_TYPE_CODE_FOR_BARCODE, "Barcode", txtBarcode.getText().toString());
dialogFragment.show(getSupportFragmentManager(), "");
}
private void setCardExpDateVisibility(boolean isShowProperty){
if(isShowProperty){
if(cardExpDate.getVisibility() == View.GONE)
cardExpDate.setVisibility(View.VISIBLE);
}else{
if(cardExpDate.getVisibility() == View.VISIBLE)
cardExpDate.setVisibility(View.GONE);
}
}
private void clearUi(){
txtId.setText("");
txtBarcode.setText("");
txtProductName.setText("");
txtExpiredDate.setText("");
}
private void setSourceBinDataToUi(PickingTaskSourceItemData sourceItemData){
clearUi();
tvLocation.setText(getResources().getString(R.string.source_location));
txtId.setText(sourceItemData.sourceBinId.trim());
txtPalletNumber.setText(sourceItemData.palletNo.trim());
txtProductName.setText(sourceItemData.productName.trim());
txtExpiredDate.setText(DateUtil.DateToStringFormat("dd/MM/yyyy", sourceItemData.expiredData).trim());
setUpCompUomInterpreter(sourceItemData.palletConversionValue, sourceItemData.getCompUom(), sourceItemData.qty);
setCurrentStepTask();
}
private void setDestinationDataToUi(PickingTaskDestItemData taskDestItemData){
clearUi();
tvLocation.setText(getResources().getString(R.string.source_destination));
txtId.setText(taskDestItemData.destBinId);
txtPalletNumber.setText(taskDestItemData.palletNo);
txtProductName.setText(taskDestItemData.productName);
txtExpiredDate.setText("");
setUpCompUomInterpreter(taskDestItemData.palletConversionValue, taskDestItemData.getCompUom(), taskDestItemData.qty);
setCurrentStepTask();
}
private void setUpCompUomInterpreter(double palletConversionValue, CompUomData compUomData, double qty){
compUomInterpreter.setPalletConversion(palletConversionValue);
compUomInterpreter.setCompUomData(compUomData);
compUomInterpreter.setQty(qty);
}
private void setCompUomInterpreterActive(){
if(currentAction.equals(CurrentActionEnum.PICKING_FROM_SOURCE.getAction()))
compUomInterpreter.setEditButtonActive(true);
else
compUomInterpreter.setEditButtonActive(false);
}
//endregion
//region Validation
private void finishTask(){
showAskDialog(getResources().getString(R.string.info), getResources().getString(R.string.ask_finish_task),
(dialog, which) -> finishPickingTaskThread(),
(dialog, which) -> dialog.dismiss());
}
private void showNextItemToUi(){
if(currentAction.equals(CurrentActionEnum.PICKING_FROM_SOURCE.getAction()))
updateSourceItemQty();
else if(currentAction.equals(CurrentActionEnum.PICKING_TO_DEST.getAction()))
updateDestinationItemQty();
}
private void updateSourceItemQty(){
if(SourceBinHelper.hasCorrectLocation){
if(compUomInterpreter.getQty() > SourceBinHelper.sourceItemData.qty){
showErrorDialog(getResources().getString(R.string.input_qty_cannot_larger_than) + " " +(int)SourceBinHelper.sourceItemData.qty);
} else{
SourceBinHelper.sourceItemData.qty = compUomInterpreter.getQty();
updatePickingSourceQtyThread();
}
}else{
showErrorDialog(getResources().getString(R.string.bin_not_selected_yet));
}
}
private void updateDestinationItemQty(){
if(DescLocationHelper.hasCorrectLocation){
if(validatePickingDest()){
DescLocationHelper.destItemData.qty = compUomInterpreter.getQty();
updatePickingDestQtyThread();
} else{
showRelevantPickingDestQtyToFill();
}
}else{
showErrorDialog(getResources().getString(R.string.dest_not_selected_yet));
}
}
private boolean validatePickingDest(){
return actualSourcePickingQty >= (compUomInterpreter.getQty() + actualDestPickingQty);
}
private void showRelevantPickingDestQtyToFill(){
double relevantQty = actualSourcePickingQty - (compUomInterpreter.getQty() + actualDestPickingQty);
if(relevantQty > 0)
showInfoDialog(getResources().getString(R.string.input_qty),getResources().getString(R.string.allowed_qty_to_input) + relevantQty);
else
showInfoDialog(getResources().getString(R.string.input_qty), getResources().getString(R.string.input_qty_has_maximum_amount));
}
private void validateLocationId(String locationId){
if(currentAction.equals(CurrentActionEnum.PICKING_FROM_SOURCE.getAction()))
validateSourceBinId(locationId);
else if(currentAction.equals(CurrentActionEnum.PICKING_TO_DEST.getAction()))
validateDestinationId(locationId);
}
private void validateSourceBinId(String locationId){
List<PickingTaskSourceItemData> sourceBin = pickingTaskData.sourceBin;
if(sourceBin.get(SourceBinHelper.currentIndex).sourceBinId.toLowerCase().equals(locationId.toLowerCase())){
SourceBinHelper.hasCorrectLocation = true;
txtBarcode.setText(locationId);
showInfoSnackBar(getResources().getString(R.string.source_bin_match));
}else{
txtBarcode.setText("");
SourceBinHelper.hasCorrectLocation = false;
showErrorSnackBar(getResources().getString(R.string.source_bin_not_match));
}
}
private void validateDestinationId(String locationId){
List<PickingTaskDestItemData> destLoc = pickingTaskData.destBin;
if(destLoc.get(DescLocationHelper.currentIndex).destBinId.toLowerCase().equals(locationId.toLowerCase())){
txtBarcode.setText(locationId);
DescLocationHelper.hasCorrectLocation = true;
showInfoSnackBar(getResources().getString(R.string.destination_bin_match));
}else{
txtBarcode.setText("");
DescLocationHelper.hasCorrectLocation = false;
showErrorSnackBar(getResources().getString(R.string.destination_bin_not_match));
}
}
//endregion
//region Threads
private void getPickingTaskDataThread(){
ThreadStart(new ThreadHandler<PickingTaskData>() {
@Override
public void onPrepare() throws Exception {
setSpinnerVisibility(true);
}
@Override
public PickingTaskData onBackground() throws Exception {
if(pickingTaskData == null)
pickingTaskData = pickingTaskManager.findAvailablePickingTask();
return pickingTaskData;
}
@Override
public void onError(Exception e) {
setSpinnerVisibility(false);
showErrorDialog(e);
}
@Override
public void onSuccess(PickingTaskData data) throws Exception {
initFirstUi(data);
}
@Override
public void onFinish() {
setSpinnerVisibility(false);
}
void initFirstUi(PickingTaskData data){
if(data.getStatus() == TaskStatusEnum.NEW){
btnStartPicking.setVisibility(View.VISIBLE);
btnStartPicking.setText(getResources().getString(R.string.start_picking_source_action_text_button));
alreadyStartTask = false;
}else if(data.getStatus() == TaskStatusEnum.PROGRESS){
btnStartPicking.setVisibility(View.GONE);
btnNextPicking.setVisibility(View.VISIBLE);
alreadyStartTask = true;
if(data.destBin.get(0).palletNo.equals(""))
showInputPalletDialog();
}
tvToolbarTitle.setText(getResources().getString(R.string.picking_source_action));
pickingTaskData = data;
currentAction = CurrentActionEnum.PICKING_FROM_SOURCE.getAction();
SourceBinHelper.currentIndex = 0;
SourceBinHelper.sourceItemData = data.sourceBin.get(SourceBinHelper.currentIndex);
setSourceBinDataToUi(SourceBinHelper.sourceItemData);
}
});
}
private void setCurrentStepTask(){
if(currentAction.equals(CurrentActionEnum.PICKING_FROM_SOURCE.getAction()))
tvToolbarCounter.setText("1/2");
else if(currentAction.equals(CurrentActionEnum.PICKING_TO_DEST.getAction()))
tvToolbarCounter.setText("2/2");
}
private void startPickingThread(){
ThreadStart(new ThreadHandler<Boolean>() {
@Override
public void onPrepare() throws Exception {
startProgressDialog(getResources().getString(R.string.start_picking_process), ProgressType.SPINNER);
}
@Override
public Boolean onBackground() throws Exception {
pickingTaskManager.startPickingTask(pickingTaskData.pickingTaskId);
return true;
}
@Override
public void onError(Exception e) {
dismissProgressDialog();
showErrorDialog(e);
}
@Override
public void onSuccess(Boolean data) throws Exception {
alreadyStartTask = true;
btnStartPicking.setVisibility(View.GONE);
btnNextPicking.setVisibility(View.VISIBLE);
if(pickingTaskData.destBin.get(0).palletNo.equals(""))
showInputPalletDialog();
}
@Override
public void onFinish() {
dismissProgressDialog();
}
});
}
private void updatePickingSourceQtyThread(){
ThreadStart(new ThreadHandler<Boolean>() {
@Override
public void onPrepare() throws Exception {
startProgressDialog(getResources().getString(R.string.saving_data), ProgressType.SPINNER);
}
@Override
public Boolean onBackground() throws Exception {
Thread.sleep(500);
pickingTaskManager.updatePickingSourceQty(SourceBinHelper.sourceItemData);
return true;
}
@Override
public void onError(Exception e) {
dismissProgressDialog();
showErrorDialog(e);
}
@Override
public void onSuccess(Boolean data) throws Exception {
setActualPickingSourceQty();
if(isPickingSourceAvailable())
updateNextPickingSourceToUi();
else
switchToPickingDest();
setCompUomInterpreterActive();
}
@Override
public void onFinish() {
dismissProgressDialog();
}
void setActualPickingSourceQty(){
PickingTaskSourceItemData data = pickingTaskData.sourceBin.get(SourceBinHelper.currentIndex);
if(data.qty != compUomInterpreter.getQty())
actualSourcePickingQty = actualSourcePickingQty + compUomInterpreter.getQty();
else
actualSourcePickingQty = actualSourcePickingQty + data.qty;
}
boolean isPickingSourceAvailable(){
return pickingTaskData.sourceBin.size()-1 > SourceBinHelper.currentIndex;
}
void updateNextPickingSourceToUi(){
SourceBinHelper.currentIndex = SourceBinHelper.currentIndex + 1;
SourceBinHelper.hasCorrectLocation = false;
SourceBinHelper.sourceItemData = pickingTaskData.sourceBin.get(SourceBinHelper.currentIndex);
setSourceBinDataToUi(SourceBinHelper.sourceItemData);
}
void switchToPickingDest(){
showInfoDialog(getResources().getString(R.string.info), getResources().getString(R.string.info_no_more_picking_source_data));
setCardExpDateVisibility(false);
tvToolbarTitle.setText(getResources().getString(R.string.picking_source_action));
SourceBinHelper.clear();
currentAction = CurrentActionEnum.PICKING_TO_DEST.getAction();
setNewDescLocationHelper();
setPickingDestToUi();
}
void setNewDescLocationHelper(){
DescLocationHelper.clear();
DescLocationHelper.destItemData = pickingTaskData.destBin.get(DescLocationHelper.currentIndex);
}
void setPickingDestToUi(){
setDestinationDataToUi(DescLocationHelper.destItemData);
}
});
}
private void updatePickingDestQtyThread(){
ThreadStart(new ThreadHandler<Boolean>() {
@Override
public void onPrepare() throws Exception {
startProgressDialog(getResources().getString(R.string.saving_data), ProgressType.SPINNER);
}
@Override
public Boolean onBackground() throws Exception {
Thread.sleep(500);
pickingTaskManager.updatePickingDestQty(DescLocationHelper.destItemData);
return true;
}
@Override
public void onError(Exception e) {
dismissProgressDialog();
showErrorDialog(e);
}
@Override
public void onSuccess(Boolean data) throws Exception {
setActualPickingDestQty();
if(isPickingDestAvailable())
updateNextPickingLocationToUi();
else
setNoMoreTaskToUi();
}
@Override
public void onFinish() {
dismissProgressDialog();
}
boolean isPickingDestAvailable(){
int nextPosition = DescLocationHelper.currentIndex + 1;
return pickingTaskData.destBin.size()-1 >= nextPosition;
}
void setActualPickingDestQty(){
actualDestPickingQty = actualDestPickingQty + compUomInterpreter.getQty();
}
void updateNextPickingLocationToUi(){
DescLocationHelper.currentIndex = DescLocationHelper.currentIndex + 1;
DescLocationHelper.hasCorrectLocation = false;
DescLocationHelper.destItemData = pickingTaskData.destBin.get(DescLocationHelper.currentIndex);
setDestinationDataToUi(DescLocationHelper.destItemData);
}
void setNoMoreTaskToUi(){
DescLocationHelper.destItemData = pickingTaskData.destBin.get(DescLocationHelper.currentIndex);
btnNextPicking.setVisibility(View.GONE);
btnFinishPicking.setVisibility(View.VISIBLE);
btnReport.setVisibility(View.VISIBLE);
btnReport.setText(getResources().getString(R.string.btn_report));
btnFinishPicking.setText(getResources().getString(R.string.btnFinish));
showInfoDialog(getResources().getString(R.string.common_information_title),
getResources().getString(R.string.info_no_more_picking_dest_data_and_finish),
(dialog, which) -> finishPickingTaskThread());
}
});
}
private void finishPickingTaskThread(){
ThreadStart(new ThreadHandler<Boolean>() {
@Override
public void onPrepare() throws Exception {
startProgressDialog(getResources().getString(R.string.finish_picking_process), ProgressType.SPINNER);
}
@Override
public Boolean onBackground() throws Exception {
Thread.sleep(1000);
pickingTaskManager.finishPickingTask(pickingTaskData.pickingTaskId);
return null;
}
@Override
public void onError(Exception e) {
dismissProgressDialog();
showErrorDialog(e);
}
@Override
public void onSuccess(Boolean data) throws Exception {
moveToTaskSwitcher();
}
@Override
public void onFinish() {
dismissProgressDialog();
}
});
}
private void moveToTaskSwitcher(){
Intent intent = new Intent(this, TaskSwitcherActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
private void UpdatePalletNumberThread(String palletNumber){
ThreadStart(new ThreadHandler<Boolean>() {
String pickingTaskId = pickingTaskData.pickingTaskId;
@Override
public void onPrepare() throws Exception {
startProgressDialog(getResources().getString(R.string.update_pallet_number_process), ProgressType.SPINNER);
}
@Override
public Boolean onBackground() throws Exception {
Thread.sleep(500);
pickingTaskManager.updateDestPalletNumber(pickingTaskId, palletNumber);
pickingTaskData = pickingTaskManager.findAvailablePickingTask();
return true;
}
@Override
public void onError(Exception e) {
dismissProgressDialog();
showErrorDialog(e);
}
@Override
public void onSuccess(Boolean data) throws Exception {
showInfoDialog(getResources().getString(R.string.update_pallet_number), "Nomor pallet berhasil di simpan");
txtPalletNumber.setText(palletNumber);
}
@Override
public void onFinish() {
dismissProgressDialog();
}
});
}
//endregion
//region Wrapper class
private static class SourceBinHelper{
static int currentIndex = 0;
static boolean hasCorrectLocation = false;
static PickingTaskSourceItemData sourceItemData;
public static void clear(){
currentIndex = 0;
hasCorrectLocation = false;
sourceItemData = null;
}
}
private static class DescLocationHelper{
static int currentIndex = 0;
static boolean hasCorrectLocation = false;
static PickingTaskDestItemData destItemData;
public static void clear(){
currentIndex = 0;
hasCorrectLocation = false;
destItemData = null;
}
}
//endregion
}
| [
"[email protected]"
]
| |
bc422cc50e8e8fcc92504e3e02a7a504b4ace572 | 7cf82ae9bff36c887299928874b4c33b1a003d4d | /sparrow-zuul-gateway/src/main/java/org/ly817/sparrow/gateway/admin/mysql/DBDynamicRouteLocator.java | c6a785f992b61d2e452312c5bf977ec5d5dd0da2 | []
| no_license | LY817/sparrow | 21b624bcd5e78775129a70c14d93e95b6ad2691e | d049dea2b0eaa539081b5b1267916450258e81e3 | refs/heads/master | 2022-06-30T23:35:03.173454 | 2020-01-20T14:14:27 | 2020-01-20T14:14:27 | 231,089,116 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,170 | java | package org.ly817.sparrow.gateway.admin.mysql;
import org.ly817.sparrow.api.pojo.GatewayApiRoute;
import org.ly817.sparrow.gateway.dynamic.AbstractDynamicRouteLocator;
import org.ly817.sparrow.gateway.dynamic.ZuulRouteServiceDBImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.util.StringUtils;
import java.util.LinkedHashMap;
import java.util.List;
/**
* @author LY
* @date 2020/01/05 22:10
* <p>
* Description:
*/
public class DBDynamicRouteLocator extends AbstractDynamicRouteLocator {
@Autowired
private ZuulRouteServiceDBImpl zuulRouteService;
public DBDynamicRouteLocator(String servletPath, ZuulProperties properties) {
super(servletPath, properties);
}
/**
* 从数据库中读取路由信息
*
*/
@Override
public LinkedHashMap<String, ZuulProperties.ZuulRoute> loadDynamicRoutes() {
LinkedHashMap<String, ZuulProperties.ZuulRoute> routes = new LinkedHashMap<>();
List<GatewayApiRoute> results = zuulRouteService.listAll();
for (GatewayApiRoute result : results) {
// 映射的
if (StringUtils.isEmpty(result.getPath()) ) {
continue;
}
// serviceId和url不能同时为空
if (StringUtils.isEmpty(result.getServiceId())
&& StringUtils.isEmpty(result.getUrl())) {
continue;
}
ZuulProperties.ZuulRoute zuulRoute = new ZuulProperties.ZuulRoute();
try {
BeanUtils.copyProperties(result, zuulRoute);
String[] pathInfo = zuulRoute.getPath().split("/");
if (zuulRoute.getPath().startsWith("/")) {
zuulRoute.setId(pathInfo[1]);
} else {
zuulRoute.setId(pathInfo[0]);
}
} catch (Exception e) {
e.printStackTrace();
}
routes.put(zuulRoute.getPath(), zuulRoute);
}
return routes;
}
}
| [
"[email protected]"
]
| |
45ea4271a73234c3b1a97d889e6f27a7e7319561 | 6bf8f155407b6614655e24f35edb473bf30aae9b | /app/src/main/java/com/example/xiao/weather/db/City.java | 734f192bed38d8b8d01e860b1f45b82f402d6a98 | []
| no_license | LinShuHang/Weather | c1c4babb9c24f4cbe223cafecf1d7b9004be4d62 | fe8d3a6f57dd87e0d67f1bf990e58fa1840f085d | refs/heads/master | 2021-07-17T10:56:24.252967 | 2017-10-22T02:12:50 | 2017-10-22T02:12:50 | 107,790,612 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 842 | java | package com.example.xiao.weather.db;
import org.litepal.crud.DataSupport;
/**
* Created by Xiao航 on 2017/10/18.
*/
public class City extends DataSupport {
private int id;
private String cityName;
private int cityCode;
private int provinceId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public int getCityCode() {
return cityCode;
}
public void setCityCode(int cityCode) {
this.cityCode = cityCode;
}
public int getProvinceId() {
return provinceId;
}
public void setProvinceId(int provinceId) {
this.provinceId = provinceId;
}
}
| [
"[email protected]"
]
| |
981c81554b5b8afd9a4f7c502b950f9546bff153 | 8b8da9b3a7d3f661eff3f4bcf5bab027284670e3 | /ChessGame/com/chess/engine/board/Move.java | b6bd703b11e3d5da06a9ae94c06baa8f86191cf5 | []
| no_license | anthony5196/ChessGame | b495002b7f29a4381258f2aa9246e0a7bb4bf110 | c999acef32a98707a87e12868a41445d658ce41f | refs/heads/master | 2022-12-07T22:33:42.681337 | 2020-08-17T23:54:24 | 2020-08-17T23:54:24 | 288,093,312 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,972 | java | package com.chess.engine.board;
import com.chess.engine.board.Board.Builder;
import com.chess.engine.pieces.Pawn;
import com.chess.engine.pieces.Piece;
import com.chess.engine.pieces.Rook;
public abstract class Move{
final Board board;
final Piece movedPiece;
final int destinationCoordinate;
public static final Move NULL_MOVE = new NullMove();
Move(final Board board,
final Piece movedPiece,
final int destinationCoordinate){
this.board = board;
this.movedPiece = movedPiece;
this.destinationCoordinate = destinationCoordinate;
}
@Override
public int hashCode() {
final int prime = 31;
int result =1;
result = prime * result + this.destinationCoordinate;
result = prime * result + this.movedPiece.hashCode();
return result;
}
@Override
public boolean equals(final Object other) {
if(this == other) {
return true;
}
if(!(other instanceof Move)) {
return false;
}
final Move otherMove = (Move) other;
return getCurrentCoordinate() == otherMove.getCurrentCoordinate() &&
getDestinationCoordinate() == otherMove.getDestinationCoordinate() &&
getMovedPiece().equals(otherMove.getMovedPiece());
}
public int getCurrentCoordinate() {
return this.getMovedPiece().getPiecePosition();
}
public int getDestinationCoordinate() {
return this.destinationCoordinate;
}
public Piece getMovedPiece() {
return this.movedPiece;
}
public boolean isAttack() {
return false;
}
public boolean isCastlingMove() {
return false;
}
public Piece getAttackedPiece() {
return null;
}
public Board execute() {
final Board.Builder builder = new Builder();
for(final Piece piece: this.board.currentPlayer().getActivePieces()) {
if(!this.movedPiece.equals(piece)) {
builder.setPiece(piece);
}
}
for(final Piece piece : this.board.currentPlayer().getOpponent().getActivePieces()) {
builder.setPiece(piece);
}
//move the moved piece!
builder.setPiece(this.movedPiece.movePiece(this));
builder.setMoveMaker(this.board.currentPlayer().getOpponent().getAlliance());
return builder.build();
}
public static final class MajorMove extends Move{
public MajorMove(final Board board,
final Piece movedPiece,
final int destinationCoordinate){
super(board, movedPiece, destinationCoordinate);
}
}
public static class AttackMove extends Move{
final Piece attackedPiece;
public AttackMove(final Board board,
final Piece movedPiece,
final int destinationCoordinate,
final Piece attackedPiece){
super(board, movedPiece, destinationCoordinate);
this.attackedPiece = attackedPiece;
}
@Override
public int hashCode() {
return this.attackedPiece.hashCode() + super.hashCode();
}
@Override
public boolean equals(final Object other) {
if(this==other) {
return true;
}
if(!(other instanceof AttackMove)) {
return false;
}
final AttackMove otherAttackMove = (AttackMove) other;
return super.equals(otherAttackMove) && getAttackedPiece().equals(otherAttackMove.getAttackedPiece());
}
@Override
public Board execute() {
return null;
}
@Override
public boolean isAttack() {
return true;
}
@Override
public Piece getAttackedPiece() {
return this.attackedPiece;
}
}
public static final class PawnMove extends Move{
public PawnMove(final Board board,
final Piece movedPiece,
final int destinationCoordinate){
super(board, movedPiece, destinationCoordinate);
}
}
public static class PawnAttackMove extends AttackMove{
public PawnAttackMove(final Board board,
final Piece movedPiece,
final int destinationCoordinate,
final Piece attackedPiece){
super(board, movedPiece, destinationCoordinate, attackedPiece);
}
}
public static final class PawnEnPassantAttackMove extends PawnAttackMove{
public PawnEnPassantAttackMove(final Board board,
final Piece movedPiece,
final int destinationCoordinate,
final Piece attackedPiece){
super(board, movedPiece, destinationCoordinate, attackedPiece);
}
}
public static final class PawnJump extends Move{
public PawnJump(final Board board,
final Piece movedPiece,
final int destinationCoordinate){
super(board, movedPiece, destinationCoordinate);
}
@Override
public Board execute() {
final Builder builder = new Builder();
for(final Piece piece : this.board.currentPlayer().getActivePieces()) {
if(!this.movedPiece.equals(piece)) {
builder.setPiece(piece);
}
}
for(final Piece piece : this.board.currentPlayer().getOpponent().getActivePieces()) {
builder.setPiece(piece);
}
final Pawn movedPawn = (Pawn)this.movedPiece.movePiece(this);
builder.setPiece(movedPawn);
builder.setEnPassantPawn(movedPawn);
builder.setMoveMaker(this.board.currentPlayer().getOpponent().getAlliance());
return builder.build();
}
}
static abstract class CastleMove extends Move{
final Rook castleRook;
final int castleRookStart;
final int castleRookDestination;
public CastleMove(final Board board,
final Piece movedPiece,
final int destinationCoordinate,
final Rook castleRook,
final int castleRookStart,
final int castleRookDestination){
super(board, movedPiece, destinationCoordinate);
this.castleRook = castleRook;
this.castleRookStart = castleRookStart;
this.castleRookDestination = castleRookDestination;
}
public Rook getCastleRook() {
return this.castleRook;
}
@Override
public boolean isCastlingMove() {
return true;
}
@Override
public Board execute() {
final Builder builder = new Builder();
for(final Piece piece : this.board.currentPlayer().getActivePieces()) {
if(!this.movedPiece.equals(piece) && !this.castleRook.equals(piece)) {
builder.setPiece(piece);
}
}
for(final Piece piece : this.board.currentPlayer().getOpponent().getActivePieces()) {
builder.setPiece(piece);
}
builder.setPiece(this.movedPiece.movePiece(this));
//todo look into the first move on normal pieces
builder.setPiece(new Rook(this.castleRook.getPieceAlliance(), this.castleRookDestination));
builder.setMoveMaker(this.board.currentPlayer().getOpponent().getAlliance());
return builder.build();
}
}
public static final class KingSideCastleMove extends CastleMove{
public KingSideCastleMove(final Board board,
final Piece movedPiece,
final int destinationCoordinate,
final Rook castleRook,
final int castleRookStart,
final int castleRookDestination){
super(board, movedPiece, destinationCoordinate, castleRook, castleRookStart, castleRookDestination);
}
@Override
public String toString() {
return "0-0";
}
}
public static final class QueenSideCastleMove extends CastleMove{
public QueenSideCastleMove(final Board board,
final Piece movedPiece,
final int destinationCoordinate,
final Rook castleRook,
final int castleRookStart,
final int castleRookDestination){
super(board, movedPiece, destinationCoordinate, castleRook, castleRookStart, castleRookDestination);
}
@Override
public String toString() {
return "0-0-0";
}
}
public static final class NullMove extends Move{
public NullMove() {
super(null, null, -1);
}
@Override
public Board execute() {
throw new RuntimeException("Cannot execute the null move!");
}
}
public static class MoveFactory {
private MoveFactory() {
throw new RuntimeException("Not instantiable!");
}
public static Move createMove(final Board board,
final int currentCoordinate,
final int destinationCoordinate) {
for(final Move move: board.currentPlayer().getLegalMoves()) {
if(move.getCurrentCoordinate() == currentCoordinate &&
move.getDestinationCoordinate() == destinationCoordinate) {
return move;
}
}
return NULL_MOVE;
}
}
} | [
"[email protected]"
]
| |
e003487c38e90846e5ccff38c933622c6f532f0f | c57f5baf6f1c45136dcc19766d4cba7d31f8ce5a | /src/examples10/App.java | df8db44d1723222bc1715fec248843440611d15a | []
| no_license | jsimas/Java_MultiThreading_examples | fcb778551e94040613285a8da7be051dbbe7aeb5 | cc9beeecac1200649c7c782c6bdaa24c6e19884e | refs/heads/master | 2021-06-16T09:10:16.996330 | 2017-05-29T16:04:42 | 2017-05-29T16:04:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 273 | java | package examples10;
import javax.swing.SwingUtilities;
public class App {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MainFrame("SwingWorker Demo");
}
});
}
}
| [
"[email protected]"
]
| |
282e9e94ccd404b715908fe372d7c05cb0889914 | 28352a778bda88af95caea91b8dddc4bafc25b3a | /backend/src/main/java/it/polito/ai/project/business/services/authentication/CustomUserDetailsService.java | 48691599134a869850ba078538746c5dd3ff5937 | [
"MIT"
]
| permissive | ToMove2017/project | fc86042f9b993fa0ece91b144d0b46a91618d2b1 | 67aa5ba540e4025e9a42c0f3750a1c695f6354fd | refs/heads/master | 2021-03-22T04:49:47.795807 | 2018-08-02T09:39:44 | 2018-08-02T09:39:44 | 94,011,913 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,896 | java | package it.polito.ai.project.business.services.authentication;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import it.polito.ai.project.repo.StatusRepository;
import it.polito.ai.project.repo.UsersRepository;
import it.polito.ai.project.repo.entities.Status;
import it.polito.ai.project.repo.entities.User;
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UsersRepository userRepository;
@Autowired
private StatusRepository statusRepository;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
// the field email is used as username (to identify customer)
// don't do confusion with nickname!!
User user = userRepository.findByEmail(email);
if (user == null) {
throw new UsernameNotFoundException(email);
}
List<GrantedAuthority> auth = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER");
// The admin has also role admin
if (email.equals("admin")) {
auth.addAll(AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN"));
}
String password = user.getPassword();
// check if user confirmed the email
Status notConfirmedStatus = statusRepository.findByValue("NOT_VERIFIED").stream().findFirst().get();
boolean enabled = !user.getStatus().getId().equals(notConfirmedStatus.getId());
return new org.springframework.security.core.userdetails.User(email, password, enabled, true, true, true, auth);
}
}
| [
"[email protected]"
]
| |
f833d414e498450510c138761d511d0e6696ec2b | cfe6fbd2773a918647294fc26e2c2f727097a28c | /src/logica/datos/TasadorBaseDatos.java | bc5ba8bc1e89e7b5fc2893ecb15fd559a3099468 | []
| no_license | aitormati99/PROYECTOINMOBILIARIA | d3e4e92d376c15c5c6d0182fa0ef7dfbbe391d59 | a82cb0002c93b841821a398b4489e4e0189d067f | refs/heads/master | 2023-02-17T17:54:41.632478 | 2021-01-15T15:36:42 | 2021-01-15T15:36:42 | 304,356,825 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 4,404 | java | package logica.datos;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import logica.negocios.Comercial;
import logica.negocios.Tasador;
import java.text.SimpleDateFormat;
/**
*
* @author Aitor
*
*/
public class TasadorBaseDatos {
/**
* creo la tabla de los comerciales
*
* @throws SQLException
* si no se hace salta la excepción
*/
public static void createTasadorTable(Connection conn) throws SQLException {
// SQL statement for creating a new table
String sql = "CREATE TABLE IF NOT EXISTS tasador (\n" + " DNI text PRIMARY KEY,\n"
+ " sueldo integer NOT NULL,\n" + " horarioLaboral integer NOT NULL,\n"
+ " contadorFacturas integer NOT NULL\n" + " );";
try (Statement stmt = conn.createStatement()) {
// create a new table
stmt.execute(sql);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
/**
* insertar los tasadores en la bd
*
* @param DNI
* dni del tasador
* @param sueldo
* sueldo del tasador
* @param horarioLaboral
* horas que trabaja el tasador
* @param contadorFacturas
* numero de facturas del tasador
* @throws SQLException
* si no se hace salta la excepción
*/
public static void insertTasador(Connection conn, String DNI, int sueldo, int horarioLaboral,
int contadorFacturas) {
String sql = "INSERT INTO tasador(DNI,sueldo, horarioLaboral,contadorFacturas) VALUES(?,?,?,?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, DNI);
pstmt.setInt(2, sueldo);
pstmt.setInt(3, horarioLaboral);
pstmt.setInt(4, contadorFacturas);
pstmt.execute();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
/**
* selecciona todos los tasadores de la bd
*
* @param conn
* conexion con la bd
* @return devuelve tasadores de la bd
*/
public static ArrayList<Tasador> selectAllTasador(Connection conn) {
String sql = "SELECT DNI, sueldo, horarioLaboral,nombreClientes FROM tasador";
ArrayList<Tasador> list = new ArrayList<Tasador>();
try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) {
// loop through the result set
while (rs.next()) {
String dni = rs.getString("DNI");
int sueldo = rs.getInt("sueldo");
int horas = rs.getInt("horarioLaboral");
int contadorFacturas = rs.getInt("contadorFacturas");
Tasador select = new Tasador(dni, sueldo, horas, contadorFacturas);
list.add(select);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return list;
}
/**
* modifica los tasadores de la bd
*
* @param conn
* conexion de la bd
*
* @param conn
* conexion de la bd
*
* @param DNI
* dni del tasador
* @param sueldo
* sueldo del tasador
* @param horasDia
* horas que trabaja el tasador
* @param contadorFacturas
* facturas de los tasadores
*/
public static void updateTasador(Connection conn, String DNI, int sueldo, int horarioLaboral,
int contadorFacturas) {
String sql = "UPDATE tasador SET sueldo = ? , horarioLaboral = ? , contadorFacturas= ? WHERE DNI = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
// set the corresponding param
pstmt.setString(1, DNI);
pstmt.setDouble(2, sueldo);
pstmt.setInt(3, horarioLaboral);
pstmt.setInt(4, contadorFacturas);
// update
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
/**
* elimina el tasador
*
* @param conn
* conexion de la bd
*
* @param dni
* dni del tasador
*/
public static void delete(Connection conn, String dni) {
String sql = "DELETE FROM tasador WHERE DNI = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
// set the corresponding param
pstmt.setString(1, dni);
// execute the delete statement
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
| [
"[email protected]"
]
| |
5ecbe06c3284cbb5ffd3c42c4de3b2d0f25d15c3 | 848444eb6c7149cd9ebbfedda774731f86536a07 | /app/src/main/java/app/christhoval/rugbypty/models/Category.java | c677eace1d079dbf5399fae11368a5615884e545 | []
| no_license | christhoval06/rugby-pty-app | 3f81862098d0997c4fdb863a9875b14705867d0f | 542833d60afcfdf1b9a77a67eb76fbc1ffcd0dab | refs/heads/main | 2023-02-23T08:10:54.798286 | 2021-01-28T03:11:35 | 2021-01-28T03:11:35 | 333,631,105 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,403 | java | package app.christhoval.rugbypty.models;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Created by christhoval
* on 07/26/16.
*/
public class Category implements Serializable {
public String _id;
public String name;
public static Category fromJSON(JSONObject json) {
Category category = new Category();
try {
category._id = json.getString("_id");
category.name = json.getString("name");
} catch (JSONException e) {
e.printStackTrace();
return null;
}
return category;
}
public String getId() {
return _id;
}
public String getName() {
return name;
}
public static ArrayList<Category> fromJSON(JSONArray jsonArray) {
JSONObject json;
ArrayList<Category> categories = new ArrayList<>(jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
try {
json = jsonArray.getJSONObject(i);
} catch (Exception e) {
e.printStackTrace();
continue;
}
Category category = Category.fromJSON(json);
if (category != null) {
categories.add(category);
}
}
return categories;
}
}
| [
"[email protected]"
]
| |
3a3df0b64c0ad26032e88a9e7d0bc9ed54d957ba | 1e212405cd1e48667657045ad91fb4dc05596559 | /lib/openflowj-3.3.0-SNAPSHOT-sources (copy)/org/projectfloodlight/openflow/protocol/ver15/OFBsnTlvIpv6PrefixVer15.java | 19b64cfde6682173bc31fe9d72f21a32b6e0f518 | [
"Apache-2.0"
]
| permissive | aamorim/floodlight | 60d4ef0b6d7fe68b8b4688f0aa610eb23dd790db | 1b7d494117f3b6b9adbdbcf23e6cb3cc3c6187c9 | refs/heads/master | 2022-07-10T21:50:11.130010 | 2019-09-03T19:02:41 | 2019-09-03T19:02:41 | 203,223,614 | 1 | 0 | Apache-2.0 | 2022-07-06T20:07:15 | 2019-08-19T18:00:01 | Java | UTF-8 | Java | false | false | 9,989 | java | // Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_class.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver15;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;
class OFBsnTlvIpv6PrefixVer15 implements OFBsnTlvIpv6Prefix {
private static final Logger logger = LoggerFactory.getLogger(OFBsnTlvIpv6PrefixVer15.class);
// version: 1.5
final static byte WIRE_VERSION = 6;
final static int LENGTH = 21;
private final static IPv6Address DEFAULT_VALUE = IPv6Address.NONE;
private final static short DEFAULT_PREFIX_LENGTH = (short) 0x0;
// OF message fields
private final IPv6Address value;
private final short prefixLength;
//
// Immutable default instance
final static OFBsnTlvIpv6PrefixVer15 DEFAULT = new OFBsnTlvIpv6PrefixVer15(
DEFAULT_VALUE, DEFAULT_PREFIX_LENGTH
);
// package private constructor - used by readers, builders, and factory
OFBsnTlvIpv6PrefixVer15(IPv6Address value, short prefixLength) {
if(value == null) {
throw new NullPointerException("OFBsnTlvIpv6PrefixVer15: property value cannot be null");
}
this.value = value;
this.prefixLength = prefixLength;
}
// Accessors for OF message fields
@Override
public int getType() {
return 0x7a;
}
@Override
public IPv6Address getValue() {
return value;
}
@Override
public short getPrefixLength() {
return prefixLength;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
public OFBsnTlvIpv6Prefix.Builder createBuilder() {
return new BuilderWithParent(this);
}
static class BuilderWithParent implements OFBsnTlvIpv6Prefix.Builder {
final OFBsnTlvIpv6PrefixVer15 parentMessage;
// OF message fields
private boolean valueSet;
private IPv6Address value;
private boolean prefixLengthSet;
private short prefixLength;
BuilderWithParent(OFBsnTlvIpv6PrefixVer15 parentMessage) {
this.parentMessage = parentMessage;
}
@Override
public int getType() {
return 0x7a;
}
@Override
public IPv6Address getValue() {
return value;
}
@Override
public OFBsnTlvIpv6Prefix.Builder setValue(IPv6Address value) {
this.value = value;
this.valueSet = true;
return this;
}
@Override
public short getPrefixLength() {
return prefixLength;
}
@Override
public OFBsnTlvIpv6Prefix.Builder setPrefixLength(short prefixLength) {
this.prefixLength = prefixLength;
this.prefixLengthSet = true;
return this;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
@Override
public OFBsnTlvIpv6Prefix build() {
IPv6Address value = this.valueSet ? this.value : parentMessage.value;
if(value == null)
throw new NullPointerException("Property value must not be null");
short prefixLength = this.prefixLengthSet ? this.prefixLength : parentMessage.prefixLength;
//
return new OFBsnTlvIpv6PrefixVer15(
value,
prefixLength
);
}
}
static class Builder implements OFBsnTlvIpv6Prefix.Builder {
// OF message fields
private boolean valueSet;
private IPv6Address value;
private boolean prefixLengthSet;
private short prefixLength;
@Override
public int getType() {
return 0x7a;
}
@Override
public IPv6Address getValue() {
return value;
}
@Override
public OFBsnTlvIpv6Prefix.Builder setValue(IPv6Address value) {
this.value = value;
this.valueSet = true;
return this;
}
@Override
public short getPrefixLength() {
return prefixLength;
}
@Override
public OFBsnTlvIpv6Prefix.Builder setPrefixLength(short prefixLength) {
this.prefixLength = prefixLength;
this.prefixLengthSet = true;
return this;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
//
@Override
public OFBsnTlvIpv6Prefix build() {
IPv6Address value = this.valueSet ? this.value : DEFAULT_VALUE;
if(value == null)
throw new NullPointerException("Property value must not be null");
short prefixLength = this.prefixLengthSet ? this.prefixLength : DEFAULT_PREFIX_LENGTH;
return new OFBsnTlvIpv6PrefixVer15(
value,
prefixLength
);
}
}
final static Reader READER = new Reader();
static class Reader implements OFMessageReader<OFBsnTlvIpv6Prefix> {
@Override
public OFBsnTlvIpv6Prefix readFrom(ByteBuf bb) throws OFParseError {
int start = bb.readerIndex();
// fixed value property type == 0x7a
short type = bb.readShort();
if(type != (short) 0x7a)
throw new OFParseError("Wrong type: Expected=0x7a(0x7a), got="+type);
int length = U16.f(bb.readShort());
if(length != 21)
throw new OFParseError("Wrong length: Expected=21(21), got="+length);
if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
// Buffer does not have all data yet
bb.readerIndex(start);
return null;
}
if(logger.isTraceEnabled())
logger.trace("readFrom - length={}", length);
IPv6Address value = IPv6Address.read16Bytes(bb);
short prefixLength = U8.f(bb.readByte());
OFBsnTlvIpv6PrefixVer15 bsnTlvIpv6PrefixVer15 = new OFBsnTlvIpv6PrefixVer15(
value,
prefixLength
);
if(logger.isTraceEnabled())
logger.trace("readFrom - read={}", bsnTlvIpv6PrefixVer15);
return bsnTlvIpv6PrefixVer15;
}
}
public void putTo(PrimitiveSink sink) {
FUNNEL.funnel(this, sink);
}
final static OFBsnTlvIpv6PrefixVer15Funnel FUNNEL = new OFBsnTlvIpv6PrefixVer15Funnel();
static class OFBsnTlvIpv6PrefixVer15Funnel implements Funnel<OFBsnTlvIpv6PrefixVer15> {
private static final long serialVersionUID = 1L;
@Override
public void funnel(OFBsnTlvIpv6PrefixVer15 message, PrimitiveSink sink) {
// fixed value property type = 0x7a
sink.putShort((short) 0x7a);
// fixed value property length = 21
sink.putShort((short) 0x15);
message.value.putTo(sink);
sink.putShort(message.prefixLength);
}
}
public void writeTo(ByteBuf bb) {
WRITER.write(bb, this);
}
final static Writer WRITER = new Writer();
static class Writer implements OFMessageWriter<OFBsnTlvIpv6PrefixVer15> {
@Override
public void write(ByteBuf bb, OFBsnTlvIpv6PrefixVer15 message) {
// fixed value property type = 0x7a
bb.writeShort((short) 0x7a);
// fixed value property length = 21
bb.writeShort((short) 0x15);
message.value.write16Bytes(bb);
bb.writeByte(U8.t(message.prefixLength));
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("OFBsnTlvIpv6PrefixVer15(");
b.append("value=").append(value);
b.append(", ");
b.append("prefixLength=").append(prefixLength);
b.append(")");
return b.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFBsnTlvIpv6PrefixVer15 other = (OFBsnTlvIpv6PrefixVer15) obj;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
if( prefixLength != other.prefixLength)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value == null) ? 0 : value.hashCode());
result = prime * result + prefixLength;
return result;
}
}
| [
"alex@VM-UFS-001"
]
| alex@VM-UFS-001 |
e1e3764732a0b320c68d6ac8d2be4ddb88c775cb | a39ed46d1e54df79e4ba89479021173f5ddabf8d | /Mobile/odk/survey/src/org/opendatakit/survey/android/activities/MediaCaptureAudioActivity.java | 68e0eeb4b8d73e92c2308430a90cea4806e75e98 | []
| no_license | pforr/ME | f9666f426f11565e05b5654b9ab276ff68766df5 | 922c4eee8e12cfd02183a79af5a2f853b61c401a | refs/heads/master | 2021-01-21T13:33:37.209663 | 2016-05-27T06:55:33 | 2016-05-27T06:55:33 | 53,647,945 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,846 | java | /*
* Copyright (C) 2012-2013 University of Washington
*
* 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.opendatakit.survey.android.activities;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.opendatakit.common.android.utilities.MediaUtils;
import org.opendatakit.common.android.utilities.ODKFileUtils;
import org.opendatakit.common.android.utilities.WebLogger;
import org.opendatakit.survey.android.R;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Audio;
import android.widget.Toast;
/**
* Simple shim for media interactions.
*
* @author [email protected]
*
*/
public class MediaCaptureAudioActivity extends Activity {
private static final String t = "MediaCaptureAudioActivity";
private static final int ACTION_CODE = 1;
private static final String MEDIA_CLASS = "audio/";
private static final String APP_NAME = "appName";
private static final String URI_FRAGMENT = "uriFragment";
private static final String CONTENT_TYPE = "contentType";
private static final String URI_FRAGMENT_NEW_FILE_BASE = "uriFragmentNewFileBase";
private static final String HAS_LAUNCHED = "hasLaunched";
private static final String AFTER_RESULT = "afterResult";
private static final String ERROR_NO_FILE = "Media file does not exist! ";
private static final String ERROR_COPY_FILE = "Media file copy failed! ";
private String appName = null;
private String uriFragmentNewFileBase = null;
private String uriFragmentToMedia = null;
private boolean afterResult = false;
private boolean hasLaunched = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
appName = extras.getString(APP_NAME);
uriFragmentToMedia = extras.getString(URI_FRAGMENT);
hasLaunched = extras.getBoolean(HAS_LAUNCHED);
afterResult = extras.getBoolean(AFTER_RESULT);
uriFragmentNewFileBase = extras.getString(URI_FRAGMENT_NEW_FILE_BASE);
}
if (savedInstanceState != null) {
appName = savedInstanceState.getString(APP_NAME);
uriFragmentToMedia = savedInstanceState.getString(URI_FRAGMENT);
hasLaunched = savedInstanceState.getBoolean(HAS_LAUNCHED);
afterResult = savedInstanceState.getBoolean(AFTER_RESULT);
uriFragmentNewFileBase = savedInstanceState.getString(URI_FRAGMENT_NEW_FILE_BASE);
}
if (appName == null) {
throw new IllegalArgumentException("Expected " + APP_NAME
+ " key in intent bundle. Not found.");
}
if (uriFragmentToMedia == null) {
if (uriFragmentNewFileBase == null) {
throw new IllegalArgumentException("Expected " + URI_FRAGMENT_NEW_FILE_BASE
+ " key in intent bundle. Not found.");
}
afterResult = false;
hasLaunched = false;
}
}
@Override
protected void onResume() {
super.onResume();
if (afterResult) {
// this occurs if we re-orient the phone during the save-recording
// action
returnResult();
} else if (!hasLaunched && !afterResult) {
Intent i = new Intent(Audio.Media.RECORD_SOUND_ACTION);
// to make the name unique...
File f = ODKFileUtils.getAsFile(appName,
(uriFragmentToMedia == null ? uriFragmentNewFileBase : uriFragmentToMedia));
int idx = f.getName().lastIndexOf('.');
if (idx == -1) {
i.putExtra(Audio.Media.DISPLAY_NAME, f.getName());
} else {
i.putExtra(Audio.Media.DISPLAY_NAME, f.getName().substring(0, idx));
}
try {
hasLaunched = true;
startActivityForResult(i, ACTION_CODE);
} catch (ActivityNotFoundException e) {
String err = getString(R.string.activity_not_found, Audio.Media.RECORD_SOUND_ACTION);
WebLogger.getLogger(appName).e(t, err);
Toast.makeText(this, err, Toast.LENGTH_SHORT).show();
setResult(Activity.RESULT_CANCELED);
finish();
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(APP_NAME, appName);
outState.putString(URI_FRAGMENT, uriFragmentToMedia);
outState.putString(URI_FRAGMENT_NEW_FILE_BASE, uriFragmentNewFileBase);
outState.putBoolean(HAS_LAUNCHED, hasLaunched);
outState.putBoolean(AFTER_RESULT, afterResult);
}
private void deleteMedia() {
if (uriFragmentToMedia == null) {
return;
}
// get the file path and delete the file
File f = ODKFileUtils.getAsFile(appName, uriFragmentToMedia);
String path = f.getAbsolutePath();
// delete from media provider
int del = MediaUtils.deleteAudioFileFromMediaProvider(this, appName, path);
WebLogger.getLogger(appName).i(t, "Deleted " + del + " rows from audio media content provider");
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == Activity.RESULT_CANCELED) {
// request was canceled -- propagate
setResult(Activity.RESULT_CANCELED);
finish();
return;
}
Uri mediaUri = intent.getData();
// it is unclear whether getData() always returns a value or if
// getDataString() does...
String str = intent.getDataString();
if (mediaUri == null && str != null) {
WebLogger.getLogger(appName).w(t, "Attempting to work around null mediaUri");
mediaUri = Uri.parse(str);
}
if (mediaUri == null) {
// we are in trouble
WebLogger.getLogger(appName).e(t, "No uri returned from RECORD_SOUND_ACTION!");
setResult(Activity.RESULT_CANCELED);
finish();
return;
}
// Remove the current media.
deleteMedia();
// get the file path and create a copy in the instance folder
String binaryPath = MediaUtils.getPathFromUri(this, (Uri)mediaUri, Audio.Media.DATA);
File source = new File(binaryPath);
String extension = binaryPath.substring(binaryPath.lastIndexOf("."));
if (uriFragmentToMedia == null) {
// use the newFileBase as a starting point...
uriFragmentToMedia = uriFragmentNewFileBase + extension;
}
// adjust the mediaPath (destination) to have the same extension
// and delete any existing file.
File f = ODKFileUtils.getAsFile(appName, uriFragmentToMedia);
File sourceMedia = new File(f.getParentFile(), f.getName().substring(0,
f.getName().lastIndexOf('.'))
+ extension);
uriFragmentToMedia = ODKFileUtils.asUriFragment(appName, sourceMedia);
deleteMedia();
try {
FileUtils.copyFile(source, sourceMedia);
} catch (IOException e) {
WebLogger.getLogger(appName).e(t, ERROR_COPY_FILE + sourceMedia.getAbsolutePath());
Toast.makeText(this, R.string.media_save_failed, Toast.LENGTH_SHORT).show();
deleteMedia();
setResult(Activity.RESULT_CANCELED);
finish();
return;
}
if (sourceMedia.exists()) {
// Add the copy to the content provier
ContentValues values = new ContentValues(6);
values.put(Audio.Media.TITLE, sourceMedia.getName());
values.put(Audio.Media.DISPLAY_NAME, sourceMedia.getName());
values.put(Audio.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Audio.Media.DATA, sourceMedia.getAbsolutePath());
Uri MediaURI = getApplicationContext().getContentResolver().insert(
Audio.Media.EXTERNAL_CONTENT_URI, values);
WebLogger.getLogger(appName).i(t, "Inserting AUDIO returned uri = " + MediaURI.toString());
uriFragmentToMedia = ODKFileUtils.asUriFragment(appName, sourceMedia);
WebLogger.getLogger(appName).i(t, "Setting current answer to " + sourceMedia.getAbsolutePath());
int delCount = getApplicationContext().getContentResolver().delete(mediaUri, null, null);
WebLogger.getLogger(appName).i(t, "Deleting original capture of file: " + mediaUri.toString() + " count: " + delCount);
} else {
WebLogger.getLogger(appName).e(t, "Inserting Audio file FAILED");
}
/*
* We saved the audio to the instance directory. Verify that it is there...
*/
returnResult();
return;
}
private void returnResult() {
File sourceMedia = (uriFragmentToMedia != null) ?
ODKFileUtils.getAsFile(appName, uriFragmentToMedia) : null;
if (sourceMedia != null && sourceMedia.exists()) {
Intent i = new Intent();
i.putExtra(URI_FRAGMENT, ODKFileUtils.asUriFragment(appName, sourceMedia));
String name = sourceMedia.getName();
i.putExtra(CONTENT_TYPE, MEDIA_CLASS + name.substring(name.lastIndexOf(".") + 1));
setResult(Activity.RESULT_OK, i);
finish();
} else {
WebLogger.getLogger(appName).e(t, ERROR_NO_FILE
+ ((uriFragmentToMedia != null) ? sourceMedia.getAbsolutePath() : "null mediaPath"));
Toast.makeText(this, R.string.media_save_failed, Toast.LENGTH_SHORT).show();
setResult(Activity.RESULT_CANCELED);
finish();
}
}
@Override
public void finish() {
hasLaunched = false;
afterResult = true;
super.finish();
}
}
| [
"[email protected]"
]
| |
6ba52a368f28d9a14e1c1346103499189f7ba6c1 | 855b4041b6a7928988a41a5f3f7e7c7ae39565e4 | /hk-core/src/main/java/com/hk/svr/impl/MsgServiceImpl.java | fe98777af3614d93cfbe57e671b83561e4ce9b85 | []
| no_license | mestatrit/newbyakwei | 60dca96c4c21ae5fcf6477d4627a0eac0f76df35 | ea9a112ac6fcbc2a51dbdc79f417a1d918aa4067 | refs/heads/master | 2021-01-10T06:29:50.466856 | 2013-03-07T08:09:58 | 2013-03-07T08:09:58 | 36,559,185 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 9,737 | java | package com.hk.svr.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.hk.bean.PvtChat;
import com.hk.bean.PvtChatMain;
import com.hk.bean.SendInfo;
import com.hk.frame.dao.query.Query;
import com.hk.frame.dao.query.QueryManager;
import com.hk.svr.MsgService;
public class MsgServiceImpl implements MsgService {
@Autowired
private QueryManager queryManager;
public SendInfo sendMsg(long userId, long senderId, String msg, byte smsflg) {
Date date = new Date();
SendInfo info = new SendInfo();
PvtChat senderPvtChat = new PvtChat();
senderPvtChat.setUserId(senderId);
senderPvtChat.setSenderId(senderId);
senderPvtChat.setCreateTime(date);
senderPvtChat.setMsg(msg);
senderPvtChat.setSmsflg(smsflg);
long mainId = this.updatePvtChatMain(senderPvtChat, userId,
PvtChatMain.READ_Y);
senderPvtChat.setMainId(mainId);
this.createPvtChat(senderPvtChat);
info.setSenderPvtChat(senderPvtChat);
PvtChat receiverPvtChat = new PvtChat();
receiverPvtChat.setUserId(userId);
receiverPvtChat.setSenderId(senderId);
receiverPvtChat.setCreateTime(date);
receiverPvtChat.setMsg(msg);
receiverPvtChat.setSmsflg(smsflg);
long main2Id = this.updatePvtChatMain(receiverPvtChat, senderId,
PvtChatMain.READ_N);
receiverPvtChat.setMainId(main2Id);
this.createPvtChat(receiverPvtChat);
info.setReceiverPvtChat(receiverPvtChat);
return info;
}
public SendInfo sendMsg(long userId, long senderId, String msg) {
return this.sendMsg(userId, senderId, msg, PvtChat.SmsFLG_N);
}
private void createPvtChat(PvtChat pvtChat) {
Query query = this.queryManager.createQuery();
query.addField("userid", pvtChat.getUserId());
query.addField("senderid", pvtChat.getSenderId());
query.addField("msg", pvtChat.getMsg());
query.addField("createtime", pvtChat.getCreateTime());
query.addField("mainid", pvtChat.getMainId());
query.addField("smsflg", pvtChat.getSmsflg());
query.addField("smsmsgid", pvtChat.getSmsmsgId());
long id = query.insert(PvtChat.class).longValue();
pvtChat.setChatId(id);
}
private long updatePvtChatMain(PvtChat pvtChat, long user2Id, byte readflg) {
int noReadAdd = 0;
String msg = pvtChat.getSenderId() + ">>" + pvtChat.getMsg() + ">>"
+ pvtChat.getCreateTime().getTime();
Query query = this.queryManager.createQuery();
query.setTable(PvtChatMain.class);
query.where("userid=? and user2id=?").setParam(pvtChat.getUserId())
.setParam(user2Id);
PvtChatMain chatMain = query.getObject(PvtChatMain.class);
long mainId = 0;
if (chatMain == null) {
query.addField("userid", pvtChat.getUserId());
query.addField("user2id", user2Id);
query.addField("last3msg", msg);
query.addField("readflg", readflg);
query.addField("createtime", pvtChat.getCreateTime());
if (readflg == PvtChatMain.READ_N) {// 未读 设置未读数量=1
noReadAdd = 1;
}
query.addField("noreadcount", noReadAdd);
mainId = query.insert(PvtChatMain.class).longValue();
}
else {
mainId = chatMain.getMainId();
if (chatMain.getLast3msg() != null) {
String[] msgs = chatMain.getLast3msg().split("<>");
List<String> slist = new ArrayList<String>();
for (int i = 0; i < msgs.length; i++) {
slist.add(msgs[i]);
}
if (slist.size() >= 1) {
slist.remove(0);
}
slist.add(msg);
StringBuilder sb = new StringBuilder();
for (String s : slist) {
sb.append(s).append("<>");
}
sb.deleteCharAt(sb.length() - 1);
sb.deleteCharAt(sb.length() - 1);
query.setTable(PvtChatMain.class);
query.addField("last3msg", sb.toString());
query.addField("readflg", readflg);
query.addField("createtime", pvtChat.getCreateTime());
if (readflg == PvtChatMain.READ_N) {// 未读+1
noReadAdd = 1;
query.addField("noreadcount", "add", noReadAdd);
}
else {
query.addField("noreadcount", 0);// 已读,设置未读数量为0
}
query.where("userid=? and user2id=?").setParam(
pvtChat.getUserId()).setParam(user2Id);
query.update();
}
}
return mainId;
}
public void deletePvtChatMain(long userId, long mainId) {
PvtChatMain main = this.getPvtChatMain(userId, mainId);
if (main == null) {
return;
}
Query query = this.queryManager.createQuery();
query.setTable(PvtChatMain.class);
query.where("userid=? and mainid=?").setParam(userId).setParam(mainId)
.delete();
query.setTable(PvtChat.class);
query.where("userid=? and mainid=?").setParam(userId).setParam(mainId)
.delete();
}
public List<PvtChat> getPvtChatList(long userId, long mainId, int begin,
int size) {
Query query = this.queryManager.createQuery();
query.setTable(PvtChat.class);
query.where("userid=? and mainid=?").setParam(userId).setParam(mainId)
.orderByDesc("chatid");
return query.list(begin, size, PvtChat.class);
}
public List<PvtChat> getPvtChatListByUserIdGt(long userId, long mainId,
long chatId, int size) {
Query query = this.queryManager.createQuery();
return query.listEx(PvtChat.class,
"userid=? and mainid=? and chatid>?", new Object[] { userId,
mainId, chatId }, "chatid desc", 0, size);
}
public List<PvtChat> getPvtChatList(long userId, long mainId, byte smsflg,
int begin, int size) {
Query query = this.queryManager.createQuery();
query.setTable(PvtChat.class);
query.where("userid=? and mainid=? and smsflg=?").setParam(userId)
.setParam(mainId).setParam(smsflg).orderByDesc("chatid");
return query.list(begin, size, PvtChat.class);
}
public List<PvtChat> getLastPvtChatList(long userId, long mainId, int size) {
Query query = this.queryManager.createQuery();
query.setTable(PvtChat.class);
query.where("userid=? and mainid=?").setParam(userId).setParam(mainId)
.orderByDesc("chatid");
return query.list(0, size, PvtChat.class);
}
public int countPvtChat(long userId, long mainId) {
Query query = this.queryManager.createQuery();
query.setTable(PvtChat.class);
query.where("userid=? and mainid=?").setParam(userId).setParam(mainId);
return query.count();
}
public PvtChatMain getPvtChatMain(long userId, long mainId) {
Query query = this.queryManager.createQuery();
query.setTable(PvtChatMain.class).where("userid=? and mainid=?")
.setParam(userId).setParam(mainId);
return query.getObject(PvtChatMain.class);
}
public PvtChatMain getPvtChatMainByUserIdAndUser2Id(long userId,
long user2Id) {
Query query = this.queryManager.createQuery();
query.setTable(PvtChatMain.class).where("userid=? and user2id=?")
.setParam(userId).setParam(user2Id);
return query.getObject(PvtChatMain.class);
}
public List<PvtChatMain> getPvtChatMainList(long userId, int begin, int size) {
Query query = this.queryManager.createQuery();
query.setTable(PvtChatMain.class).where("userid=?").setParam(userId)
.orderByDesc("createtime");
return query.list(begin, size, PvtChatMain.class);
}
public int countPvtChatMain(long userId) {
Query query = this.queryManager.createQuery();
return query.count(PvtChatMain.class, "userid=?",
new Object[] { userId });
}
public int countNoRead(long userId) {
Query query = this.queryManager.createQuery();
query.setTable(PvtChatMain.class).where("userid=? and readflg=?")
.setParam(userId).setParam(PvtChatMain.READ_N);
return query.count();
}
public void setRead(long userId, long mainId) {
Query query = this.queryManager.createQuery();
query.setTable(PvtChatMain.class);
query.addField("readflg", 1);
query.addField("noreadcount", 0);
query.where("userid=? and mainid=?").setParam(userId).setParam(mainId);
query.update();
}
public PvtChatMain getLastNoReadPvtChatMain(long userId) {
Query query = this.queryManager.createQuery();
query.setTable(PvtChatMain.class);
query.where("userid=? and readflg=?").setParam(userId).setParam(
PvtChatMain.READ_N).orderByDesc("mainid");
return query.getObject(PvtChatMain.class);
}
public void deleteChat(long userId, long chatId) {
PvtChat pvtChat = this.getPvtChat(chatId);
if (pvtChat == null) {
return;
}
Query query = this.queryManager.createQuery();
query.setTable(PvtChat.class);
query.where("chatid=? and userid=?").setParam(chatId).setParam(userId);
query.delete();
List<PvtChat> list = this.getLastPvtChatList(userId, pvtChat
.getMainId(), 1);
if (list.size() == 0) {
this.deletePvtChatMain(userId, pvtChat.getMainId());
}
else {
PvtChat o = list.iterator().next();
String last3msg = o.getSenderId() + ">>" + o.getMsg() + ">>"
+ o.getCreateTime().getTime();
query.setTable(PvtChatMain.class);
query.addField("last3msg", last3msg);
query.where("mainid=?").setParam(pvtChat.getMainId());
query.update();
}
}
public PvtChat getPvtChat(long chatId) {
Query query = this.queryManager.createQuery();
return query.getObjectById(PvtChat.class, chatId);
}
public void updatePvtChatSmsmsgId(long userId, long senderId, long smsmsgId) {
Query query = this.queryManager.createQuery();
query.addField("smsmsgid", smsmsgId);
query.update(PvtChat.class, "userid=? and senderid=?", new Object[] {
userId, senderId });
}
public void updatePvtChatSmsmsgId(long chatId, long smsmsgId) {
Query query = this.queryManager.createQuery();
query.addField("smsmsgid", smsmsgId);
query.update(PvtChat.class, "chatid=?", new Object[] { chatId });
}
} | [
"[email protected]"
]
| |
8848b5771a911006b408e73a2b8d880adae4916e | b5d45036c5fa06c76cbe4f9e55e52d6ae014103d | /src/test/java/br/com/uendel/blogapp/web/rest/UserResourceIT.java | b0b4c399cd572c3705e9f7f47e8d0cbae677b986 | []
| no_license | UendelC/jhipster-example | bf11e3ff1a0981b79876bd4a3c6521827faa0dbd | cfa772072414c98c67057bc1bc5180e74f78570f | refs/heads/master | 2022-08-12T11:03:43.550385 | 2020-02-21T21:17:22 | 2020-02-21T21:17:22 | 240,012,086 | 0 | 0 | null | 2022-07-07T16:32:10 | 2020-02-12T12:52:31 | Java | UTF-8 | Java | false | false | 26,394 | java | package br.com.uendel.blogapp.web.rest;
import br.com.uendel.blogapp.AppApp;
import br.com.uendel.blogapp.domain.Authority;
import br.com.uendel.blogapp.domain.User;
import br.com.uendel.blogapp.repository.UserRepository;
import br.com.uendel.blogapp.repository.search.UserSearchRepository;
import br.com.uendel.blogapp.security.AuthoritiesConstants;
import br.com.uendel.blogapp.service.MailService;
import br.com.uendel.blogapp.service.UserService;
import br.com.uendel.blogapp.service.dto.UserDTO;
import br.com.uendel.blogapp.service.mapper.UserMapper;
import br.com.uendel.blogapp.web.rest.errors.ExceptionTranslator;
import br.com.uendel.blogapp.web.rest.vm.ManagedUserVM;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.CacheManager;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.time.Instant;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Integration tests for the {@link UserResource} REST controller.
*/
@SpringBootTest(classes = AppApp.class)
public class UserResourceIT {
private static final String DEFAULT_LOGIN = "johndoe";
private static final String UPDATED_LOGIN = "jhipster";
private static final String DEFAULT_ID = "id1";
private static final String DEFAULT_PASSWORD = "passjohndoe";
private static final String UPDATED_PASSWORD = "passjhipster";
private static final String DEFAULT_EMAIL = "johndoe@localhost";
private static final String UPDATED_EMAIL = "jhipster@localhost";
private static final String DEFAULT_FIRSTNAME = "john";
private static final String UPDATED_FIRSTNAME = "jhipsterFirstName";
private static final String DEFAULT_LASTNAME = "doe";
private static final String UPDATED_LASTNAME = "jhipsterLastName";
private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50";
private static final String UPDATED_IMAGEURL = "http://placehold.it/40x40";
private static final String DEFAULT_LANGKEY = "en";
private static final String UPDATED_LANGKEY = "fr";
@Autowired
private UserRepository userRepository;
/**
* This repository is mocked in the br.com.uendel.blogapp.repository.search test package.
*
* @see br.com.uendel.blogapp.repository.search.UserSearchRepositoryMockConfiguration
*/
@Autowired
private UserSearchRepository mockUserSearchRepository;
@Autowired
private MailService mailService;
@Autowired
private UserService userService;
@Autowired
private UserMapper userMapper;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private CacheManager cacheManager;
private MockMvc restUserMockMvc;
private User user;
@BeforeEach
public void setup() {
cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).clear();
cacheManager.getCache(UserRepository.USERS_BY_EMAIL_CACHE).clear();
UserResource userResource = new UserResource(userService, userRepository, mailService, mockUserSearchRepository);
this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter)
.build();
}
/**
* Create a User.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which has a required relationship to the User entity.
*/
public static User createEntity() {
User user = new User();
user.setLogin(DEFAULT_LOGIN);
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
user.setEmail(DEFAULT_EMAIL);
user.setFirstName(DEFAULT_FIRSTNAME);
user.setLastName(DEFAULT_LASTNAME);
user.setImageUrl(DEFAULT_IMAGEURL);
user.setLangKey(DEFAULT_LANGKEY);
return user;
}
@BeforeEach
public void initTest() {
userRepository.deleteAll();
user = createEntity();
}
@Test
public void createUser() throws Exception {
int databaseSizeBeforeCreate = userRepository.findAll().size();
// Create the User
ManagedUserVM managedUserVM = new ManagedUserVM();
managedUserVM.setLogin(DEFAULT_LOGIN);
managedUserVM.setPassword(DEFAULT_PASSWORD);
managedUserVM.setFirstName(DEFAULT_FIRSTNAME);
managedUserVM.setLastName(DEFAULT_LASTNAME);
managedUserVM.setEmail(DEFAULT_EMAIL);
managedUserVM.setActivated(true);
managedUserVM.setImageUrl(DEFAULT_IMAGEURL);
managedUserVM.setLangKey(DEFAULT_LANGKEY);
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(post("/api/users")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isCreated());
// Validate the User in the database
List<User> userList = userRepository.findAll();
assertThat(userList).hasSize(databaseSizeBeforeCreate + 1);
User testUser = userList.get(userList.size() - 1);
assertThat(testUser.getLogin()).isEqualTo(DEFAULT_LOGIN);
assertThat(testUser.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
assertThat(testUser.getLastName()).isEqualTo(DEFAULT_LASTNAME);
assertThat(testUser.getEmail()).isEqualTo(DEFAULT_EMAIL);
assertThat(testUser.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
assertThat(testUser.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
}
@Test
public void createUserWithExistingId() throws Exception {
int databaseSizeBeforeCreate = userRepository.findAll().size();
ManagedUserVM managedUserVM = new ManagedUserVM();
managedUserVM.setId("1L");
managedUserVM.setLogin(DEFAULT_LOGIN);
managedUserVM.setPassword(DEFAULT_PASSWORD);
managedUserVM.setFirstName(DEFAULT_FIRSTNAME);
managedUserVM.setLastName(DEFAULT_LASTNAME);
managedUserVM.setEmail(DEFAULT_EMAIL);
managedUserVM.setActivated(true);
managedUserVM.setImageUrl(DEFAULT_IMAGEURL);
managedUserVM.setLangKey(DEFAULT_LANGKEY);
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// An entity with an existing ID cannot be created, so this API call must fail
restUserMockMvc.perform(post("/api/users")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isBadRequest());
// Validate the User in the database
List<User> userList = userRepository.findAll();
assertThat(userList).hasSize(databaseSizeBeforeCreate);
}
@Test
public void createUserWithExistingLogin() throws Exception {
// Initialize the database
userRepository.save(user);
mockUserSearchRepository.save(user);
int databaseSizeBeforeCreate = userRepository.findAll().size();
ManagedUserVM managedUserVM = new ManagedUserVM();
managedUserVM.setLogin(DEFAULT_LOGIN);// this login should already be used
managedUserVM.setPassword(DEFAULT_PASSWORD);
managedUserVM.setFirstName(DEFAULT_FIRSTNAME);
managedUserVM.setLastName(DEFAULT_LASTNAME);
managedUserVM.setEmail("anothermail@localhost");
managedUserVM.setActivated(true);
managedUserVM.setImageUrl(DEFAULT_IMAGEURL);
managedUserVM.setLangKey(DEFAULT_LANGKEY);
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Create the User
restUserMockMvc.perform(post("/api/users")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isBadRequest());
// Validate the User in the database
List<User> userList = userRepository.findAll();
assertThat(userList).hasSize(databaseSizeBeforeCreate);
}
@Test
public void createUserWithExistingEmail() throws Exception {
// Initialize the database
userRepository.save(user);
mockUserSearchRepository.save(user);
int databaseSizeBeforeCreate = userRepository.findAll().size();
ManagedUserVM managedUserVM = new ManagedUserVM();
managedUserVM.setLogin("anotherlogin");
managedUserVM.setPassword(DEFAULT_PASSWORD);
managedUserVM.setFirstName(DEFAULT_FIRSTNAME);
managedUserVM.setLastName(DEFAULT_LASTNAME);
managedUserVM.setEmail(DEFAULT_EMAIL);// this email should already be used
managedUserVM.setActivated(true);
managedUserVM.setImageUrl(DEFAULT_IMAGEURL);
managedUserVM.setLangKey(DEFAULT_LANGKEY);
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Create the User
restUserMockMvc.perform(post("/api/users")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isBadRequest());
// Validate the User in the database
List<User> userList = userRepository.findAll();
assertThat(userList).hasSize(databaseSizeBeforeCreate);
}
@Test
public void getAllUsers() throws Exception {
// Initialize the database
userRepository.save(user);
mockUserSearchRepository.save(user);
// Get all the users
restUserMockMvc.perform(get("/api/users")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN)))
.andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME)))
.andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME)))
.andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL)))
.andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL)))
.andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY)));
}
@Test
public void getUser() throws Exception {
// Initialize the database
userRepository.save(user);
mockUserSearchRepository.save(user);
assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNull();
// Get the user
restUserMockMvc.perform(get("/api/users/{login}", user.getLogin()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.login").value(user.getLogin()))
.andExpect(jsonPath("$.firstName").value(DEFAULT_FIRSTNAME))
.andExpect(jsonPath("$.lastName").value(DEFAULT_LASTNAME))
.andExpect(jsonPath("$.email").value(DEFAULT_EMAIL))
.andExpect(jsonPath("$.imageUrl").value(DEFAULT_IMAGEURL))
.andExpect(jsonPath("$.langKey").value(DEFAULT_LANGKEY));
assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNotNull();
}
@Test
public void getNonExistingUser() throws Exception {
restUserMockMvc.perform(get("/api/users/unknown"))
.andExpect(status().isNotFound());
}
@Test
public void updateUser() throws Exception {
// Initialize the database
userRepository.save(user);
mockUserSearchRepository.save(user);
int databaseSizeBeforeUpdate = userRepository.findAll().size();
// Update the user
User updatedUser = userRepository.findById(user.getId()).get();
ManagedUserVM managedUserVM = new ManagedUserVM();
managedUserVM.setId(updatedUser.getId());
managedUserVM.setLogin(updatedUser.getLogin());
managedUserVM.setPassword(UPDATED_PASSWORD);
managedUserVM.setFirstName(UPDATED_FIRSTNAME);
managedUserVM.setLastName(UPDATED_LASTNAME);
managedUserVM.setEmail(UPDATED_EMAIL);
managedUserVM.setActivated(updatedUser.getActivated());
managedUserVM.setImageUrl(UPDATED_IMAGEURL);
managedUserVM.setLangKey(UPDATED_LANGKEY);
managedUserVM.setCreatedBy(updatedUser.getCreatedBy());
managedUserVM.setCreatedDate(updatedUser.getCreatedDate());
managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy());
managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate());
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(put("/api/users")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isOk());
// Validate the User in the database
List<User> userList = userRepository.findAll();
assertThat(userList).hasSize(databaseSizeBeforeUpdate);
User testUser = userList.get(userList.size() - 1);
assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME);
assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME);
assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL);
assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL);
assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY);
}
@Test
public void updateUserLogin() throws Exception {
// Initialize the database
userRepository.save(user);
mockUserSearchRepository.save(user);
int databaseSizeBeforeUpdate = userRepository.findAll().size();
// Update the user
User updatedUser = userRepository.findById(user.getId()).get();
ManagedUserVM managedUserVM = new ManagedUserVM();
managedUserVM.setId(updatedUser.getId());
managedUserVM.setLogin(UPDATED_LOGIN);
managedUserVM.setPassword(UPDATED_PASSWORD);
managedUserVM.setFirstName(UPDATED_FIRSTNAME);
managedUserVM.setLastName(UPDATED_LASTNAME);
managedUserVM.setEmail(UPDATED_EMAIL);
managedUserVM.setActivated(updatedUser.getActivated());
managedUserVM.setImageUrl(UPDATED_IMAGEURL);
managedUserVM.setLangKey(UPDATED_LANGKEY);
managedUserVM.setCreatedBy(updatedUser.getCreatedBy());
managedUserVM.setCreatedDate(updatedUser.getCreatedDate());
managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy());
managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate());
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(put("/api/users")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isOk());
// Validate the User in the database
List<User> userList = userRepository.findAll();
assertThat(userList).hasSize(databaseSizeBeforeUpdate);
User testUser = userList.get(userList.size() - 1);
assertThat(testUser.getLogin()).isEqualTo(UPDATED_LOGIN);
assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME);
assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME);
assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL);
assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL);
assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY);
}
@Test
public void updateUserExistingEmail() throws Exception {
// Initialize the database with 2 users
userRepository.save(user);
mockUserSearchRepository.save(user);
User anotherUser = new User();
anotherUser.setLogin("jhipster");
anotherUser.setPassword(RandomStringUtils.random(60));
anotherUser.setActivated(true);
anotherUser.setEmail("jhipster@localhost");
anotherUser.setFirstName("java");
anotherUser.setLastName("hipster");
anotherUser.setImageUrl("");
anotherUser.setLangKey("en");
userRepository.save(anotherUser);
mockUserSearchRepository.save(anotherUser);
// Update the user
User updatedUser = userRepository.findById(user.getId()).get();
ManagedUserVM managedUserVM = new ManagedUserVM();
managedUserVM.setId(updatedUser.getId());
managedUserVM.setLogin(updatedUser.getLogin());
managedUserVM.setPassword(updatedUser.getPassword());
managedUserVM.setFirstName(updatedUser.getFirstName());
managedUserVM.setLastName(updatedUser.getLastName());
managedUserVM.setEmail("jhipster@localhost");// this email should already be used by anotherUser
managedUserVM.setActivated(updatedUser.getActivated());
managedUserVM.setImageUrl(updatedUser.getImageUrl());
managedUserVM.setLangKey(updatedUser.getLangKey());
managedUserVM.setCreatedBy(updatedUser.getCreatedBy());
managedUserVM.setCreatedDate(updatedUser.getCreatedDate());
managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy());
managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate());
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(put("/api/users")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isBadRequest());
}
@Test
public void updateUserExistingLogin() throws Exception {
// Initialize the database
userRepository.save(user);
mockUserSearchRepository.save(user);
User anotherUser = new User();
anotherUser.setLogin("jhipster");
anotherUser.setPassword(RandomStringUtils.random(60));
anotherUser.setActivated(true);
anotherUser.setEmail("jhipster@localhost");
anotherUser.setFirstName("java");
anotherUser.setLastName("hipster");
anotherUser.setImageUrl("");
anotherUser.setLangKey("en");
userRepository.save(anotherUser);
mockUserSearchRepository.save(anotherUser);
// Update the user
User updatedUser = userRepository.findById(user.getId()).get();
ManagedUserVM managedUserVM = new ManagedUserVM();
managedUserVM.setId(updatedUser.getId());
managedUserVM.setLogin("jhipster");// this login should already be used by anotherUser
managedUserVM.setPassword(updatedUser.getPassword());
managedUserVM.setFirstName(updatedUser.getFirstName());
managedUserVM.setLastName(updatedUser.getLastName());
managedUserVM.setEmail(updatedUser.getEmail());
managedUserVM.setActivated(updatedUser.getActivated());
managedUserVM.setImageUrl(updatedUser.getImageUrl());
managedUserVM.setLangKey(updatedUser.getLangKey());
managedUserVM.setCreatedBy(updatedUser.getCreatedBy());
managedUserVM.setCreatedDate(updatedUser.getCreatedDate());
managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy());
managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate());
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(put("/api/users")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isBadRequest());
}
@Test
public void deleteUser() throws Exception {
// Initialize the database
userRepository.save(user);
mockUserSearchRepository.save(user);
int databaseSizeBeforeDelete = userRepository.findAll().size();
// Delete the user
restUserMockMvc.perform(delete("/api/users/{login}", user.getLogin())
.accept(TestUtil.APPLICATION_JSON))
.andExpect(status().isNoContent());
assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNull();
// Validate the database is empty
List<User> userList = userRepository.findAll();
assertThat(userList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
public void getAllAuthorities() throws Exception {
restUserMockMvc.perform(get("/api/users/authorities")
.accept(TestUtil.APPLICATION_JSON)
.contentType(TestUtil.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").value(hasItems(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN)));
}
@Test
public void testUserEquals() throws Exception {
TestUtil.equalsVerifier(User.class);
User user1 = new User();
user1.setId("id1");
User user2 = new User();
user2.setId(user1.getId());
assertThat(user1).isEqualTo(user2);
user2.setId("id2");
assertThat(user1).isNotEqualTo(user2);
user1.setId(null);
assertThat(user1).isNotEqualTo(user2);
}
@Test
public void testUserDTOtoUser() {
UserDTO userDTO = new UserDTO();
userDTO.setId(DEFAULT_ID);
userDTO.setLogin(DEFAULT_LOGIN);
userDTO.setFirstName(DEFAULT_FIRSTNAME);
userDTO.setLastName(DEFAULT_LASTNAME);
userDTO.setEmail(DEFAULT_EMAIL);
userDTO.setActivated(true);
userDTO.setImageUrl(DEFAULT_IMAGEURL);
userDTO.setLangKey(DEFAULT_LANGKEY);
userDTO.setCreatedBy(DEFAULT_LOGIN);
userDTO.setLastModifiedBy(DEFAULT_LOGIN);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
User user = userMapper.userDTOToUser(userDTO);
assertThat(user.getId()).isEqualTo(DEFAULT_ID);
assertThat(user.getLogin()).isEqualTo(DEFAULT_LOGIN);
assertThat(user.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
assertThat(user.getLastName()).isEqualTo(DEFAULT_LASTNAME);
assertThat(user.getEmail()).isEqualTo(DEFAULT_EMAIL);
assertThat(user.getActivated()).isEqualTo(true);
assertThat(user.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
assertThat(user.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
assertThat(user.getCreatedBy()).isNull();
assertThat(user.getCreatedDate()).isNotNull();
assertThat(user.getLastModifiedBy()).isNull();
assertThat(user.getLastModifiedDate()).isNotNull();
assertThat(user.getAuthorities()).extracting("name").containsExactly(AuthoritiesConstants.USER);
}
@Test
public void testUserToUserDTO() {
user.setId(DEFAULT_ID);
user.setCreatedBy(DEFAULT_LOGIN);
user.setCreatedDate(Instant.now());
user.setLastModifiedBy(DEFAULT_LOGIN);
user.setLastModifiedDate(Instant.now());
Set<Authority> authorities = new HashSet<>();
Authority authority = new Authority();
authority.setName(AuthoritiesConstants.USER);
authorities.add(authority);
user.setAuthorities(authorities);
UserDTO userDTO = userMapper.userToUserDTO(user);
assertThat(userDTO.getId()).isEqualTo(DEFAULT_ID);
assertThat(userDTO.getLogin()).isEqualTo(DEFAULT_LOGIN);
assertThat(userDTO.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
assertThat(userDTO.getLastName()).isEqualTo(DEFAULT_LASTNAME);
assertThat(userDTO.getEmail()).isEqualTo(DEFAULT_EMAIL);
assertThat(userDTO.isActivated()).isEqualTo(true);
assertThat(userDTO.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
assertThat(userDTO.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
assertThat(userDTO.getCreatedBy()).isEqualTo(DEFAULT_LOGIN);
assertThat(userDTO.getCreatedDate()).isEqualTo(user.getCreatedDate());
assertThat(userDTO.getLastModifiedBy()).isEqualTo(DEFAULT_LOGIN);
assertThat(userDTO.getLastModifiedDate()).isEqualTo(user.getLastModifiedDate());
assertThat(userDTO.getAuthorities()).containsExactly(AuthoritiesConstants.USER);
assertThat(userDTO.toString()).isNotNull();
}
@Test
public void testAuthorityEquals() {
Authority authorityA = new Authority();
assertThat(authorityA).isEqualTo(authorityA);
assertThat(authorityA).isNotEqualTo(null);
assertThat(authorityA).isNotEqualTo(new Object());
assertThat(authorityA.hashCode()).isEqualTo(0);
assertThat(authorityA.toString()).isNotNull();
Authority authorityB = new Authority();
assertThat(authorityA).isEqualTo(authorityB);
authorityB.setName(AuthoritiesConstants.ADMIN);
assertThat(authorityA).isNotEqualTo(authorityB);
authorityA.setName(AuthoritiesConstants.USER);
assertThat(authorityA).isNotEqualTo(authorityB);
authorityB.setName(AuthoritiesConstants.USER);
assertThat(authorityA).isEqualTo(authorityB);
assertThat(authorityA.hashCode()).isEqualTo(authorityB.hashCode());
}
}
| [
"[email protected]"
]
| |
500b18744448fb7c5c8d9e93a94b9b83071d427c | 58bc27f14a27de1e5f36f19bea215d0e40e63c7a | /LCS/src/com/lcs/math/TeamTotal.java | 4e6d68db0145aca3fd83dcf7bcc7a1bb62fde470 | []
| no_license | junbin1/LCS | da97cec32e28630ec22d86187112884ce2e6cd86 | 03125eba4af9798b1a5ab5e99bc80b2ca68fae13 | refs/heads/master | 2020-06-05T11:09:39.167028 | 2014-06-11T22:49:48 | 2014-06-11T22:49:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 132 | java | package com.lcs.math;
public class TeamTotal {
// populate team default model
// use team JSON object to calculate total
}
| [
"[email protected]"
]
| |
77a8530b30e48043e86845b11e16ed152e4df093 | 4378205179a8ce56c9565afddebfb4361f482120 | /src/com/demo03/ForDemo01.java | 25051262795d6181cdf274d51fd9b6e326aaea0a | []
| no_license | qtvb1987/java08 | 63ac0dfe924584163ada8f2be37c288b2281fb27 | 7586c75610df6b0a3f73723c95f8206d58b68a5d | refs/heads/master | 2023-01-07T03:00:23.499934 | 2020-11-11T15:05:41 | 2020-11-11T15:05:41 | 298,840,115 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 237 | java | package com.demo03;
/**
* For
*/
public class ForDemo01 {
public static void main(String[] args) {
for (int i=0;i<10;i++){
System.out.println("hello"+i);
}
System.out.println("结束");
}
}
| [
"[email protected]"
]
| |
dc7eb41eb7fd9633169d1682c1a674c55c151168 | ed7dfd75ae1e66b5b3842f4f0850c1caa4aec358 | /java_problems/introduction/JavaStdinStdout2.java | ba31abd0bb5f0d605c832f66abb19d27ed5e18e5 | [
"MIT"
]
| permissive | Kshitij-Vijay/HackerRank | ce6e5a3ff4b6666294113fcdb4987ec4f4d6a94e | 24d6dd785dd6475ac3b7d08f393cdc2794b8c340 | refs/heads/master | 2022-04-09T15:32:38.319651 | 2016-11-12T17:19:28 | 2016-11-12T17:19:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,417 | java | package java_problems.introduction;
import java.util.*;
/*
* In this problem you just need to read the inputs from stdin and print them
* in stdout.
* Input Format:
* There will be three lines of input. The first line will have an integer. The
* second line will have a double number. The last line will consist of a
* string.
* Output Format:
* Print the string in the first line, the double in the second line and the
* integer in the third line. See the sample output for exact formatting.
*
* Sample Input:
* 42
* 3.1415
* Welcome to Hackerrank Java tutorials!
*
* Note: Don't worry about the precision of the double, you can simply print
* it using System.out.println. There might be leading or trailing spaces
* in the string, keep it exactly as it is.
*/
public class JavaStdinStdout2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer: ");
int num1 = Integer.parseInt(sc.nextLine());
System.out.println("Enter a double: ");
double num2 = Double.parseDouble(sc.nextLine());
System.out.println("Enter a string: ");
String welcome = sc.nextLine();
System.out.println("String: " + welcome);
System.out.println("Double: " + num2);
System.out.println("Int: " + num1);
sc.close();
}
} | [
"[email protected]"
]
| |
2d6473fae6e2dd78d0e8d80e61f8674246ba39d2 | 3d5cd3e2066e8da1e4bc363ffc9af8463328be87 | /src/Main.java | 9e18bba1accf934ea65444d519e202dff62b1c4f | []
| no_license | Surgutov/Java1-2 | 42b06806d7f42592f7ca148486b3d18a3e248e45 | 48835725819da2418dc3f70f9301e2a08edf3afe | refs/heads/master | 2022-06-19T15:14:06.378285 | 2020-05-05T13:46:23 | 2020-05-05T13:46:23 | 261,178,623 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,107 | java | public class Main {
public static void main(String[] args) {
// TODO: подставлять номер карты нужно сюда между двойными кавычками, без пробелов
String number = "676196000494451892";
System.out.println(String.format("Result is %s", isValidCardNumber(number) ? "OK" : "FAIL"));
}
public static boolean isValidCardNumber(String number) {
if (number == null) {
return false;
}
if (number.length() != 16) {
return false;
}
long result = 0;
for (int i = 0; i < number.length(); i++) {
int digit;
try {
digit = Integer.parseInt(number.charAt(i) + "");
} catch (NumberFormatException e) {
return false;
}
if (i % 2 == 0) {
digit *= 2;
if (digit > 9) {
digit -= 9;
}
}
result += digit;
}
return (result != 0) && (result % 10 == 0);
}
}
| [
"[email protected]"
]
| |
85d9c59edd1a330f224ce3797b45e3107d5f8e52 | 6667472646670227d7101a93f7e9d15813eae420 | /helloWorled/src/helloWorled/helloWorled.java | f9bc8630d374a43fa345d6197f500d7528748e84 | [
"Unlicense"
]
| permissive | mostafazaghlol/Java-UriOnline | 88306c27c0a65c8dfb66bc9fa829d23f4a13fd24 | 23deb1f6ed277fe139715acdbe53d0c92632d777 | refs/heads/master | 2021-01-20T00:05:27.842765 | 2017-06-14T03:34:19 | 2017-06-14T03:34:19 | 89,075,360 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 82 | java | package helloWorled;
public class helloWorled {
System.out.println("hi");
}
| [
"[email protected]"
]
| |
b9b2a4921c102bae6e3465187542226a194ce74c | 3a2f6ce4873362e69ed4df7858cd6bd51190976f | /src/main/java/com/example/demo/datatypes/response/BaseResponse.java | 522aa84317c6664c5f02904fcd9f94caeb4e24d8 | []
| no_license | Naorsh/Checknmarx | 256b5c264a4246fed62d455d5e2227068ca3e2c2 | 5b4963b39590d7861a5ec65dab53e6653c540297 | refs/heads/master | 2023-02-03T02:27:22.687181 | 2020-12-23T15:18:22 | 2020-12-23T15:18:22 | 323,934,608 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 161 | java | package com.example.demo.datatypes.response;
import lombok.Data;
@Data
public class BaseResponse {
private String status;
private String message;
}
| [
"[email protected]"
]
| |
4b503c870cf76c887459d48283c02d32dd8d2581 | c326db0703172206a592fc8570414a471db348f3 | /ProyectSanax-ejb/src/java/co/edu/unipiloto/usuario/entity/Cita.java | 27c0604faca73457a6216f343d19d0cd56a96960 | []
| no_license | N1c0ep/RepositorioSanax | d2bc16b41c917ac3deedb479717f4bfd62b73848 | 549504131a001f5ae5f0aae90ceeb287a2f3dd9d | refs/heads/master | 2023-05-12T17:11:01.808714 | 2021-05-29T22:48:31 | 2021-05-29T22:48:31 | 353,785,534 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 4,724 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package co.edu.unipiloto.usuario.entity;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author jorge_j3qr4sd
*/
@Entity
@Table(name = "CITA")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Cita.findAll", query = "SELECT c FROM Cita c")
, @NamedQuery(name = "Cita.findByIdCita", query = "SELECT c FROM Cita c WHERE c.idCita = :idCita")
, @NamedQuery(name = "Cita.findByFecha", query = "SELECT c FROM Cita c WHERE c.fecha = :fecha")
, @NamedQuery(name = "Cita.findByHora", query = "SELECT c FROM Cita c WHERE c.hora = :hora")
, @NamedQuery(name = "Cita.findByFase", query = "SELECT c FROM Cita c WHERE c.fase = :fase")})
public class Cita implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "ID_CITA")
private Integer idCita;
@Size(max = 50)
@Column(name = "FECHA")
private String fecha;
@Size(max = 50)
@Column(name = "HORA")
private String hora;
@Size(max = 50)
@Column(name = "FASE")
private String fase;
@OneToMany(mappedBy = "idCita")
private Collection<ReporteVacunacion> reporteVacunacionCollection;
@JoinColumn(name = "ID_SITIO", referencedColumnName = "ID_SITIO")
@ManyToOne
private Sitio idSitio;
@JoinColumn(name = "IDENTIFICACION", referencedColumnName = "ID")
@ManyToOne
private Usuariosnuevos identificacion;
public Cita() {
}
public Cita(Integer idCita) {
this.idCita = idCita;
}
public Cita(String fecha, String hora, String fase, Sitio idSitio, Usuariosnuevos identificacion) {
this.fecha = fecha;
this.hora = hora;
this.fase = fase;
this.idSitio = idSitio;
this.identificacion = identificacion;
}
public Integer getIdCita() {
return idCita;
}
public void setIdCita(Integer idCita) {
this.idCita = idCita;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public String getHora() {
return hora;
}
public void setHora(String hora) {
this.hora = hora;
}
public String getFase() {
return fase;
}
public void setFase(String fase) {
this.fase = fase;
}
@XmlTransient
public Collection<ReporteVacunacion> getReporteVacunacionCollection() {
return reporteVacunacionCollection;
}
public void setReporteVacunacionCollection(Collection<ReporteVacunacion> reporteVacunacionCollection) {
this.reporteVacunacionCollection = reporteVacunacionCollection;
}
public Sitio getIdSitio() {
return idSitio;
}
public void setIdSitio(Sitio idSitio) {
this.idSitio = idSitio;
}
public Usuariosnuevos getIdentificacion() {
return identificacion;
}
public void setIdentificacion(Usuariosnuevos identificacion) {
this.identificacion = identificacion;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idCita != null ? idCita.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Cita)) {
return false;
}
Cita other = (Cita) object;
if ((this.idCita == null && other.idCita != null) || (this.idCita != null && !this.idCita.equals(other.idCita))) {
return false;
}
return true;
}
@Override
public String toString() {
return "co.edu.unipiloto.usuario.entity.Cita[ idCita=" + idCita + " ]";
}
}
| [
"[email protected]"
]
| |
9b3d63be0722147f6049a51db7d78bd514fc2bb8 | 171b363c8486306cb7453516de3eb150041e290c | /headFirstDesignPatterns/src/com/naren/headfirst/chapter4/factory/VeggiePizza.java | 22e1f2f800f4344cbb73a273128c83c6f67e9040 | []
| no_license | narendrar/practice | 482d37500575f7aed1cee704abdc376d32a69b8a | 705a482e684d2697da9ae22c43de64fadf2f30ba | refs/heads/master | 2020-05-23T03:20:53.169384 | 2020-03-21T05:18:26 | 2020-03-21T05:18:26 | 186,615,953 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 76 | java | package com.naren.headfirst.chapter4.factory;
public class VeggiePizza {
}
| [
"[email protected]"
]
| |
46911a707738e87b12b0f7db8ca35933462017b8 | 03d2e85e8c16a30e96ad341dd4a3d56e961a2917 | /services/LensService.java | 257891d4db73f19b11562236e79292ac3b27cb84 | []
| no_license | ViktorDimitrov1989/DBAppsExamPrep | 9e78607d74d234249886233d47de526604d4e8dd | efbacc9ea4c702c3ac803e6d21cdba3bc5c8e8b9 | refs/heads/master | 2021-06-25T13:16:58.833578 | 2017-08-12T18:30:36 | 2017-08-12T18:30:36 | 100,016,423 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 224 | java | package app.services;
import app.dto.add.AddLensDto;
import app.models.Lens;
import java.util.List;
public interface LensService {
void saveLens(AddLensDto lensDto);
List<Lens> findByIdIn(Iterable<Long> id);
}
| [
"[email protected]"
]
| |
e88cac7983f8aa65d54884bf586fe71ed1e8b523 | 1b1c7963a7d9c89b2da0ad6f6c8a76ce9ed1241a | /src/leetcode/pathSum113.java | 465de3b2521ea7ae00a7223abc6c0c3c7909acb1 | []
| no_license | AnnualSalary100W/algorithm | fdbeb23054cdf5737b78b42a43b25737e2ea5545 | 26c4aadf4c6413bba35a5b6b66ee3b3f34831cc5 | refs/heads/master | 2023-05-05T09:25:21.298782 | 2021-04-29T03:50:18 | 2021-04-29T03:50:18 | 264,645,862 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,572 | java | package leetcode;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public class pathSum113 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
// Java 文档中 Stack 类建议使用 Deque 代替 Stack,注意:只使用栈的相关接口
Deque<Integer> path = new ArrayDeque<>();
pathSum(root, sum, path, res);
return res;
}
public void pathSum(TreeNode node, int sum, Deque<Integer> path, List<List<Integer>> res) {
// 打开注释调试
// System.out.println(path);
// 递归终止条件
if (node == null) {
return;
}
// 沿途结点必须选择,这个时候要做两件事:1、sum 减去这个结点的值;2、添加到 path 里
sum -= node.val;
path.addLast(node.val);
if (sum == 0 && node.left == null && node.right == null) {
// path 全局只有一份,必须做拷贝
res.add(new ArrayList<>(path));
// 注意:这里 return 之前必须重置
path.removeLast();
return;
}
pathSum(node.left, sum, path, res);
pathSum(node.right, sum, path, res);
// 递归完成以后,必须重置变量
path.removeLast();
}
}
| [
"[email protected]"
]
| |
8ca9e6b76ada2a2c2cf184a6e5d37cf4df7b6dc7 | 1cd3a9a0ff4906157875fb355c930820145ced88 | /src/main/java/org/restlet/ext/simpledb/util/RestletUtil.java | 45918b0cb8275712fddf21d09abd41ff96a391d1 | []
| no_license | barchart/carrot-org.restlet.ext.simpledb | 250bbe186d2af9aee4051b7067ba099261a849f9 | 7c30c854f0c25d2d537dbe13763c3648bb53b86e | refs/heads/master | 2023-08-23T10:04:18.765301 | 2012-04-12T23:09:12 | 2012-04-12T23:09:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 718 | java | package org.restlet.ext.simpledb.util;
import org.restlet.Message;
import org.restlet.resource.UniformResource;
public class RestletUtil {
public static String componentURI(String path) {
String uri = "riap://component" + path;
return uri;
}
public static String getReqAttr(UniformResource resource, String name) {
String attr = (String) resource.getRequestAttributes().get(name);
return attr;
}
public static String getRspAttr(UniformResource resource, String name) {
String attr = (String) resource.getResponseAttributes().get(name);
return attr;
}
public static String getAttr(Message message, String name) {
String attr = (String) message.getAttributes().get(name);
return attr;
}
}
| [
"[email protected]"
]
| |
fc167f9f11e2783303fe4050d259d63a4b929403 | 470fccd48db81589d3e5332eff851b919d703b07 | /hulkstore/src/main/java/com/store/hulkstore/dominio/servicio/ProductoServicio.java | d6ac50c18e7b681f0961ebf6c572d1fad4679e91 | []
| no_license | reylycans/Prueba-java | 4460dc28d129523027e3c6257349b05c2fdc4d60 | 5781a3bd1e7ab5ba07bbb84268f60d2cee9bce7f | refs/heads/master | 2023-04-04T06:51:24.199704 | 2021-04-19T04:18:10 | 2021-04-19T04:18:10 | 359,326,531 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 791 | java | package com.store.hulkstore.dominio.servicio;
import com.store.hulkstore.dominio.modelo.Producto;
import com.store.hulkstore.dominio.repositorio.ProductoRepositorio;
import com.store.hulkstore.infraestructura.persistencia.entidad.ProductoEntity;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class ProductoServicio {
private final ProductoRepositorio productoRepositorio;
public ProductoServicio(ProductoRepositorio productoRepositorio){
this.productoRepositorio = productoRepositorio;
}
public void crearProducto(Producto producto){
this.productoRepositorio.crearProducto(producto);
}
public List<ProductoEntity>obtenerProductos(){
return this.productoRepositorio.obtenerProductos();
}
}
| [
"[email protected]"
]
| |
50d587f75292ff8209c9a9440198beb930be4c07 | 838b4b5c690fdc28fd3ed7dd3e12a82a22913483 | /hrms/src/main/java/ilayda/hrms/business/concretes/AuthManager.java | 9784af8900a84d8c1144eb1611a85b90ac51d545 | []
| no_license | ilaydaez/HumanResourcesManagementSystem | 0c4839553115286184e9e26efb8211f6c0d26521 | 0c68f466459b3d457d81b182deb17e9535c1e5b0 | refs/heads/master | 2023-05-30T01:58:59.602994 | 2021-06-04T13:37:51 | 2021-06-04T13:37:51 | 367,191,630 | 6 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,497 | java | package ilayda.hrms.business.concretes;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ilayda.hrms.business.abstracts.AuthService;
import ilayda.hrms.business.abstracts.EmployeeService;
import ilayda.hrms.business.abstracts.EmployerService;
import ilayda.hrms.business.abstracts.UserService;
import ilayda.hrms.core.fakeServices.EmailService;
import ilayda.hrms.core.fakeServices.MernisService;
import ilayda.hrms.core.utilities.result.DataResult;
import ilayda.hrms.core.utilities.result.ErrorDataResult;
import ilayda.hrms.core.utilities.result.SuccessDataResult;
import ilayda.hrms.entities.concretes.Employee;
import ilayda.hrms.entities.concretes.Employer;
@Service
public class AuthManager implements AuthService{
private MernisService mernisService;
private EmailService emailService;
private EmployeeService employeeService;
private EmployerService employerService;
@Autowired
public AuthManager(MernisService mernisService,EmailService emailService,EmployerService employerService,
EmployeeService employeeService) {
this.mernisService=mernisService;
this.emailService=emailService;
this.employeeService=employeeService;
this.employerService=employerService;
}
//Employee kayıt olma başlangıc
@Override
public DataResult<List<Employee>> registerEmployee(Employee employee, String password) {
if (!checkIfNullInfoForUser(employee)) {
return new ErrorDataResult<List<Employee>>("Lütfen zorunlu alanları doldurunuz!!");
}
if (!checkIfEqualPasswordAndConfirmPassword(employee.getPassword(), password)) {
return new ErrorDataResult<List<Employee>>("Parolalar eşleşmiyor");
}
mernisService.checkUser(employee.getIdentityNumber(), employee.getFirstName(), employee.getLastName(), employee.getBirthDate());
employeeService.add(employee);
return new SuccessDataResult<List<Employee>>("Doğrulama Kodu : "+ employee.getValidationCode()+" "+
emailService.sendEmail(employee.getEmail()));
}
private boolean checkIfNullInfoForUser(Employee employee) {
if (employee.getFirstName() !=null || employee.getLastName()!=null || employee.getIdentityNumber() !=null ||
employee.getBirthDate()!=null || employee.getPassword()!=null || employee.getEmail()!=null) {
return true;
}
return false;
}
private boolean checkIfEqualPasswordAndConfirmPassword(String password, String confirmPassword) {
if (!password.equals(confirmPassword)) {
return false;
}
return true;
}
//Employee kayıt olma bitis
//Employer kayıt olma baslangıc
@Override
public DataResult<List<Employer>> registerEmployer(Employer employer, String password) {
if (!checkIfNullInfoForUser(employer)) {
return new ErrorDataResult<List<Employer>>("Lütfen zorunlu alanları doldurunuz!!");
}
if (!checkIfEqualPasswordAndConfirmPassword(employer.getPassword(), password)) {
return new ErrorDataResult<List<Employer>>("Parolalar eşleşmiyor");
}
employerService.add(employer);
return new SuccessDataResult<List<Employer>>("Doğrulama Kodu : "+ employer.getValidationCode()+" "+
emailService.sendEmail(employer.getEmail()));
}
private boolean checkIfNullInfoForUser(Employer employer) {
if (employer.getCompanyName() !=null || employer.getEmail()!=null || employer.getPhone() !=null ||employer.getPassword()!=null) {
return true;
}
return false;
}
//Employer kayıt olma bitis
}
| [
"[email protected]"
]
| |
6c596c8366eda02a148bbb5c75c038ebb2c8585b | 64e16b491b0db004e2a04d81d061cf1d0bdde1cb | /src/main/java/br/com/exemplo/angular/pessoaservice/JWT/JwtAuthEntryPoint.java | 7e543fc08b0ab9faafc3b99db255dfb98c982eb3 | []
| no_license | francisco01/ApiJava | 2fc5379f6554e72f55c0db401567034c90a4b3bf | 762905fa4f7a37e6e18ece7610d9147be92788f1 | refs/heads/master | 2020-07-16T07:26:24.763521 | 2019-09-13T17:26:41 | 2019-09-13T17:26:41 | 205,747,309 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,081 | java | package br.com.exemplo.angular.pessoaservice.JWT;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
@Component
public class JwtAuthEntryPoint implements AuthenticationEntryPoint {
private static final Logger logger = LoggerFactory.getLogger(JwtAuthEntryPoint.class);
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException e)
throws IOException, ServletException {
logger.error("Unauthorized error. Message - {}", e.getMessage());
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Error -> Unauthorized");
}
}
| [
"[email protected]"
]
| |
5f9d8a783065ebd8033815a0349b219948cd3de4 | 039037fe29729a9120821a5aea79d0f3fef416eb | /Java/RestfulAPI/src/main/java/com/hxhy/config/exception/LoginAttempFailureException.java | 8f9ba7d0ed3695d82688e9d7ebe5b1f5911ede11 | []
| no_license | hmhcy/Common | ea17c61042c4268337c4f5b7ed44fcefd6fd38ab | c70988a1f00a6c034cda7b845d7fe25ed3f8696e | refs/heads/master | 2021-01-22T22:24:42.141133 | 2018-06-15T02:51:16 | 2018-06-15T02:51:16 | 85,543,249 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 336 | java | package com.hxhy.config.exception;
public class LoginAttempFailureException extends Exception {
/**
*
*/
private static final long serialVersionUID = 5708879678025194865L;
public LoginAttempFailureException() {
super("尝试登陆次数超出限制");
}
public LoginAttempFailureException(String s) {
super(s);
}
}
| [
"[email protected]"
]
| |
921b2a342c47e64526b740fa4de986fada813611 | 602fd38ea7d275e7e93f9a20f2321f00aca1d5bf | /qsq-test/src/main/java/com/qsq/test/po/SysUser.java | b687874950898ac854edc79836dfcf78931a1fe3 | []
| no_license | javaqsq/qsq-future | 9b372b45cba55da8c0e90663134cf73094caff11 | 2be28560648f0671b4df3d710acd325ece65c8d0 | refs/heads/master | 2020-12-07T23:38:55.910342 | 2020-05-11T13:11:19 | 2020-05-11T13:11:19 | 232,826,838 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,186 | java | package com.qsq.test.po;
import com.baomidou.mybatisplus.annotation.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableId;
import com.qsq.common.model.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* 用户表
* </p>
*
* @author qsq
* @since 2019-12-29
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
public class SysUser extends BaseEntity {
private static final long serialVersionUID=1L;
@TableId(value = "user_id", type = IdType.AUTO)
private Integer userId;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 昵称
*/
private String nickname;
/**
* 手机号码
*/
private String mobile;
/**
* 生日
*/
private Date birthday;
/**
* 邮箱
*/
private String email;
/**
* 性别:1:男 ;0:女
*/
private Integer sex;
/**
* 是否锁定 : 1:锁定 ; 0:正常
*/
private Integer lockSign;
/**
* 地址
*/
private String address;
}
| [
"[email protected]"
]
| |
a6c708e466c25ee9d324f17633570fe6375d2574 | 31834723aa1d231a212e977618c18a78a0f9d0a5 | /reservation/src/main/java/kr/or/connect/reservation/dto/Promotion.java | 49f35f162cba6d1b2f0506bfc067d1f4a5f78b6c | []
| no_license | minsung8/Spring_ReservationProject | 306a3df27a827990a5f6c77f6e0324ceb8106aa7 | d1ccad648a2d2f5914fa3fb0c9d22e0df50f98cd | refs/heads/master | 2023-01-05T10:35:18.262659 | 2020-10-23T13:20:15 | 2020-10-23T13:20:15 | 295,557,183 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,557 | java | package kr.or.connect.reservation.dto;
public class Promotion {
int id;
int productId;
int categoryId;
String categoryName;
String description;
int fileId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getFileId() {
return fileId;
}
public void setFileId(int fileId) {
this.fileId = fileId;
}
@Override
public String toString() {
return "Promotion [id=" + id + ", productId=" + productId + ", categoryId=" + categoryId + ", categoryName="
+ categoryName + ", description=" + description + ", fileId=" + fileId + ", getId()=" + getId()
+ ", getProductId()=" + getProductId() + ", getCategoryId()=" + getCategoryId() + ", getCategoryName()="
+ getCategoryName() + ", getDescription()=" + getDescription() + ", getFileId()=" + getFileId()
+ ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString()
+ "]";
}
}
| [
"[email protected]"
]
| |
81e3f192de3d114348ad693820f1b1fd89269292 | c37d2a36312534a55c319b19b61060649c7c862c | /app/src/main/java/com/spongycastle/cms/OriginatorInformation.java | 4c37662e327ff5a92bd097bb82fe9b5eb39e7b68 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | trwinowiecki/AndroidTexting | f5626ad91a07ea7b3cd3ee75893abf8b1fe7154f | 27e84a420b80054e676c390b898705856364b340 | refs/heads/master | 2020-12-30T23:10:17.542572 | 2017-02-01T01:46:13 | 2017-02-01T01:46:13 | 80,580,124 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,702 | java | package com.spongycastle.cms;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import com.spongycastle.asn1.ASN1Encodable;
import com.spongycastle.asn1.ASN1Primitive;
import com.spongycastle.asn1.ASN1Sequence;
import com.spongycastle.asn1.ASN1Set;
import com.spongycastle.asn1.cms.OriginatorInfo;
import com.spongycastle.asn1.x509.Certificate;
import com.spongycastle.asn1.x509.CertificateList;
import com.spongycastle.cert.X509CRLHolder;
import com.spongycastle.cert.X509CertificateHolder;
import com.spongycastle.util.CollectionStore;
import com.spongycastle.util.Store;
public class OriginatorInformation
{
private OriginatorInfo originatorInfo;
OriginatorInformation(OriginatorInfo originatorInfo)
{
this.originatorInfo = originatorInfo;
}
/**
* Return the certificates stored in the underlying OriginatorInfo object.
*
* @return a Store of X509CertificateHolder objects.
*/
public Store getCertificates()
{
ASN1Set certSet = originatorInfo.getCertificates();
if (certSet != null)
{
List certList = new ArrayList(certSet.size());
for (Enumeration en = certSet.getObjects(); en.hasMoreElements();)
{
ASN1Primitive obj = ((ASN1Encodable)en.nextElement()).toASN1Primitive();
if (obj instanceof ASN1Sequence)
{
certList.add(new X509CertificateHolder(Certificate.getInstance(obj)));
}
}
return new CollectionStore(certList);
}
return new CollectionStore(new ArrayList());
}
/**
* Return the CRLs stored in the underlying OriginatorInfo object.
*
* @return a Store of X509CRLHolder objects.
*/
public Store getCRLs()
{
ASN1Set crlSet = originatorInfo.getCRLs();
if (crlSet != null)
{
List crlList = new ArrayList(crlSet.size());
for (Enumeration en = crlSet.getObjects(); en.hasMoreElements();)
{
ASN1Primitive obj = ((ASN1Encodable)en.nextElement()).toASN1Primitive();
if (obj instanceof ASN1Sequence)
{
crlList.add(new X509CRLHolder(CertificateList.getInstance(obj)));
}
}
return new CollectionStore(crlList);
}
return new CollectionStore(new ArrayList());
}
/**
* Return the underlying ASN.1 object defining this SignerInformation object.
*
* @return a OriginatorInfo.
*/
public OriginatorInfo toASN1Structure()
{
return originatorInfo;
}
}
| [
"[email protected]"
]
| |
05e6b49a5c76dba02449dc7dfda1e0e55e5a7e54 | 964bb72c38ef49bd0dbef5833a5c1981c49e2607 | /src/com/lamp/gxpk/adapter/HomeVpAdapter.java | 9eb97ebb922ed11cfc9baa987af8cfdc764ecbb4 | []
| no_license | lgxing/pianke | b977c056db51114a13dbfd3ec262d5a285f48294 | 46e19680f847d5f7f969d76c2ccd921b8dc01c8c | refs/heads/master | 2021-01-10T08:43:37.747283 | 2016-04-05T12:51:18 | 2016-04-05T12:51:18 | 55,507,345 | 1 | 0 | null | null | null | null | GB18030 | Java | false | false | 682 | java | package com.lamp.gxpk.adapter;
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.lamp.gxpk.base.BaseFragment;
/**
* 主页面ViewPager的Adapter
* @author Administrator
*
*/
public class HomeVpAdapter extends FragmentPagerAdapter {
//ViewPager的数据源
private List<BaseFragment> frags;
public HomeVpAdapter(FragmentManager fm,List<BaseFragment> frags) {
super(fm);
this.frags = frags;
}
@Override
public Fragment getItem(int arg0) {
return frags.get(arg0);
}
@Override
public int getCount() {
return frags.size();
}
}
| [
"[email protected]"
]
| |
cb77df6286aeea0e90451fce32e46b2bbdec67a9 | b0b8944ec2fb017479e0b5337c5fe891f11ab389 | /xcschool-server/src/main/java/com/example/xcschoolserver/util/Resp.java | 03bad64f9b10b4517069a2ab02e51063ecb41b56 | []
| no_license | poll0524/xc_project | 7fd503a4f5f616bab616b179a3d345aaa87996b4 | e90d15f677a419f04c83cc6b4c1efd9e6d060a02 | refs/heads/master | 2023-02-11T01:41:48.135460 | 2021-01-01T10:29:27 | 2021-01-01T10:29:27 | 326,009,276 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,122 | java | package com.example.xcschoolserver.util;
/**
* 响应实体
* @author sunnyzyq
* @since 2019/04/23
*/
public class Resp<T> {
public static final int SUCCESS = 0;
public static final int ERROR = 1;
int code = SUCCESS;
String msg;
T body;
public Resp() {}
public Resp(T t) {
this.body = t;
}
public Resp(int code, String msg, T body) {
this.code = code;
this.msg = msg;
this.body = body;
}
public static <T> Resp<T> error() {
return new Resp<>(ERROR, null, null);
}
public static <T> Resp<T> error(String msg) {
return new Resp<>(ERROR, msg, null);
}
public static <T> Resp<T> error(String msg, T body) {
return new Resp<>(ERROR, msg, body);
}
public static <T> Resp<T> success() {
return new Resp<>(SUCCESS, null, null);
}
public static <T> Resp<T> success(String msg) {
return new Resp<>(SUCCESS, msg, null);
}
public static <T> Resp<T> success(T body) {
return new Resp<>(SUCCESS, "", body);
}
public static <T> Resp<T> success(String msg, T body) {
return new Resp<>(SUCCESS, msg, body);
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public void setBody(T body) {
this.body = body;
}
public T getBody() {
return body;
}
public boolean isError() {
return code != SUCCESS;
}
public boolean isSuccess() {
return code == SUCCESS;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("}");
sb.append("code:").append(code).append(",");
if (msg != null) {
sb.append("msg:").append(msg).append(",");
}
if (body != null) {
sb.append("body:").append(body.toString());
}
sb.append("}");
return sb.toString();
}
}
| [
"[email protected]"
]
| |
ffa4d766362dbafcb60d7277ca542440d59c13e3 | 642909ac958375593293d630a70166357df67a67 | /fsa.java | 0355c2a923cfa460f5983ecc2b2be34c968659a6 | []
| no_license | theyruu122/CS311Proj1 | 2516ee0a6d2ddb9be47a9a13f95124123fdfb875 | 61db3ff3f6fb10229797e3acd06543be1cfb9af9 | refs/heads/master | 2021-01-19T15:29:54.166020 | 2012-10-18T15:56:34 | 2012-10-18T15:56:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,692 | java | /**
* Date: October 18, 2012
* Course: CS311-01
*
* Description:
* Universal Finite State Automata
* Compile:
* Compile this file : javac fsa.java
*/
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class fsa {
public static void main(String[] args) throws IOException {
FileInputStream fs = new FileInputStream("input.dat");
DataInputStream di = new DataInputStream(fs);
BufferedReader br = new BufferedReader(new InputStreamReader(di));
fsaLanguageParser f = new fsaLanguageParser();
String s;
int count = 1;
int fsa = 1;
boolean first = true;
while ((s = br.readLine()) != null) {
if (s.equals("||||||||||")) {
count = 1; // reset
f = new fsaLanguageParser();
fsa++;
first = true;
continue;
}
else if (count == 1) {
f.parseNumberOfStates(s);
}
else if (count == 2) {
f.parseFinalStates(s);
}
else if (count == 3) {
f.parseAlphabet(s);
}
else if (s.length() != 0 && s.charAt(0) == '(') {
f.parseTransition(s);
}
else {
if (first) {
f.printSummary(fsa);
first = false;
}
f.parseSample(s);
}
count++;
}
fs.close();
di.close();
br.close();
}
}
| [
"[email protected]"
]
| |
d956f4411509c36a0063e590136284972320b3b5 | 1de2721fda45d5ac71547eda0ab912ddb5855b5e | /android-app/src/main/java/org/solovyev/android/calculator/about/CalculatorReleaseNotesFragment.java | 56754d85b820a6f8995633d25ea2d93a75f50ff8 | []
| no_license | GeekyTrash/android-calculatorpp | d0039cb3fd33cb8df3cf916deec34bfdb656ae0f | 73bcbde57bbe21121b7baac29ee06667560bd383 | refs/heads/master | 2020-12-25T03:10:30.856463 | 2013-04-01T09:08:05 | 2013-04-01T09:08:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,680 | java | /*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact [email protected]
* or visit http://se.solovyev.org
*/
package org.solovyev.android.calculator.about;
import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.TextView;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.AndroidUtils;
import org.solovyev.android.calculator.CalculatorApplication;
import org.solovyev.android.calculator.CalculatorFragment;
import org.solovyev.android.calculator.CalculatorFragmentType;
import org.solovyev.android.calculator.R;
import org.solovyev.common.text.StringUtils;
/**
* User: serso
* Date: 12/25/11
* Time: 12:00 AM
*/
public class CalculatorReleaseNotesFragment extends CalculatorFragment {
public CalculatorReleaseNotesFragment() {
super(CalculatorFragmentType.release_notes);
}
@Override
public void onViewCreated(View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
final TextView releaseNotes = (TextView) root.findViewById(R.id.releaseNotesTextView);
releaseNotes.setMovementMethod(LinkMovementMethod.getInstance());
releaseNotes.setText(Html.fromHtml(getReleaseNotes(this.getActivity())));
}
@NotNull
public static String getReleaseNotes(@NotNull Context context) {
return getReleaseNotes(context, 0);
}
@NotNull
public static String getReleaseNotes(@NotNull Context context, int minVersion) {
final StringBuilder result = new StringBuilder();
final String releaseNotesForTitle = context.getString(R.string.c_release_notes_for_title);
final int version = AndroidUtils.getAppVersionCode(context, CalculatorApplication.class.getPackage().getName());
final TextHelper textHelper = new TextHelper(context.getResources(), CalculatorApplication.class.getPackage().getName());
boolean first = true;
for ( int i = version; i >= minVersion; i-- ) {
String releaseNotesForVersion = textHelper.getText("c_release_notes_for_" + i);
if (!StringUtils.isEmpty(releaseNotesForVersion)){
assert releaseNotesForVersion != null;
if ( !first ) {
result.append("<br/><br/>");
} else {
first = false;
}
releaseNotesForVersion = releaseNotesForVersion.replace("\n", "<br/>");
result.append("<b>").append(releaseNotesForTitle).append(i).append("</b><br/><br/>");
result.append(releaseNotesForVersion);
}
}
return result.toString();
}
}
| [
"[email protected]"
]
| |
eb987ec7bb1cef2e63b5a25849ebc476b0ed8e3d | 0a99304acf75dff6620d931b8ec1e1e5a8d9f543 | /app/src/main/java/com/ysy15350/easyquickcustomer/account/MainBusinessListViewInterface.java | 20d37cdd6e665bf6c38086c81e69fbd9627f25a1 | []
| no_license | ysy15350/EasyQuickCustomer | 1aac5bcab1480aa724ca37daa594674d92f3f4d7 | 65f7ca2059dc3b95345d4620aa98e4b805084c20 | refs/heads/master | 2021-08-30T20:55:19.490710 | 2017-12-19T12:01:57 | 2017-12-19T12:01:57 | 114,760,266 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 207 | java | package com.ysy15350.easyquickcustomer.account;
import api.base.model.Response;
public interface MainBusinessListViewInterface {
public void bank_cardlistCallback(boolean isCache, Response response);
}
| [
"[email protected]"
]
| |
1fffe7824b4bda5993730c9276d2a28633ed2ea4 | ac6da3a1cbed381ecadf766ddca2d1fa8011ddc2 | /EnterpriseApp-ejb/src/test/java/com/bonarea/service/StudentBeanTest.java | 326356ab922dcb119c9345ad39b617b1d0ac4903 | []
| no_license | Xarli9/enterprise | 43e8d5bf6696c67f6fbc50319b3f003b74317f5c | 3b5fb1b0c47ed2938100537664cf5eb9bb11d5d5 | refs/heads/master | 2021-05-04T13:01:20.801986 | 2018-02-05T13:04:09 | 2018-02-05T13:04:09 | 120,305,603 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,736 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bonarea.service;
import com.bonarea.model.Student;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.embeddable.EJBContainer;
import javax.naming.NamingException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author traiandida
*/
public class StudentBeanTest {
static EJBContainer container = null;
static IStudentBeanLocal instance = null;
public StudentBeanTest() {
}
@BeforeClass
public static void setUpClass() throws NamingException {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("org.glassfish.ejb.embedded.glassfish.installation.root", "/Users/Carles/Library/Application Support/Payara Server/glassfish");
properties.put("org.glassfish.ejb.embedded.glassfish.configuration.file", "domain-universe.xml");
container = javax.ejb.embeddable.EJBContainer.createEJBContainer(properties);
instance = (IStudentBeanLocal)container.getContext().lookup("java:global/classes/StudentBean");
}
@AfterClass
public static void tearDownClass() {
container.close();
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of add method, of class StudentBean.
*/
@Test
public void testAdd() throws Exception {
System.out.println("add");
Student model = new Student();
model.setStudent_id(46001000);
model.setName("Carles");
model.setSurname("Noguera");
model.setCard_id("12345678Z");
int expResult = 1;
int result = instance.add(model);
assertEquals(expResult, result);
}
@Test
public void testGetAll() throws Exception{
System.out.println("getAll");
List<Student> studentList = instance.getAll();
assertTrue(studentList.size() > 0);
}
@Test
public void testDelete() throws Exception {
System.out.println("delete");
Student model = new Student();
model.setStudent_id(46001000);
model.setCard_id("12345678Z");
int expResult = 1;
int resultDelete = instance.delete(model);
assertEquals(expResult, resultDelete);
}
}
| [
"[email protected]"
]
| |
52e04c282797979f93d89631c5a229bb7643ef79 | 47f08412d4a519c2977857018196f85cc8c5cc3c | /src/exception/Car.java | 1800b6aba384ce2d3d982357bb7e2e9d40cddf9a | []
| no_license | Stason1o/Java-Exceptions | 9f35456f6e978c67da5fa6bf321846edfabbeac4 | c9e8c3b9033f7c9fab872368232d541c808ef787 | refs/heads/master | 2021-01-01T05:19:44.283553 | 2016-04-20T17:01:31 | 2016-04-20T17:01:31 | 56,142,833 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,865 | java | package exception;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
class Car {
ArrayList<Crashes> crashes = new ArrayList<Crashes>();//arraylist который будет содержать объекты типа Crashes
int year;//год авто
String carName;//имя авто
float maxSpeed;//макс скорость авто
public static int nrCars;//переменная, считающаякол-во созд. объектов
Car(String filename){
File rFile = new File(filename);
Scanner sc;
try {
try{
sc = new Scanner(rFile);
carName = sc.next();
maxSpeed = sc.nextFloat();
year = sc.nextInt();
while(sc.hasNext())
crashes.add(new Crashes(sc.nextDouble(), sc.nextByte(), sc.nextInt(), sc.nextInt(), sc.nextInt()));
nrCars++;
}
catch(IOException | NullPointerException | NumberFormatException | ArrayIndexOutOfBoundsException | InputMismatchException x){
throw new CarExcp(x);
}
}
catch (CarExcp ex) {
ex.analyze();
}
}
Car() {//конструктор по-умолчанию
boolean flag = false;
do{
flag = false;
try{
//do{
System.out.println("Enter name of car: ");
carName = inString();//ввод с кл.
if(carName.equals(""))
throw new CarExcp(carName);
//}while(carName.equals(""));
int numOfCrashes;
do{
System.out.println("Enter number of crashes: ");
numOfCrashes = inInt();
if(numOfCrashes <= 0 || numOfCrashes > 10)
System.out.println("numOfCrashes is not in range 0 - 10");
}while(numOfCrashes <= 0 || numOfCrashes > 10);
System.out.println("Enter repair prices for " + numOfCrashes + " crashes");
for (int i = 0; i < numOfCrashes; i++)//кол-во записей arrayList'a зависит от лок-го поля numOfCrashes
crashes.add(new Crashes());//добавление записей
//do{
System.out.println("Enter car's year: ");
year = inInt();
if(year < 1806 || year > 2017)//если условие не выполняется выкидывает ошибку
throw new CarExcp(year);
//System.out.println("The year of car is wrong! Reenter year.");
//}while((year < 1806) && (year > 2017));
//do{
System.out.println("Enter car's max speed: ");
maxSpeed = inFloat();
if(!(maxSpeed > 0 && maxSpeed < 1227.996))
throw new CarExcp(maxSpeed);
//}while(maxSpeed < 0 && maxSpeed > 1227.996);
}
catch(CarExcp error){
flag = true;
error.analyze();
}
// catch(IOException ioe){
//
// }
} while(flag);
nrCars++;
}
//конструктор с одним параметром
Car(int newCrashes) {
System.out.println("Enter quantity of crashes: ");
boolean flag = false;
do{
flag = false;
try{
System.out.println("Enter name of car: ");
carName = inString();
if(carName.equals(""))
throw new CarExcp(carName);
// int numOfCrashes;
// do{
// numOfCrashes = inInt();
// }while(numOfCrashes < 0 || numOfCrashes > 10);
System.out.println("Enter repair prices for " + newCrashes + " crashes");
for (int i = 0; i < newCrashes; i++)//кол-во записей arrayList'a зависит от лок-го поля numOfCrashes
crashes.add(new Crashes());//добавление записей
//do{
System.out.println("Enter car's year: ");
year = inInt();
if(year < 1806 && year > 2017)
throw new CarExcp(year);
//System.out.println("The year of car is wrong! Reenter year.");
//}while((year < 1806) && (year > 2017));
//do{
System.out.println("Enter car's max speed: ");
maxSpeed = inFloat();
if(!(maxSpeed > 0 && maxSpeed < 1227.996))
throw new CarExcp(maxSpeed);
//}while(maxSpeed < 0 && maxSpeed > 1227.996);
}
catch(CarExcp error){
error.analyze();
flag = true;
}
} while(flag);
nrCars++;
}
//конструктор с 3-мя параметрами
Car(String newName,int newYear,int newSpeed){
carName = newName;
System.out.println("Enter quantity of crashes: ");
int numOfCrashes;
do{
numOfCrashes = inInt();
if(numOfCrashes < 0 || numOfCrashes > 10)
System.out.println("Reenter number of crashes (0 - 10)");
}while(numOfCrashes < 0 || numOfCrashes > 10);
System.out.println("Enter repair prices for " + numOfCrashes + " crashes");
for (int i = 0; i < numOfCrashes; i++)//кол-во записей arrayList'a зависит от лок-го поля numOfCrashes
crashes.add(new Crashes());//добавление записей
year = newYear;
//System.out.println("The year of car is wrong! Reenter year.");
maxSpeed = newSpeed;
nrCars++;
}
Car(String newName,int newYear,int newSpeed, double _price, byte _drunk, int _day, int _month, int _year) throws IOException{
crashes.add(new Crashes(_price, _drunk, _day, _month, _year));
carName = newName;
year = newYear;
maxSpeed = newSpeed;
nrCars++;
}
Car(Car oldCar){
crashes = oldCar.crashes;
carName = oldCar.carName;
year = oldCar.year;
maxSpeed = oldCar.maxSpeed;
nrCars++;
}
static String inString() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String str = "";
try{
str = reader.readLine();
} catch(IOException e){}
return str;
}
static int inInt(){
return (Integer.valueOf(inString()).intValue());
}
static float inFloat(){
return (Float.valueOf(inString()).intValue());
}
//метод записи в файл
@SuppressWarnings("ConvertToTryWithResources")
public void writeInFile(String filename) throws IOException{
File outF = new File(filename + ".txt");
FileWriter fWrite = new FileWriter(outF);
PrintWriter pWrite = new PrintWriter(fWrite);
pWrite.println(carName + "\t");
pWrite.println("Количество аварий: " + crashes.size());
for (Crashes x:crashes)
pWrite.println(x.price);
pWrite.println(maxSpeed);
pWrite.println(year);
System.out.println("Characteristics were saved in " + filename + ".txt");
pWrite.close();
}
// методы изменения полей класса
public void setName(String newName) throws CarExcp{
if(newName.equals(""))
throw new CarExcp(newName);
else
carName = newName;
}
public void setYear(int newYear) throws CarExcp{
if((newYear < 1806) || (newYear > 2017))
throw new CarExcp(newYear);
else
year = newYear;
}
public void setSpeed(float newSpeed) throws CarExcp{
if((newSpeed < 0) || (newSpeed > 1227.966))
throw new CarExcp(newSpeed);
else
maxSpeed = newSpeed;
}
// public void setCrashPrice(int pos, int price, ArrayList<Crashes> list){
// try{
// if((pos < 0) || (pos >= crashes.size()))
// throw new CarExcp(price, pos);
// list.get(pos).setCrashPrice(price);
// }
// catch(CarExcp error){
// error.analyze();
// }
// }
//мутоды доступа к полям класса
public ArrayList<Crashes> getCrashes(){
return crashes;
}
public String getName(){
return carName;
}
public int getYear(){
return year;
}
public float getSpeed(){
return maxSpeed;
}
public double getCrashPrice(int pos,ArrayList<Crashes> list){
return list.get(pos).getCrashPrice();
}
void printCar(){//печать данных
System.out.println("Name of car: " + carName);
System.out.println("Year of car: " + year);
System.out.println("Car's max speed: " + maxSpeed);
System.out.println("Quantity of numOfCrashes: " + crashes.size());
System.out.println("Information about crashes: ");
for (Crashes x: crashes){
x.printInfo();
}
}
public void compareTwoCars(Car sCar){//сравнение 2-х автомоблей
if(crashes.size() < sCar.crashes.size())//если кол-во аварий меньше....
System.out.println(carName + " has more numOfCrashes than second car");
System.out.println(sCar.carName + " has more numOfCrashes than first car");
}
public int calcRepairSum(){//подсче суммы ремонтов
int sum = 0;
for (Crashes x: crashes)
sum += x.getCrashPrice();
return sum;
}
public static int calcRepairSumOfTwoCars(Car car1,Car car2){//подсчет суммы ремонтов 2-х автомобилей
int sum = 0;
for (Crashes x: car1.crashes)
sum += x.getCrashPrice();
for(Crashes y: car2.crashes)
sum += y.getCrashPrice();
return sum;
}
public static void main(String[] args) throws IOException {
System.out.println("ВВЕДИТЕ ДАННЫЕ ВСЕХ АВТОМОБИЛЕЙ:");
Car Lamborgini = new Car("file.txt");
Lamborgini.printCar();
Lamborgini.calcRepairSum();
System.out.println("-------------------------------");
Car Ferrari = new Car();
Ferrari.printCar();
Ferrari.calcRepairSum();
// System.out.println("--------------------------------");
// CarList Lambo = new CarList(Ferrari);
// Lambo.printCar();
// Lambo.calcRepairSum();
//
// System.out.println("--------------------------------");
// CarList Lada = new CarList(5);
// Lada.printCar();
// Lada.calcRepairSum();
//
// System.out.println("--------------------------------");
// CarList Audi = new CarList("Audi R8",2014,300, 1111,10,"january", 2005, false, 0.4f);
// Audi.printCar();
// Audi.calcRepairSum();
//Создание и инициализация динамического массива автомобилей
System.out.println("--------------------------------");
ArrayList<Car> vector= new ArrayList<Car>();
// vector.add(new CarList());
// vector.add(Lambo);
vector.add(new Car("Audi R8", 2014, 300, 1234,(byte)50, 10, 01, 2000));
// vector.add(new CarList(5));
// vector.add(Audi);
// vector.add(Lada);
vector.add(Ferrari);
//Вывод информации об элементах в массиве
for(Car x: vector)
x.printCar();
try{
Ferrari.writeInFile(Ferrari.getName());
// Lambo.writeInFile("Lambo");
// Lada.writeInFile(Lada.getName());
// Audi.writeInFile(Audi.getName());
}catch(IOException x){
System.err.println("Can't write in file");
}
// System.out.println("-------------Сравнение пар атомобилей-------------------");
// Ferrari.compareTwoCars(Audi);
// System.out.println("--------------------------------");
// Lambo.compareTwoCars(Lada);
// System.out.println("--------------------------------");
//Подсчет полной стоимость всех ремонтов автомобилей
int sum = 0;
for (Car x: vector)
sum += x.calcRepairSum();
// for (Crashes x: Lambo.crashes)
// sum += x.getCrashPrice();
// for (Crashes x: Ferrari.crashes)
// sum += x.getCrashPrice();
// for (Crashes x: Lada.crashes)
// sum += x.getCrashPrice();
// for (Crashes x: Audi.crashes)
// sum += x.getCrashPrice();
System.out.println("Общая стоимость ремонтов всех созданных автомобилей: " + sum);
System.out.println("количество созданных автомобилей: " + nrCars);
}
}
| [
"[email protected]"
]
| |
5008f00948b5e1ca9141cdbf2d6c54699f0a052d | c6506e4c6206e5b227b5f284f484167c5b2ab345 | /tile/domain/src/main/java/com/exercise/tarmag/dao/CustomerDao.java | f9c98b140142da9677ef5be7c80edc3b3c856f33 | []
| no_license | yranibee/exercise | 2fd765af9b61eef321605c9ce83b7378a05fcb1d | af1a6bd6626595b22505fd9d11be61639e2812cd | refs/heads/master | 2021-07-09T16:28:18.636731 | 2017-10-10T06:46:49 | 2017-10-10T06:46:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,787 | java | package com.dt.tarmag.dao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.dt.framework.dao.DaoImpl;
import com.dt.framework.util.Constant;
import com.dt.framework.util.Page;
import com.dt.tarmag.model.Customer;
import com.dt.tarmag.util.PageResult;
/**
* @author yuwei
* @Time 2015-6-25下午12:38:21
*/
@Repository
public class CustomerDao extends DaoImpl<Customer, Long> implements ICustomerDao {
@Override
public Customer getCustomer(Customer user) {
String sql = "SELECT c.* FROM DT_CUSTOMER c WHERE c.user_name = ? and c.password = ? and c.deleted = 'N'";
return this.queryForObject(sql, Customer.class, new Object[]{user.getUserName(), user.getPassword()});
}
@Override
public Customer getCustomerByUserName(String userName) {
if(userName == null || userName.trim().equals("")) {
return null;
}
String sql = "SELECT * FROM DT_CUSTOMER WHERE USER_NAME = ?";
return queryForObject(sql, Customer.class, new Object[]{userName.trim()});
}
@Override
public PageResult<Map<String, Object>> findCustomer(Map<String, Object> params, Page page) {
String selectSql = "SELECT CR.ID id, CR.USER_NAME userName,C.ID companyId, C.COMPANY_NAME companyName,A.USER_NAME createUserName,CR.CREATE_DATE_TIME creteDateTime";
String countSql = "SELECT COUNT(1)";
StringBuffer whereBuf = new StringBuffer(" FROM DT_CUSTOMER CR INNER JOIN DT_COMPANY C ON C.DELETED='N' AND C.ID=CR.COMPANY_ID INNER JOIN DT_SYS_ADMIN A ON A.DELETED='N' AND A.ID=CR.CREATE_USER_ID WHERE CR.DELETED='N' AND CR.IS_ADMIN=:isAdmin");
params.put("isAdmin", 1);
if(params.containsKey("companyId")){
whereBuf.append(" AND CR.COMPANY_ID=:companyId");
}
if(params.containsKey("userName")){
whereBuf.append(" AND CR.USER_NAME LIKE :userName");
params.put("userName", "%"+params.get("userName")+"%");
}
List<Map<String, Object>> customers = this.queryForMapList(selectSql + whereBuf.toString(), page.getCurrentPage(), page.getPageSize(), params);
int count = this.queryCount(countSql + whereBuf, params);
page.setRowCount(count);
return new PageResult<Map<String,Object>>(page, customers);
}
@Override
public List<Customer> getCustomerListByCompanyId(Map<String, Object> params, int pageNo ,int pageSize) {
StringBuffer sql = new StringBuffer("SELECT * FROM DT_CUSTOMER WHERE COMPANY_ID =:companyId AND IS_ADMIN =:isAdmin AND DELETED = 'N'");
if(params.containsKey("userName")){
sql.append(" AND USER_NAME LIKE :userName");
params.put("userName", "%"+params.get("userName")+"%");
}
return query(sql.toString(), Customer.class, pageNo, pageSize, params);
}
@Override
public int getCountCustomerListByCompanyId(Map<String, Object> params) {
StringBuffer sql = new StringBuffer("SELECT count(1) FROM DT_CUSTOMER WHERE COMPANY_ID =:companyId AND IS_ADMIN =:isAdmin AND DELETED = 'N'");
if(params.containsKey("userName")){
sql.append(" AND USER_NAME LIKE :userName");
params.put("userName", "%"+params.get("userName")+"%");
}
return queryCount(sql.toString(), params);
}
@Override
public int getCustomerCountByCompanyId(long companyId, boolean isAdmin, String userName) {
StringBuffer sql = new StringBuffer("");
sql.append(" SELECT COUNT(ID) ")
.append(" FROM DT_CUSTOMER ")
.append(" WHERE COMPANY_ID = :companyId ")
.append(" AND IS_ADMIN = :isAdmin ")
.append(" AND DELETED = :deleted ");
Map<String, Object> params = new HashMap<String, Object>();
params.put("companyId", companyId);
params.put("isAdmin", isAdmin);
params.put("deleted", Constant.MODEL_DELETED_N);
if(userName != null && !userName.trim().equals("")) {
sql.append(" AND USER_NAME LIKE :userName ");
params.put("userName", "%" + userName.trim() + "%");
}
return queryCount(sql.toString(), params);
}
@Override
public List<Customer> getCustomerListByCompanyId(long companyId, boolean isAdmin, String userName, int pageNo, int pageSize) {
StringBuffer sql = new StringBuffer("");
sql.append(" SELECT * ")
.append(" FROM DT_CUSTOMER ")
.append(" WHERE COMPANY_ID = :companyId ")
.append(" AND IS_ADMIN = :isAdmin ")
.append(" AND DELETED = :deleted ");
Map<String, Object> params = new HashMap<String, Object>();
params.put("companyId", companyId);
params.put("isAdmin", isAdmin);
params.put("deleted", Constant.MODEL_DELETED_N);
if(userName != null && !userName.trim().equals("")) {
sql.append(" AND USER_NAME LIKE :userName ");
params.put("userName", "%" + userName.trim() + "%");
}
return query(sql.toString(), Customer.class, params);
}
}
| [
"[email protected]"
]
| |
106a511c7d164ed5c297582300cdbcb11c233925 | 6a5e1c7fd25e38251c19b74ab719f659d767c416 | /archive-transformation-steps/src/main/java/ui/steps/numberrange/NumberRangeDialog.java | ca40858237649eb19e5c68ab0825d9ad0e4e3b78 | [
"Apache-2.0"
]
| permissive | marciojv/hopOLD | d734576991460ee9275602a505a4d806c166b1a3 | 461d0608069fd5c66ac3113ca03f94417353a0c4 | refs/heads/master | 2022-04-13T23:14:29.027246 | 2020-04-08T17:19:13 | 2020-04-08T17:19:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,709 | java | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* 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.apache.hop.ui.trans.steps.numberrange;
import org.apache.hop.core.Const;
import org.apache.hop.core.exception.HopException;
import org.apache.hop.core.row.RowMetaInterface;
import org.apache.hop.core.util.Utils;
import org.apache.hop.i18n.BaseMessages;
import org.apache.hop.trans.TransMeta;
import org.apache.hop.trans.step.BaseStepMeta;
import org.apache.hop.trans.step.StepDialogInterface;
import org.apache.hop.trans.steps.numberrange.NumberRangeMeta;
import org.apache.hop.trans.steps.numberrange.NumberRangeRule;
import org.apache.hop.ui.core.dialog.ErrorDialog;
import org.apache.hop.ui.core.widget.ColumnInfo;
import org.apache.hop.ui.core.widget.TableView;
import org.apache.hop.ui.trans.step.BaseStepDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
/**
* Configuration dialog for the NumberRange
*
* @author [email protected]
*/
public class NumberRangeDialog extends BaseStepDialog implements StepDialogInterface {
private static Class<?> PKG = NumberRangeMeta.class; // for i18n purposes, needed by Translator2!!
private NumberRangeMeta input;
private CCombo inputFieldControl;
private Text outputFieldControl;
private Text fallBackValueControl;
private TableView rulesControl;
private FormData fdFields;
public NumberRangeDialog( Shell parent, Object in, TransMeta transMeta, String sname ) {
super( parent, (BaseStepMeta) in, transMeta, sname );
input = (NumberRangeMeta) in;
}
public String open() {
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX );
props.setLook( shell );
setShellImage( shell, input );
ModifyListener lsMod = new ModifyListener() {
public void modifyText( ModifyEvent e ) {
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout( formLayout );
shell.setText( BaseMessages.getString( PKG, "NumberRange.TypeLongDesc" ) );
// Create controls
wStepname = createLine( lsMod, BaseMessages.getString( PKG, "NumberRange.StepName" ), null );
inputFieldControl =
createLineCombo( lsMod, BaseMessages.getString( PKG, "NumberRange.InputField" ), wStepname );
outputFieldControl =
createLine( lsMod, BaseMessages.getString( PKG, "NumberRange.OutputField" ), inputFieldControl );
inputFieldControl.addFocusListener( new FocusListener() {
public void focusLost( org.eclipse.swt.events.FocusEvent e ) {
}
public void focusGained( org.eclipse.swt.events.FocusEvent e ) {
Cursor busy = new Cursor( shell.getDisplay(), SWT.CURSOR_WAIT );
shell.setCursor( busy );
loadComboOptions();
shell.setCursor( null );
busy.dispose();
}
} );
fallBackValueControl =
createLine( lsMod, BaseMessages.getString( PKG, "NumberRange.DefaultValue" ), outputFieldControl );
createRulesTable( lsMod );
// Some buttons
wOK = new Button( shell, SWT.PUSH );
wOK.setText( "OK" );
wCancel = new Button( shell, SWT.PUSH );
wCancel.setText( "Cancel" );
BaseStepDialog.positionBottomButtons( shell, new Button[] { wOK, wCancel }, props.getMargin(), rulesControl );
// Add listeners
lsCancel = new Listener() {
public void handleEvent( Event e ) {
cancel();
}
};
lsOK = new Listener() {
public void handleEvent( Event e ) {
ok();
}
};
wCancel.addListener( SWT.Selection, lsCancel );
wOK.addListener( SWT.Selection, lsOK );
lsDef = new SelectionAdapter() {
public void widgetDefaultSelected( SelectionEvent e ) {
ok();
}
};
wStepname.addSelectionListener( lsDef );
inputFieldControl.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() {
public void shellClosed( ShellEvent e ) {
cancel();
}
} );
// Set the shell size, based upon previous time...
setSize();
getData();
input.setChanged( changed );
shell.open();
while ( !shell.isDisposed() ) {
if ( !display.readAndDispatch() ) {
display.sleep();
}
}
return stepname;
}
/**
* Creates the table of rules
*/
private void createRulesTable( ModifyListener lsMod ) {
Label rulesLable = new Label( shell, SWT.NONE );
rulesLable.setText( BaseMessages.getString( PKG, "NumberRange.Ranges" ) );
props.setLook( rulesLable );
FormData lableFormData = new FormData();
lableFormData.left = new FormAttachment( 0, 0 );
lableFormData.right = new FormAttachment( props.getMiddlePct(), -props.getMargin() );
lableFormData.top = new FormAttachment( fallBackValueControl, props.getMargin() );
rulesLable.setLayoutData( lableFormData );
final int FieldsRows = input.getRules().size();
ColumnInfo[] colinf = new ColumnInfo[ 3 ];
colinf[ 0 ] =
new ColumnInfo(
BaseMessages.getString( PKG, "NumberRange.LowerBound" ), ColumnInfo.COLUMN_TYPE_TEXT, false );
colinf[ 1 ] =
new ColumnInfo(
BaseMessages.getString( PKG, "NumberRange.UpperBound" ), ColumnInfo.COLUMN_TYPE_TEXT, false );
colinf[ 2 ] =
new ColumnInfo( BaseMessages.getString( PKG, "NumberRange.Value" ), ColumnInfo.COLUMN_TYPE_TEXT, false );
rulesControl =
new TableView(
transMeta, shell, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, colinf, FieldsRows, lsMod, props );
fdFields = new FormData();
fdFields.left = new FormAttachment( 0, 0 );
fdFields.top = new FormAttachment( rulesLable, props.getMargin() );
fdFields.right = new FormAttachment( 100, 0 );
fdFields.bottom = new FormAttachment( 100, -50 );
rulesControl.setLayoutData( fdFields );
}
private Text createLine( ModifyListener lsMod, String lableText, Control prevControl ) {
// Value line
Label lable = new Label( shell, SWT.RIGHT );
lable.setText( lableText );
props.setLook( lable );
FormData lableFormData = new FormData();
lableFormData.left = new FormAttachment( 0, 0 );
lableFormData.right = new FormAttachment( props.getMiddlePct(), -props.getMargin() );
// In case it is the first control
if ( prevControl != null ) {
lableFormData.top = new FormAttachment( prevControl, props.getMargin() );
} else {
lableFormData.top = new FormAttachment( 0, props.getMargin() );
}
lable.setLayoutData( lableFormData );
Text control = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( control );
control.addModifyListener( lsMod );
FormData widgetFormData = new FormData();
widgetFormData.left = new FormAttachment( props.getMiddlePct(), 0 );
// In case it is the first control
if ( prevControl != null ) {
widgetFormData.top = new FormAttachment( prevControl, props.getMargin() );
} else {
widgetFormData.top = new FormAttachment( 0, props.getMargin() );
}
widgetFormData.right = new FormAttachment( 100, 0 );
control.setLayoutData( widgetFormData );
return control;
}
private CCombo createLineCombo( ModifyListener lsMod, String lableText, Control prevControl ) {
// Value line
Label lable = new Label( shell, SWT.RIGHT );
lable.setText( lableText );
props.setLook( lable );
FormData lableFormData = new FormData();
lableFormData.left = new FormAttachment( 0, 0 );
lableFormData.right = new FormAttachment( props.getMiddlePct(), -props.getMargin() );
// In case it is the first control
if ( prevControl != null ) {
lableFormData.top = new FormAttachment( prevControl, props.getMargin() );
} else {
lableFormData.top = new FormAttachment( 0, props.getMargin() );
}
lable.setLayoutData( lableFormData );
CCombo control = new CCombo( shell, SWT.BORDER );
props.setLook( control );
control.addModifyListener( lsMod );
FormData widgetFormData = new FormData();
widgetFormData.left = new FormAttachment( props.getMiddlePct(), 0 );
// In case it is the first control
if ( prevControl != null ) {
widgetFormData.top = new FormAttachment( prevControl, props.getMargin() );
} else {
widgetFormData.top = new FormAttachment( 0, props.getMargin() );
}
widgetFormData.right = new FormAttachment( 100, 0 );
control.setLayoutData( widgetFormData );
return control;
}
// Read data from input (TextFileInputInfo)
public void getData() {
// Get fields
wStepname.setText( stepname );
String inputField = input.getInputField();
if ( inputField != null ) {
inputFieldControl.setText( inputField );
}
String outputField = input.getOutputField();
if ( outputField != null ) {
outputFieldControl.setText( outputField );
}
String fallBackValue = input.getFallBackValue();
if ( fallBackValue != null ) {
fallBackValueControl.setText( fallBackValue );
}
for ( int i = 0; i < input.getRules().size(); i++ ) {
NumberRangeRule rule = input.getRules().get( i );
TableItem item = rulesControl.table.getItem( i );
// Empty value is equal to minimal possible value
if ( rule.getLowerBound() > -Double.MAX_VALUE ) {
String lowerBoundStr = String.valueOf( rule.getLowerBound() );
item.setText( 1, lowerBoundStr );
}
// Empty value is equal to maximal possible value
if ( rule.getUpperBound() < Double.MAX_VALUE ) {
String upperBoundStr = String.valueOf( rule.getUpperBound() );
item.setText( 2, upperBoundStr );
}
item.setText( 3, rule.getValue() );
}
rulesControl.setRowNums();
rulesControl.optWidth( true );
}
private void cancel() {
stepname = null;
input.setChanged( changed );
dispose();
}
private void ok() {
if ( Utils.isEmpty( wStepname.getText() ) ) {
return;
}
stepname = wStepname.getText(); // return value
String inputField = inputFieldControl.getText();
input.setInputField( inputField );
input.emptyRules();
String fallBackValue = fallBackValueControl.getText();
input.setFallBackValue( fallBackValue );
input.setOutputField( outputFieldControl.getText() );
int count = rulesControl.nrNonEmpty();
for ( int i = 0; i < count; i++ ) {
TableItem item = rulesControl.getNonEmpty( i );
String lowerBoundStr =
Utils.isEmpty( item.getText( 1 ) ) ? String.valueOf( -Double.MAX_VALUE ) : item.getText( 1 );
String upperBoundStr =
Utils.isEmpty( item.getText( 2 ) ) ? String.valueOf( Double.MAX_VALUE ) : item.getText( 2 );
String value = item.getText( 3 );
try {
double lowerBound = Double.parseDouble( lowerBoundStr );
double upperBound = Double.parseDouble( upperBoundStr );
input.addRule( lowerBound, upperBound, value );
} catch ( NumberFormatException e ) {
throw new IllegalArgumentException( "Bounds of this rule are not numeric: lowerBound="
+ lowerBoundStr + ", upperBound=" + upperBoundStr + ", value=" + value, e );
}
}
dispose();
}
private void loadComboOptions() {
try {
String fieldvalue = null;
if ( inputFieldControl.getText() != null ) {
fieldvalue = inputFieldControl.getText();
}
RowMetaInterface r = transMeta.getPrevStepFields( stepname );
if ( r != null ) {
inputFieldControl.setItems( r.getFieldNames() );
}
if ( fieldvalue != null ) {
inputFieldControl.setText( fieldvalue );
}
} catch ( HopException ke ) {
new ErrorDialog( shell, BaseMessages.getString( PKG, "NumberRange.TypeLongDesc" ), "Can't get fields", ke );
}
}
}
| [
"[email protected]"
]
| |
a41a04efa158c05c1dc77d3102a25976b43943ec | 4282b4f9001df8d0b540fa7eef4d5dc4ca3f2f24 | /src/main/java/com/practice/jpashop2/domain/Item.java | 3d01f1b0363c1aba1f4c88969891bcbee4b934c0 | []
| no_license | yeonnwoo/SimpleShop | b8ff2b7b77a5ed374ec85f11a3757f13f5ef4f93 | 1f11badca84d679c2bfb2c18eb2496c901beb17d | refs/heads/main | 2023-06-12T08:10:03.134215 | 2021-07-10T00:37:32 | 2021-07-10T00:37:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,111 | java | package com.practice.jpashop2.domain;
import com.practice.jpashop2.exception.NotEnoughStockException;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "dtype")
@Getter @Setter
public class Item {
@Id @GeneratedValue
@Column(name = "item_id")
private Long id;
private String name;
private int price;
private int stockQuantity;
@ManyToMany(mappedBy = "items")
private List<Category> categories = new ArrayList<>();
/**
* todo : 비즈니스 로직
* 1. 재고 수량 추가
* 2. 재고 수량 감소 (0보다 작을 시, 오류 발생)
*/
public void addStock(int quantity)
{
this.stockQuantity+=quantity;
}
public void removeStock(int quantity)
{
int restStock=this.stockQuantity-quantity;
if(restStock<0)
{
throw new NotEnoughStockException("need more stock");
}
this.stockQuantity=restStock;
}
}
| [
"[email protected]"
]
| |
9488f7082623d8cb770598ffc21250b8033d5cf2 | d92aa574eaadbb717cecc01dfc32f1780ae105f8 | /src/main/java/com/barbara/pereira/vacina/controller/AplicacaoVacinaController.java | 7e8b4bff99904833d1f4fa3a896aa36ff03ac578 | []
| no_license | barbarapereira/teste-api-vacina | 237c25663c66d343bea3607b78e77a59ef9e23ee | 2307d3ff9f69f01cb69e3e68d967d1d4052ca763 | refs/heads/main | 2023-03-23T04:00:37.888608 | 2021-03-04T19:30:34 | 2021-03-04T19:30:34 | 344,296,239 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,094 | java | package com.barbara.pereira.vacina.controller;
import com.barbara.pereira.vacina.dto.AplicacaoVacinaDto;
import com.barbara.pereira.vacina.dto.UsuarioDto;
import com.barbara.pereira.vacina.entity.AplicacaoVacina;
import com.barbara.pereira.vacina.entity.Usuario;
import com.barbara.pereira.vacina.repository.AplicacaoVacinaRepository;
import com.barbara.pereira.vacina.services.AplicacaoVacinaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RestController
@RequestMapping("/aplicacaoVacinas")
public class AplicacaoVacinaController {
@Autowired
AplicacaoVacinaService aplicacaoVacinaService;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public AplicacaoVacinaDto incluir(@RequestBody @Valid AplicacaoVacinaDto novaVacinaDto){
AplicacaoVacina aplicacaoVacina =
aplicacaoVacinaService.incluirNovaAplicacao(novaVacinaDto.criarNovaVacina());
return aplicacaoVacina.criarDto();
}
}
| [
"[email protected]"
]
| |
b1f023081822c46e839bd2f14f95727a5b58df2b | 78318a61a32be442ecdf809a36f5fcd8ef960722 | /src/main/java/net/tx0/jason/Json.java | 9f25e796e994eac2fc8554fa50db4ee46513f966 | [
"MIT"
]
| permissive | gl1tor/jason | e8b6462efa99e774988368052c19d05c049189ad | 70500e71dde77dc426be85088c4c154e16309503 | refs/heads/main | 2023-05-13T01:32:50.444534 | 2021-05-31T18:57:37 | 2021-05-31T18:57:37 | 372,593,398 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,997 | java | package net.tx0.jason;
import java.io.*;
import java.nio.charset.Charset;
/**
* <h1>Json serialization library</h1>
*
* <h2>Features</h2>
*
* <ul>
* <li>Provides JSON serialization and deserialization</li>
* <li>Json arrays and objects implement {@link java.util.List}s and {@link java.util.Map}s </li>
* <li>Standards (RFC 7159) compliant</li>
* <li>Opinionated convenience methods and defaults</li>
* <li>Takes and supplies Java primitives, uses Java null</li>
* <li>No dependencies</li>
* <li>No checked exceptions</li>
* <li>No marshalling of user types</li>
* </ul>
*
* <h2>Usage and overview</h2>
*
* <p>
* Reading or writing JSON is ultimately done using either a {@link JsonReader} or a {@link JsonWriter}, respectively.
* This class provides overloaded static methods to construct instances of these interfaces.
* In addition to using these classes directly there are a number of convenience methods provided that either accept
* a reader or writer or create one on their own. Readers and writers require a {@link JsonConfig}, methods that read
* or write json but don't take neither a reader nor a config as an argument rely on a default configuration.
* </p>
*
* <p>
* The {@link JsonFactory} is another way to construct instances of {@link JsonReader} and {@link JsonWriter}.
* </p>
*
* <table>
* <tr>
* <th>Interface</th>
* <th>Explicit config</th>
* <th>Default config</th>
* <th>Using factory's config</th>
* </tr>
* <tr>
* <td>{@link JsonReader}</td>
* <td>{@link #createReader(JsonConfig, InputStream)}</td>
* <td>{@link #createReader(InputStream)}</td>
* <td>{@link JsonFactory#createReader(InputStream)}</td>
* </tr>
* <tr>
* <td>{@link JsonWriter}</td>
* <td>{@link #createWriter(JsonConfig, OutputStream)}</td>
* <td>{@link #createWriter(OutputStream)}</td>
* <td>{@link JsonFactory#createWriter(OutputStream)}</td>
* </tr>
* </table>
*
* <h2>Serialization and deserialization</h2>
*
* <p>
* This class provides several overloaded methods to serialize an object tree ({@link JsonValue} into a JSON text, and
* vice versa methods to deserialize a JSON text into a generic object tree.
* </p>
*
* <p>
* Various variants exist and differ by configuration used and the target written to, or read from in case of deserialization.
* {@link JsonResource} provides a way to deserialize from general resources.
* </p>
*
* <p>
* The object tree is modelled by a type hierarchy starting at {@link JsonValue}. {@link JsonObject} and {@link JsonArray}
* being two prominent subclasses providing various methods to easily access contained values.
* </p>
*
* <h2>Example</h2>
*
* <pre>
* JsonValue value = Json.deserialize("{ \"naem\" : \"Tom\" }");
* value.asObject().rename( "naem", "name" );
* System.out.print( Json.serialize( value ) );
* </pre>
*
* <h2>Exceptions</h2>
*
* <p>
* This library does not throw checked exceptions. It wraps {@link IOException}s which occur during reading
* or writing in {@link JsonIOException}s. This is a trade-off between usability in callbacks and pure in-memory
* operations (i.e. parsing a string), and consistency with remaining I/O related code.
* </p>
*
* <p>An exception to this are methods that take {@link File}s as an argument and perform I/O on these files.</p>
*
* <h2>Closable streams</h2>
*
* This api takes {@link InputStream}s and {@link OutputStream}s at various
* points and generally doesn't close them. The streams can be reused, f.i.
* serialize can be called multiple times with the same output stream, or
* the stream could be interleaved with other data.
*
* @see JsonFactory
* @see JsonValue
*/
public abstract class Json {
private static final class DefaultConfigHolder {
private static final JsonConfig INSTANCE = new JsonConfigBuilder().build();
}
static JsonConfig getDefaultConfig() {
return DefaultConfigHolder.INSTANCE;
}
private Json() {
}
public static JsonValue deserialize( JsonResource resource ) {
return deserialize( null, resource );
}
public static JsonValue deserialize( String string ) {
return deserialize( null, string );
}
public static JsonValue deserialize( File file ) throws IOException {
return deserialize( null, file );
}
public static String serialize( JsonValue value ) {
return serialize(null, value);
}
public static void serialize( JsonValue value, File file ) throws IOException {
serialize( null, value, file, null );
}
public static void serialize( JsonValue value, File file, Charset encoding ) throws IOException {
serialize( null, value, file, encoding );
}
public static void serialize( JsonWriter writer ) {
serialize( null, writer );
}
public static void serialize( JsonValue value, OutputStream outputStream ) {
serialize( value, null, outputStream );
}
public static void serialize( JsonValue value, Writer writer ) {
serialize( value, null, writer );
}
public static JsonReader createReader( Reader reader ) {
return createReader( null, reader );
}
public static JsonReader createReader( InputStream inputStream ) {
return createReader( null, inputStream );
}
public static JsonWriter createWriter( OutputStream outputStream ) {
return createWriter( null, outputStream );
}
public static JsonWriter createWriter( Writer writer ) {
return createWriter( null, writer );
}
public static JsonValue deserialize( JsonConfig config, JsonResource resource ) {
try {
return resource.readFrom( (is)-> deserialize( createReader( config, is ) ) );
} catch ( IOException e ) {
throw JsonException.wrap(e);
}
}
public static JsonValue deserialize( JsonConfig config, String string ) {
return deserialize( config, JsonResource.forString( string ) );
}
public static JsonValue deserialize( JsonConfig config, File file ) throws IOException {
try {
return deserialize(config, JsonResource.forFile(file));
} catch ( JsonIOException e ) {
throw e.getCause();
}
}
public static JsonValue deserialize( JsonConfig config, ClassLoader classLoader, String name ) {
return deserialize( config, JsonResource.forClasspath( classLoader, name ) );
}
public static JsonValue deserialize( JsonReader reader ) {
return JsonParser.parseText(reader);
}
public static String serialize( JsonConfig config, JsonValue value ) {
StringWriter sw = new StringWriter();
serialize( value, config, sw );
return sw.toString();
}
public static void serialize( JsonConfig config, JsonValue value, File file ) throws IOException {
serialize( config, value, file, null );
}
public static void serialize( JsonConfig config, JsonValue value, File file, Charset encoding ) throws IOException {
if ( config == null )
config = getDefaultConfig();
if ( encoding == null )
encoding = config.getCharset();
boolean notClosed = true;
FileOutputStream outputStream = new FileOutputStream(file);
try {
OutputStreamWriter writer = new OutputStreamWriter(outputStream, encoding);
try {
serialize(value, config, writer);
} catch ( JsonIOException e ) {
throw e.getCause();
} finally {
writer.close();
notClosed = false;
}
} finally {
if ( notClosed )
outputStream.close();
}
}
public static void serialize( JsonValue value, JsonWriter writer ) {
if ( value == null ) {
writer.writeNull();
} else {
value.write(writer);
}
}
public static void serialize( JsonValue value, JsonConfig config, OutputStream outputStream ) {
JsonWriter writer = createWriter(config, outputStream);
serialize(value,writer);
writer.close(); // no finally
}
public static void serialize( JsonValue value, JsonConfig config, Writer writer ) {
JsonWriter jsonWriter = createWriter(config, writer);
serialize(value,jsonWriter);
jsonWriter.close(); // no finally
}
public static JsonReader createReader( JsonConfig config, Reader reader ) {
if ( config == null )
config = getDefaultConfig();
return new JsonReaderImpl( config, new JsonScanner( config, reader ) );
}
public static JsonReader createReader( JsonConfig config, InputStream inputStream ) {
if ( config == null )
config = getDefaultConfig();
return new JsonReaderImpl( config, new JsonScanner( config, inputStream) );
}
public static JsonWriter createWriter( JsonConfig config, OutputStream outputStream ) {
if ( config == null )
config = getDefaultConfig();
return createWriter( config, new OutputStreamWriter( outputStream, config.getCharset() ) );
}
public static JsonWriter createWriter( JsonConfig config, Writer writer ) {
if ( config == null )
config = getDefaultConfig();
return new JsonWriterImpl( config, writer );
}
/**
* Copies json tokens from the supplied source to the supplied target.
*/
public static void copy( JsonReader source, JsonWriter target ) {
while ( source.hasNext() ) {
JsonToken tag = source.next();
switch ( tag ) {
case BOOLEAN:
target.write( source.getBooleanValue() );
break;
case END_ARRAY:
target.writeEndArray();
break;
case END_OBJECT:
target.writeEndObject();
break;
case NUMBER:
target.write( source.getNumberValue() );
break;
case NULL:
target.writeNull();
break;
case BEGIN_ARRAY:
target.writeBeginArray();
break;
case MEMBER_NAME:
target.writeMember( source.getMemberName() );
break;
case BEGIN_OBJECT:
target.writeStartObject();
break;
case STRING:
target.write( source.getStringValue() );
break;
default:
throw new IllegalStateException( "Unknown json token encountered" );
}
}
}
}
| [
"[email protected]"
]
| |
ccba89a903e25c96ec48c723c292ed94914c503a | 5a9fed26917d37054ee84d6eaf24d12d2fd0d9ba | /zhouhangbasicPlus/src/com/zhouhang/day08homework/test03/Test03.java | 953d574d1e0cfc4b877e473a4e70af25f5ea9163 | []
| no_license | AntonyZhouPlus/basicProject | 6deaecc707f6280b2de05c1944763530f777afa6 | 0ab867d8d60e72c04ea8b834bf0163fdd03cc8b4 | refs/heads/master | 2020-03-18T21:38:33.134152 | 2018-06-15T02:15:05 | 2018-06-15T02:15:05 | 135,291,876 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 781 | java | package com.zhouhang.day08homework.test03;
/**
* com.zhouhang.day08homework
*
* @author zhouhang
* @date 2018/6/8 下午8:39
* 描述:猴子吃桃子问题,猴子第一天摘下若干个桃子,当即吃了快一半,还不过瘾,
* 又多吃了一个。第二天又将仅剩下的桃子吃掉了一半,又多吃了一个。
* 以后每天都吃了前一天剩下的一半多一个。
* 到第十天,只剩下一个桃子。试求第一天共摘了多少桃子?
*/
public class Test03 {
public static void main(String[] args) {
System.out.println(monkeyEat(10));
}
public static int monkeyEat(int day) {
if (day == 1) {
return 1;
} else {
return (monkeyEat(day - 1) + 1) * 2;
}
}
}
| [
"[email protected]"
]
| |
999ae0fb69ec85e3051253b2c8c7bfce40231bc6 | adf5c6aa53341d88b620f7d11897e085a48e07eb | /src/edu/ucsb/cs56/drawings/colinmai/advanced/WritePictureToFile.java | 8a3cd6fda44cc360340f450d45065f93e6b310a8 | [
"MIT"
]
| permissive | jmangel/F16-lab04 | 2f2bbe634b345c97c384ed558699195c4c7d1e3d | 2bc3b05a04ddf2faba2616d00540ce1aaa141f80 | refs/heads/master | 2021-01-11T05:34:08.509872 | 2016-11-05T21:16:22 | 2016-11-05T21:16:22 | 71,507,014 | 0 | 9 | null | 2016-11-05T21:14:30 | 2016-10-20T21:47:32 | Java | UTF-8 | Java | false | false | 2,696 | java | package edu.ucsb.cs56.drawings.colinmai.advanced;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.io.File;
import javax.imageio.ImageIO;
import java.io.IOException;
/**
* A class with a main method that can write a drawing to a graphics file.
*
* @author P. Conrad,
* @version for CS56, W16, UCSB
*/
public class WritePictureToFile
{
public static void usage()
{
System.out.println("Usage: java WritePictureToFile whichImage mypic");
// @@@ modify the next line to describe your picture
System.out.println(" whichImage should be 1,2 or 3");
System.out.println(" whichImage chooses from drawPicture1, 2 or 3");
System.out.println(" .png gets added to the filename");
System.out.println(" e.g. if you pass mypic, filename is mypic.png");
System.out.println("Example: java WritePictureToFile 3 foo");
System.out.println(" produces foo.png from drawPicture3");
}
/** Write the chosen picture to a file.
*
* @param args command line arguments
*/
public static void main(String[] args)
{
if (args.length != 2) {
usage();
System.exit(1);
}
String whichPicture = args[0]; // first command line arg is 1, 2, 3
String outputfileName = args[1]; // second command line arg is which pic
final int WIDTH = 640;
final int HEIGHT = 480;
// create a new image
// TYPE_INT_ARGB is "RGB image" with transparency (A = alpha channel)
BufferedImage bi =
new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = bi.createGraphics();
if (whichPicture.equals("1")) {
AllMyDrawings.drawPicture1(g2);
} else if (whichPicture.equals("2")) {
AllMyDrawings.drawPicture2(g2);
} else if (whichPicture.equals("3")) {
AllMyDrawings.drawPicture3(g2);
}
final String imageType = "png"; // choices: "gif", "png", "jpg"
// We must declare this variable outside the try block,
// so we can see it inside the catch block
String fullFileName = "";
try {
fullFileName = outputfileName + "." + imageType;
File outputfile = new File(fullFileName);
ImageIO.write(bi, imageType, outputfile); // actually writes file
System.out.println("I created " + fullFileName); // tell the user
} catch (IOException e) {
System.err.println("Sorry, an error occurred--I could not create "
+ fullFileName
+"\n The error was: "
+ e.toString());
}
}
}
| [
"[email protected]"
]
| |
dcbde1a1b61413e39d1abe49bebb3a35867c1bc8 | a0abc81533d9c8acbffd2b5771f08799c5d733dc | /Java/176_E_Second_Highest_Salary.java | b0d98c1be73be5cafbe51c649fbf9b160525a07c | []
| no_license | yashadukia/leetcode-solutions | 25c28d0251410ce11a55f570f834dfd6aef6e9cc | 0443a2a0a986a1c8981157a7f90c1c40f30aa6b5 | refs/heads/main | 2023-05-10T12:41:24.521823 | 2021-05-22T18:03:09 | 2021-05-22T18:03:09 | 357,020,786 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 788 | java | # Write your MySQL query statement below
SELECT (
SELECT DISTINCT Salary FROM Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1) AS SecondHighestSalary;
# The SELECT DISTINCT statement is used to return only distinct (different) values.
# Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.
# The ORDER BY keyword is used to sort the result-set in ascending or descending order.
# The AS command is used to rename a column or table with an alias.
# https://www.sqltutorial.org/sql-limit/
# The row_count determines the number of rows that will be returned.
# The OFFSET clause skips the offset rows before beginning to return the rows. | [
"[email protected]"
]
| |
30f160a02ccbe058aabe7c6b3f48712122915c6b | da2647e6ff3a28a68909e3d4249fecfa145a4c69 | /app/src/main/java/com/simona/todo/to_doapp/controller/ItemVOAdapter.java | a0a8671676548e992257af149f129340d105dccf | []
| no_license | Simute/Simute | d0aba90832e444c8bcbd179d988e484cc1f06263 | 91b2833166f04cf04af4394317065891c1591c1f | refs/heads/master | 2021-05-08T14:41:00.388475 | 2018-02-03T13:59:00 | 2018-02-03T13:59:00 | 120,094,775 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,617 | java | package com.simona.todo.to_doapp.controller;
/**
* Created by Simonos on 2/3/2018.
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import com.simona.todo.to_doapp.R;
import com.simona.todo.to_doapp.model.DBActions;
import com.simona.todo.to_doapp.model.ItemVO;
import java.util.ArrayList;
public class ItemVOAdapter extends ArrayAdapter<ItemVO> implements CompoundButton.OnCheckedChangeListener, View.OnClickListener {
// Model
private DBActions dbActions;
public ItemVOAdapter(Context context, ArrayList<ItemVO> items, DBActions dbActions) {
super(context, 0, items);
this.dbActions = dbActions;
}
@Override
public void onClick(View view) {
View parentRow = (View) view.getParent();
ListView listView = (ListView) parentRow.getParent();
int position = listView.getPositionForView(parentRow);
ItemVO itemVO = getItem(position);
dbActions.deleteItem(itemVO);
((MainActivity) getContext()).updateView();
}
@Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
View parentRow = (View) view.getParent();
ListView listView = (ListView) parentRow.getParent();
if (listView == null) {
return;
}
int position = listView.getPositionForView(parentRow);
ItemVO itemVO = getItem(position);
if(isChecked == true){
itemVO.done=1;
}else{
itemVO.done=0;
}
dbActions.updateItem(itemVO);
((MainActivity) getContext()).updateView();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ItemVO item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.layout_item_vo, parent, false);
}
CheckBox itemCheckbox = (CheckBox) convertView.findViewById(R.id.item_checkbox);
itemCheckbox.setText(item.title);
itemCheckbox.setChecked(item.done == 1);
itemCheckbox.setOnCheckedChangeListener(this);
Button deleteButton = (Button) convertView.findViewById(R.id.item_delete);
deleteButton.setOnClickListener(this);
return convertView;
}
} | [
"[email protected]"
]
| |
735c375262d80b397e30e71a705b4068d832d84d | 995df1d32ffae384eabb36f5770f6a9d3c9e791e | /QuizGenerator.java | 883e749c5f94f12003d1254a68a9d7d8ee5dee61 | [
"MIT"
]
| permissive | AditiSharma97/QuizApplication | 8a1b70df0827c067e8fe01533ecdd572a906b110 | 615365988be723d4ef214772b789d28b81967602 | refs/heads/master | 2021-08-20T05:59:24.090861 | 2017-11-28T10:49:13 | 2017-11-28T10:49:13 | 112,321,108 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,431 | java | import java.io.*;
import java.util.*;
import java.lang.*;
class QuizGenerator
{
static MultipleChoiceQuestion [] mcqarr = new MultipleChoiceQuestion [1];
static TrueOrFalseQuestion [] tofarr = new TrueOrFalseQuestion [1];
static FillInTheBlanksQuestion [] fitbarr = new FillInTheBlanksQuestion [1];
static Question [] ques = new Question [1];
int numberOfQuestions;
QuizGenerator (int no, int ch, int type, FileNames fileNames) //ch = 0 for question set, ch = 1 for answer set
{
numberOfQuestions = no;
ques = new Question [no];
mcqarr = new MultipleChoiceQuestion [no];
tofarr = new TrueOrFalseQuestion [no];
fitbarr = new FillInTheBlanksQuestion [no];
String questionsInSubjectFileName = fileNames.questionsInSubjectFileName;
String fileName = new String ();
int min = 0;
switch (type)
{
case 0:
fileName = fileNames.mcqFileName;
switch (UserInterface.subject)
{
case 0:
min = 101;
break;
case 1:
min = 401;
break;
case 2:
min = 701;
break;
}
break;
case 1:
fileName = fileNames.trueOrFalseFileName;
switch (UserInterface.subject)
{
case 0:
min = 201;
break;
case 1:
min = 501;
break;
case 2:
min = 801;
break;
}
break;
case 2:
fileName = fileNames.fillInTheBlanksFileName;
switch (UserInterface.subject)
{
case 0:
min = 301;
break;
case 1:
min = 601;
break;
case 2:
min = 901;
break;
}
break;
}
int randomNos [] = new int [no];
int max;
int [] qno = new int [3];
try
{
FileReader fr1 = new FileReader (questionsInSubjectFileName);
BufferedReader br1 = new BufferedReader (fr1);
for (int i = 0; i < 3; i++)
qno[i] = Integer.parseInt(br1.readLine());
br1.close();
fr1.close();
}
catch (Exception e)
{
System.out.println ("Exception found in QuizGenerator class: " + e);
}
try {
max = qno[type];
if (no > max % 100)
{
no = max % 100;
numberOfQuestions = no;
}
final Random RANDOMISER = new Random();
randomNos[0] = RANDOMISER.nextInt((max+1)-min)+min;
int flag = 0;
for (int i = 1; i < no; i++)
{
flag = 0;
int x = RANDOMISER.nextInt((max+1)-min)+min;
int j;
for (j = 0; j < i; j++)
{
if (x == randomNos[j])
{
flag = 1;
}
}
if (flag == 1)
{
i--;
continue;
}
if (j == i)
randomNos[i] = x;
}
FileReader fr = new FileReader (fileName);
BufferedReader br = new BufferedReader (fr);
String s [] = new String [no];
for (int i = 0; i < no; i++)
s[i] = Integer.toString(randomNos[i]);
int index = 0;
if (type == 0)
{
MultipleChoiceQuestion mcq1;
String a = br.readLine();
while (a!=null)
{
mcq1 = new MultipleChoiceQuestion ();
try {
mcq1.qID = Long.parseLong(a);
mcq1.question = br.readLine();
mcq1.options [0] = br.readLine();
mcq1.options [1] = br.readLine();
mcq1.options [2] = br.readLine();
mcq1.options [3] = br.readLine();
mcq1.answer = Integer.parseInt(br.readLine());
for (int j = 0; j < no; j++)
{
if (a.equals(s[j]))
{
mcqarr[index] = new MultipleChoiceQuestion();
mcqarr[index] = mcq1;
index++;
}
}
a = br.readLine();
}
catch (Exception e)
{
System.out.println ("Exception found in QuizGenerator class: " + e);
System.exit(0);
}
}
br.close();
ques = mcqarr;
}
else if (type == 1)
{
TrueOrFalseQuestion tof;
String a = br.readLine();
while (a!=null)
{
tof = new TrueOrFalseQuestion ();
try {
tof.qID = Long.parseLong(a);
tof.question = br.readLine();
tof.answer = (br.readLine().equalsIgnoreCase("True"))?true:false;
for (int j = 0; j < no; j++)
{
if (a.equals(s[j]))
{
tofarr[index] = new TrueOrFalseQuestion();
tofarr[index] = tof;
index++;
}
}
a = br.readLine();
}
catch (Exception e)
{
System.out.println ("Exception found in QuizGenerator class: " + e);
System.exit(0);
}
}
br.close();
ques = tofarr;
}
else if (type == 2)
{
FillInTheBlanksQuestion fitb;
String a = br.readLine();
while (a!=null)
{
fitb = new FillInTheBlanksQuestion ();
try {
fitb.qID = Long.parseLong(a);
fitb.question = br.readLine();
fitb.answer = br.readLine();
for (int j = 0; j < no; j++)
{
if (a.equals(s[j]))
{
fitbarr[index] = new FillInTheBlanksQuestion();
fitbarr[index] = fitb;
index++;
}
}
a = br.readLine();
}
catch (Exception e)
{
System.out.println ("Exception found in QuizGenerator class: " + e);
System.exit(0);
}
}
br.close();
ques = fitbarr;
}
}
catch (IOException ioe)
{
System.out.println ("Exception found in QuizGenerator class: " + ioe);
}
}
Question [] returnQuestionsArray ()
{
return ques;
}
}
| [
"[email protected]"
]
| |
e8dad065c47477a5d749e770d74af558d51646e6 | 4342f5ad625ef161509d661bb851115135b86d45 | /src/main/java/alkemy/service/ProfessorServiceImpl.java | 09d2d6654d753b84f05b5f234f4018a9b2c4b1b7 | []
| no_license | fransantt0s/AlkemyChallenge | ff4ced2b653a13a63c15dcb5d5583fe6886458e5 | f730ba5931ac05bdf0f1e97fe73526c6a6b22c9d | refs/heads/master | 2023-03-16T05:20:44.086446 | 2021-02-27T22:19:28 | 2021-02-27T22:19:28 | 342,969,941 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,031 | java | package alkemy.service;
import alkemy.dao.ProfessorDao;
import alkemy.domain.Professor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class ProfessorServiceImpl implements ProfessorService {
@Autowired
private ProfessorDao professorDao;
@Override
@Transactional(readOnly = true)
public List<Professor> professorList() {
return (List<Professor>) professorDao.findAll();
}
@Override
@Transactional
public void save(Professor professor) {
professorDao.save(professor);
}
@Override
@Transactional
public void deleteProfessor(Professor professor) {
professorDao.delete(professor);
}
@Override
@Transactional(readOnly = true)
public Professor findProfessor(Professor professor) {
return professorDao.findById(professor.getIdProfessor()).orElse(null);
}
}
| [
"[email protected]"
]
| |
009f6fb7980eb84bdb25de9d82664c9c3ceeda5e | 1b28b9341ca4260d91c78fb1a3506df840adc621 | /adventura-ancient-hero/src/UI/VeciProstor.java | 9d5edd411a4538b55c1dea9b431337ac74cf7eff | []
| no_license | NightingaleV/4it115-sw-ing | 48c114a9f3a242321b0be807c56e8f9a135b8142 | faeaa63af8ee43e8b3cfaa7ff22bfe5f7d365d64 | refs/heads/master | 2021-08-20T08:52:17.870243 | 2017-11-28T16:57:26 | 2017-11-28T16:57:26 | 105,562,855 | 0 | 0 | null | 2017-11-21T09:45:35 | 2017-10-02T17:21:42 | HTML | UTF-8 | Java | false | false | 4,286 | java | package UI;
import javafx.scene.layout.AnchorPane;
import java.util.Map;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.geometry.Insets;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import logika.IHra;
import logika.Vec;
import main.Main;
import utils.Observer;
public class VeciProstor extends VBox implements Observer {
private IHra hra;
private Map<String, Vec> veciProstoru;
private Button tlacitkoVeci;
private Label vecLabel;
private TextArea centralText;
/**
* kontruktor
* @param hra -
* @param text - vypisuje text v centru adventury
*/
public VeciProstor(IHra hra, TextArea text) {
this.hra = hra;
hra.getHerniPlan().registerObserver(this);
this.centralText = text;
init();
}
private void init() {
vecLabel = new Label("Věci v prostoru:");
getVecLabel().setFont(Font.font("Arial", FontWeight.BOLD, 18));
getVecLabel().setPrefWidth(200);
veciProstoru = hra.getHerniPlan().getAktualniProstor().getVeci();
/**
* tlacitka pridavajici itemy do inventare
*/
this.getChildren().clear();
for (String vec : veciProstoru.keySet()) {
Vec item = veciProstoru.get(vec);
tlacitkoVeci = new Button(item.getNazev());
tlacitkoVeci.setMinSize(100,50);
tlacitkoVeci.setPadding(new Insets(5, 5, 5, 5));
tlacitkoVeci.setStyle("-fx-font: 18 arial;");
this.getChildren().add(getTlacitkoVeci());
tlacitkoVeci.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent click) {
String vstupniPrikaz = "vezmi " + item.getNazev();
String odpovedHry = hra.zpracujPrikaz(vstupniPrikaz);
centralText.appendText("\n" + vstupniPrikaz + "\n");
centralText.appendText("\n" + odpovedHry + "\n");
hra.getHerniPlan().notifyAllObservers();
}
});
}
}
@Override
public void update() {
this.getChildren().clear();
veciProstoru = hra.getHerniPlan().getAktualniProstor().getVeci();
for (String vec : veciProstoru.keySet()) {
try {
Vec item = veciProstoru.get(vec);
tlacitkoVeci = new Button(item.getNazev());
tlacitkoVeci.setMinSize(100,50);
tlacitkoVeci.setStyle("-fx-font: 18 arial;");
this.getChildren().add(getTlacitkoVeci());
tlacitkoVeci.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent click) {
/**
* Pozor na záměnu pomocna.getNazev() a tlacitkoVeci.getText()!!
* EventHandler pak sebere špatný item
*/
String vstupniPrikaz = "vezmi " + item.getNazev();
String odpovedHry = hra.zpracujPrikaz(vstupniPrikaz);
/**
* přidání odpovědí hry do centralTextu, jako u Inventáře
*/
centralText.appendText("\n" + vstupniPrikaz + "\n");
centralText.appendText("\n" + odpovedHry + "\n");
hra.getHerniPlan().notifyAllObservers();
}
});
} catch (Exception exception) {
}
}
}
/**
* viz východy
* @param novaHra -
*/
/**
* Aktualizuje věci v místnosti Buttony s obrázkem a popiskem
*/
/**
* @return the vecLabel
*/
public Label getVecLabel() {
return vecLabel;
}
/**
* @return the tlacitkoVeci
*/
public Button getTlacitkoVeci() {
return tlacitkoVeci;
}
}
| [
"[email protected]"
]
| |
7b30f14ae517a6061010c0cafe84db2f896b2654 | 6cee9d4fa32fb431707d97fff9bb9ac77c4f0f17 | /src/test/java/com/companyslack/app/web/rest/UserJWTControllerIT.java | bea5c287003727de7f309c34bff17159df554a97 | []
| no_license | minhnc3012/jhipster-mt-sample-angular | 300f41307509eec0471353ba94e97936384d82b0 | a9009afb83cbfcdbd840dcb25b83e0bb074d5dd4 | refs/heads/master | 2022-03-16T15:01:47.888331 | 2019-12-10T10:16:08 | 2019-12-10T10:16:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,832 | java | package com.companyslack.app.web.rest;
import com.companyslack.app.SampleMultitenancyAppAngularApp;
import com.companyslack.app.domain.User;
import com.companyslack.app.repository.UserRepository;
import com.companyslack.app.security.jwt.TokenProvider;
import com.companyslack.app.web.rest.errors.ExceptionTranslator;
import com.companyslack.app.web.rest.vm.LoginVM;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.isEmptyString;
import static org.hamcrest.Matchers.not;
/**
* Integration tests for the {@link UserJWTController} REST controller.
*/
@SpringBootTest(classes = SampleMultitenancyAppAngularApp.class)
public class UserJWTControllerIT {
@Autowired
private TokenProvider tokenProvider;
@Autowired
private AuthenticationManagerBuilder authenticationManager;
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private ExceptionTranslator exceptionTranslator;
private MockMvc mockMvc;
@BeforeEach
public void setup() {
UserJWTController userJWTController = new UserJWTController(tokenProvider, authenticationManager);
this.mockMvc = MockMvcBuilders.standaloneSetup(userJWTController)
.setControllerAdvice(exceptionTranslator)
.build();
}
@Test
@Transactional
public void testAuthorize() throws Exception {
User user = new User();
user.setLogin("user-jwt-controller");
user.setEmail("[email protected]");
user.setActivated(true);
user.setPassword(passwordEncoder.encode("test"));
userRepository.saveAndFlush(user);
LoginVM login = new LoginVM();
login.setUsername("user-jwt-controller");
login.setPassword("test");
mockMvc.perform(post("/api/authenticate")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(login)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id_token").isString())
.andExpect(jsonPath("$.id_token").isNotEmpty())
.andExpect(header().string("Authorization", not(nullValue())))
.andExpect(header().string("Authorization", not(isEmptyString())));
}
@Test
@Transactional
public void testAuthorizeWithRememberMe() throws Exception {
User user = new User();
user.setLogin("user-jwt-controller-remember-me");
user.setEmail("[email protected]");
user.setActivated(true);
user.setPassword(passwordEncoder.encode("test"));
userRepository.saveAndFlush(user);
LoginVM login = new LoginVM();
login.setUsername("user-jwt-controller-remember-me");
login.setPassword("test");
login.setRememberMe(true);
mockMvc.perform(post("/api/authenticate")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(login)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id_token").isString())
.andExpect(jsonPath("$.id_token").isNotEmpty())
.andExpect(header().string("Authorization", not(nullValue())))
.andExpect(header().string("Authorization", not(isEmptyString())));
}
@Test
public void testAuthorizeFails() throws Exception {
LoginVM login = new LoginVM();
login.setUsername("wrong-user");
login.setPassword("wrong password");
mockMvc.perform(post("/api/authenticate")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(login)))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.id_token").doesNotExist())
.andExpect(header().doesNotExist("Authorization"));
}
}
| [
"[email protected]"
]
| |
3120aca8f342b3e3caddab00eab8d5aadc3b53fb | b5e3afc17bde0a3499af56b75cdefb5c371da081 | /src/main/java/com/javalearning/demo/concurrency/concurrency_collection/blocking_collection/linkedblockingdeque/Main.java | 3d3ed0b1e505b87faa467bd0ab914308be170d13 | []
| no_license | hhliagn/java-learning | c04ee451f743367adafae94f929400fb8dd77476 | 6c3fc36ba99dc75286709b8c05784354d10e5533 | refs/heads/master | 2022-06-30T08:17:14.027765 | 2021-06-16T13:30:24 | 2021-06-16T13:30:24 | 230,693,009 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,169 | java | package com.javalearning.demo.concurrency.concurrency_collection.blocking_collection.linkedblockingdeque;
import java.util.Date;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
LinkedBlockingDeque<String> list = new LinkedBlockingDeque<>(3);
Client client = new Client(list);
Thread thread = new Thread(client);
thread.start();
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
try {
// 如果集合为空,这个操作会阻塞直到集合有新的元素加入
String take = list.take();
System.out.printf("Main: %s at %s, Size: %s\n", list, new Date(), list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
TimeUnit.MILLISECONDS.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Main End.");
}
}
| [
"[email protected]"
]
| |
f7c3a8e387797a1dbc0e2e4f1f86d7f25a11d32b | 2cb3ee5d082a54ab0a7ed39fa74c8726787ce5e2 | /src/uva/Conection.java | 4af246acab295cee3fa369a834d8be6df6d904ef | []
| no_license | srodrigo23/java-tricks | 9f9d56828feacf52665b7d2074be5f69c3f62066 | 24ad1453352536e5a5670d6e4715250b2e938374 | refs/heads/master | 2023-07-30T15:34:25.433340 | 2021-09-16T22:24:17 | 2021-09-16T22:24:17 | 322,155,931 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,469 | java |
import com.dropbox.core.DbxException;
import com.dropbox.core.DbxRequestConfig;
import com.dropbox.core.v2.DbxClientV2;
import com.dropbox.core.v2.files.GetTemporaryLinkResult;
import com.dropbox.core.v2.files.ListFolderResult;
import com.dropbox.core.v2.files.Metadata;
import com.dropbox.core.v2.users.FullAccount;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author rodrigo
*/
public class Conection {
private final DbxRequestConfig config;
private final String token;
private DbxClientV2 client;
Conection(){
config = new DbxRequestConfig("mbp", Locale.getDefault().toString());
token = "G1IxlFL41tAAAAAAAAABpAZ_2O29pQ_CdLNx2ni0j6cdbbX7ivyK4rmwzLKXnDxS";
client = new DbxClientV2(config, token);
}
private FullAccount getAccount() throws DbxException{
return client.users().getCurrentAccount();
}
public void mostrarInfoAccount() throws DbxException{
FullAccount fa = getAccount();
System.out.println(fa.getName().getDisplayName());
System.out.println(fa.getAccountType().toString());
System.out.println(fa.getCountry());
System.out.println(fa.getEmail());
}
private ListFolderResult getFolderResult(String path){
try {
return client.files().listFolder(path);
} catch (DbxException ex) {
Logger.getLogger(Conection.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
private GetTemporaryLinkResult getTemporalLink(String path) throws DbxException{
return client.files().getTemporaryLink(path);
}
public void mostrarContenido(String path) throws DbxException{
List<Metadata> dir = getFolderResult(path).getEntries();
String link;
for (Iterator<Metadata> iterator = dir.iterator(); iterator.hasNext();) {
Metadata next = iterator.next();
System.out.println(getTemporalLink(next.getPathLower()).getLink());
if(isFolder(next.toString()))
mostrarContenido(next.getPathLower());
}
}
private boolean isFolder(String desc){
return desc.contains(".tag\":\"folder");
}
public static void main(String[] args) throws DbxException {
new Conection().mostrarContenido("/music");
}
}
| [
"[email protected]"
]
| |
895c42703d583beb45f038507ecfe8a690b986b1 | 8c6ada212e005a40a55fb9d7ad9724fec9bf1005 | /src/main/java/org/qi_bench/api/root/ElectronicRegulatoryPortalsResource.java | 8bbc4b794beaa163ec8db5a03a9ff4d5529e9a1a | []
| no_license | cpatrick/QI-Bench-Java-API | 001e0c8847a03f14f0086a8d965b0e8f042f9beb | 40833faeebea1b30fced21b0d1309eaff00c5ad2 | refs/heads/master | 2020-04-17T16:41:35.952332 | 2013-06-25T13:03:39 | 2013-06-25T13:03:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,181 | java | package org.qi_bench.api.root;
import org.qi_bench.api.domain.ServeStaticFile;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.StreamingOutput;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
@Path("/")
public class ElectronicRegulatoryPortalsResource {
public ElectronicRegulatoryPortalsResource() {
}
// Handle the request. If there is an explicit request for XML in an accept
// header then honor the request otherwise return JSON as the default.
@GET
@Path("electronic-regulatory-portals")
public StreamingOutput ResourceInterface(@HeaderParam("accept") @DefaultValue("application/json") String HPValue) {
if (HPValue.equals("application/xml")) { // The only way to get XML is explicit request in an accept header
return new StreamingOutput() {
public void write(OutputStream outputStream) throws IOException, WebApplicationException {
PrintStream writer = new PrintStream(outputStream);
writer.println("<qi-bench-api>");
writer.println(" <electronic-regulatory-portals>NOT YET IMPLEMENTED</electronic-regulatory-portals>");
writer.println("</qi-bench-api>");
}
};
}
return new StreamingOutput() {
public void write(OutputStream outputStream) throws IOException, WebApplicationException {
PrintStream writer = new PrintStream(outputStream);
writer.println("{\"qi-bench-api\": " +
"{\"electronic-regulatory-portals\": \"NOT YET IMPLEMENTED\"" +
"}}");
}
};
}
@GET
@Path("api-docs/electronic-regulatory-portals")
@Produces("application/json")
public StreamingOutput SO_API_DOCS_JSON() {
ServeStaticFile ssf = new ServeStaticFile();
return ssf.StaticFile("apiDocs/electronic-regulatory-portals.json");
}
}
| [
"[email protected]"
]
| |
bd7edb23be443db870073076363003cefecc7b26 | 4a2ff4f4787435511932d16dc22dd4143a6b5c68 | /src/sample/controllers/ControllerTask.java | 9f8d61027ae4b7d297f6566282d2a6477e334fe0 | []
| no_license | stephanieyao11/bot-o-mat | dbd5fcb74b6d94b98645517bfc30f8bd984e8d3f | 3149aef6a4f7c619869ff3c0e5ed74b9d0e5d18b | refs/heads/master | 2023-01-22T19:44:07.859269 | 2020-11-22T21:34:49 | 2020-11-22T21:34:49 | 314,941,168 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,049 | java | package sample.controllers;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.text.Text;
import java.util.Map;
import java.util.HashMap;
import java.util.Random;
import sample.models.Player;
import java.io.IOException;
public class ControllerTask extends ControllerConfig{
@FXML
private Text task1;
@FXML
private Text task2;
@FXML
private Text task3;
@FXML
private Text task4;
@FXML
private Text task5;
@FXML
private Text task6;
@FXML
private Text task7;
@FXML
private Text task8;
@FXML
private Text task9;
@FXML
private Text task10;
@FXML
private Label completedSlot1;
@FXML
private Label completedSlot2;
@FXML
private Label completedSlot3;
@FXML
private Label completedSlot4;
@FXML
private Label completedSlot5;
@FXML
private Label completedSlot6;
@FXML
private Label completedSlot7;
@FXML
private Label completedSlot8;
@FXML
private Label completedSlot9;
@FXML
private Label completedSlot10;
@FXML
private Label robotName;
@FXML
private Label robotName1;
protected static Map<String, Integer> taskMap= new HashMap<>() {{
put("Do the dishes", 1000);
put("Sweep the house", 3000);
put("Do the laundry", 10000);
put("Take out the recycling", 4000);
put("Make a sammich", 7000);
put("Mow the lawn", 20000);
put("Rake the leaves", 18000);
put("Give the dog a bath", 14500);
put("Bake some cookies", 8000);
put("Wash the car", 20000);
}};
protected static String[] taskArr = {"Do the dishes", "Sweep the house", "Do the laundry", "Take out the recycling", "Make a sammich",
"Mow the lawn", "Rake the leaves", "Give the dog a bath", "Bake some cookies", "Wash the car"};
protected static boolean start1 = true;
public void initialize() {
if (start1) {
robotName.setText("Tasks for " + model.getName());
if (!(model.getNewTask().isEmpty() || model.getNewTask().isBlank())) {
task1.setText(model.getNewTask());
taskMap.put(model.getNewTask(), model.getNewTaskTime());
} else {
task1.setText(taskArr[(int) (Math.random() * taskArr.length)]);
}
task2.setText(taskArr[(int) (Math.random() * taskArr.length)]);
task3.setText(taskArr[(int) (Math.random() * taskArr.length)]);
task4.setText(taskArr[(int) (Math.random() * taskArr.length)]);
task5.setText(taskArr[(int) (Math.random() * taskArr.length)]);
if (!(model1.getName().isBlank() || model1.getName().isEmpty())) {
robotName1.setText("Tasks for " + model1.getName());
task6.setText(taskArr[(int) (Math.random() * taskArr.length)]);
task7.setText(taskArr[(int) (Math.random() * taskArr.length)]);
task8.setText(taskArr[(int) (Math.random() * taskArr.length)]);
task9.setText(taskArr[(int) (Math.random() * taskArr.length)]);
task10.setText(taskArr[(int) (Math.random() * taskArr.length)]);
}
}
}
@FXML
public void handleMouseClick1(MouseEvent event) {
if (!(task1.getText().isBlank() || task1.getText().isEmpty())) {
System.out.println("Waiting to complete task...");
try {
Thread.sleep(taskMap.get(task1.getText()));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
Random rand = new Random();
int rselector = rand.nextInt(10);
if (rselector > 5 && rselector != 0 && model.getScore() >= 10) {
Alert a1 = new Alert(Alert.AlertType.NONE,
"Your robot broke down! Score decreased by "
+ rselector + " points.", ButtonType.OK);
model.decScore(rselector);
a1.show();
}
model.incScore(10);
completedSlot1.setText(task1.getText());
task1.setText("Complete!");
System.out.println("Task complete");
}
}
@FXML
public void handleMouseClick2(MouseEvent event) {
if (!(task2.getText().isBlank() || task2.getText().isEmpty())) {
System.out.println("Waiting to complete task...");
try {
Thread.sleep(taskMap.get(task2.getText()));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
Random rand = new Random();
int rselector = rand.nextInt(10);
if (rselector < 5 && rselector != 0 && model.getScore() >= 10) {
Alert a1 = new Alert(Alert.AlertType.NONE,
"Your robot broke down! Score decreased by "
+ rselector + " points.", ButtonType.OK);
model.decScore(rselector);
a1.show();
}
model.incScore(10);
completedSlot2.setText(task2.getText());
task2.setText("Complete!");
System.out.println("Task complete");
}
}
@FXML
public void handleMouseClick3(MouseEvent event) {
if (!(task3.getText().isBlank() || task3.getText().isEmpty())) {
System.out.println("Waiting to complete task...");
try {
Thread.sleep(taskMap.get(task3.getText()));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
Random rand = new Random();
int rselector = rand.nextInt(10);
if (rselector > 5 && rselector != 0) {
Alert a1 = new Alert(Alert.AlertType.NONE,
"Your robot received the new update! Score increased by "
+ rselector + " points.", ButtonType.OK);
model.incScore(rselector);
a1.show();
}
model.incScore(10);
completedSlot3.setText(task3.getText());
task3.setText("Complete!");
System.out.println("Task complete");
}
}
@FXML
public void handleMouseClick4(MouseEvent event) {
if (!(task4.getText().isBlank() || task4.getText().isEmpty())) {
System.out.println("Waiting to complete task...");
try {
Thread.sleep(taskMap.get(task4.getText()));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
Random rand = new Random();
int rselector = rand.nextInt(10);
if (rselector < 5 && rselector != 0) {
Alert a1 = new Alert(Alert.AlertType.NONE,
"Your robot received the new update! Score increased by "
+ rselector + " points.", ButtonType.OK);
model.incScore(rselector);
a1.show();
}
model.incScore(10);
completedSlot4.setText(task4.getText());
task4.setText("Complete!");
System.out.println("Task complete");
}
}
@FXML
public void handleMouseClick5(MouseEvent event) {
if (!(task5.getText().isBlank() || task5.getText().isEmpty())) {
System.out.println("Waiting to complete task...");
try {
Thread.sleep(taskMap.get(task5.getText()));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
model.incScore(10);
completedSlot5.setText(task5.getText());
task5.setText("Complete!");
System.out.println("Task complete");
}
}
@FXML
public void handleMouseClick6(MouseEvent event) {
if (!(task6.getText().isBlank() || task6.getText().isEmpty())) {
System.out.println("Waiting to complete task...");
try {
Thread.sleep(taskMap.get(task6.getText()));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
Random rand = new Random();
int rselector = rand.nextInt(10);
if (rselector < 5 && rselector != 0) {
Alert a1 = new Alert(Alert.AlertType.NONE,
"Your robot received the new update! Score increased by "
+ rselector + " points.", ButtonType.OK);
model1.incScore(rselector);
a1.show();
}
model1.incScore(10);
completedSlot6.setText(task6.getText());
task6.setText("Complete!");
System.out.println("Task complete");
}
}
@FXML
public void handleMouseClick7(MouseEvent event) {
if (!(task7.getText().isBlank() || task7.getText().isEmpty())) {
System.out.println("Waiting to complete task...");
try {
Thread.sleep(taskMap.get(task6.getText()));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
Random rand = new Random();
int rselector = rand.nextInt(10);
if (rselector > 5 && rselector != 0) {
Alert a1 = new Alert(Alert.AlertType.NONE,
"Your robot received the new update! Score increased by "
+ rselector + " points.", ButtonType.OK);
model1.incScore(rselector);
a1.show();
}
model1.incScore(10);
completedSlot7.setText(task7.getText());
task7.setText("Complete!");
System.out.println("Task complete");
}
}
@FXML
public void handleMouseClick8(MouseEvent event) {
if (!(task8.getText().isBlank() || task8.getText().isEmpty())) {
System.out.println("Waiting to complete task...");
try {
Thread.sleep(taskMap.get(task6.getText()));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
Random rand = new Random();
int rselector = rand.nextInt(10);
if (rselector < 5 && model.getScore() >= 10 && rselector != 0) {
Alert a1 = new Alert(Alert.AlertType.NONE,
"Your robot broke down! Score decreased by "
+ rselector + " points.", ButtonType.OK);
model1.decScore(rselector);
a1.show();
}
model1.incScore(10);
completedSlot8.setText(task8.getText());
task8.setText("Complete!");
System.out.println("Task complete");
}
}
@FXML
public void handleMouseClick9(MouseEvent event) {
if (!(task9.getText().isBlank() || task9.getText().isEmpty())) {
System.out.println("Waiting to complete task...");
try {
Thread.sleep(taskMap.get(task9.getText()));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
Random rand = new Random();
int rselector = rand.nextInt(10);
if (rselector > 5 && model.getScore() >= 10 && rselector != 0) {
Alert a1 = new Alert(Alert.AlertType.NONE,
"Your robot broke down! Score decreased by "
+ rselector + " points.", ButtonType.OK);
model1.decScore(rselector);
a1.show();
}
model1.incScore(10);
completedSlot9.setText(task9.getText());
task9.setText("Complete!");
System.out.println("Task complete");
}
}
@FXML
public void handleMouseClick10(MouseEvent event) {
if (!(task10.getText().isBlank() || task10.getText().isEmpty())) {
System.out.println("Waiting to complete task...");
try {
Thread.sleep(taskMap.get(task10.getText()));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
model1.incScore(10);
completedSlot10.setText(task10.getText());
task10.setText("Complete!");
System.out.println("Task complete");
}
}
@FXML
public void setLeader(ActionEvent actionEvent) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("../views/leader.fxml"));
stage.setScene(new Scene(root, 600, 458));
stage.show();
}
}
| [
"[email protected]"
]
| |
e8b2d0ea9441c3cc13b00f31498a5249b7d01260 | c6e0db866dfb97374cacc22e5de16bf64ab47278 | /fireworm-lib/src/main/java/at/d4muck/fireworm/reflection/read/InstanceReferenceReader.java | f21e83cc3790bcc411f6dafb592c250e7488a7bf | [
"Apache-2.0"
]
| permissive | D4Muck/fireworm | 6b763e3253e093f6734e6a7103c59b00264b2b14 | 477e34df1ba65c23a4c89d8fe554724e3e564b5d | refs/heads/master | 2021-01-21T00:45:11.045484 | 2016-07-07T07:04:56 | 2016-07-07T07:04:56 | 62,450,368 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,710 | java | /*
* Copyright 2016 Christoph Muck
*
* 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 at.d4muck.fireworm.reflection.read;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import at.d4muck.fireworm.reflection.model.ReflectiveModel;
import at.d4muck.fireworm.reflection.model.ReflectiveModelFactory;
/**
* @author Christoph Muck
*/
class InstanceReferenceReader implements ReferenceReader {
private final ReflectiveModelFactory reflectiveModelFactory;
private final ReflectiveModel modelResolver;
private final Field field;
private Set<ReflectiveModel> referenceReflectiveModels;
InstanceReferenceReader(ReflectiveModel model, Field field, ReflectiveModelFactory reflectiveModelFactory) {
this.modelResolver = model;
this.field = field;
this.reflectiveModelFactory = reflectiveModelFactory;
}
@Override
public Set<ReflectiveModel> getReferenceReflectiveModels() {
return referenceReflectiveModels;
}
@Override
public void readReferences(Object references) {
referenceReflectiveModels = new HashSet<>();
if (references == null) return;
String id = (String) references;
Class<?> type = field.getType();
Object referenceModel;
try {
referenceModel = type.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
ReflectiveModel referenceReflectiveModel = reflectiveModelFactory.newReflectiveModelOf(referenceModel);
referenceReflectiveModel.resolveFieldDeclarations();
referenceReflectiveModel.resolveId();
referenceReflectiveModel.setId(id);
setReferenceModel(referenceModel);
referenceReflectiveModels = Collections.singleton(referenceReflectiveModel);
}
private void setReferenceModel(Object model) {
try {
field.set(modelResolver.getModel(), model);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
| [
"[email protected]"
]
| |
11050cadc4f006f89dc2074adcd110b50b67e33e | a34cba2c3d8c295416aeb5f2f0b9a15b7151b0b6 | /src/msc/slt/student_slt.java | 2be6a70374e8d7d9366499e9c9373d1732ad1090 | []
| no_license | gnosis-xian/StudentMarkManagement | 05694dda8626c1252f9a46391e24acf09ba3412e | 97e7525850f24bd635e45f3fc658c31c5ab87005 | refs/heads/master | 2021-06-25T11:12:15.255230 | 2017-09-11T02:55:47 | 2017-09-11T02:55:47 | null | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 5,477 | java | package msc.slt;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Vector;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import msc.dao.*;
import msc.vo.Student;
public class student_slt extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String action = request.getParameter("action");
if ("new".equalsIgnoreCase(action)) {
doAdd(request,response);
}
if("delete".equalsIgnoreCase(action)){
doDelete(request,response);
}
if("update".equalsIgnoreCase(action)){
doUpdate(request,response);
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doAdd(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String sid=request.getParameter("sid");
String sname=request.getParameter("sname");
String smajor=request.getParameter("smajor");
String sclass=request.getParameter("sclass");
String scode=request.getParameter("scode");
StudentDAO sdao=new StudentDAO();
UserDAO udao=new UserDAO();
try {
sdao.InsertStudent(sid, sname, smajor, sclass, scode);
udao.InsertUser(sid, sname, scode, "student");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY bgcolor=#8dd8f8>");
out.print(" <img src=image/t.png ><font size=6 color=red> 添加成功!</font> ");
out.println(" </BODY>");
out.println("</HTML>");
} catch (Exception e) {
// TODO Auto-generated catch block
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY bgcolor=#8dd8f8>");
out.print(" <img src=image/f.png ><font size=6 color=red> 添加失败!</font> ");
out.println(" </BODY>");
out.println("</HTML>");
}
out.flush();
out.close();
}
public void doDelete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String sid=request.getParameter("sid");
StudentDAO sdao=new StudentDAO();
UserDAO udao=new UserDAO();
try {
sdao.DeletebyID(sid);
udao.DeletebyID(sid);
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY bgcolor=#8dd8f8>");
out.print(" <img src=image/t.png ><font size=6 color=red> 删除成功!</font> ");
out.println(" </BODY>");
out.println("</HTML>");
} catch (Exception e) {
// TODO Auto-generated catch block
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY bgcolor=#8dd8f8>");
out.print(" <img src=image/f.png ><font size=6 color=red> 删除失败!</font> ");
out.println(" </BODY>");
out.println("</HTML>");
}
out.flush();
out.close();
}
public void doUpdate(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String sid=request.getParameter("sid");
String sname=request.getParameter("sname");
String sclass=request.getParameter("sclass");
String smajor=request.getParameter("smajor");
String scode=request.getParameter("scode");
UserDAO udao=new UserDAO();
StudentDAO sdao=new StudentDAO();
try {
sdao.UpdatebyID(sid, sname, smajor, sclass, scode);
udao.UpdatebyID(sid, sname, scode, "student");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY bgcolor=#8dd8f8>");
out.print(" <img src=image/t.png ><font size=6 color=red> 修改成功!</font> ");
out.println(" </BODY>");
out.println("</HTML>");
} catch (Exception e) {
// TODO Auto-generated catch block
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY bgcolor=#8dd8f8>");
out.print(" <img src=image/f.png ><font size=6 color=red>修改失败!</font> ");
out.println(" </BODY>");
out.println("</HTML>");
}
out.flush();
out.close();
}
}
| [
"[email protected]"
]
| |
54baa7b96a27f059f7e5ee44c6a41efda8b466a6 | 5f82aae041ab05a5e6c3d9ddd8319506191ab055 | /Projects/Math/42/src/test/java/org/apache/commons/math/util/MathUtilsTest.java | 824e612b81acf1d7cf4a31c20ade672fe74d819b | []
| no_license | lingming/prapr_data | e9ddabdf971451d46f1ef2cdbee15ce342a6f9dc | be9ababc95df45fd66574c6af01122ed9df3db5d | refs/heads/master | 2023-08-14T20:36:23.459190 | 2021-10-17T13:49:39 | 2021-10-17T13:49:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,602 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.apache.commons.math.util;
import org.apache.commons.math.exception.MathArithmeticException;
import org.apache.commons.math.exception.NotFiniteNumberException;
import org.apache.commons.math.exception.NullArgumentException;
import org.apache.commons.math.exception.util.LocalizedFormats;
import org.apache.commons.math.random.RandomDataImpl;
import org.junit.Assert;
import org.junit.Test;
/**
* Test cases for the MathUtils class.
* @version $Id$
* 2007) $
*/
public final class MathUtilsTest {
@Test
public void testHash() {
double[] testArray = {
Double.NaN,
Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY,
1d,
0d,
1E-14,
(1 + 1E-14),
Double.MIN_VALUE,
Double.MAX_VALUE };
for (int i = 0; i < testArray.length; i++) {
for (int j = 0; j < testArray.length; j++) {
if (i == j) {
Assert.assertEquals(MathUtils.hash(testArray[i]), MathUtils.hash(testArray[j]));
Assert.assertEquals(MathUtils.hash(testArray[j]), MathUtils.hash(testArray[i]));
} else {
Assert.assertTrue(MathUtils.hash(testArray[i]) != MathUtils.hash(testArray[j]));
Assert.assertTrue(MathUtils.hash(testArray[j]) != MathUtils.hash(testArray[i]));
}
}
}
}
@Test
public void testArrayHash() {
Assert.assertEquals(0, MathUtils.hash((double[]) null));
Assert.assertEquals(MathUtils.hash(new double[] {
Double.NaN, Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, 1d, 0d
}),
MathUtils.hash(new double[] {
Double.NaN, Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, 1d, 0d
}));
Assert.assertFalse(MathUtils.hash(new double[] { 1d }) ==
MathUtils.hash(new double[] { FastMath.nextAfter(1d, 2d) }));
Assert.assertFalse(MathUtils.hash(new double[] { 1d }) ==
MathUtils.hash(new double[] { 1d, 1d }));
}
/**
* Make sure that permuted arrays do not hash to the same value.
*/
@Test
public void testPermutedArrayHash() {
double[] original = new double[10];
double[] permuted = new double[10];
RandomDataImpl random = new RandomDataImpl();
// Generate 10 distinct random values
for (int i = 0; i < 10; i++) {
original[i] = random.nextUniform(i + 0.5, i + 0.75);
}
// Generate a random permutation, making sure it is not the identity
boolean isIdentity = true;
do {
int[] permutation = random.nextPermutation(10, 10);
for (int i = 0; i < 10; i++) {
if (i != permutation[i]) {
isIdentity = false;
}
permuted[i] = original[permutation[i]];
}
} while (isIdentity);
// Verify that permuted array has different hash
Assert.assertFalse(MathUtils.hash(original) == MathUtils.hash(permuted));
}
@Test
public void testIndicatorByte() {
Assert.assertEquals((byte)1, MathUtils.copySign((byte)1, (byte)2));
Assert.assertEquals((byte)1, MathUtils.copySign((byte)1, (byte)0));
Assert.assertEquals((byte)(-1), MathUtils.copySign((byte)1, (byte)(-2)));
}
@Test
public void testIndicatorInt() {
Assert.assertEquals(1, MathUtils.copySign(1, 2));
Assert.assertEquals(1, MathUtils.copySign(1, 0));
Assert.assertEquals((-1), MathUtils.copySign(1, -2));
}
@Test
public void testIndicatorLong() {
Assert.assertEquals(1L, MathUtils.copySign(1L, 2L));
Assert.assertEquals(1L, MathUtils.copySign(1L, 0L));
Assert.assertEquals(-1L, MathUtils.copySign(1L, -2L));
}
@Test
public void testIndicatorShort() {
Assert.assertEquals((short)1, MathUtils.copySign((short)1, (short)2));
Assert.assertEquals((short)1, MathUtils.copySign((short)1, (short)0));
Assert.assertEquals((short)(-1), MathUtils.copySign((short)1, (short)(-2)));
}
@Test
public void testNormalizeAngle() {
for (double a = -15.0; a <= 15.0; a += 0.1) {
for (double b = -15.0; b <= 15.0; b += 0.2) {
double c = MathUtils.normalizeAngle(a, b);
Assert.assertTrue((b - FastMath.PI) <= c);
Assert.assertTrue(c <= (b + FastMath.PI));
double twoK = FastMath.rint((a - c) / FastMath.PI);
Assert.assertEquals(c, a - twoK * FastMath.PI, 1.0e-14);
}
}
}
@Test
public void testReduce() {
final double period = -12.222;
final double offset = 13;
final double delta = 1.5;
double orig = offset + 122456789 * period + delta;
double expected = delta;
Assert.assertEquals(expected,
MathUtils.reduce(orig, period, offset),
1e-7);
Assert.assertEquals(expected,
MathUtils.reduce(orig, -period, offset),
1e-7);
orig = offset - 123356789 * period - delta;
expected = Math.abs(period) - delta;
Assert.assertEquals(expected,
MathUtils.reduce(orig, period, offset),
1e-6);
Assert.assertEquals(expected,
MathUtils.reduce(orig, -period, offset),
1e-6);
orig = offset - 123446789 * period + delta;
expected = delta;
Assert.assertEquals(expected,
MathUtils.reduce(orig, period, offset),
1e-6);
Assert.assertEquals(expected,
MathUtils.reduce(orig, -period, offset),
1e-6);
Assert.assertTrue(Double.isNaN(MathUtils.reduce(orig, Double.NaN, offset)));
Assert.assertTrue(Double.isNaN(MathUtils.reduce(Double.NaN, period, offset)));
Assert.assertTrue(Double.isNaN(MathUtils.reduce(orig, period, Double.NaN)));
Assert.assertTrue(Double.isNaN(MathUtils.reduce(orig, period,
Double.POSITIVE_INFINITY)));
Assert.assertTrue(Double.isNaN(MathUtils.reduce(Double.POSITIVE_INFINITY,
period, offset)));
Assert.assertTrue(Double.isNaN(MathUtils.reduce(orig,
Double.POSITIVE_INFINITY, offset)));
Assert.assertTrue(Double.isNaN(MathUtils.reduce(orig,
Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)));
Assert.assertTrue(Double.isNaN(MathUtils.reduce(Double.POSITIVE_INFINITY,
period, Double.POSITIVE_INFINITY)));
Assert.assertTrue(Double.isNaN(MathUtils.reduce(Double.POSITIVE_INFINITY,
Double.POSITIVE_INFINITY, offset)));
Assert.assertTrue(Double.isNaN(MathUtils.reduce(Double.POSITIVE_INFINITY,
Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)));
}
@Test
public void testReduceComparedWithNormalizeAngle() {
final double tol = Math.ulp(1d);
final double period = 2 * Math.PI;
for (double a = -15; a <= 15; a += 0.5) {
for (double center = -15; center <= 15; center += 1) {
final double nA = MathUtils.normalizeAngle(a, center);
final double offset = center - Math.PI;
final double r = MathUtils.reduce(a, period, offset);
Assert.assertEquals(nA, r + offset, tol);
}
}
}
@Test
public void testSignByte() {
Assert.assertEquals((byte) 1, MathUtils.sign((byte) 2));
Assert.assertEquals((byte) 0, MathUtils.sign((byte) 0));
Assert.assertEquals((byte) (-1), MathUtils.sign((byte) (-2)));
}
@Test
public void testSignInt() {
Assert.assertEquals(1, MathUtils.sign(2));
Assert.assertEquals(0, MathUtils.sign(0));
Assert.assertEquals((-1), MathUtils.sign((-2)));
}
@Test
public void testSignLong() {
Assert.assertEquals(1L, MathUtils.sign(2L));
Assert.assertEquals(0L, MathUtils.sign(0L));
Assert.assertEquals(-1L, MathUtils.sign(-2L));
}
@Test
public void testSignShort() {
Assert.assertEquals((short) 1, MathUtils.sign((short) 2));
Assert.assertEquals((short) 0, MathUtils.sign((short) 0));
Assert.assertEquals((short) (-1), MathUtils.sign((short) (-2)));
}
@Test
public void testCheckFinite() {
try {
MathUtils.checkFinite(Double.POSITIVE_INFINITY);
Assert.fail("an exception should have been thrown");
} catch (NotFiniteNumberException e) {
// Expected
}
try {
MathUtils.checkFinite(Double.NEGATIVE_INFINITY);
Assert.fail("an exception should have been thrown");
} catch (NotFiniteNumberException e) {
// Expected
}
try {
MathUtils.checkFinite(Double.NaN);
Assert.fail("an exception should have been thrown");
} catch (NotFiniteNumberException e) {
// Expected
}
try {
MathUtils.checkFinite(new double[] {0, -1, Double.POSITIVE_INFINITY, -2, 3});
Assert.fail("an exception should have been thrown");
} catch (NotFiniteNumberException e) {
// Expected
}
try {
MathUtils.checkFinite(new double[] {1, Double.NEGATIVE_INFINITY, -2, 3});
Assert.fail("an exception should have been thrown");
} catch (NotFiniteNumberException e) {
// Expected
}
try {
MathUtils.checkFinite(new double[] {4, 3, -1, Double.NaN, -2, 1});
Assert.fail("an exception should have been thrown");
} catch (NotFiniteNumberException e) {
// Expected
}
}
@Test
public void testCheckNotNull1() {
try {
Object obj = null;
MathUtils.checkNotNull(obj);
} catch (NullArgumentException e) {
// Expected.
}
}
@Test
public void testCheckNotNull2() {
try {
double[] array = null;
MathUtils.checkNotNull(array, LocalizedFormats.INPUT_ARRAY);
} catch (NullArgumentException e) {
// Expected.
}
}
@Test
public void testCopySignByte() {
byte a = MathUtils.copySign(Byte.MIN_VALUE, (byte) -1);
Assert.assertEquals(Byte.MIN_VALUE, a);
final byte minValuePlusOne = Byte.MIN_VALUE + (byte) 1;
a = MathUtils.copySign(minValuePlusOne, (byte) 1);
Assert.assertEquals(Byte.MAX_VALUE, a);
a = MathUtils.copySign(Byte.MAX_VALUE, (byte) -1);
Assert.assertEquals(minValuePlusOne, a);
final byte one = 1;
byte val = -2;
a = MathUtils.copySign(val, one);
Assert.assertEquals(-val, a);
final byte minusOne = -one;
val = 2;
a = MathUtils.copySign(val, minusOne);
Assert.assertEquals(-val, a);
val = 0;
a = MathUtils.copySign(val, minusOne);
Assert.assertEquals(val, a);
val = 0;
a = MathUtils.copySign(val, one);
Assert.assertEquals(val, a);
}
@Test(expected=MathArithmeticException.class)
public void testCopySignByte2() {
MathUtils.copySign(Byte.MIN_VALUE, (byte) 1);
}
}
| [
"[email protected]"
]
| |
3c2a4e30dbbc5fc18c8cd1d89fa670b0cf0dc180 | dfdc2c4805cf0fead91983434765fbbd525e0de0 | /src/fitnesse/slim/test/TestSlim.java | 388559d80c05578091573bda5545508c7a8ab7c7 | []
| no_license | smryoo/fitnesse | fb2b997e357ce5a18c602b87cb40ad959a1a49b3 | 77a11a67cfb9fc3d18cdf3182af4ef8061c4934b | refs/heads/master | 2020-12-25T03:12:07.458197 | 2008-12-09T15:00:26 | 2008-12-09T15:00:26 | 88,666 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,101 | java | package fitnesse.slim.test;
import java.util.List;
public class TestSlim {
private boolean niladWasCalled = false;
private String stringArg;
private int intArg;
private double doubleArg;
private Integer integerObjectArg;
private Double doubleObjectArg;
private char charArg;
private List<Object> listArg;
private int constructorArg;
private String[] stringArray;
private Integer[] integerArray;
private Boolean[] booleanArray;
private Double[] doubleArray;
public TestSlim() {
}
public TestSlim(int constructorArg) {
this.constructorArg = constructorArg;
}
public void nilad() {
niladWasCalled = true;
}
public int returnConstructorArg() {
return constructorArg;
}
public void voidFunction() {
}
public boolean niladWasCalled() {
return niladWasCalled;
}
public String returnString() {
return "string";
}
public int returnInt() {
return 7;
}
public void setString(String arg) {
stringArg = arg;
}
public void oneString(String arg) {
stringArg = arg;
}
public void oneList(List<Object> l) {
listArg = l;
}
public List<Object> getListArg() {
return listArg;
}
public String getStringArg() {
return stringArg;
}
public void oneInt(int arg) {
intArg = arg;
}
public int getIntArg() {
return intArg;
}
public void oneDouble(double arg) {
doubleArg = arg;
}
public double getDoubleArg() {
return doubleArg;
}
public void manyArgs(Integer i, Double d, char c) {
integerObjectArg = i;
doubleObjectArg = d;
charArg = c;
}
public Integer getIntegerObjectArg() {
return integerObjectArg;
}
public double getDoubleObjectArg() {
return doubleObjectArg;
}
public char getCharArg() {
return charArg;
}
public int addTo(int a, int b) {
return a + b;
}
public int echoInt(int i) {
return i;
}
public String echoString(String s) {
return s;
}
public List<Object> echoList(List<Object> l) {
return l;
}
public boolean echoBoolean(boolean b) {
return b;
}
public double echoDouble(double d) {
return d;
}
public void execute() {
}
public void die() {
throw new Error("blah");
}
public void setNoSuchConverter(NoSuchConverter x) {
}
public NoSuchConverter noSuchConverter() {
return new NoSuchConverter();
}
public void setStringArray(String array[]) {
stringArray = array;
}
public String[] getStringArray() {
return stringArray;
}
public void setIntegerArray(Integer array[]) {
integerArray = array;
}
public Integer[] getIntegerArray() {
return integerArray;
}
public Boolean[] getBooleanArray() {
return booleanArray;
}
public void setBooleanArray(Boolean[] booleanArray) {
this.booleanArray = booleanArray;
}
public Double[] getDoubleArray() {
return doubleArray;
}
public void setDoubleArray(Double[] doubleArray) {
this.doubleArray = doubleArray;
}
public String nullString() {
return null;
}
class NoSuchConverter {
}
;
}
| [
"robertmartin"
]
| robertmartin |
a13275159ada0b41b724bc5c5e9e31d229229dfd | 8f281f8d4f70e8a4fcf526a31868fb5dea8c922d | /HospitalManagementsystem/src/dao/SelectHospitalDetail.java | f0d1d8a809a4265d647c823ba245d893f2b2d10f | []
| no_license | Hrithik-12345/HospitalManagementSystem | f7557ec86e60819e0bd732981e1e92c052289e1f | 95b41bfe3fd235b006bf1fb7aa196b4bab8d8690 | refs/heads/master | 2023-04-27T21:24:36.143383 | 2021-05-15T17:34:30 | 2021-05-15T17:34:30 | 367,659,509 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,894 | java | package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import dbutility.DbConnection;
import model.AdminHospitalPojo;
public class SelectHospitalDetail {
//static final Logger LOGGER=Logger.getLogger( SelectHospitalDetail.class);
public static AdminHospitalPojo getHospitalById(int HospitalID) {
//LOGGER.info("inside AdminHospitalPojo method (dao)");
AdminHospitalPojo h=new AdminHospitalPojo();
try {
//LOGGER.info("Try to Established Connection");
Connection con = DbConnection.getCon();
PreparedStatement ps = con.prepareStatement("SELECT * from hospitaldetails where HospitalID=?");
ps.setInt(1, HospitalID);
ResultSet rs=ps.executeQuery();
if(rs.next()) {
h.setHospitalID(rs.getInt(1));
h.setHospitalName(rs.getString(2));
h.setHospitalType(rs.getString(3));
h.setTotalBeds(rs.getString(4));
h.setAvailableBeds(rs.getString(5));
//LOGGER.info("storing data to database");
}
con.close();
}catch(Exception ex) {ex.printStackTrace();}
return h;
}
public static List<AdminHospitalPojo> getAllHospital(){
List<AdminHospitalPojo> list=new ArrayList<AdminHospitalPojo>();
try {
//LOGGER.info("Try to Established Connection");
Connection con = DbConnection.getCon();
PreparedStatement ps = con.prepareStatement("SELECT * from hospitaldetails");
ResultSet rs=ps.executeQuery();
while(rs.next()) {
AdminHospitalPojo h=new AdminHospitalPojo();
h.setHospitalID(rs.getInt(1));
h.setHospitalName(rs.getString(2));
h.setHospitalType(rs.getString(3));
h.setTotalBeds(rs.getString(4));
h.setAvailableBeds(rs.getString(5));
list.add(h);
//LOGGER.info("fetching hospital data ");
}
con.close();
}catch(Exception ex) {ex.printStackTrace();}
return list;
}
}
| [
"[email protected]"
]
| |
3ffec84b038f7153306534561a05260e474a50f5 | b90584002d2e22ab9f9a44cebe8e44d1b1bf51e7 | /module/yt-data-auth/src/com/etong/data/auth/session/SessionMapper.java | 4dc5be6065914f723e4a6fce235f161fb7a46241 | []
| no_license | zhenghuasheng/yy-dubbox-framework | 6c10b7c0be0a5047f7619caf84dacda973defdad | 400a6412cd240eb6929a1a13a0c279a301662abf | refs/heads/master | 2020-07-12T22:39:37.960872 | 2017-12-14T03:21:45 | 2017-12-14T03:21:45 | 73,898,436 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,943 | java | package com.etong.data.auth.session;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface SessionMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_pm_session
*
* @mbggenerated Mon Nov 30 12:03:44 CST 2015
*/
int countByExample(SessionExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_pm_session
*
* @mbggenerated Mon Nov 30 12:03:44 CST 2015
*/
int deleteByExample(SessionExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_pm_session
*
* @mbggenerated Mon Nov 30 12:03:44 CST 2015
*/
int insert(Session record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_pm_session
*
* @mbggenerated Mon Nov 30 12:03:44 CST 2015
*/
int insertSelective(Session record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_pm_session
*
* @mbggenerated Mon Nov 30 12:03:44 CST 2015
*/
List<Session> selectByExample(SessionExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_pm_session
*
* @mbggenerated Mon Nov 30 12:03:44 CST 2015
*/
int updateByExampleSelective(@Param("record") Session record, @Param("example") SessionExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_pm_session
*
* @mbggenerated Mon Nov 30 12:03:44 CST 2015
*/
int updateByExample(@Param("record") Session record, @Param("example") SessionExample example);
} | [
"[email protected]"
]
| |
e1a2fddd3add46ef756a991f7283a66e21a4b821 | 19a272b606ea3352c730ac1e7e03d681d028a661 | /leesin-base-consumer/src/main/java/com/dabanjia/leesin/base/LeesinBaseConsumerApplication.java | 9521d72b1d47d31338d6239419866ffbc549f95b | []
| no_license | xujiajun945/leesin | 28bbf151bb594b34cd8e90f85e5c2590f389b3ea | 0f973512343bac0290f652ffd0a1145812b86bbe | refs/heads/master | 2020-11-28T16:32:24.883546 | 2020-02-05T04:52:13 | 2020-02-05T04:52:13 | 229,868,842 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 683 | java | package com.dabanjia.leesin.base;
import com.dabanjia.leesin.base.configuration.FeignConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* @author xujiajun
* @since 2019/12/23
*/
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(defaultConfiguration = FeignConfiguration.class)
public class LeesinBaseConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(LeesinBaseConsumerApplication.class, args);
}
}
| [
"[email protected]"
]
| |
c8e427c0317fd09eae0dbf78d7fffda5909330ce | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/28/28_f5bdd3250c1baaca0e407f8e058fb0a9bff2c3b0/MainActivity/28_f5bdd3250c1baaca0e407f8e058fb0a9bff2c3b0_MainActivity_t.java | 69a08d989cf2a278c3943cb843c33ca4fbda2df4 | []
| no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 2,588 | java | package com.hyperactivity.android_app.activities;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import com.hyperactivity.android_app.R;
import com.hyperactivity.android_app.core.Engine;
public class MainActivity extends Activity {
private Boolean isLocked;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView welcomeNameTextView = (TextView) findViewById(R.id.welcomeName);
welcomeNameTextView.setText(((Engine) getApplication()).getAccount().getUsername());
// Set up our lock button stuff
isLocked = true;
final View topBar = (View) findViewById(R.id.top_bar);
final ImageView lockImage = (ImageView) findViewById(R.id.lockButton);
final TextView lockTextView = (TextView) findViewById(R.id.lockText);
lockImage.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0) {
System.out.println("clicked");
isLocked = !isLocked;
if (isLocked) {
lockTextView.setText((String) getResources().getString(R.string.top_bar_private));
lockImage.setImageResource(R.drawable.locked);
}
else {
lockTextView.setText((String) getResources().getString(R.string.top_bar_public));
lockImage.setImageResource(R.drawable.unlocked);
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
/**
* Triggers when an item in the menu is clicked such as "Settings" or "Help"
*/
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
// Settings has been clicked, check the android version to decide if to use fragmented settings or not
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
startActivity(new Intent(this, SettingsActivity.class));
} else {
startActivity(new Intent(this, SettingsActivityHoneycomb.class));
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| [
"[email protected]"
]
| |
8f53bcc962251f3263f049ba7d87faa1369ae699 | cc6a7d89f0d085ebff5b10ee61cbccb747a5b5f1 | /CursoJava/src/Exercicios/Ex4.java | e4cca94204b52a4d2503145e678b19a073c654b6 | []
| no_license | SarahRafaela/JavaCurse | 790057ee2f7aecfde6e6969ca761385ae05ba71d | ccbda74bcc0ee30294cc68fb35bb0c5f6504eea5 | refs/heads/master | 2021-05-18T06:32:41.732906 | 2020-04-15T01:47:25 | 2020-04-15T01:47:25 | 251,160,020 | 0 | 0 | null | null | null | null | WINDOWS-1252 | Java | false | false | 257 | java | package Exercicios;
public class Ex4 {
public static void main(String[] args) {
Integer v = 2;
Integer q, c;
q = v * v;
c = q * v;
System.out.println("O quadrado de " + v + " é: " + q + " e o cubo de " + v + " é: " + c);
}
}
| [
"[email protected]"
]
| |
d83c03af411383b2c3cf043db4783fd19f25a961 | 0a9ac13471cd7f3ede54ac85c570a16672274365 | /978-4-7741-5377-3/junit-tutorial/test/junit/tutorial/IsDateTest.java | dce19b9c74fc2e27d35cc6a54fc02fb479352051 | []
| no_license | Chuo-Computer-Communication-College/CCC_Java_JUnit_Eclipse | 479cfc0f2ee99f2247ca3ced5e971035c424964f | 8a6290d63e5f7141a99c36b8459ef72e4a907309 | refs/heads/develop | 2022-10-17T04:40:44.661900 | 2020-06-12T10:27:50 | 2020-06-12T10:27:50 | 267,541,809 | 0 | 0 | null | 2020-06-12T10:27:52 | 2020-05-28T08:59:04 | JavaScript | UTF-8 | Java | false | false | 344 | java | package junit.tutorial;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import java.util.Date;
import org.junit.Test;
public class IsDateTest
{
@Test
public void 日付の比較() throws Exception
{
Date date = new Date();
assertThat(date, is(IsDate.dateOf(2011, 2, 10)));
}
}
| [
"[email protected]"
]
| |
23c4843cbe135f26329f8d95b22e735b0cb5cf1b | 55f24996c0c23ffccd9313aab2f6e592045299b6 | /core/cocoon-pipeline/cocoon-pipeline-impl/src/main/java/org/apache/cocoon/components/pipeline/spring/PipelineComponentProxyDecorator.java | 561e6b15b1ab3c21badca5dcfcf8a6e83426e914 | [
"Apache-2.0"
]
| permissive | apache/cocoon | 8c02bc6adf53488e11da3ccdd2bfeda74d831710 | 68e7a576e54e43b5e10ecdf3e713aef224ddda21 | refs/heads/trunk | 2023-09-03T15:52:29.338373 | 2023-08-01T08:49:28 | 2023-08-01T08:49:28 | 206,428 | 22 | 34 | Apache-2.0 | 2023-08-01T07:30:54 | 2009-05-21T02:12:25 | Java | UTF-8 | Java | false | false | 4,907 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cocoon.components.pipeline.spring;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.apache.cocoon.generation.Generator;
import org.apache.cocoon.serialization.Serializer;
import org.apache.cocoon.transformation.Transformer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class PipelineComponentProxyDecorator implements BeanPostProcessor {
private PipelineComponentScopeHolder holder;
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Generator || bean instanceof Transformer || bean instanceof Serializer) {
bean = Proxy.newProxyInstance(bean.getClass().getClassLoader(), getInterfaces(bean.getClass()),
new ScopeChangerProxy(bean, holder));
}
return bean;
}
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
public PipelineComponentScopeHolder getHolder() {
return holder;
}
public void setHolder(PipelineComponentScopeHolder holder) {
this.holder = holder;
}
private class ScopeChangerProxy implements InvocationHandler {
private Map beans;
private Map destructionCallbacks;
private PipelineComponentScopeHolder holder;
private Object wrapped;
public ScopeChangerProxy(Object wrapped, PipelineComponentScopeHolder holder) {
this.wrapped = wrapped;
this.holder = holder;
this.beans = new HashMap();
this.destructionCallbacks = new HashMap();
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result;
boolean modified = false;
try {
if (!holder.getInScope()) {
holder.setParentBeans(holder.getBeans());
holder.setParentDestructionCallbacks(holder.getDestructionCallbacks());
holder.setBeans(beans);
holder.setDestructionCallbacks(destructionCallbacks);
holder.setInScope(true);
modified = true;
}
result = method.invoke(wrapped, args);
} finally {
if (modified) {
holder.setBeans(holder.getParentBeans());
holder.setDestructionCallbacks(holder.getParentDestructionCallbacks());
holder.setParentBeans(null);
holder.setParentDestructionCallbacks(null);
holder.setInScope(false);
}
}
return result;
}
}
//Copied from org.apache.cocoon.servletservice.DispatcherServlet
private void getInterfaces(Set interfaces, Class clazz) {
Class[] clazzInterfaces = clazz.getInterfaces();
for (int i = 0; i < clazzInterfaces.length; i++) {
//add all interfaces extended by this interface or directly
//implemented by this class
getInterfaces(interfaces, clazzInterfaces[i]);
}
//the superclazz is null if class is instanceof Object, is
//an interface, a primitive type or void
Class superclazz = clazz.getSuperclass();
if (superclazz != null) {
//add all interfaces of the superclass to the list
getInterfaces(interfaces, superclazz);
}
interfaces.addAll(Arrays.asList(clazzInterfaces));
}
private Class[] getInterfaces(Class clazz) {
Set interfaces = new LinkedHashSet();
getInterfaces(interfaces, clazz);
return (Class[]) interfaces.toArray(new Class[interfaces.size()]);
}
}
| [
"[email protected]"
]
| |
c56b0fdb3bbdb645b0f41bdf8426bf891239895d | f965bd686de9b78b982b6b1b967f0cfbc93ac43e | /src/main/java/ni/gob/minsa/sivin/domain/Encuesta.java | 631e8522d7e5add79b0f605541b12eb755d655d7 | []
| no_license | wmonterrey/sivin-web | 1b5c76b655d27decf93cabc96597df1cb9d8d106 | e02b6b4063b84820e8112d8b98dffae9dd7106a4 | refs/heads/master | 2021-05-06T05:23:35.331167 | 2019-05-20T03:04:07 | 2019-05-20T03:04:07 | 115,147,785 | 0 | 0 | null | null | null | null | IBM852 | Java | false | false | 56,316 | java | package ni.gob.minsa.sivin.domain;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.hibernate.annotations.ForeignKey;
import ni.gob.minsa.sivin.domain.audit.Auditable;
/**
* Encuesta es la clase que representa el registro de una encuesta.<br><br>
*
* Nombre de la tabla<br>
* Table(name = "encuesta", catalog = "sivin", uniqueConstraints={UniqueConstraint((columnNames = {"codigo","pasivo"})})<br><br>
*
* Encuesta se relaciona con:
*
* <ul>
* <li>Segmento
* <li>Encuestador
* <li>Supervisor
* </ul>
*
*
* @author William AvilÚs
* @version 1.0
* @since 1.0
*/
@Entity
@Table(name = "encuesta", catalog = "sivin", uniqueConstraints={@UniqueConstraint(columnNames = {"codigo","pasivo"})})
public class Encuesta extends BaseMetaData implements Auditable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String ident;
private String codigo;
private Segmento segmento;
private String latitud;
private String longitud;
private Integer numEncuesta;
private Date fechaEntrevista;
private String jefeFamilia;
private String sexJefeFamilia;
private Integer numPersonas;
private Encuestador encuestador;
private Supervisor supervisor;
//Seccion A
private String agua;
private String oagua;
private Integer cuartos;
private String lugNecesidades;
private String olugNecesidades;
private String usaCocinar;
private String ousaCocinar;
private String articulos;
private String oarticulos;
//SECCION B
private String conoceFNac;
private Date fnacEnt;
private String edadEnt;
private String leerEnt;
private String escribirEnt;
private String leeescEnt;
private String nivelEnt;
private String gradoEnt;
private String entRealizada;
private String entEmb;
private String entEmbUnico;
private String entDioluz;
private String entHieacfol;
private String entMeseshierro;
private String entRecHierro;
private String entORecHierro;
private String tiemHierroUnd;
private String tiemHierro;
private String dondeHierro;
private String dondeHierroBesp;
private String dondeHierroFesp;
private String tomadoHierro;
private String vita;
private String tiempVita;
private String evitaEmb;
private String dondeAntic;
private String nuevoEmb;
private String hierro;
private String dHierro;
//SECCION C
private String numNinos;
private String n1;
private String n2;
private String n3;
private String n4;
private String n5;
private String n6;
private String e1;
private String e2;
private String e3;
private String e4;
private String e5;
private String e6;
private String nselec;
private String nomselec;
private Date fnacselec;
private String eselect;
private String sexselec;
private String calim;
private String vcome;
private String consalim;
private String calimenf;
private String clecheenf;
//SECCION D
private String hierron;
private String thierround;
private String thierrocant;
private String fhierro;
private String ghierro;
private String donhierro;
private String donhierrobesp;
private String donhierrofesp;
private String fuhierro;
private Date fuhierror;
private Date fauhierror;
private String nvita;
private String ncvita;
private String tvitaund;
private String tvitacant;
private String ndvita;
private String ndvitao;
private String tdvita;
private Date fuvita;
private Date fauvita;
private String ncnut;
private String ncnutund;
private String ncnutcant;
private String doncnut;
private String doncnutfotro;
private String parasit;
private String cvparas;
private String mParasitario;
private String otroMpEsp;
private String donMp;
private String otroDonMp;
private String evitarParasito;
private String oEvitarParasito;
//SECCION E
private String nlactmat;
private String sexlmat;
private String emeseslmat;
private Date fnaclmat;
private String pecho;
private String motNopecho;
private String motNopechoOtro;
private String dapecho;
private String tiempecho;
private String tiemmama;
private String tiemmamaMins;
private String dospechos;
private String vecespechodia;
private String vecespechonoche;
private String elmatexcund;
private String elmatexccant;
private String ediopechound;
private String ediopechocant;
private String combeb;
private String ealimund;
private String ealimcant;
private String bebeLiq;
private String reunionPeso;
private String quienReunionPeso;
private String quienReunionPesoOtro;
private String assitioReunionPeso;
//SECCION F
private String pesoTallaEnt;
private Float pesoEnt1;
private Float pesoEnt2;
private Float tallaEnt1;
private Float tallaEnt2;
private String pesoTallaNin;
private Float pesoNin1;
private Float pesoNin2;
private Float longNin1;
private Float longNin2;
private Float tallaNin1;
private Float tallaNin2;
// SECCION G
private String msEnt;
private String codMsEnt;
private Float hbEnt;
private String msNin;
private String codMsNin;
private Float hbNin;
private String moEnt;
private String codMoEnt;
private String pan;
private String sal;
private String marcaSal;
private String azucar;
private String marcaAzucar;
// SECCION H
private String patConsAzuc;
private String patConsAzucFrec;
private String patConsSal;
private String patConsSalFrec;
private String patConsArroz;
private String patConsArrozFrec;
private String patConsAcei;
private String patConsAceiFrec;
private String patConsFri;
private String patConsFriFrec;
private String patConsCebo;
private String patConsCeboFrec;
private String patConsChi;
private String patConsChiFrec;
private String patConsQue;
private String patConsQueFrec;
private String patConsCafe;
private String patConsCafeFrec;
private String patConsTor;
private String patConsTorFrec;
private String patConsCar;
private String patConsCarFrec;
private String patConsHue;
private String patConsHueFrec;
private String patConsPan;
private String patConsPanFrec;
private String patConsBan;
private String patConsBanFrec;
private String patConsPanDul;
private String patConsPanDulFrec;
private String patConsPla;
private String patConsPlaFrec;
private String patConsPapa;
private String patConsPapaFrec;
private String patConsLec;
private String patConsLecFrec;
private String patConsSalTom;
private String patConsSalTomFrec;
private String patConsGas;
private String patConsGasFrec;
private String patConsCarRes;
private String patConsCarResFrec;
private String patConsAvena;
private String patConsAvenaFrec;
private String patConsNaran;
private String patConsNaranFrec;
private String patConsPasta;
private String patConsPastaFrec;
private String patConsAyote;
private String patConsAyoteFrec;
private String patConsMagg;
private String patConsMaggFrec;
private String patConsFrut;
private String patConsFrutFrec;
private String patConsRaic;
private String patConsRaicFrec;
private String patConsMenei;
private String patConsMeneiFrec;
private String patConsRepollo;
private String patConsRepolloFrec;
private String patConsZana;
private String patConsZanaFrec;
private String patConsPinolillo;
private String patConsPinolilloFrec;
private String patConsOVerd;
private String patConsOVerdFrec;
private String patConsPesc;
private String patConsPescFrec;
private String patConsAlimComp;
private String patConsAlimCompFrec;
private String patConsLecPol;
private String patConsLecPolFrec;
private String patConsCarCer;
private String patConsCarCerFrec;
private String patConsEmb;
private String patConsEmbFrec;
private String patConsMar;
private String patConsMarFrec;
private String patConsCarCaza;
private String patConsCarCazaFrec;
public Encuesta() {
super();
}
@Id
@Column(name = "identificador", nullable = false, length = 50)
public String getIdent() {
return ident;
}
public void setIdent(String ident) {
this.ident = ident;
}
@Column(name = "codigo", nullable = false, length = 115)
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
@ManyToOne(optional=false)
@JoinColumn(name="segmento")
@ForeignKey(name = "FK_SEGMENTO_ENCUESTA")
public Segmento getSegmento() {
return segmento;
}
public void setSegmento(Segmento segmento) {
this.segmento = segmento;
}
@Column(name = "latitud", nullable = true, length = 50)
public String getLatitud() {
return latitud;
}
public void setLatitud(String latitud) {
this.latitud = latitud;
}
@Column(name = "longitud", nullable = true, length = 50)
public String getLongitud() {
return longitud;
}
public void setLongitud(String longitud) {
this.longitud = longitud;
}
@ManyToOne(optional=true)
@JoinColumn(name="encuestador")
@ForeignKey(name = "FK_ENCUESTADOR_ENCUESTA")
public Encuestador getEncuestador() {
return encuestador;
}
public void setEncuestador(Encuestador encuestador) {
this.encuestador = encuestador;
}
@ManyToOne(optional=true)
@JoinColumn(name="supervisor")
@ForeignKey(name = "FK_SUPERVISOR_ENCUESTA")
public Supervisor getSupervisor() {
return supervisor;
}
public void setSupervisor(Supervisor supervisor) {
this.supervisor = supervisor;
}
@Column(name = "numEncuesta", nullable = false)
public Integer getNumEncuesta() {
return numEncuesta;
}
public void setNumEncuesta(Integer numEncuesta) {
this.numEncuesta = numEncuesta;
}
@Column(name = "fechaEntrevista", nullable = false)
public Date getFechaEntrevista() {
return fechaEntrevista;
}
public void setFechaEntrevista(Date fechaEntrevista) {
this.fechaEntrevista = fechaEntrevista;
}
@Column(name = "jefeFamilia", nullable = false, length = 250)
public String getJefeFamilia() {
return jefeFamilia;
}
public void setJefeFamilia(String jefeFamilia) {
this.jefeFamilia = jefeFamilia;
}
@Column(name = "sexJefeFamilia", nullable = false, length = 5)
public String getSexJefeFamilia() {
return sexJefeFamilia;
}
public void setSexJefeFamilia(String sexJefeFamilia) {
this.sexJefeFamilia = sexJefeFamilia;
}
@Column(name = "numPersonas", nullable = false, length = 2)
public Integer getNumPersonas() {
return numPersonas;
}
public void setNumPersonas(Integer numPersonas) {
this.numPersonas = numPersonas;
}
@Column(name = "agua", nullable = true, length = 2)
public String getAgua() {
return agua;
}
public void setAgua(String agua) {
this.agua = agua;
}
@Column(name = "oagua", nullable = true, length = 255)
public String getOagua() {
return oagua;
}
public void setOagua(String oagua) {
this.oagua = oagua;
}
@Column(name = "cuartos", nullable = true)
public Integer getCuartos() {
return cuartos;
}
public void setCuartos(Integer cuartos) {
this.cuartos = cuartos;
}
@Column(name = "lugnecesidades", nullable = true, length = 2)
public String getLugNecesidades() {
return lugNecesidades;
}
public void setLugNecesidades(String lugNecesidades) {
this.lugNecesidades = lugNecesidades;
}
@Column(name = "olugnecesidades", nullable = true, length = 255)
public String getOlugNecesidades() {
return olugNecesidades;
}
public void setOlugNecesidades(String olugNecesidades) {
this.olugNecesidades = olugNecesidades;
}
@Column(name = "usacocinar", nullable = true, length = 2)
public String getUsaCocinar() {
return usaCocinar;
}
public void setUsaCocinar(String usaCocinar) {
this.usaCocinar = usaCocinar;
}
@Column(name = "ousacocinar", nullable = true, length = 255)
public String getOusaCocinar() {
return ousaCocinar;
}
public void setOusaCocinar(String ousaCocinar) {
this.ousaCocinar = ousaCocinar;
}
@Column(name = "articulos", nullable = true, length = 25)
public String getArticulos() {
return articulos;
}
public void setArticulos(String articulos) {
this.articulos = articulos;
}
@Column(name = "oarticulos", nullable = true, length = 255)
public String getOarticulos() {
return oarticulos;
}
public void setOarticulos(String oarticulos) {
this.oarticulos = oarticulos;
}
@Column(name = "conocefnac", nullable = true, length = 1)
public String getConoceFNac() {
return conoceFNac;
}
public void setConoceFNac(String conoceFNac) {
this.conoceFNac = conoceFNac;
}
@Column(name = "fnacent", nullable = true)
public Date getFnacEnt() {
return fnacEnt;
}
public void setFnacEnt(Date fnacEnt) {
this.fnacEnt = fnacEnt;
}
@Column(name = "edadent", nullable = true, length = 2)
public String getEdadEnt() {
return edadEnt;
}
public void setEdadEnt(String edadEnt) {
this.edadEnt = edadEnt;
}
@Column(name = "leerent", nullable = true, length = 1)
public String getLeerEnt() {
return leerEnt;
}
public void setLeerEnt(String leerEnt) {
this.leerEnt = leerEnt;
}
@Column(name = "escribirent", nullable = true, length = 1)
public String getEscribirEnt() {
return escribirEnt;
}
public void setEscribirEnt(String escribirEnt) {
this.escribirEnt = escribirEnt;
}
@Column(name = "leeescent", nullable = true, length = 1)
public String getLeeescEnt() {
return leeescEnt;
}
public void setLeeescEnt(String leeescEnt) {
this.leeescEnt = leeescEnt;
}
@Column(name = "nivelent", nullable = true, length = 1)
public String getNivelEnt() {
return nivelEnt;
}
public void setNivelEnt(String nivelEnt) {
this.nivelEnt = nivelEnt;
}
@Column(name = "gradoent", nullable = true, length = 1)
public String getGradoEnt() {
return gradoEnt;
}
public void setGradoEnt(String gradoEnt) {
this.gradoEnt = gradoEnt;
}
@Column(name = "entrealizada", nullable = true, length = 1)
public String getEntRealizada() {
return entRealizada;
}
public void setEntRealizada(String entRealizada) {
this.entRealizada = entRealizada;
}
@Column(name = "entemb", nullable = true, length = 1)
public String getEntEmb() {
return entEmb;
}
public void setEntEmb(String entEmb) {
this.entEmb = entEmb;
}
@Column(name = "entEmbUnico", nullable = true, length = 1)
public String getEntEmbUnico() {
return entEmbUnico;
}
public void setEntEmbUnico(String entEmbUnico) {
this.entEmbUnico = entEmbUnico;
}
@Column(name = "entDioluz", nullable = true, length = 1)
public String getEntDioluz() {
return entDioluz;
}
public void setEntDioluz(String entDioluz) {
this.entDioluz = entDioluz;
}
@Column(name = "enthieacfol", nullable = true, length = 1)
public String getEntHieacfol() {
return entHieacfol;
}
public void setEntHieacfol(String entHieacfol) {
this.entHieacfol = entHieacfol;
}
@Column(name = "entmeseshierro", nullable = true, length = 2)
public String getEntMeseshierro() {
return entMeseshierro;
}
public void setEntMeseshierro(String entMeseshierro) {
this.entMeseshierro = entMeseshierro;
}
@Column(name = "entrechierro", nullable = true, length = 1)
public String getEntRecHierro() {
return entRecHierro;
}
public void setEntRecHierro(String entRecHierro) {
this.entRecHierro = entRecHierro;
}
@Column(name = "entorechierro", nullable = true, length = 155)
public String getEntORecHierro() {
return entORecHierro;
}
public void setEntORecHierro(String entORecHierro) {
this.entORecHierro = entORecHierro;
}
@Column(name = "tiemhierround", nullable = true, length = 1)
public String getTiemHierroUnd() {
return tiemHierroUnd;
}
public void setTiemHierroUnd(String tiemHierroUnd) {
this.tiemHierroUnd = tiemHierroUnd;
}
@Column(name = "tiemhierro", nullable = true, length = 2)
public String getTiemHierro() {
return tiemHierro;
}
public void setTiemHierro(String tiemHierro) {
this.tiemHierro = tiemHierro;
}
@Column(name = "dondehierro", nullable = true, length = 25)
public String getDondeHierro() {
return dondeHierro;
}
public void setDondeHierro(String dondeHierro) {
this.dondeHierro = dondeHierro;
}
@Column(name = "dondehierrobesp", nullable = true, length = 255)
public String getDondeHierroBesp() {
return dondeHierroBesp;
}
public void setDondeHierroBesp(String dondeHierroBesp) {
this.dondeHierroBesp = dondeHierroBesp;
}
@Column(name = "dondehierrofesp", nullable = true, length = 255)
public String getDondeHierroFesp() {
return dondeHierroFesp;
}
public void setDondeHierroFesp(String dondeHierroFesp) {
this.dondeHierroFesp = dondeHierroFesp;
}
@Column(name = "tomadohierro", nullable = true, length = 1)
public String getTomadoHierro() {
return tomadoHierro;
}
public void setTomadoHierro(String tomadoHierro) {
this.tomadoHierro = tomadoHierro;
}
@Column(name = "vita", nullable = true, length = 1)
public String getVita() {
return vita;
}
public void setVita(String vita) {
this.vita = vita;
}
@Column(name = "tiempvita", nullable = true, length = 1)
public String getTiempVita() {
return tiempVita;
}
public void setTiempVita(String tiempVita) {
this.tiempVita = tiempVita;
}
@Column(name = "evitaemb", nullable = true, length = 2)
public String getEvitaEmb() {
return evitaEmb;
}
public void setEvitaEmb(String evitaEmb) {
this.evitaEmb = evitaEmb;
}
@Column(name = "dondeantic", nullable = true, length = 1)
public String getDondeAntic() {
return dondeAntic;
}
public void setDondeAntic(String dondeAntic) {
this.dondeAntic = dondeAntic;
}
@Column(name = "nuevoemb", nullable = true, length = 1)
public String getNuevoEmb() {
return nuevoEmb;
}
public void setNuevoEmb(String nuevoEmb) {
this.nuevoEmb = nuevoEmb;
}
@Column(name = "hierro", nullable = true, length = 1)
public String getHierro() {
return hierro;
}
public void setHierro(String hierro) {
this.hierro = hierro;
}
@Column(name = "dhierro", nullable = true, length = 1)
public String getdHierro() {
return dHierro;
}
public void setdHierro(String dHierro) {
this.dHierro = dHierro;
}
@Column(name = "numNinos", nullable = true, length = 1)
public String getNumNinos() {
return numNinos;
}
public void setNumNinos(String numNinos) {
this.numNinos = numNinos;
}
@Column(name = "n1", nullable = true, length = 100)
public String getN1() {
return n1;
}
public void setN1(String n1) {
this.n1 = n1;
}
@Column(name = "n2", nullable = true, length = 100)
public String getN2() {
return n2;
}
public void setN2(String n2) {
this.n2 = n2;
}
@Column(name = "n3", nullable = true, length = 100)
public String getN3() {
return n3;
}
public void setN3(String n3) {
this.n3 = n3;
}
@Column(name = "n4", nullable = true, length = 100)
public String getN4() {
return n4;
}
public void setN4(String n4) {
this.n4 = n4;
}
@Column(name = "n5", nullable = true, length = 100)
public String getN5() {
return n5;
}
public void setN5(String n5) {
this.n5 = n5;
}
@Column(name = "n6", nullable = true, length = 100)
public String getN6() {
return n6;
}
public void setN6(String n6) {
this.n6 = n6;
}
@Column(name = "e1", nullable = true, length = 2)
public String getE1() {
return e1;
}
public void setE1(String e1) {
this.e1 = e1;
}
@Column(name = "e2", nullable = true, length = 2)
public String getE2() {
return e2;
}
public void setE2(String e2) {
this.e2 = e2;
}
@Column(name = "e3", nullable = true, length = 2)
public String getE3() {
return e3;
}
public void setE3(String e3) {
this.e3 = e3;
}
@Column(name = "e4", nullable = true, length = 2)
public String getE4() {
return e4;
}
public void setE4(String e4) {
this.e4 = e4;
}
@Column(name = "e5", nullable = true, length = 2)
public String getE5() {
return e5;
}
public void setE5(String e5) {
this.e5 = e5;
}
@Column(name = "e6", nullable = true, length = 2)
public String getE6() {
return e6;
}
public void setE6(String e6) {
this.e6 = e6;
}
@Column(name = "nselec", nullable = true, length = 1)
public String getNselec() {
return nselec;
}
public void setNselec(String nselec) {
this.nselec = nselec;
}
@Column(name = "nomselec", nullable = true, length = 100)
public String getNomselec() {
return nomselec;
}
public void setNomselec(String nomselec) {
this.nomselec = nomselec;
}
@Column(name = "fnacselec", nullable = true)
public Date getFnacselec() {
return fnacselec;
}
public void setFnacselec(Date fnacselec) {
this.fnacselec = fnacselec;
}
@Column(name = "eselect", nullable = true, length = 2)
public String getEselect() {
return eselect;
}
public void setEselect(String eselect) {
this.eselect = eselect;
}
@Column(name = "sexselec", nullable = true, length = 1)
public String getSexselec() {
return sexselec;
}
public void setSexselec(String sexselec) {
this.sexselec = sexselec;
}
@Column(name = "calim", nullable = true, length = 1)
public String getCalim() {
return calim;
}
public void setCalim(String calim) {
this.calim = calim;
}
@Column(name = "vcome", nullable = true, length = 2)
public String getVcome() {
return vcome;
}
public void setVcome(String vcome) {
this.vcome = vcome;
}
@Column(name = "consalim", nullable = true, length = 1)
public String getConsalim() {
return consalim;
}
public void setConsalim(String consalim) {
this.consalim = consalim;
}
@Column(name = "calimenf", nullable = true, length = 1)
public String getCalimenf() {
return calimenf;
}
public void setCalimenf(String calimenf) {
this.calimenf = calimenf;
}
@Column(name = "clecheenf", nullable = true, length = 1)
public String getClecheenf() {
return clecheenf;
}
public void setClecheenf(String clecheenf) {
this.clecheenf = clecheenf;
}
@Column(name = "hierron", nullable = true, length = 1)
public String getHierron() {
return hierron;
}
public void setHierron(String hierron) {
this.hierron = hierron;
}
@Column(name = "thierround", nullable = true, length = 1)
public String getThierround() {
return thierround;
}
public void setThierround(String thierround) {
this.thierround = thierround;
}
@Column(name = "thierrocant", nullable = true, length = 2)
public String getThierrocant() {
return thierrocant;
}
public void setThierrocant(String thierrocant) {
this.thierrocant = thierrocant;
}
@Column(name = "fhierro", nullable = true, length = 2)
public String getFhierro() {
return fhierro;
}
public void setFhierro(String fhierro) {
this.fhierro = fhierro;
}
@Column(name = "ghierro", nullable = true, length = 1)
public String getGhierro() {
return ghierro;
}
public void setGhierro(String ghierro) {
this.ghierro = ghierro;
}
@Column(name = "donhierro", nullable = true, length = 25)
public String getDonhierro() {
return donhierro;
}
public void setDonhierro(String donhierro) {
this.donhierro = donhierro;
}
@Column(name = "donhierrobesp", nullable = true, length = 255)
public String getDonhierrobesp() {
return donhierrobesp;
}
public void setDonhierrobesp(String donhierrobesp) {
this.donhierrobesp = donhierrobesp;
}
@Column(name = "donhierrofesp", nullable = true, length = 255)
public String getDonhierrofesp() {
return donhierrofesp;
}
public void setDonhierrofesp(String donhierrofesp) {
this.donhierrofesp = donhierrofesp;
}
@Column(name = "fuhierro", nullable = true, length = 1)
public String getFuhierro() {
return fuhierro;
}
public void setFuhierro(String fuhierro) {
this.fuhierro = fuhierro;
}
@Column(name = "fuhierror", nullable = true)
public Date getFuhierror() {
return fuhierror;
}
public void setFuhierror(Date fuhierror) {
this.fuhierror = fuhierror;
}
@Column(name = "fauhierror", nullable = true)
public Date getFauhierror() {
return fauhierror;
}
public void setFauhierror(Date fauhierror) {
this.fauhierror = fauhierror;
}
@Column(name = "nvita", nullable = true, length = 1)
public String getNvita() {
return nvita;
}
public void setNvita(String nvita) {
this.nvita = nvita;
}
@Column(name = "ncvita", nullable = true, length = 2)
public String getNcvita() {
return ncvita;
}
public void setNcvita(String ncvita) {
this.ncvita = ncvita;
}
@Column(name = "tvitaund", nullable = true, length = 1)
public String getTvitaund() {
return tvitaund;
}
public void setTvitaund(String tvitaund) {
this.tvitaund = tvitaund;
}
@Column(name = "tvitacant", nullable = true, length = 2)
public String getTvitacant() {
return tvitacant;
}
public void setTvitacant(String tvitacant) {
this.tvitacant = tvitacant;
}
@Column(name = "ndvita", nullable = true, length = 1)
public String getNdvita() {
return ndvita;
}
public void setNdvita(String ndvita) {
this.ndvita = ndvita;
}
@Column(name = "ndvitao", nullable = true, length = 155)
public String getNdvitao() {
return ndvitao;
}
public void setNdvitao(String ndvitao) {
this.ndvitao = ndvitao;
}
@Column(name = "tdvita", nullable = true, length = 1)
public String getTdvita() {
return tdvita;
}
public void setTdvita(String tdvita) {
this.tdvita = tdvita;
}
@Column(name = "fuvita", nullable = true)
public Date getFuvita() {
return fuvita;
}
public void setFuvita(Date fuvita) {
this.fuvita = fuvita;
}
@Column(name = "fauvita", nullable = true)
public Date getFauvita() {
return fauvita;
}
public void setFauvita(Date fauvita) {
this.fauvita = fauvita;
}
@Column(name = "ncnut", nullable = true, length = 1)
public String getNcnut() {
return ncnut;
}
public void setNcnut(String ncnut) {
this.ncnut = ncnut;
}
@Column(name = "ncnutund", nullable = true, length = 1)
public String getNcnutund() {
return ncnutund;
}
public void setNcnutund(String ncnutund) {
this.ncnutund = ncnutund;
}
@Column(name = "ncnutcant", nullable = true, length = 2)
public String getNcnutcant() {
return ncnutcant;
}
public void setNcnutcant(String ncnutcant) {
this.ncnutcant = ncnutcant;
}
@Column(name = "doncnut", nullable = true, length = 25)
public String getDoncnut() {
return doncnut;
}
public void setDoncnut(String doncnut) {
this.doncnut = doncnut;
}
@Column(name = "doncnutfotro", nullable = true, length = 155)
public String getDoncnutfotro() {
return doncnutfotro;
}
public void setDoncnutfotro(String doncnutfotro) {
this.doncnutfotro = doncnutfotro;
}
@Column(name = "parasit", nullable = true, length = 1)
public String getParasit() {
return parasit;
}
public void setParasit(String parasit) {
this.parasit = parasit;
}
@Column(name = "cvparas", nullable = true, length = 2)
public String getCvparas() {
return cvparas;
}
public void setCvparas(String cvparas) {
this.cvparas = cvparas;
}
@Column(name = "mParasitario", nullable = true, length = 25)
public String getmParasitario() {
return mParasitario;
}
public void setmParasitario(String mParasitario) {
this.mParasitario = mParasitario;
}
@Column(name = "otroMpEsp", nullable = true, length = 255)
public String getOtroMpEsp() {
return otroMpEsp;
}
public void setOtroMpEsp(String otroMpEsp) {
this.otroMpEsp = otroMpEsp;
}
@Column(name = "donMp", nullable = true, length = 25)
public String getDonMp() {
return donMp;
}
public void setDonMp(String donMp) {
this.donMp = donMp;
}
@Column(name = "otroDonMp", nullable = true, length = 255)
public String getOtroDonMp() {
return otroDonMp;
}
public void setOtroDonMp(String otroDonMp) {
this.otroDonMp = otroDonMp;
}
@Column(name = "evitarParasito", nullable = true, length = 25)
public String getEvitarParasito() {
return evitarParasito;
}
public void setEvitarParasito(String evitarParasito) {
this.evitarParasito = evitarParasito;
}
@Column(name = "oEvitarParasito", nullable = true, length = 255)
public String getoEvitarParasito() {
return oEvitarParasito;
}
public void setoEvitarParasito(String oEvitarParasito) {
this.oEvitarParasito = oEvitarParasito;
}
@Column(name = "nlactmat", nullable = true, length = 1)
public String getNlactmat() {
return nlactmat;
}
public void setNlactmat(String nlactmat) {
this.nlactmat = nlactmat;
}
@Column(name = "sexlmat", nullable = true, length = 1)
public String getSexlmat() {
return sexlmat;
}
public void setSexlmat(String sexlmat) {
this.sexlmat = sexlmat;
}
@Column(name = "emeseslmat", nullable = true, length = 2)
public String getEmeseslmat() {
return emeseslmat;
}
public void setEmeseslmat(String emeseslmat) {
this.emeseslmat = emeseslmat;
}
@Column(name = "fnaclmat", nullable = true)
public Date getFnaclmat() {
return fnaclmat;
}
public void setFnaclmat(Date fnaclmat) {
this.fnaclmat = fnaclmat;
}
@Column(name = "pecho", nullable = true, length = 2)
public String getPecho() {
return pecho;
}
public void setPecho(String pecho) {
this.pecho = pecho;
}
@Column(name = "motNopecho", nullable = true, length = 2)
public String getMotNopecho() {
return motNopecho;
}
public void setMotNopecho(String motNopecho) {
this.motNopecho = motNopecho;
}
@Column(name = "motNopechoOtro", nullable = true, length = 255)
public String getMotNopechoOtro() {
return motNopechoOtro;
}
public void setMotNopechoOtro(String motNopechoOtro) {
this.motNopechoOtro = motNopechoOtro;
}
@Column(name = "dapecho", nullable = true, length = 2)
public String getDapecho() {
return dapecho;
}
public void setDapecho(String dapecho) {
this.dapecho = dapecho;
}
@Column(name = "tiempecho", nullable = true, length = 2)
public String getTiempecho() {
return tiempecho;
}
public void setTiempecho(String tiempecho) {
this.tiempecho = tiempecho;
}
@Column(name = "tiemmama", nullable = true, length = 2)
public String getTiemmama() {
return tiemmama;
}
public void setTiemmama(String tiemmama) {
this.tiemmama = tiemmama;
}
@Column(name = "tiemmamaMins", nullable = true, length = 2)
public String getTiemmamaMins() {
return tiemmamaMins;
}
public void setTiemmamaMins(String tiemmamaMins) {
this.tiemmamaMins = tiemmamaMins;
}
@Column(name = "dospechos", nullable = true, length = 2)
public String getDospechos() {
return dospechos;
}
public void setDospechos(String dospechos) {
this.dospechos = dospechos;
}
@Column(name = "vecespechodia", nullable = true, length = 2)
public String getVecespechodia() {
return vecespechodia;
}
public void setVecespechodia(String vecespechodia) {
this.vecespechodia = vecespechodia;
}
@Column(name = "vecespechonoche", nullable = true, length = 2)
public String getVecespechonoche() {
return vecespechonoche;
}
public void setVecespechonoche(String vecespechonoche) {
this.vecespechonoche = vecespechonoche;
}
@Column(name = "elmatexcund", nullable = true, length = 2)
public String getElmatexcund() {
return elmatexcund;
}
public void setElmatexcund(String elmatexcund) {
this.elmatexcund = elmatexcund;
}
@Column(name = "elmatexccant", nullable = true, length = 2)
public String getElmatexccant() {
return elmatexccant;
}
public void setElmatexccant(String elmatexccant) {
this.elmatexccant = elmatexccant;
}
@Column(name = "ediopechound", nullable = true, length = 2)
public String getEdiopechound() {
return ediopechound;
}
public void setEdiopechound(String ediopechound) {
this.ediopechound = ediopechound;
}
@Column(name = "ediopechocant", nullable = true, length = 2)
public String getEdiopechocant() {
return ediopechocant;
}
public void setEdiopechocant(String ediopechocant) {
this.ediopechocant = ediopechocant;
}
@Column(name = "combeb", nullable = true, length = 2)
public String getCombeb() {
return combeb;
}
public void setCombeb(String combeb) {
this.combeb = combeb;
}
@Column(name = "ealimund", nullable = true, length = 2)
public String getEalimund() {
return ealimund;
}
public void setEalimund(String ealimund) {
this.ealimund = ealimund;
}
@Column(name = "ealimcant", nullable = true, length = 2)
public String getEalimcant() {
return ealimcant;
}
public void setEalimcant(String ealimcant) {
this.ealimcant = ealimcant;
}
@Column(name = "bebeLiq", nullable = true, length = 25)
public String getBebeLiq() {
return bebeLiq;
}
public void setBebeLiq(String bebeLiq) {
this.bebeLiq = bebeLiq;
}
@Column(name = "reunionPeso", nullable = true, length = 2)
public String getReunionPeso() {
return reunionPeso;
}
public void setReunionPeso(String reunionPeso) {
this.reunionPeso = reunionPeso;
}
@Column(name = "quienReunionPeso", nullable = true, length = 2)
public String getQuienReunionPeso() {
return quienReunionPeso;
}
public void setQuienReunionPeso(String quienReunionPeso) {
this.quienReunionPeso = quienReunionPeso;
}
@Column(name = "quienReunionPesoOtro", nullable = true, length = 255)
public String getQuienReunionPesoOtro() {
return quienReunionPesoOtro;
}
public void setQuienReunionPesoOtro(String quienReunionPesoOtro) {
this.quienReunionPesoOtro = quienReunionPesoOtro;
}
@Column(name = "assitioReunionPeso", nullable = true, length = 2)
public String getAssitioReunionPeso() {
return assitioReunionPeso;
}
public void setAssitioReunionPeso(String assitioReunionPeso) {
this.assitioReunionPeso = assitioReunionPeso;
}
@Column(name = "pesoTallaEnt", nullable = true, length = 2)
public String getPesoTallaEnt() {
return pesoTallaEnt;
}
public void setPesoTallaEnt(String pesoTallaEnt) {
this.pesoTallaEnt = pesoTallaEnt;
}
@Column(name = "pesoTallaNin", nullable = true, length = 2)
public String getPesoTallaNin() {
return pesoTallaNin;
}
public void setPesoTallaNin(String pesoTallaNin) {
this.pesoTallaNin = pesoTallaNin;
}
@Column(name = "pesoent1", nullable = true)
public Float getPesoEnt1() {
return pesoEnt1;
}
public void setPesoEnt1(Float pesoEnt1) {
this.pesoEnt1 = pesoEnt1;
}
@Column(name = "pesoent2", nullable = true)
public Float getPesoEnt2() {
return pesoEnt2;
}
public void setPesoEnt2(Float pesoEnt2) {
this.pesoEnt2 = pesoEnt2;
}
@Column(name = "tallaent1", nullable = true)
public Float getTallaEnt1() {
return tallaEnt1;
}
public void setTallaEnt1(Float tallaEnt1) {
this.tallaEnt1 = tallaEnt1;
}
@Column(name = "tallaent2", nullable = true)
public Float getTallaEnt2() {
return tallaEnt2;
}
public void setTallaEnt2(Float tallaEnt2) {
this.tallaEnt2 = tallaEnt2;
}
@Column(name = "pesonin1", nullable = true)
public Float getPesoNin1() {
return pesoNin1;
}
public void setPesoNin1(Float pesoNin1) {
this.pesoNin1 = pesoNin1;
}
@Column(name = "pesonin2", nullable = true)
public Float getPesoNin2() {
return pesoNin2;
}
public void setPesoNin2(Float pesoNin2) {
this.pesoNin2 = pesoNin2;
}
@Column(name = "longnin1", nullable = true)
public Float getLongNin1() {
return longNin1;
}
public void setLongNin1(Float longNin1) {
this.longNin1 = longNin1;
}
@Column(name = "longnin2", nullable = true)
public Float getLongNin2() {
return longNin2;
}
public void setLongNin2(Float longNin2) {
this.longNin2 = longNin2;
}
@Column(name = "tallanin1", nullable = true)
public Float getTallaNin1() {
return tallaNin1;
}
public void setTallaNin1(Float tallaNin1) {
this.tallaNin1 = tallaNin1;
}
@Column(name = "tallanin2", nullable = true)
public Float getTallaNin2() {
return tallaNin2;
}
public void setTallaNin2(Float tallaNin2) {
this.tallaNin2 = tallaNin2;
}
@Column(name = "msent", nullable = true, length = 1)
public String getMsEnt() {
return msEnt;
}
public void setMsEnt(String msEnt) {
this.msEnt = msEnt;
}
@Column(name = "codMsEnt", nullable = true, length = 50)
public String getCodMsEnt() {
return codMsEnt;
}
public void setCodMsEnt(String codMsEnt) {
this.codMsEnt = codMsEnt;
}
@Column(name = "hbent", nullable = true)
public Float getHbEnt() {
return hbEnt;
}
public void setHbEnt(Float hbEnt) {
this.hbEnt = hbEnt;
}
@Column(name = "msnin", nullable = true, length = 1)
public String getMsNin() {
return msNin;
}
public void setMsNin(String msNin) {
this.msNin = msNin;
}
@Column(name = "codMsNin", nullable = true, length = 50)
public String getCodMsNin() {
return codMsNin;
}
public void setCodMsNin(String codMsNin) {
this.codMsNin = codMsNin;
}
@Column(name = "hbnin", nullable = true)
public Float getHbNin() {
return hbNin;
}
public void setHbNin(Float hbNin) {
this.hbNin = hbNin;
}
@Column(name = "moent", nullable = true, length = 1)
public String getMoEnt() {
return moEnt;
}
public void setMoEnt(String moEnt) {
this.moEnt = moEnt;
}
@Column(name = "codMoEnt", nullable = true, length = 50)
public String getCodMoEnt() {
return codMoEnt;
}
public void setCodMoEnt(String codMoEnt) {
this.codMoEnt = codMoEnt;
}
@Column(name = "pan", nullable = true, length = 100)
public String getPan() {
return pan;
}
public void setPan(String pan) {
this.pan = pan;
}
@Column(name = "sal", nullable = true, length = 1)
public String getSal() {
return sal;
}
public void setSal(String sal) {
this.sal = sal;
}
@Column(name = "marcasal", nullable = true, length = 100)
public String getMarcaSal() {
return marcaSal;
}
public void setMarcaSal(String marcaSal) {
this.marcaSal = marcaSal;
}
@Column(name = "azucar", nullable = true, length = 1)
public String getAzucar() {
return azucar;
}
public void setAzucar(String azucar) {
this.azucar = azucar;
}
@Column(name = "marcaazucar", nullable = true, length = 100)
public String getMarcaAzucar() {
return marcaAzucar;
}
public void setMarcaAzucar(String marcaAzucar) {
this.marcaAzucar = marcaAzucar;
}
@Column(name = "patConsAzuc", nullable = true, length = 1)
public String getPatConsAzuc() {
return patConsAzuc;
}
public void setPatConsAzuc(String patConsAzuc) {
this.patConsAzuc = patConsAzuc;
}
@Column(name = "patConsAzucFrec", nullable = true, length = 1)
public String getPatConsAzucFrec() {
return patConsAzucFrec;
}
public void setPatConsAzucFrec(String patConsAzucFrec) {
this.patConsAzucFrec = patConsAzucFrec;
}
@Column(name = "patConsSal", nullable = true, length = 1)
public String getPatConsSal() {
return patConsSal;
}
public void setPatConsSal(String patConsSal) {
this.patConsSal = patConsSal;
}
@Column(name = "patConsSalFrec", nullable = true, length = 1)
public String getPatConsSalFrec() {
return patConsSalFrec;
}
public void setPatConsSalFrec(String patConsSalFrec) {
this.patConsSalFrec = patConsSalFrec;
}
@Column(name = "patConsArroz", nullable = true, length = 1)
public String getPatConsArroz() {
return patConsArroz;
}
public void setPatConsArroz(String patConsArroz) {
this.patConsArroz = patConsArroz;
}
@Column(name = "patConsArrozFrec", nullable = true, length = 1)
public String getPatConsArrozFrec() {
return patConsArrozFrec;
}
public void setPatConsArrozFrec(String patConsArrozFrec) {
this.patConsArrozFrec = patConsArrozFrec;
}
@Column(name = "patConsAcei", nullable = true, length = 1)
public String getPatConsAcei() {
return patConsAcei;
}
public void setPatConsAcei(String patConsAcei) {
this.patConsAcei = patConsAcei;
}
@Column(name = "patConsAceiFrec", nullable = true, length = 1)
public String getPatConsAceiFrec() {
return patConsAceiFrec;
}
public void setPatConsAceiFrec(String patConsAceiFrec) {
this.patConsAceiFrec = patConsAceiFrec;
}
@Column(name = "patConsFri", nullable = true, length = 1)
public String getPatConsFri() {
return patConsFri;
}
public void setPatConsFri(String patConsFri) {
this.patConsFri = patConsFri;
}
@Column(name = "patConsFriFrec", nullable = true, length = 1)
public String getPatConsFriFrec() {
return patConsFriFrec;
}
public void setPatConsFriFrec(String patConsFriFrec) {
this.patConsFriFrec = patConsFriFrec;
}
@Column(name = "patConsCebo", nullable = true, length = 1)
public String getPatConsCebo() {
return patConsCebo;
}
public void setPatConsCebo(String patConsCebo) {
this.patConsCebo = patConsCebo;
}
@Column(name = "patConsCeboFrec", nullable = true, length = 1)
public String getPatConsCeboFrec() {
return patConsCeboFrec;
}
public void setPatConsCeboFrec(String patConsCeboFrec) {
this.patConsCeboFrec = patConsCeboFrec;
}
@Column(name = "patConsChi", nullable = true, length = 1)
public String getPatConsChi() {
return patConsChi;
}
public void setPatConsChi(String patConsChi) {
this.patConsChi = patConsChi;
}
@Column(name = "patConsChiFrec", nullable = true, length = 1)
public String getPatConsChiFrec() {
return patConsChiFrec;
}
public void setPatConsChiFrec(String patConsChiFrec) {
this.patConsChiFrec = patConsChiFrec;
}
@Column(name = "patConsQue", nullable = true, length = 1)
public String getPatConsQue() {
return patConsQue;
}
public void setPatConsQue(String patConsQue) {
this.patConsQue = patConsQue;
}
@Column(name = "patConsQueFrec", nullable = true, length = 1)
public String getPatConsQueFrec() {
return patConsQueFrec;
}
public void setPatConsQueFrec(String patConsQueFrec) {
this.patConsQueFrec = patConsQueFrec;
}
@Column(name = "patConsCafe", nullable = true, length = 1)
public String getPatConsCafe() {
return patConsCafe;
}
public void setPatConsCafe(String patConsCafe) {
this.patConsCafe = patConsCafe;
}
@Column(name = "patConsCafeFrec", nullable = true, length = 1)
public String getPatConsCafeFrec() {
return patConsCafeFrec;
}
public void setPatConsCafeFrec(String patConsCafeFrec) {
this.patConsCafeFrec = patConsCafeFrec;
}
@Column(name = "patConsTor", nullable = true, length = 1)
public String getPatConsTor() {
return patConsTor;
}
public void setPatConsTor(String patConsTor) {
this.patConsTor = patConsTor;
}
@Column(name = "patConsTorFrec", nullable = true, length = 1)
public String getPatConsTorFrec() {
return patConsTorFrec;
}
public void setPatConsTorFrec(String patConsTorFrec) {
this.patConsTorFrec = patConsTorFrec;
}
@Column(name = "patConsCar", nullable = true, length = 1)
public String getPatConsCar() {
return patConsCar;
}
public void setPatConsCar(String patConsCar) {
this.patConsCar = patConsCar;
}
@Column(name = "patConsCarFrec", nullable = true, length = 1)
public String getPatConsCarFrec() {
return patConsCarFrec;
}
public void setPatConsCarFrec(String patConsCarFrec) {
this.patConsCarFrec = patConsCarFrec;
}
@Column(name = "patConsHue", nullable = true, length = 1)
public String getPatConsHue() {
return patConsHue;
}
public void setPatConsHue(String patConsHue) {
this.patConsHue = patConsHue;
}
@Column(name = "patConsHueFrec", nullable = true, length = 1)
public String getPatConsHueFrec() {
return patConsHueFrec;
}
public void setPatConsHueFrec(String patConsHueFrec) {
this.patConsHueFrec = patConsHueFrec;
}
@Column(name = "patConsPan", nullable = true, length = 1)
public String getPatConsPan() {
return patConsPan;
}
public void setPatConsPan(String patConsPan) {
this.patConsPan = patConsPan;
}
@Column(name = "patConsPanFrec", nullable = true, length = 1)
public String getPatConsPanFrec() {
return patConsPanFrec;
}
public void setPatConsPanFrec(String patConsPanFrec) {
this.patConsPanFrec = patConsPanFrec;
}
@Column(name = "patConsBan", nullable = true, length = 1)
public String getPatConsBan() {
return patConsBan;
}
public void setPatConsBan(String patConsBan) {
this.patConsBan = patConsBan;
}
@Column(name = "patConsBanFrec", nullable = true, length = 1)
public String getPatConsBanFrec() {
return patConsBanFrec;
}
public void setPatConsBanFrec(String patConsBanFrec) {
this.patConsBanFrec = patConsBanFrec;
}
@Column(name = "patConsPanDul", nullable = true, length = 1)
public String getPatConsPanDul() {
return patConsPanDul;
}
public void setPatConsPanDul(String patConsPanDul) {
this.patConsPanDul = patConsPanDul;
}
@Column(name = "patConsPanDulFrec", nullable = true, length = 1)
public String getPatConsPanDulFrec() {
return patConsPanDulFrec;
}
public void setPatConsPanDulFrec(String patConsPanDulFrec) {
this.patConsPanDulFrec = patConsPanDulFrec;
}
@Column(name = "patConsPla", nullable = true, length = 1)
public String getPatConsPla() {
return patConsPla;
}
public void setPatConsPla(String patConsPla) {
this.patConsPla = patConsPla;
}
@Column(name = "patConsPlaFrec", nullable = true, length = 1)
public String getPatConsPlaFrec() {
return patConsPlaFrec;
}
public void setPatConsPlaFrec(String patConsPlaFrec) {
this.patConsPlaFrec = patConsPlaFrec;
}
@Column(name = "patConsPapa", nullable = true, length = 1)
public String getPatConsPapa() {
return patConsPapa;
}
public void setPatConsPapa(String patConsPapa) {
this.patConsPapa = patConsPapa;
}
@Column(name = "patConsPapaFrec", nullable = true, length = 1)
public String getPatConsPapaFrec() {
return patConsPapaFrec;
}
public void setPatConsPapaFrec(String patConsPapaFrec) {
this.patConsPapaFrec = patConsPapaFrec;
}
@Column(name = "patConsLec", nullable = true, length = 1)
public String getPatConsLec() {
return patConsLec;
}
public void setPatConsLec(String patConsLec) {
this.patConsLec = patConsLec;
}
@Column(name = "patConsLecFrec", nullable = true, length = 1)
public String getPatConsLecFrec() {
return patConsLecFrec;
}
public void setPatConsLecFrec(String patConsLecFrec) {
this.patConsLecFrec = patConsLecFrec;
}
@Column(name = "patConsSalTom", nullable = true, length = 1)
public String getPatConsSalTom() {
return patConsSalTom;
}
public void setPatConsSalTom(String patConsSalTom) {
this.patConsSalTom = patConsSalTom;
}
@Column(name = "patConsSalTomFrec", nullable = true, length = 1)
public String getPatConsSalTomFrec() {
return patConsSalTomFrec;
}
public void setPatConsSalTomFrec(String patConsSalTomFrec) {
this.patConsSalTomFrec = patConsSalTomFrec;
}
@Column(name = "patConsGas", nullable = true, length = 1)
public String getPatConsGas() {
return patConsGas;
}
public void setPatConsGas(String patConsGas) {
this.patConsGas = patConsGas;
}
@Column(name = "patConsGasFrec", nullable = true, length = 1)
public String getPatConsGasFrec() {
return patConsGasFrec;
}
public void setPatConsGasFrec(String patConsGasFrec) {
this.patConsGasFrec = patConsGasFrec;
}
@Column(name = "patConsCarRes", nullable = true, length = 1)
public String getPatConsCarRes() {
return patConsCarRes;
}
public void setPatConsCarRes(String patConsCarRes) {
this.patConsCarRes = patConsCarRes;
}
@Column(name = "patConsCarResFrec", nullable = true, length = 1)
public String getPatConsCarResFrec() {
return patConsCarResFrec;
}
public void setPatConsCarResFrec(String patConsCarResFrec) {
this.patConsCarResFrec = patConsCarResFrec;
}
@Column(name = "patConsAvena", nullable = true, length = 1)
public String getPatConsAvena() {
return patConsAvena;
}
public void setPatConsAvena(String patConsAvena) {
this.patConsAvena = patConsAvena;
}
@Column(name = "patConsAvenaFrec", nullable = true, length = 1)
public String getPatConsAvenaFrec() {
return patConsAvenaFrec;
}
public void setPatConsAvenaFrec(String patConsAvenaFrec) {
this.patConsAvenaFrec = patConsAvenaFrec;
}
@Column(name = "patConsNaran", nullable = true, length = 1)
public String getPatConsNaran() {
return patConsNaran;
}
public void setPatConsNaran(String patConsNaran) {
this.patConsNaran = patConsNaran;
}
@Column(name = "patConsNaranFrec", nullable = true, length = 1)
public String getPatConsNaranFrec() {
return patConsNaranFrec;
}
public void setPatConsNaranFrec(String patConsNaranFrec) {
this.patConsNaranFrec = patConsNaranFrec;
}
@Column(name = "patConsPasta", nullable = true, length = 1)
public String getPatConsPasta() {
return patConsPasta;
}
public void setPatConsPasta(String patConsPasta) {
this.patConsPasta = patConsPasta;
}
@Column(name = "patConsPastaFrec", nullable = true, length = 1)
public String getPatConsPastaFrec() {
return patConsPastaFrec;
}
public void setPatConsPastaFrec(String patConsPastaFrec) {
this.patConsPastaFrec = patConsPastaFrec;
}
@Column(name = "patConsAyote", nullable = true, length = 1)
public String getPatConsAyote() {
return patConsAyote;
}
public void setPatConsAyote(String patConsAyote) {
this.patConsAyote = patConsAyote;
}
@Column(name = "patConsAyoteFrec", nullable = true, length = 1)
public String getPatConsAyoteFrec() {
return patConsAyoteFrec;
}
public void setPatConsAyoteFrec(String patConsAyoteFrec) {
this.patConsAyoteFrec = patConsAyoteFrec;
}
@Column(name = "patConsMagg", nullable = true, length = 1)
public String getPatConsMagg() {
return patConsMagg;
}
public void setPatConsMagg(String patConsMagg) {
this.patConsMagg = patConsMagg;
}
@Column(name = "patConsMaggFrec", nullable = true, length = 1)
public String getPatConsMaggFrec() {
return patConsMaggFrec;
}
public void setPatConsMaggFrec(String patConsMaggFrec) {
this.patConsMaggFrec = patConsMaggFrec;
}
@Column(name = "patConsFrut", nullable = true, length = 1)
public String getPatConsFrut() {
return patConsFrut;
}
public void setPatConsFrut(String patConsFrut) {
this.patConsFrut = patConsFrut;
}
@Column(name = "patConsFrutFrec", nullable = true, length = 1)
public String getPatConsFrutFrec() {
return patConsFrutFrec;
}
public void setPatConsFrutFrec(String patConsFrutFrec) {
this.patConsFrutFrec = patConsFrutFrec;
}
@Column(name = "patConsRaic", nullable = true, length = 1)
public String getPatConsRaic() {
return patConsRaic;
}
public void setPatConsRaic(String patConsRaic) {
this.patConsRaic = patConsRaic;
}
@Column(name = "patConsRaicFrec", nullable = true, length = 1)
public String getPatConsRaicFrec() {
return patConsRaicFrec;
}
public void setPatConsRaicFrec(String patConsRaicFrec) {
this.patConsRaicFrec = patConsRaicFrec;
}
@Column(name = "patConsMenei", nullable = true, length = 1)
public String getPatConsMenei() {
return patConsMenei;
}
public void setPatConsMenei(String patConsMenei) {
this.patConsMenei = patConsMenei;
}
@Column(name = "patConsMeneiFrec", nullable = true, length = 1)
public String getPatConsMeneiFrec() {
return patConsMeneiFrec;
}
public void setPatConsMeneiFrec(String patConsMeneiFrec) {
this.patConsMeneiFrec = patConsMeneiFrec;
}
@Column(name = "patConsRepollo", nullable = true, length = 1)
public String getPatConsRepollo() {
return patConsRepollo;
}
public void setPatConsRepollo(String patConsRepollo) {
this.patConsRepollo = patConsRepollo;
}
@Column(name = "patConsRepolloFrec", nullable = true, length = 1)
public String getPatConsRepolloFrec() {
return patConsRepolloFrec;
}
public void setPatConsRepolloFrec(String patConsRepolloFrec) {
this.patConsRepolloFrec = patConsRepolloFrec;
}
@Column(name = "patConsZana", nullable = true, length = 1)
public String getPatConsZana() {
return patConsZana;
}
public void setPatConsZana(String patConsZana) {
this.patConsZana = patConsZana;
}
@Column(name = "patConsZanaFrec", nullable = true, length = 1)
public String getPatConsZanaFrec() {
return patConsZanaFrec;
}
public void setPatConsZanaFrec(String patConsZanaFrec) {
this.patConsZanaFrec = patConsZanaFrec;
}
@Column(name = "patConsPinolillo", nullable = true, length = 1)
public String getPatConsPinolillo() {
return patConsPinolillo;
}
public void setPatConsPinolillo(String patConsPinolillo) {
this.patConsPinolillo = patConsPinolillo;
}
@Column(name = "patConsPinolilloFrec", nullable = true, length = 1)
public String getPatConsPinolilloFrec() {
return patConsPinolilloFrec;
}
public void setPatConsPinolilloFrec(String patConsPinolilloFrec) {
this.patConsPinolilloFrec = patConsPinolilloFrec;
}
@Column(name = "patConsOVerd", nullable = true, length = 1)
public String getPatConsOVerd() {
return patConsOVerd;
}
public void setPatConsOVerd(String patConsOVerd) {
this.patConsOVerd = patConsOVerd;
}
@Column(name = "patConsOVerdFrec", nullable = true, length = 1)
public String getPatConsOVerdFrec() {
return patConsOVerdFrec;
}
public void setPatConsOVerdFrec(String patConsOVerdFrec) {
this.patConsOVerdFrec = patConsOVerdFrec;
}
@Column(name = "patConsPesc", nullable = true, length = 1)
public String getPatConsPesc() {
return patConsPesc;
}
public void setPatConsPesc(String patConsPesc) {
this.patConsPesc = patConsPesc;
}
@Column(name = "patConsPescFrec", nullable = true, length = 1)
public String getPatConsPescFrec() {
return patConsPescFrec;
}
public void setPatConsPescFrec(String patConsPescFrec) {
this.patConsPescFrec = patConsPescFrec;
}
@Column(name = "patConsAlimComp", nullable = true, length = 1)
public String getPatConsAlimComp() {
return patConsAlimComp;
}
public void setPatConsAlimComp(String patConsAlimComp) {
this.patConsAlimComp = patConsAlimComp;
}
@Column(name = "patConsAlimCompFrec", nullable = true, length = 1)
public String getPatConsAlimCompFrec() {
return patConsAlimCompFrec;
}
public void setPatConsAlimCompFrec(String patConsAlimCompFrec) {
this.patConsAlimCompFrec = patConsAlimCompFrec;
}
@Column(name = "patConsLecPol", nullable = true, length = 1)
public String getPatConsLecPol() {
return patConsLecPol;
}
public void setPatConsLecPol(String patConsLecPol) {
this.patConsLecPol = patConsLecPol;
}
@Column(name = "patConsLecPolFrec", nullable = true, length = 1)
public String getPatConsLecPolFrec() {
return patConsLecPolFrec;
}
public void setPatConsLecPolFrec(String patConsLecPolFrec) {
this.patConsLecPolFrec = patConsLecPolFrec;
}
@Column(name = "patConsCarCer", nullable = true, length = 1)
public String getPatConsCarCer() {
return patConsCarCer;
}
public void setPatConsCarCer(String patConsCarCer) {
this.patConsCarCer = patConsCarCer;
}
@Column(name = "patConsCarCerFrec", nullable = true, length = 1)
public String getPatConsCarCerFrec() {
return patConsCarCerFrec;
}
public void setPatConsCarCerFrec(String patConsCarCerFrec) {
this.patConsCarCerFrec = patConsCarCerFrec;
}
@Column(name = "patConsEmb", nullable = true, length = 1)
public String getPatConsEmb() {
return patConsEmb;
}
public void setPatConsEmb(String patConsEmb) {
this.patConsEmb = patConsEmb;
}
@Column(name = "patConsEmbFrec", nullable = true, length = 1)
public String getPatConsEmbFrec() {
return patConsEmbFrec;
}
public void setPatConsEmbFrec(String patConsEmbFrec) {
this.patConsEmbFrec = patConsEmbFrec;
}
@Column(name = "patConsMar", nullable = true, length = 1)
public String getPatConsMar() {
return patConsMar;
}
public void setPatConsMar(String patConsMar) {
this.patConsMar = patConsMar;
}
@Column(name = "patConsMarFrec", nullable = true, length = 1)
public String getPatConsMarFrec() {
return patConsMarFrec;
}
public void setPatConsMarFrec(String patConsMarFrec) {
this.patConsMarFrec = patConsMarFrec;
}
@Column(name = "patConsCarCaza", nullable = true, length = 1)
public String getPatConsCarCaza() {
return patConsCarCaza;
}
public void setPatConsCarCaza(String patConsCarCaza) {
this.patConsCarCaza = patConsCarCaza;
}
@Column(name = "patConsCarCazaFrec", nullable = true, length = 1)
public String getPatConsCarCazaFrec() {
return patConsCarCazaFrec;
}
public void setPatConsCarCazaFrec(String patConsCarCazaFrec) {
this.patConsCarCazaFrec = patConsCarCazaFrec;
}
@Override
public boolean isFieldAuditable(String fieldname) {
//Campos no auditables en la tabla
return true;
}
@Override
public String toString(){
return this.codigo;
}
@Override
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof Encuesta))
return false;
Encuesta castOther = (Encuesta) other;
return (this.getIdent().equals(castOther.getIdent()));
}
}
| [
"[email protected]"
]
| |
55eced531f1028eaf858cd8560e055b8bffc37fd | 214ec0c0362c3e9dd67bffae2acff56c2fac60f5 | /app/src/main/java/com/yan/booksearch/MainActivity.java | 3a9378b7ff6a17851e23242d62d00bd45a511c71 | [
"Apache-2.0"
]
| permissive | Go0AT/NovelSearch | 7a42de60536e758ab0eba3f7530c615d3a3b4c58 | eebea1e831f469aa593314810e0c45a18146be72 | refs/heads/master | 2020-04-12T20:14:57.025014 | 2018-12-21T18:50:07 | 2018-12-21T18:50:07 | 162,730,435 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,768 | java | package com.yan.booksearch;
import android.content.Intent;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
private List<Books> booksList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.send_btn);
final EditText sendEdit = (EditText) findViewById(R.id.input_message);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String msg = sendEdit.getText().toString();
HttpUtil.sendHttpRequest(msg, new HttpCallBackListener() {
@Override
public void onFinish(String response) {
booksList = getBooks(response);
}
@Override
public void onError(Exception e) {
}
});
TimerTask task = new TimerTask() {
@Override
public void run() {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
intent.putExtra("extra_data", (Serializable) booksList);
startActivity(intent);
}
};
Timer timer = new Timer();
timer.schedule(task, 3000);
}
});
}
private List<Books> getBooks(String jsonData){
List<Books> booksList = new ArrayList<>();
try{
JSONObject jsonObject = new JSONObject(jsonData);
String string = jsonObject.getString("data");
JSONArray jsonArray = new JSONArray(string);
for(int i = 0;i<jsonArray.length();i++){
Books books = new Books();
books.setName(jsonArray.getString(i));
booksList.add(books);
Log.d("MainActivity",jsonArray.getString(i));
}
} catch (Exception e) {
e.printStackTrace();
}
return booksList;
}
}
| [
"[email protected]"
]
| |
eba2e391e359f238f96b01f622ae4e2c2e6eac27 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/20/20_4f9af87b130811040cc2c021cff39a0ba99841cd/SchoolCoursePackageEditor/20_4f9af87b130811040cc2c021cff39a0ba99841cd_SchoolCoursePackageEditor_t.java | ce21c7204fa118baa4f8108a2dc93ebe1493a6ac | []
| no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 16,005 | java | /*
* $Id: SchoolCoursePackageEditor.java,v 1.3 2005/07/07 09:48:59 laddi Exp $
* Created on Jul 6, 2005
*
* Copyright (C) 2005 Idega Software hf. All Rights Reserved.
*
* This software is the proprietary information of Idega hf.
* Use is subject to license terms.
*/
package se.idega.idegaweb.commune.adulteducation.presentation;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Iterator;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;
import se.idega.idegaweb.commune.adulteducation.data.AdultEducationCourse;
import se.idega.idegaweb.commune.adulteducation.data.SchoolCoursePackage;
import com.idega.block.school.data.SchoolSeason;
import com.idega.block.school.data.SchoolStudyPath;
import com.idega.business.IBORuntimeException;
import com.idega.data.IDORelationshipException;
import com.idega.event.IWPageEventListener;
import com.idega.idegaweb.IWException;
import com.idega.presentation.IWContext;
import com.idega.presentation.Table;
import com.idega.presentation.text.Break;
import com.idega.presentation.text.Link;
import com.idega.presentation.text.Text;
import com.idega.presentation.ui.DropdownMenu;
import com.idega.presentation.ui.Form;
import com.idega.presentation.ui.HiddenInput;
import com.idega.presentation.ui.SubmitButton;
import com.idega.presentation.ui.TextInput;
import com.idega.presentation.ui.util.SelectorUtility;
/**
* Last modified: $Date: 2005/07/07 09:48:59 $ by $Author: laddi $
*
* @author <a href="mailto:[email protected]">laddi</a>
* @version $Revision: 1.3 $
*/
public class SchoolCoursePackageEditor extends AdultEducationBlock implements IWPageEventListener {
private static final String PARAMETER_ACTION = "prm_action";
private static final String PARAMETER_SEASON = "prm_season";
private static final String PARAMETER_SCHOOL = "prm_school";
private static final String PARAMETER_STUDY_PATH_GROUP = "prm_study_path_group";
private static final String PARAMETER_COURSE_SEASON = "prm_course_season";
private static final String PARAMETER_FREE_TEXT = "prm_free_text";
private static final String PARAMETER_SCHOOL_COURSE_PACKAGE = "prm_school_course_package";
private static final String PARAMETER_COURSE = "prm_course";
private static final int ACTION_VIEW = 1;
private static final int ACTION_STORE = 2;
private static final int ACTION_REMOVE_COURSE = 3;
private static final int ACTION_REMOVE = 4;
private static final int ACTION_ACTIVATE = 5;
/* (non-Javadoc)
* @see se.idega.idegaweb.commune.adulteducation.presentation.AdultEducationBlock#present(com.idega.presentation.IWContext)
*/
public void present(IWContext iwc) {
try {
switch (parseAction(iwc)) {
case ACTION_VIEW:
showForm();
break;
case ACTION_STORE:
storePackage(iwc);
showForm();
break;
case ACTION_REMOVE_COURSE:
removeCourse(iwc);
showForm();
break;
case ACTION_REMOVE:
removePackage(iwc);
showForm();
break;
case ACTION_ACTIVATE:
activatePackage(iwc);
showForm();
break;
}
}
catch (RemoteException re) {
throw new IBORuntimeException(re);
}
}
private void showForm() throws RemoteException {
Form form = new Form();
form.setEventListener(SchoolCoursePackageEditor.class);
form.addParameter(PARAMETER_ACTION, ACTION_VIEW);
SchoolCoursePackage schoolPackage = null;
if (getSession().getChosenSchool() != null && getSession().getSchoolSeason() != null && getSession().getCoursePackage() != null) {
try {
schoolPackage = getBusiness().getSchoolCoursePackage(getSession().getChosenSchool(), getSession().getSchoolSeason(), getSession().getCoursePackage());
}
catch (FinderException fe) {
//No school package available.
}
}
form.add(getNavigation(schoolPackage));
form.add(new Break());
if (schoolPackage != null) {
form.add(new HiddenInput(PARAMETER_SCHOOL_COURSE_PACKAGE, schoolPackage.getPrimaryKey().toString()));
form.add(getText(localize("courses_connected_to_package", "Courses connected to package") + ": "));
form.add(getHeader(getSession().getCoursePackage().getName()));
if (schoolPackage.getFreeText() != null) {
form.add(getHeader(" - " + schoolPackage.getFreeText()));
}
form.add(new Break());
form.add(getConnectedCourses(schoolPackage));
form.add(new Break());
if (!schoolPackage.isActive()) {
SubmitButton removePackage = (SubmitButton) getButton(new SubmitButton(localize("remove_package", "Remove package")));
SubmitButton activatePackage = (SubmitButton) getButton(new SubmitButton(localize("activate_package", "Activate package")));
form.add(removePackage);
form.add(Text.getNonBrakingSpace());
form.add(activatePackage);
form.add(new Break());
removePackage.setValueOnClick(PARAMETER_ACTION, String.valueOf(ACTION_REMOVE));
removePackage.setSubmitConfirm(localize("remove_package_confirm", "Are you sure you want to remove this package?"));
activatePackage.setValueOnClick(PARAMETER_ACTION, String.valueOf(ACTION_ACTIVATE));
activatePackage.setSubmitConfirm(localize("activate_package_confirm", "Are you sure you want to activate this package?"));
}
}
form.add(getHeader(localize("select_courses_to_connect_to_package", "Select courses to connect to package")));
form.add(new Break());
form.add(getCourseNavigation());
form.add(new Break());
form.add(getCourses(schoolPackage));
form.add(new Break());
if (getSession().getChosenSchool() != null && getSession().getSchoolSeason() != null && getSession().getCoursePackage() != null) {
SubmitButton save = (SubmitButton) getButton(new SubmitButton(localize("store_package", "Store package")));
save.setValueOnClick(PARAMETER_ACTION, String.valueOf(ACTION_STORE));
form.add(save);
}
add(form);
}
private Table getNavigation(SchoolCoursePackage schoolPackage) throws RemoteException {
Table table = new Table(4, 3);
table.setCellpadding(3);
table.setCellspacing(0);
table.setWidth(Table.HUNDRED_PERCENT);
SelectorUtility util = new SelectorUtility();
DropdownMenu seasons = (DropdownMenu) getStyledInterface(util.getSelectorFromIDOEntities(new DropdownMenu(PARAMETER_SEASON), getBusiness().getSeasons(), "getSeasonName"));
if (getSession().getSchoolSeason() != null) {
seasons.setSelectedElement(getSession().getSchoolSeason().getPrimaryKey().toString());
}
seasons.setToSubmit();
DropdownMenu schools = (DropdownMenu) getStyledInterface(util.getSelectorFromIDOEntities(new DropdownMenu(PARAMETER_SCHOOL), getBusiness().getSchools(), "getSchoolName"));
schools.addMenuElementFirst("", localize("select_school", "Select school"));
if (getSession().getChosenSchool() != null) {
schools.setSelectedElement(getSession().getChosenSchool().getPrimaryKey().toString());
}
schools.setToSubmit();
DropdownMenu coursePackages = (DropdownMenu) getStyledInterface(util.getSelectorFromIDOEntities(new DropdownMenu(PARAMETER_COURSE_PACKAGE), getBusiness().getCoursePackages(), "getName"));
coursePackages.addMenuElementFirst("", localize("select_course_package", "Select course package"));
if (getSession().getCoursePackage() != null) {
coursePackages.setSelectedElement(getSession().getCoursePackage().getPrimaryKey().toString());
}
coursePackages.setToSubmit();
TextInput freeText = (TextInput) getStyledInterface(new TextInput(PARAMETER_FREE_TEXT));
if (schoolPackage != null && schoolPackage.getFreeText() != null) {
freeText.setContent(schoolPackage.getFreeText());
}
table.add(getHeader(localize("school", "School") + ":"), 1, 1);
table.add(schools, 2, 1);
table.add(getHeader(localize("course_package", "Course package") + ":"), 3, 1);
table.add(coursePackages, 4, 1);
table.add(getHeader(localize("school_season", "Season") + ":"), 1, 3);
table.add(seasons, 2, 3);
table.add(getHeader(localize("package_name", "Package name") + ":"), 3, 3);
table.add(freeText, 4, 3);
return table;
}
private Table getConnectedCourses(SchoolCoursePackage schoolPackage) {
Table table = new Table();
table.setCellpadding(getCellpadding());
table.setCellspacing(getCellspacing());
table.setColumns(35);
table.setWidth(Table.HUNDRED_PERCENT);
table.setRowColor(1, getHeaderColor());
int column = 1;
int row = 1;
table.add(getLocalizedSmallHeader("nr", "Nr"), column++, row++);
table.add(getLocalizedSmallHeader("study_path", "Study path"), column++, row);
table.add(getLocalizedSmallHeader("code", "Code"), column++, row);
table.add(getLocalizedSmallHeader("period", "Period"), column++, row++);
if (schoolPackage != null) {
try {
Collection courses = schoolPackage.getCourses();
Iterator iter = courses.iterator();
while (iter.hasNext()) {
column = 1;
AdultEducationCourse course = (AdultEducationCourse) iter.next();
SchoolStudyPath path = course.getStudyPath();
SchoolSeason season = course.getSchoolSeason();
table.add(getSmallText(String.valueOf(row - 1)), column++, row);
table.add(getSmallText(path.getDescription()), column++, row);
table.add(getSmallText(course.getCode()), column++, row);
table.add(getSmallText(season.getSchoolSeasonName()), column++, row);
if (!schoolPackage.isActive()) {
Link remove = new Link(getDeleteIcon(localize("remove_course_from_package", "Remove course from package")));
remove.addParameter(PARAMETER_ACTION, ACTION_REMOVE_COURSE);
remove.addParameter(PARAMETER_COURSE, course.getPrimaryKey().toString());
remove.addParameter(PARAMETER_SCHOOL_COURSE_PACKAGE, schoolPackage.getPrimaryKey().toString());
table.add(remove, column++, row);
}
row++;
}
}
catch (IDORelationshipException ire) {
ire.printStackTrace();
}
}
table.setWidth(1, 12);
table.setWidth(5, 12);
return table;
}
private Table getCourses(SchoolCoursePackage schoolPackage) throws RemoteException {
Table table = new Table();
table.setCellpadding(getCellpadding());
table.setCellspacing(getCellspacing());
table.setColumns(3);
table.setWidth(Table.HUNDRED_PERCENT);
table.setRowColor(1, getHeaderColor());
int column = 1;
int row = 1;
table.add(getLocalizedSmallHeader("study_path", "Study path"), column++, row);
table.add(getLocalizedSmallHeader("code", "Code"), column++, row++);
if (getSession().getChosenSchool() != null && getSession().getCourseSeason() != null && getSession().getStudyPathGroup() != null) {
Collection courses = getBusiness().getCourses(getSession().getChosenSchool().getPrimaryKey(), getSession().getCourseSeason().getPrimaryKey(), getSession().getStudyPathGroup().getPrimaryKey());
if (schoolPackage != null) {
try {
Collection connectedCourses = schoolPackage.getCourses();
courses.removeAll(connectedCourses);
}
catch (IDORelationshipException ire) {
ire.printStackTrace();
}
}
Iterator iter = courses.iterator();
while (iter.hasNext()) {
column = 1;
AdultEducationCourse course = (AdultEducationCourse) iter.next();
SchoolStudyPath path = course.getStudyPath();
table.add(getSmallText(path.getDescription()), column++, row);
table.add(getSmallText(course.getCode()), column++, row);
table.add(getCheckBox(PARAMETER_COURSE, course.getPrimaryKey().toString()), column++, row++);
}
}
table.setWidth(3, 12);
return table;
}
private Table getCourseNavigation() throws RemoteException {
Table table = new Table(4, 1);
table.setCellpadding(3);
table.setCellspacing(0);
table.setWidth(Table.HUNDRED_PERCENT);
SelectorUtility util = new SelectorUtility();
DropdownMenu groups = (DropdownMenu) getStyledInterface(util.getSelectorFromIDOEntities(new DropdownMenu(PARAMETER_STUDY_PATH_GROUP), getBusiness().getStudyPathsGroups(), "getLocalizationKey", getResourceBundle()));
groups.addMenuElementFirst("", localize("select_study_path_group", "Select group"));
if (getSession().getStudyPathGroup() != null) {
groups.setSelectedElement(getSession().getStudyPathGroup().getPrimaryKey().toString());
}
groups.setToSubmit();
DropdownMenu seasons = (DropdownMenu) getStyledInterface(new DropdownMenu(PARAMETER_COURSE_SEASON));
seasons.addMenuElementFirst("", localize("select_school_season", "Select season"));
if (getSession().getSchoolSeason() != null) {
Collection nextSeasons = getBusiness().getNextSeasons(getSession().getSchoolSeason());
Iterator iter = nextSeasons.iterator();
while (iter.hasNext()) {
SchoolSeason season = (SchoolSeason) iter.next();
seasons.addMenuElement(season.getPrimaryKey().toString(), season.getSchoolSeasonName());
}
}
seasons.setToSubmit();
table.add(getHeader(localize("study_path_group", "Study path group") + ":"), 1, 1);
table.add(groups, 2, 1);
table.add(getHeader(localize("school_season", "Season") + ":"), 3, 1);
table.add(seasons, 4, 1);
return table;
}
private void storePackage(IWContext iwc) throws RemoteException {
try {
getBusiness().storeSchoolPackage(getSession().getCoursePackage(), getSession().getChosenSchool(), getSession().getSchoolSeason(), iwc.getParameter(PARAMETER_FREE_TEXT), iwc.getParameterValues(PARAMETER_COURSE));
}
catch (CreateException ce) {
ce.printStackTrace();
}
}
private void activatePackage(IWContext iwc) throws RemoteException {
getBusiness().activatePackage(iwc.getParameter(PARAMETER_SCHOOL_COURSE_PACKAGE));
}
private void removePackage(IWContext iwc) throws RemoteException {
try {
getBusiness().removeSchoolPackage(iwc.getParameter(PARAMETER_SCHOOL_COURSE_PACKAGE));
}
catch (RemoveException re) {
re.printStackTrace();
}
}
private void removeCourse(IWContext iwc) throws RemoteException {
getBusiness().removeCourseFromPackage(iwc.getParameter(PARAMETER_SCHOOL_COURSE_PACKAGE), iwc.getParameter(PARAMETER_COURSE));
}
private int parseAction(IWContext iwc) {
int action = ACTION_VIEW;
if (iwc.isParameterSet(PARAMETER_ACTION)) {
action = Integer.parseInt(iwc.getParameter(PARAMETER_ACTION));
}
return action;
}
public boolean actionPerformed(IWContext iwc) throws IWException {
boolean actionPerformed = false;
if (iwc.isParameterSet(PARAMETER_SEASON)) {
try {
getSession(iwc).setSeason(iwc.getParameter(PARAMETER_SEASON));
actionPerformed = true;
}
catch (RemoteException re) {
throw new IBORuntimeException(re);
}
}
if (iwc.isParameterSet(PARAMETER_SCHOOL)) {
try {
getSession(iwc).setChosenSchool(iwc.getParameter(PARAMETER_SCHOOL));
actionPerformed = true;
}
catch (RemoteException re) {
throw new IBORuntimeException(re);
}
}
if (iwc.isParameterSet(PARAMETER_STUDY_PATH_GROUP)) {
try {
getSession(iwc).setStudyPathGroup(iwc.getParameter(PARAMETER_STUDY_PATH_GROUP));
actionPerformed = true;
}
catch (RemoteException re) {
throw new IBORuntimeException(re);
}
}
if (iwc.isParameterSet(PARAMETER_COURSE_PACKAGE)) {
try {
getSession(iwc).setCoursePackage(iwc.getParameter(PARAMETER_COURSE_PACKAGE));
actionPerformed = true;
}
catch (RemoteException re) {
throw new IBORuntimeException(re);
}
}
if (iwc.isParameterSet(PARAMETER_COURSE_SEASON)) {
try {
getSession(iwc).setCourseSeason(iwc.getParameter(PARAMETER_COURSE_SEASON));
actionPerformed = true;
}
catch (RemoteException re) {
throw new IBORuntimeException(re);
}
}
return actionPerformed;
}
}
| [
"[email protected]"
]
| |
32705289a2c79fda7741ea791ef2592d360874c2 | eb9f655206c43c12b497c667ba56a0d358b6bc3a | /java/java-tests/testData/inspection/invokeHandleSignature/Getter.java | 743af3af10841d933917061f37d49404564c8171 | [
"Apache-2.0"
]
| permissive | JetBrains/intellij-community | 2ed226e200ecc17c037dcddd4a006de56cd43941 | 05dbd4575d01a213f3f4d69aa4968473f2536142 | refs/heads/master | 2023-09-03T17:06:37.560889 | 2023-09-03T11:51:00 | 2023-09-03T12:12:27 | 2,489,216 | 16,288 | 6,635 | Apache-2.0 | 2023-09-12T07:41:58 | 2011-09-30T13:33:05 | null | UTF-8 | Java | false | false | 2,337 | java | import java.lang.invoke.*;
import java.util.*;
class Main {
void foo() throws Exception {
MethodHandles.Lookup l = MethodHandles.lookup();
l.findGetter(Test.class, "myInt", int.class);
l.findGetter(Test.class, "myInts", int[].class);
l.findGetter(Test.class, "myList", List.class);
l.findGetter(Test.class, "myLists", List[].class);
l.findGetter(Test.class, "myString", String.class);
l.findStaticGetter(Test.class, "ourInt", int.class);
l.findStaticGetter(Test.class, "ourInts", int[].class);
l.findStaticGetter(Test.class, "ourList", List.class);
l.findStaticGetter(Test.class, "ourLists", List[].class);
l.findStaticGetter(Test.class, "ourString", String.class);
l.findGetter(Test.class, <warning descr="Cannot resolve field 'doesntExist'">"doesntExist"</warning>, String.class);
l.findStaticGetter(Test.class, <warning descr="Cannot resolve field 'doesntExist'">"doesntExist"</warning>, String.class);
l.findGetter(Test.class, "myInt", <warning descr="The type of field 'myInt' is 'int'">void.class</warning>);
l.findGetter(Test.class, "myInts", <warning descr="The type of field 'myInts' is 'int[]'">int.class</warning>);
l.findGetter(Test.class, "myString", <warning descr="The type of field 'myString' is 'java.lang.String'">List.class</warning>);
l.findStaticGetter(Test.class, "ourInt", <warning descr="The type of field 'ourInt' is 'int'">void.class</warning>);
l.findStaticGetter(Test.class, "ourInts", <warning descr="The type of field 'ourInts' is 'int[]'">int.class</warning>);
l.findStaticGetter(Test.class, "ourString", <warning descr="The type of field 'ourString' is 'java.lang.String'">List.class</warning>);
l.<warning descr="Field 'ourString' is static">findGetter</warning>(Test.class, "ourString", String.class);
l.<warning descr="Field 'myString' is not static">findStaticGetter</warning>(Test.class, "myString", String.class);
}
}
class Test {
public int myInt;
public String myString;
public int[] myInts;
public List<String> myList;
@SuppressWarnings("unchecked")
public List<String>[] myLists;
public static int ourInt;
public static String ourString;
public static int[] ourInts;
public static List<String> ourList;
@SuppressWarnings("unchecked")
public static List<String>[] ourLists;
} | [
"[email protected]"
]
| |
d14d1eac357cc86dce782be85a1081fc3b4dc393 | 930dd40fe6056610106935f63c508ab51e5b2034 | /zapp-cache/src/test/java/com/zfoo/app/zapp/cache/ApplicationTest.java | 7b140554f36ac0a0a5070c6fbc183b7c66ba20af | [
"Apache-2.0"
]
| permissive | qzmfreedom/zapp | bcd8f8dacd226720c83e7c2da8244f959b175a50 | da51773447545fce1f9949b014bcf827065ba66e | refs/heads/main | 2023-08-25T02:33:51.732215 | 2021-10-20T09:55:38 | 2021-10-20T09:55:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,071 | java | /*
* Copyright (C) 2020 The zfoo Authors
*
* 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.zfoo.app.zapp.cache;
import com.zfoo.app.zapp.common.constant.ZappDeployEnum;
import com.zfoo.util.ThreadUtils;
import org.junit.Ignore;
import org.junit.Test;
/**
* @author jaysunxiao
* @version 1.0
* @since 2019-11-08 10:53
*/
@Ignore
public class ApplicationTest {
static {
ZappDeployEnum.initDevDeploy();
}
@Test
public void startApplication() {
Application.main(null);
ThreadUtils.sleep(Long.MAX_VALUE);
}
}
| [
"[email protected]"
]
| |
95114cdbb73b80e834970acc405d55e0be9d016a | f7714fd0f3c8a271f0a2f285dd98667ec64e2f3e | /src/main/java/com/annotation/dao/DtuCommentMapper.java | 31b56b6214fcb2ac71986f53b720231b1035ddca | []
| no_license | RyanXu0-0/textannotion | b4c9596067c1a090dbba01c8a1f19c6ef34287b8 | a63a47672e40c3c103da58827ab0ad663ed56ae5 | refs/heads/master | 2022-06-30T05:37:28.965570 | 2020-05-14T08:38:56 | 2020-05-14T08:38:56 | 191,073,087 | 2 | 1 | null | 2022-06-29T17:25:54 | 2019-06-10T01:06:15 | TSQL | UTF-8 | Java | false | false | 564 | java | package com.annotation.dao;
import com.annotation.model.DtuComment;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface DtuCommentMapper {
int deleteByPrimaryKey(Integer dtuId);
int deleteByDtdIdAndUId(@Param("dtdId")Integer dtdId,
@Param("uId")Integer uId);
int insert(DtuComment record);
DtuComment selectByPrimaryKey(Integer dtuId);
List<DtuComment> selectAll();
int updateByPrimaryKey(DtuComment record);
} | [
"[email protected]"
]
| |
25825edbbb7fb2fe696e3679fe0adb36bac3197f | 27c4babc1a6b83e7e98e1c1ac6785d0c09ff3350 | /src/com/briup/woss/BIDR.java | b1121d8307ff7d42caea61041c98ac976923c444 | []
| no_license | shihua-guo/SimpleWoss | c6b67fdf072dbc97d46733b7078391d627833129 | 0811c9977cbb27fe44fbc1c8b7a26ea2d3f675eb | refs/heads/master | 2020-06-17T06:53:41.287761 | 2016-11-29T02:19:20 | 2016-11-29T02:19:20 | 75,031,919 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 659 | java | package com.briup.woss;
import java.io.Serializable;
public class BIDR implements Serializable {
//属性
String AAA_login_name;//登陆名
String login_ip;//登陆IP
String login_date;//登陆时间
String logout_date;//登出时间
String NAS_ip;//NAS IP =null
long time_duration;//在线时间
public BIDR(){}
public BIDR(String AAA_login_name,String login_ip, String login_date,
String logout_date,long time_duration){
this.AAA_login_name = AAA_login_name;
this.login_ip = login_ip;
this.login_date = login_date;
this.logout_date =logout_date;
this.NAS_ip = null;
this.time_duration = time_duration;
}
}
| [
"[email protected]"
]
| |
9c8f6d5cb2f36493c10759e3a759f8caef302d0a | fa15d65898f3f74d31bff06db1be5fd3cda9ccc9 | /LibUpdater/src/main/java/dy/utils/libupdater/notice/VersionNotice.java | 4719c305f31e1445548bc67e77b1fb1368e9381d | []
| no_license | dy60420667/DUtils | 1db41367413ce2449baa19dd8b18c5a2a242bafb | 8f64233a38a1745b9248f09e31b0dbde39c9c0a6 | refs/heads/master | 2020-04-06T04:27:14.545885 | 2018-03-07T04:42:10 | 2018-03-07T04:42:10 | 82,897,208 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,881 | java | package dy.utils.libupdater.notice;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.text.SpannableString;
import android.widget.RemoteViews;
import dy.utils.libupdater.R;
import dy.utils.libupdater.bean.VersionBean;
import dy.utils.libupdater.download.DownloadManager;
import dy.utils.libupdater.download.utils.IDownloadListener;
import dy.utils.libupdater.utils.ToolSpan;
import dy.utils.libupdater.utils.ToolUtils;
/**
* Created by dy on 2016/5/5.
*/
public class VersionNotice implements IDownloadListener {
private Context context;
private VersionNotice() {
}
private static volatile VersionNotice instance;
public static VersionNotice getInstance() {
if (instance == null) {
synchronized (VersionNotice.class) {
if (instance == null) {
instance = new VersionNotice();
}
}
}
return instance;
}
private static final int NOTIFY_ID = 0;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder builder;
private RemoteViews contentView;
private VersionBean bean;
public void clearNotification(Context context) {
if(mNotificationManager==null){
mNotificationManager = (NotificationManager) context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
}
if (mNotificationManager != null) {
mNotificationManager.cancel(NOTIFY_ID);
}
}
/**
* 创建通知
*/
public void setUpNotification(Context context, VersionBean bean) {
this.context = context;
this.bean = bean;
mNotificationManager = (NotificationManager) context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
if (builder == null) {
contentView = new RemoteViews(context.getPackageName(), R.layout.download_notification_layout);
contentView.setImageViewResource(R.id.image_tips,context.getApplicationInfo().icon);
builder = new NotificationCompat.Builder(context);
builder.setContent(contentView)
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_DEFAULT)
.setSmallIcon(context.getApplicationInfo().icon)
.setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
.setOngoing(true);// ture,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
try{
changeSmallIcon(context,builder);
}catch (Exception e){
e.printStackTrace();
}
}
contentView.setTextViewText(R.id.name, ToolUtils.getAppname(context));
contentView.setTextViewText(R.id.tv_progress, context.getString(R.string.updater_loading));
builder.setOngoing(true);
Notification notification = builder.build();
contentView.setOnClickPendingIntent(R.id.layout_root, getContentIntent("0"));
mNotificationManager.notify(NOTIFY_ID, notification);
DownloadManager.getDownloadManager().register(this);
}
private void changeSmallIcon(Context context, NotificationCompat.Builder builder) {
if(bean==null){
return;
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH ){
if(bean.getIcon_small_drawable_5_0()!=0){
//5.0以上系统采用纸片化图片
builder.setSmallIcon(bean.getIcon_small_drawable_5_0());
}else{
builder.setSmallIcon(context.getApplicationInfo().icon);
}
}else {
builder.setSmallIcon(context.getApplicationInfo().icon);
}
}
@Override
public void onDownloadSize(long offsize, long size, String speed) {
try {
contentView.setTextViewText(R.id.name, ToolUtils.getAppname(context));
contentView.setImageViewResource(R.id.image_tips,context.getApplicationInfo().icon);
contentView.setTextViewText(R.id.tv_progress, ToolUtils.getSize(offsize) + "/" + ToolUtils.getSize(size));
contentView.setProgressBar(R.id.progressbar, (int) size, (int) offsize, false);
builder.setOngoing(true);
Notification notification = builder.build();
mNotificationManager.notify(NOTIFY_ID, notification);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onComplete() {
try {
mNotificationManager.cancel(NOTIFY_ID);
} catch (Exception e) {
e.printStackTrace();
}
DownloadManager.getDownloadManager().unRegister(this);
}
@Override
public void onError(String error) {
try {
String name = ToolUtils.getAppname(context);
SpannableString sb = new SpannableString(name + "(" + error + ")");
sb = ToolSpan.addForeColorSpan(sb, name.length(), sb.length(), ContextCompat.getColor(context,R.color.updater_color_item_normal));
builder.setOngoing(false);
contentView.setOnClickPendingIntent(R.id.layout_root, getContentIntent("1"));
contentView.setImageViewResource(R.id.image_tips,context.getApplicationInfo().icon);
contentView.setTextViewText(R.id.name, sb);
contentView.setTextViewText(R.id.tv_progress, "");
Notification notification = builder.build();
mNotificationManager.notify(NOTIFY_ID, notification);
} catch (Exception e) {
e.printStackTrace();
}
DownloadManager.getDownloadManager().unRegister(this);
}
@Override
public void onCancle() {
try {
mNotificationManager.cancel(NOTIFY_ID);
} catch (Exception e) {
e.printStackTrace();
}
DownloadManager.getDownloadManager().unRegister(this);
}
//1点击重试.0表示下载中
private PendingIntent getContentIntent(String isTips) {
Intent intent = new Intent(context, NotificationClickReceiver.class);
intent.putExtra("bean", bean);
intent.putExtra("tip", isTips);
PendingIntent contentIntent = PendingIntent.getBroadcast(context, (int) (System.currentTimeMillis() / 1000), intent, PendingIntent.FLAG_CANCEL_CURRENT);
return contentIntent;
}
}
| [
"[email protected]"
]
| |
b65ec93929b6a2405850613799fba1644746284e | bd009005a3ccfb5e4f2afb96c68acd14595aaab8 | /app/src/main/java/com/leichui/shortviedeo/Fragment/MyBFragment.java | 668746ad798e78aaca0369e825a61f4b1088bb0a | [
"Apache-2.0"
]
| permissive | kknet/VideoChat | 90e61addca8db1aa5afcf6a594008aaece1cf458 | 8f8f69b200886d4b6671bcc0b2eb11a5343fd7fd | refs/heads/master | 2022-12-09T03:13:22.228023 | 2020-09-18T09:23:18 | 2020-09-18T09:23:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 709 | java | package com.leichui.shortviedeo.Fragment;
import android.os.Bundle;
import com.yiw.circledemo.adapter.CircleAdapter;
public class MyBFragment extends BFragment {
public static MyBFragment newInstance(String userId) {
MyBFragment newFragment = new MyBFragment();
Bundle bundle = new Bundle();
bundle.putString("userId", userId);
newFragment.setArguments(bundle);
return newFragment;
}
protected void myBMethod(){
isMyBFragment = true;
userId = getActivity().getIntent().getStringExtra("userId");
BFragment_HEADVIEW_SIZE = 0;
}
public void createAdapter(){
mAdapter = new CircleAdapter(getContext(),0);
}
}
| [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.