blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
12722c37ce8b8dd0af25c2e4a4b9206c971e2fe8
Java
huannd0101/Android_HIT_2021
/MiniAppMusic/app/src/main/java/com/example/miniappmusic/MainActivity.java
UTF-8
8,915
2.109375
2
[]
no_license
package com.example.miniappmusic; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { TextView tvTitle, tvTime, tvSum, listSong; ImageButton rewind, play, stop, forward; SeekBar sb; List<Song> songList; int position = 0; MediaPlayer mediaPlayer; ImageView imgView; Animation animation, animationTitle; int REQUEST_CODE = 123; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar actionBar = getSupportActionBar(); actionBar.hide(); AnhXa(); animation = AnimationUtils.loadAnimation(this, R.anim.disc_rotate); imgView.startAnimation(animation); // animationTitle = AnimationUtils.loadAnimation(this, R.anim.name_of_song); // tvTitle.startAnimation(animationTitle); AddSong(); mediaPlayer = MediaPlayer.create(MainActivity.this, songList.get(position).getFile()); tvTitle.setText(songList.get(position).getTitle()); SetTimeTotal(); // KhoiTaoMediaPlayer(); // UpdateTimeSong(); listSong.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, ListSong.class); startActivityForResult(intent, REQUEST_CODE); } }); play.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mediaPlayer.isPlaying()){ mediaPlayer.pause(); play.setImageResource(R.drawable.play); }else { mediaPlayer.start(); play.setImageResource(R.drawable.pause); } UpdateTimeSong(); } }); stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mediaPlayer.stop(); play.setImageResource(R.drawable.play); KhoiTaoMediaPlayer(); SetTimeTotal(); } }); rewind.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mediaPlayer.isPlaying()) mediaPlayer.stop(); if(position != 0){ position--; }else { position = songList.size() - 1; } KhoiTaoMediaPlayer(); mediaPlayer.start(); play.setImageResource(R.drawable.pause); SetTimeTotal(); UpdateTimeSong(); } }); forward.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mediaPlayer.isPlaying()) mediaPlayer.stop(); if (position == songList.size() - 1){ position = 0; }else { position++; } KhoiTaoMediaPlayer(); mediaPlayer.start(); play.setImageResource(R.drawable.pause); SetTimeTotal(); UpdateTimeSong(); } }); sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { //trường hợp này cho dừng lại kéo thả thì mới cập nhập mediaPlayer.seekTo(sb.getProgress()); } }); } private void UpdateTimeSong(){ Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss"); tvTime.setText(simpleDateFormat.format(mediaPlayer.getCurrentPosition())); //update sb sb.setProgress(mediaPlayer.getCurrentPosition()); //ktra khi hết thì chuyển bài mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { //code của chuyển bài if(mediaPlayer.isPlaying()) mediaPlayer.stop(); if (position == songList.size() - 1){ position = 0; }else { position++; } KhoiTaoMediaPlayer(); mediaPlayer.start(); play.setImageResource(R.drawable.pause); SetTimeTotal(); UpdateTimeSong(); } }); //gọi lại k ngừng handler.postDelayed(this, 500); } }, 100); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null){ int fileSong = data.getIntExtra("fileSong", 0); Song song = new Song(); for(Song i : songList){ if(i.getFile() == fileSong){ song = i; break; } } if (mediaPlayer.isPlaying()) mediaPlayer.stop(); mediaPlayer = MediaPlayer.create(MainActivity.this, song.getFile()); tvTitle.setText(song.getTitle()); SetTimeTotal(); UpdateTimeSong(); }else { Toast.makeText(this, "Lỗi", Toast.LENGTH_SHORT).show(); } super.onActivityResult(requestCode, resultCode, data); } private void SetTimeTotal(){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss"); tvSum.setText(simpleDateFormat.format(mediaPlayer.getDuration())); sb.setMax(mediaPlayer.getDuration()); //gán thanh seekbar bằng thời gian của bài hát tvTime.setText(simpleDateFormat.format(mediaPlayer.getCurrentPosition())); } private void KhoiTaoMediaPlayer(){ mediaPlayer = MediaPlayer.create(MainActivity.this, songList.get(position).getFile()); tvTitle.setText(songList.get(position).getTitle()); } private void AddSong(){ songList = new ArrayList<>(); songList.add(new Song("Đôi ta", R.raw.doi_ta)); songList.add(new Song("Chỉ muốn bên em lúc này", R.raw.chi_muon_ben_em_luc_nay)); songList.add(new Song("Anh sẽ không đổi thay", R.raw.anh_se_khong_doi_thay)); songList.add(new Song("Níu Duyên", R.raw.niu_duyen)); songList.add(new Song("Không phải em đúng không", R.raw.khong_phai_em_dung_khong)); songList.add(new Song("Lời xin lỗi vụng về", R.raw.loi_xin_loi_vung_ve)); songList.add(new Song("Điều anh biết", R.raw.dieu_anh_biet)); songList.add(new Song("Kẹo bông gòn", R.raw.keo_bong_gon)); songList.add(new Song("Làm vợ anh nhé", R.raw.lam_vo_anh_nhe)); songList.add(new Song("1 2 3 4 - Chi Dân", R.raw.mot_hai_ba_bon)); songList.add(new Song("Níu Duyên", R.raw.niu_duyen)); } private void AnhXa(){ sb = findViewById(R.id.sb); tvTitle = findViewById(R.id.tvTitle); rewind = findViewById(R.id.rewind); play = findViewById(R.id.play); stop = findViewById(R.id.stop); forward = findViewById(R.id.forward); tvTime = findViewById(R.id.tvTime); tvSum = findViewById(R.id.tvSum); imgView = findViewById(R.id.imgView); listSong = findViewById(R.id.listSong); } }
true
58db08eac30e149511580cb5cf779bc558c6981d
Java
trysivaprakash/SampleSpringBoot
/src/main/java/com/myorg/perfmotor/controller/PerfMotorRouter.java
UTF-8
11,333
1.773438
2
[]
no_license
package com.myorg.perfmotor.controller; import com.myorg.perfmotor.beans.PerfMotorExecVars; import com.myorg.perfmotor.beans.ServiceDetails; import com.myorg.perfmotor.gatling.PerfMotorEnvHolder; import com.myorg.perfmotor.util.Assister; import com.myorg.perfmotor.util.PerfMotorException; import io.gatling.app.Gatling; import io.gatling.core.config.GatlingPropertiesBuilder; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.ResourceBundle; import java.util.concurrent.CompletableFuture; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.json.JSONObject; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class PerfMotorRouter { private final String reportPath = System.getProperty("user.dir") + "/src/main/webapp/resources"; //private final String simulationClass = "com.myorg.perfmotor.gatling.PerfMotorSimulation"; private final String dataDirectory = System.getProperty("user.dir") + "/src/main/webapp/data"; @RequestMapping(value = "/runPerfMotor", method = RequestMethod.POST) @ResponseBody public synchronized String runPerformanceTest(@RequestBody String message, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws PerfMotorException { try { FileUtils.deleteDirectory(new File(reportPath)); } catch (IOException e) { throw new PerfMotorException("Exception while deleting existing report file", e); } System.out.println(">>>>>>> received message : " + message); JSONObject jsonMessage = new JSONObject(message); System.out.println("httpMethod from the jsonObject : "+jsonMessage.getString("method")); System.out.println("url from the jsonObject : "+jsonMessage.getString("url")); System.out.println("nbrOfReq from the jsonObject : "+jsonMessage.getString("nbrOfReq")); System.out.println("nbrOfLoops from the jsonObject : "+jsonMessage.getString("nbrOfLoops")); //System.out.println("bodyPart from the jsonObject : "+jsonMessage.getString("body")); //System.out.println("fileContent from the jsonObject : "+jsonMessage.getBoolean("fileContent")); //System.out.println("fileContent from the jsonObject : "+jsonMessage.getBoolean("fileContent")); String baseUrl = "http://localhost:8082/ford/cars"; String endPointUrl = jsonMessage.getString("url"); String httpMethod = jsonMessage.getString("method"); int loopCount = Integer.parseInt(jsonMessage.getString("nbrOfLoops")); int requestNumber = Integer.parseInt(jsonMessage.getString("nbrOfReq")); String contentType = "application/json"; String feederDataFileName = dataDirectory + "/dataNew.csv"; //String jsonBody = "{\"content\":\"${carName}\"}"; // to test passing a reference in the json body String jsonBody = null; try { jsonBody = jsonMessage.getString("body"); System.out.println("nbrOfLoops from the jsonObject : "+jsonBody); }catch(Exception exception) { } try { System.out.println(">>>>>>>>> decoded url : "+URLDecoder.decode(endPointUrl, StandardCharsets.UTF_8.toString())); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block System.out.println(">>>>>>>>> decoded url faild "); //e.printStackTrace(); } PerfMotorExecVars perfMotorExecVars = new PerfMotorExecVars(); if(jsonMessage.get("fileContent") instanceof String){ writeDataToFile(jsonMessage); PerfMotorEnvHolder.dataDirectory_$eq(feederDataFileName); } else { PerfMotorEnvHolder.dataDirectory_$eq("defaultDataPath.csv"); } String simulationClass = "com.myorg.perfmotor.gatling.PerfMotorSimulation"; GatlingPropertiesBuilder props = new GatlingPropertiesBuilder(); props.simulationClass(simulationClass); props.resultsDirectory(reportPath); props.dataDirectory(dataDirectory); System.out.println(">>>>>>dat dir "+dataDirectory); //PerfMotorExecVars perfMotorExecVars = new PerfMotorExecVars(); perfMotorExecVars.setBaseUrl(baseUrl); perfMotorExecVars.setMaxRespTime(50); perfMotorExecVars.setRequestName("Sample Request Name"); perfMotorExecVars.setScenarioName("Sample Scenario Name"); try { PerfMotorEnvHolder.baseUrl_$eq(URLDecoder.decode(endPointUrl, StandardCharsets.UTF_8.toString())); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } PerfMotorEnvHolder.maxRespTime_$eq(500); PerfMotorEnvHolder.requestName_$eq("Sample_req"); PerfMotorEnvHolder.scenarioName_$eq("sample scen"); PerfMotorEnvHolder.loopCount_$eq(loopCount); PerfMotorEnvHolder.rampUp_$eq(requestNumber); PerfMotorEnvHolder.token_$eq("beare "+httpServletRequest.getHeader("Authorization")); // PerfMotorEnvHolder.dataDirectory_$eq(feederDataFileName); PerfMotorEnvHolder.httpMethod_$eq(httpMethod); PerfMotorEnvHolder.test_$eq(jsonBody); executeRun(props); perfMotorExecVars = null; File file = new File(System.getProperty("user.dir") + "/src/main/webapp/resources"); String[] listOfSubfolders = file.list(); String actualReportFolder = listOfSubfolders[0]; System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>... Actual report folder name: "+actualReportFolder); return "resources/" + actualReportFolder + "/index.html"; } @RequestMapping(method = RequestMethod.GET, value = "/perfMotor") public String loadServiceDetails(HttpServletRequest request) { StringBuilder url = getUrl(request); try { ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true); scanner.addIncludeFilter( new AnnotationTypeFilter(org.springframework.stereotype.Controller.class)); Class<?> clazz = null; ServiceDetails serviceDetails; for (BeanDefinition bd : scanner.findCandidateComponents("com.myorg.samplespringboot")) { serviceDetails = new ServiceDetails(); try { clazz = Class.forName(bd.getBeanClassName()); String basePath = Assister.getBasePath(clazz); if (null != basePath) { serviceDetails.setBasePath(basePath); Assister.getEndPointDetails(clazz); } } catch (ClassNotFoundException e) { throw new PerfMotorException("Exception in finding base path", e); } } } catch (PerfMotorException e) { //TODO implement } return "perf-motor"; } /*@RequestMapping(value = "/runPerformanceTest", method = RequestMethod.GET) //@ResponseBody public String runPerformanceTest(HttpServletRequest httpServletRequest) throws PerfMotorException { //String baseUrl = "http://localhost:8080/students/${USER_ID}"; //String baseUrl = "http://localhost:8082/ford/cars/colors/${carName}"; String baseUrl = "http://localhost:8082/ford/cars"; String httpMethod = "POST"; String contentType = "application/json"; String feederDataFileName = "placeHoldeFeeder.csv"; //String jsonBody = "{\"content\":\"John\"}"; // to test with plian json body only String jsonBody = "{\"content\":\"${carName}\"}"; // to test passing a reference in the json body String simulationClass = "com.myorg.perfmotor.gatling.PerfMotorSimulation"; GatlingPropertiesBuilder props = new GatlingPropertiesBuilder(); props.simulationClass(simulationClass); props.resultsDirectory(reportPath); props.dataDirectory(dataDirectory); //props.outputDirectoryBaseName("hello"); System.out.println(">>>>>>dat dir "+dataDirectory); PerfMotorExecVars perfMotorExecVars = new PerfMotorExecVars(); perfMotorExecVars.setBaseUrl(baseUrl); perfMotorExecVars.setMaxRespTime(50); perfMotorExecVars.setRequestName("Sample Request Name"); perfMotorExecVars.setScenarioName("Sample Scenario Name"); PerfMotorEnvHolder.baseUrl_$eq(baseUrl); PerfMotorEnvHolder.maxRespTime_$eq(500); PerfMotorEnvHolder.requestName_$eq("Sample_req"); PerfMotorEnvHolder.scenarioName_$eq("sample scen"); PerfMotorEnvHolder.loopCount_$eq(2); PerfMotorEnvHolder.rampUp_$eq(10); PerfMotorEnvHolder.token_$eq("beare "+httpServletRequest.getHeader("Authorization")); PerfMotorEnvHolder.dataDirectory_$eq(feederDataFileName); PerfMotorEnvHolder.httpMethod_$eq(httpMethod); PerfMotorEnvHolder.test_$eq(jsonBody); executeRun(props); perfMotorExecVars = null; File file = new File(System.getProperty("user.dir") + "/src/main/webapp/resources"); String[] listOfSubfolders = file.list(); String actualReportFolder = listOfSubfolders[0]; System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>... Actual report folder name: "+actualReportFolder); return actualReportFolder + "/index"; }*/ private StringBuilder getUrl(HttpServletRequest request) { StringBuilder url = new StringBuilder() .append(request.getScheme()) .append("://") .append(request.getServerName()); if (-1 != request.getServerPort()) { url.append(":").append(request.getServerPort()); } return url; } private void executeRun(GatlingPropertiesBuilder props) throws PerfMotorException { // FileUtils.deleteDirectory(new File(reportPath)); Gatling.fromMap(props.build()); props = null; } private void clearFileDirectory(String filePath) { try { FileUtils.deleteDirectory(new File(filePath+"/data")); System.out.println(">>>>>>> data directory cleared"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void writeDataToFile(JSONObject feederData) { FileWriter writer =null; try { writer = new FileWriter(dataDirectory+"/dataNew.csv", false); writer.append(feederData.getString("fileContent")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { if(null != writer) { try { System.out.println(">>>>>>>>>>>>>>> flushing the writer"); writer.flush(); writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
true
99a43108647413dda68280403f767ac145996e72
Java
16692899298/RentCar
/src/utils/ViewSet.java
WINDOWS-1252
299
2.203125
2
[]
no_license
package utils; import java.util.Date; public class ViewSet { public static String tocase(int i) { if(i==0){ return ""; }else{ return""; } } public static String tocase(Date string) { if(string==null){ return ""; }else{ return string.toString(); } } }
true
98a8a614504fb1ea5b25c2c3331bb469ebbbd99c
Java
varunam/RemoteBindingClientSide
/app/src/main/java/app/remotebindingclient/com/remotebindingclientside/MainActivity.java
UTF-8
4,878
2.375
2
[]
no_license
package app.remotebindingclient.com.remotebindingclientside; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = MainActivity.class.getSimpleName(); private Button bindServiceButton, unbindServiceButton, getRandomNumberButton; private TextView randomNumberTextView; private Intent serviceIntent; private boolean isServiceBound; private int randomNumber; private Messenger randomNumberRequestMessenger, randomNumberReceiveMessenger; private static final int GET_RANDOM_NUMBER = 0; private ServiceConnection randomNumberServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { randomNumberRequestMessenger = new Messenger(iBinder); randomNumberReceiveMessenger = new Messenger(new RandomNumberReceiveHandler()); Log.e(TAG,"Service connected"); isServiceBound = true; } @Override public void onServiceDisconnected(ComponentName componentName) { isServiceBound = false; Log.e(TAG,"Service disconnected"); randomNumberRequestMessenger = null; randomNumberReceiveMessenger = null; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bindServiceButton = findViewById(R.id.bind_service_button_id); unbindServiceButton = findViewById(R.id.unbind_service_button_id); getRandomNumberButton = findViewById(R.id.get_random_number_button_id); randomNumberTextView = findViewById(R.id.random_number_textview_id); bindServiceButton.setOnClickListener(this); unbindServiceButton.setOnClickListener(this); getRandomNumberButton.setOnClickListener(this); serviceIntent = new Intent(); serviceIntent.setComponent(new ComponentName("app.remotebindingserver.com.remotebindingserver", "app.remotebindingserver.com.remotebindingserver.BoundService")); } @Override public void onClick(View view) { int id = view.getId(); switch (id) { case R.id.get_random_number_button_id: fetchRandomNumber(); break; case R.id.unbind_service_button_id: unbindRemoteServicex(); break; case R.id.bind_service_button_id: bindToRemoteService(); break; } } @Override protected void onDestroy() { randomNumberServiceConnection = null; super.onDestroy(); } private void fetchRandomNumber() { if (isServiceBound) { Message randomNumberRequestMessage = Message.obtain(null, GET_RANDOM_NUMBER); randomNumberRequestMessage.replyTo = randomNumberReceiveMessenger; try { randomNumberRequestMessenger.send(randomNumberRequestMessage); } catch (RemoteException e) { e.printStackTrace(); } } else randomNumberTextView.setText(getString(R.string.service_not_bound)); } private void unbindRemoteServicex() { isServiceBound = false; unbindService(randomNumberServiceConnection); Toast.makeText(getApplicationContext(), "Service unbound", Toast.LENGTH_LONG).show(); } private void bindToRemoteService() { Log.e(TAG, "Activity bound to remote service"); Toast.makeText(getApplicationContext(), "Service bound", Toast.LENGTH_LONG).show(); bindService(serviceIntent, randomNumberServiceConnection, BIND_AUTO_CREATE); } private class RandomNumberReceiveHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case GET_RANDOM_NUMBER: randomNumber = msg.arg1; String randomNumberString = getString(R.string.random_number) + " " + randomNumber; randomNumberTextView.setText(randomNumberString); break; default: break; } } } }
true
cfcfa25ac2090689d3a4abb2aac9d10a9efb8c34
Java
bellmit/lol-java
/src/main/java/wsg/lol/common/pojo/dto/match/MatchDto.java
UTF-8
1,114
1.914063
2
[]
no_license
package wsg.lol.common.pojo.dto.match; import com.alibaba.fastjson.annotation.JSONField; import lombok.Data; import lombok.EqualsAndHashCode; import wsg.lol.common.base.BaseDto; import wsg.lol.common.enums.match.GameModeEnum; import wsg.lol.common.enums.match.GameTypeEnum; import wsg.lol.common.enums.match.MatchQueueEnum; import wsg.lol.common.enums.share.MapEnum; import wsg.lol.common.enums.share.SeasonEnum; import wsg.lol.common.enums.system.RegionEnum; import wsg.lol.common.pojo.serialize.SecondDurationDeserializer; import java.time.Duration; import java.util.Date; /** * DTO for a match. * * @author Kingen */ @EqualsAndHashCode(callSuper = true) @Data public class MatchDto extends BaseDto { private Long gameId; private RegionEnum platformId; private Date gameCreation; @JSONField(deserializeUsing = SecondDurationDeserializer.class) private Duration gameDuration; private MapEnum mapId; private SeasonEnum seasonId; private String gameVersion; private GameModeEnum gameMode; private GameTypeEnum gameType; private MatchQueueEnum queueId; }
true
25a5077b5de0faf9429d08a57dd7763c048ccc1e
Java
zhangchiZC/clinic
/src/cs/PharmacyDoctor.java
UTF-8
5,300
2.5625
3
[]
no_license
package cs; /** * Created by ZC on 2019/7/3. */ import po.MedicalList; import util.DbUtil; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JScrollPane; import javax.swing.JList; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JButton; public class PharmacyDoctor extends JFrame { private JPanel contentPane; private JTextField textField; DbUtil db = new DbUtil(); List<MedicalList> medicalLists = new ArrayList<>(); List<String> info = new ArrayList<>(); /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { PharmacyDoctor frame = new PharmacyDoctor(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public PharmacyDoctor() { // setTitle("药房医师"); // setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // setBounds(100, 100, 737, 535); // contentPane = new JPanel(); // contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); // setContentPane(contentPane); // contentPane.setLayout(null); // JScrollPane scrollPane = new JScrollPane(); // scrollPane.setBounds(28, 31, 595, 268); // contentPane.add(scrollPane); class MyTask extends TimerTask { @Override public void run() { // } // } setTitle("药房医师"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 737, 535); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(28, 31, 595, 268); contentPane.add(scrollPane); // for (int n=0;n<3;n++){ // try { // info.add(db.findPatientsWhoPayed().get(n).getPatient_code()+" "+db.findPatientsWhoPayed().get(n).getPatient_name()); // } catch (SQLException e) { // e.printStackTrace(); // } // } try { medicalLists = db.findPatientsWhoPayed(); for (int i = 0; i < medicalLists.size(); i++) { for (int j = 0; j < medicalLists.get(i).getMedicine_name().split(",").length; j++) { info.add(medicalLists.get(i).getPatient_code() + " " + medicalLists.get(i).getPatient_name() + " " + medicalLists.get(i).getMedicine_name().split(",")[j] + "*" + medicalLists.get(i).getMedicine_amount().split(",")[j]); } } } catch (SQLException e) { e.printStackTrace(); } JList list = new JList(info.toArray()); scrollPane.setViewportView(list); JLabel label = new JLabel("\u6302\u53F7\u5355\u53F7"); label.setBounds(28, 342, 72, 18); contentPane.add(label); textField = new JTextField(); textField.setBounds(104, 339, 173, 24); contentPane.add(textField); textField.setColumns(10); JButton btnNewButton = new JButton("\u786E\u8BA4\u62FF\u836F"); btnNewButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { db.updateMedicineInventory(textField.getText().toString().trim()); db.deleteAfterConfirmMedicine(textField.getText().toString().trim()); // db.updateMedicineInventory(textField.getText().toString().trim()); MyTask.this.run(); } catch (SQLException e1) { e1.printStackTrace(); } } }); btnNewButton.setBounds(333, 338, 113, 27); contentPane.add(btnNewButton); info.clear(); medicalLists.clear(); setBounds(100, 100, 738, 535); } } Timer timer = new Timer(); timer.scheduleAtFixedRate(new MyTask(), 0, 10000); } }
true
367f3b50ae2cfd807ba57bd8b7143ff2011c0aa3
Java
abreslav/java2ecore
/org.abreslav.java2ecore.transformation/src/org/abreslav/java2ecore/transformation/declarations/EEnumDeclaration.java
UTF-8
449
2.109375
2
[]
no_license
package org.abreslav.java2ecore.transformation.declarations; import org.eclipse.emf.ecore.EEnum; import org.eclipse.jdt.core.dom.EnumDeclaration; public class EEnumDeclaration extends AbstractDeclaration<EnumDeclaration, EEnum> { public EEnumDeclaration(EnumDeclaration declaration, EEnum declaredElement) { super(declaration, declaredElement); } public void accept(IDeclarationVisitor visitor) { visitor.visit(this); } }
true
1b6256e8c0694dbbde5578ec234e3b4e0a6119b8
Java
pradhp1999/dhruva
/server/src/test/java/com/cisco/dhruva/app/DialInShortUriCMRCallFlowActorTest.java
UTF-8
1,657
1.945313
2
[]
no_license
package com.cisco.dhruva.app; import com.cisco.dhruva.common.context.ExecutionContext; import com.cisco.dhruva.common.messaging.MessageConvertor; import com.cisco.dhruva.common.messaging.models.IDhruvaMessage; import com.cisco.dhruva.common.messaging.models.MessageBodyType; import com.cisco.dhruva.sip.stack.DsLibs.DsSipObject.DsSipRequest; import com.cisco.dhruva.util.SIPRequestBuilder; import org.testng.Assert; import org.testng.annotations.Test; public class DialInShortUriCMRCallFlowActorTest { @Test public void testValidCase() throws Exception { ExecutionContext context = new ExecutionContext(); DsSipRequest request = SIPRequestBuilder.createRequest( new SIPRequestBuilder() .getRequestAsString(SIPRequestBuilder.RequestMethod.INVITE, "12345678@webex.com")); IDhruvaMessage reqMsg = MessageConvertor.convertSipMessageToDhruvaMessage( request, MessageBodyType.SIPREQUEST, context); Assert.assertTrue(DialInShortUriCMRCallFlowActor.getFilter().test(reqMsg)); } @Test public void testValidCaseWithParams() throws Exception { ExecutionContext context = new ExecutionContext(); DsSipRequest request = SIPRequestBuilder.createRequest( new SIPRequestBuilder() .getRequestAsString( SIPRequestBuilder.RequestMethod.INVITE, "12345678@webex.com;call-type=dialInShortUri")); IDhruvaMessage reqMsg = MessageConvertor.convertSipMessageToDhruvaMessage( request, MessageBodyType.SIPREQUEST, context); Assert.assertTrue(DialInShortUriCMRCallFlowActor.getFilter().test(reqMsg)); } }
true
f24124c63c0cec19768a25c659c6c13c90f11904
Java
tangyoucheng/smart_site
/src/main/java/com/zty/smart_site/service/QualityshowService.java
UTF-8
5,714
1.601563
2
[]
no_license
package com.zty.smart_site.service; import com.zty.smart_site.dao.QualityshowDao; import com.zty.smart_site.entity.Qualityshow; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Service public class QualityshowService implements QualityshowDao { @Autowired private QualityshowDao qualityshowDao; @Override public int InsertQualityshow(Map map) { return qualityshowDao.InsertQualityshow(map); } @Override public int DeleteQualityshow(Map map) { return qualityshowDao.DeleteQualityshow(map); } @Override public Qualityshow FindQualityshowById(Map map) { return qualityshowDao.FindQualityshowById(map); } @Override public List<Qualityshow> FindQualityshow(Map map) { return qualityshowDao.FindQualityshow(map); } @Override public long Total(Map map) { return qualityshowDao.Total(map); } @Override public List<Qualityshow> FindQualityshow_JCJL(Map map) { return qualityshowDao.FindQualityshow_JCJL(map); } @Override public long Total_JCJL(Map map) { return qualityshowDao.Total_JCJL(map); } @Override public List<Qualityshow> FindQualityshow_WXJL(Map map) { return qualityshowDao.FindQualityshow_WXJL(map); } @Override public long Total_WXJL(Map map) { return qualityshowDao.Total_WXJL(map); } @Override public List<Qualityshow> FindQualityshow_DZG(Map map) { return qualityshowDao.FindQualityshow_DZG(map); } @Override public long Total_DZG(Map map) { return qualityshowDao.Total_DZG(map); } @Override public List<Qualityshow> FindQualityshow_ZGFC(Map map) { return qualityshowDao.FindQualityshow_ZGFC(map); } @Override public long Total_ZGFC(Map map) { return qualityshowDao.Total_ZGFC(map); } @Override public List<Qualityshow> FindQualityshow_JCJL_PC(Map map) { return qualityshowDao.FindQualityshow_JCJL_PC(map); } @Override public long Total_JCJL_PC(Map map) { return qualityshowDao.Total_JCJL_PC(map); } @Override public List<Qualityshow> FindQualityshow_DZG_PC(Map map) { return qualityshowDao.FindQualityshow_DZG_PC(map); } @Override public long Total_DGZ_PC(Map map) { return qualityshowDao.Total_DGZ_PC(map); } @Override public List<Qualityshow> FindQualityshow_YZG_PC(Map map) { return qualityshowDao.FindQualityshow_YZG_PC(map); } @Override public long Total_YZG_PC(Map map) { return qualityshowDao.Total_YZG_PC(map); } @Override public List<Qualityshow> FindQualityshow_ZGDY_PC(Map map) { return qualityshowDao.FindQualityshow_ZGDY_PC(map); } @Override public long Total_ZGDY_PC(Map map) { return qualityshowDao.Total_ZGDY_PC(map); } @Override public List<Qualityshow> FindQualityshowByStaffIdALL(Map map) { return qualityshowDao.FindQualityshowByStaffIdALL(map); } @Override public int UpdateActiveY(Map map) { return qualityshowDao.UpdateActiveY(map); } @Override public int UpdateActiveW(Map map) { return qualityshowDao.UpdateActiveW(map); } @Override public int UpdatePlanTime(Map map) { return qualityshowDao.UpdatePlanTime(map); } @Override public int UpdateZgUrl(Map map) { return qualityshowDao.UpdateZgUrl(map); } @Override public int UpdateActiveYZG(Map map) { return qualityshowDao.UpdateActiveYZG(map); } @Override public int UpdateActiveCQWZG(Map map) { return qualityshowDao.UpdateActiveCQWZG(map); } @Override public int UpdateStatusH(Map map) { return qualityshowDao.UpdateStatusH(map); } @Override public int UpdateStatusB(Map map) { return qualityshowDao.UpdateStatusB(map); } @Override public int CountQualityShow(Map map) { return qualityshowDao.CountQualityShow(map); } @Override public int CountQualityShowByYZG(Map map) { return qualityshowDao.CountQualityShowByYZG(map); } @Override public int CountQualityShowByWZG(Map map) { return qualityshowDao.CountQualityShowByWZG(map); } @Override public int CountQualityShowByCQWZG(Map map) { return qualityshowDao.CountQualityShowByCQWZG(map); } @Override public int find_month() { return qualityshowDao.find_month(); } @Override public int find_qualityshow_top(Map map) { return qualityshowDao.find_qualityshow_top(map); } @Override public int find_qualityshow_mid(Map map) { return qualityshowDao.find_qualityshow_mid(map); } @Override public int find_qualityshow_end(Map map) { return qualityshowDao.find_qualityshow_end(map); } @Override public int find_qualityshow_top_y(Map map) { return qualityshowDao.find_qualityshow_top_y(map); } @Override public int find_qualityshow_mid_y(Map map) { return qualityshowDao.find_qualityshow_mid_y(map); } @Override public int find_qualityshow_end_y(Map map) { return qualityshowDao.find_qualityshow_end_y(map); } @Override public List<Qualityshow> CountQualityshowByQualityId(Map map) { return qualityshowDao.CountQualityshowByQualityId(map); } @Override public List<Qualityshow> CountQualityshowBySubId(Map map) { return qualityshowDao.CountQualityshowBySubId(map); } }
true
d76de2830014fe8419385cf6533e00d1af410dd9
Java
superRookIt/Process
/4월/jsp_0421/src/com/javalec/ex/MemberDao.java
UTF-8
8,014
2.734375
3
[]
no_license
package com.javalec.ex; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; public class MemberDao { private MemberDao() { } // MemberDao mdao = new MemberDao(); private static MemberDao instance = new MemberDao(); // instance ★★★ public static MemberDao getInstance() { return instance; } //객체선언 Context ct = null; DataSource ds = null; Connection con = null; PreparedStatement ps = null; ResultSet rs = null; MemberDto mdto = null; String sql; // 아이디 중복 체크 public int confirmId(String id) { int check = 0; sql="select id from b_member where id=?"; try { con=getConnection(); //Context에서 커넥션 가져오기 ps=con.prepareStatement(sql); ps.setString(1, id); rs=ps.executeQuery(); if(rs.next()) { //중복 아이디가 존재 check=1; }else { //중복 아이디가 없음 check=0; } } catch (Exception e) { e.printStackTrace(); }finally { try { if(rs!=null) rs.close(); if(con!=null) con.close(); if(ps!=null) ps.close(); } catch (Exception e2) { e2.printStackTrace(); } } return check; } //커넥션 풀에서 1개의 커넥션 가지고 오는 메소드 private Connection getConnection() { Context context = null; DataSource ds = null; Connection con = null; try { context = new InitialContext(); ds = (DataSource) context.lookup("java:comp/env/jdbc/oracle11g"); con = ds.getConnection(); } catch (Exception e) { e.printStackTrace(); } return con; } // member 여러개 public ArrayList<MemberDto> getmembers() { ArrayList<MemberDto> list = new ArrayList<MemberDto>(); /* Context ct = null; DataSource ds = null; Connection con = null; PreparedStatement ps = null; ResultSet rs = null; */ sql = "select * from b_member order by b_date desc"; try { ct = new InitialContext(); ds = (DataSource) ct.lookup("java:comp/env/jdbc/oracle11g"); con = ds.getConnection(); // con = getConnection(); ps = con.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { // db에서 데이터 읽어와서 dto에 입력 mdto = new MemberDto(); mdto.setId(rs.getString("id")); mdto.setPw(rs.getString("pw")); mdto.setName(rs.getString("name")); mdto.setEmail(rs.getString("email")); mdto.setAddress(rs.getString("address")); mdto.setB_date(rs.getTimestamp("b_date")); list.add(mdto); } } catch ( Exception e) { e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (ps != null) ps.close(); if (con != null) con.close(); } catch (Exception e2) { e2.printStackTrace(); } } return list; } // 멤버 1개 public MemberDto getMember(String id) { /* Context ct = null; DataSource ds = null; Connection con = null; PreparedStatement ps = null; ResultSet rs = null; */ mdto = null; sql = "select * from b_member where id=?"; try { ct = new InitialContext(); ds = (DataSource) ct.lookup("java:comp/env/jdbc/oracle11g"); con = ds.getConnection(); ps = con.prepareStatement(sql); ps.setString(1, id); rs = ps.executeQuery(); if (rs.next()) { // if(rs !=null) -> rs null 리턴값을 돌려줍니다. // while (rs.next()) { // db에서 데이터 읽어와서 dto에 입력 mdto = new MemberDto(); mdto.setId(rs.getString("id")); mdto.setPw(rs.getString("pw")); mdto.setName(rs.getString("name")); mdto.setEmail(rs.getString("email")); mdto.setAddress(rs.getString("address")); mdto.setB_date(rs.getTimestamp("b_date")); // } while } else { } } catch (Exception e) { e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (ps != null) ps.close(); if (con != null) con.close(); } catch (Exception e2) { e2.printStackTrace(); } } return mdto; } //회원 가입 입력 메소드 public int insertMember(MemberDto mdto) { int check =0; sql ="insert into b_member (id, pw, name, email, address) values (?,?,?,?,?)"; try { con=getConnection(); ps=con.prepareStatement(sql); ps.setString(1, mdto.getId()); ps.setString(2, mdto.getPw()); ps.setString(3, mdto.getName()); ps.setString(4, mdto.getEmail()); ps.setString(5, mdto.getAddress()); check = ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (con != null) con.close(); if (ps != null) ps.close(); } catch (Exception e2) { e2.printStackTrace(); } } return check; } // 아이디,패스워드 체크 메소드 public int userCheck(String id, String pw) { int check = 0;// db에서 결과 리턴값 /* Context ct = null; DataSource ds = null; Connection con = null; PreparedStatement ps = null; ResultSet rs = null; */ sql = "select id,pw from b_member where id=?"; try { String ch_id; String ch_pw; ct = new InitialContext(); ds = (DataSource) ct.lookup("java:comp/env/jdbc/oracle11g"); con = ds.getConnection(); ps = con.prepareStatement(sql); ps.setString(1, id); rs = ps.executeQuery(); if (rs.next()) { // 데이터가 있을 경우 // while (rs.next()) { ch_id = rs.getString("id"); ch_pw = rs.getString("pw"); if (ch_pw.equals(pw)) { check = 1; // 패스워드 일치 } else { check = 0; // 패스워드 불일치 } // } // while } else { // 데이터가 없을 경우 check = -1; // 아이디가 존재하지 않음 } } catch (Exception e) { e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (con != null) con.close(); if (ps != null) ps.close(); } catch (Exception e2) { e2.printStackTrace(); } } return check; // 일치=1, 불일치=0, 존재하지 않음=-1 }// userCheck //update 메소드 public int updateMember(MemberDto mdto) { int check = 0; sql="update b_member set pw = ? ,name = ? , email = ?, address = ? , b_date = sysdate where id=?"; try { con = getConnection(); // Context에서 커넥션 가져오기 ps = con.prepareStatement(sql); ps.setString(1, mdto.getPw()); ps.setString(2, mdto.getName()); ps.setString(3, mdto.getEmail()); ps.setString(4, mdto.getAddress()); ps.setString(5, mdto.getId()); check=ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); }finally { try { if(con!=null) con.close(); if(ps!=null) ps.close(); } catch (Exception e2) { e2.printStackTrace(); } } return check; } //delete 메소드 public int deleteMember(String id) { int check=0; sql="delete b_member where id=?"; try { con = getConnection(); // Context에서 커넥션 가져오기 ps = con.prepareStatement(sql); ps.setString(1, id); check=ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); }finally { try { if(con!=null) con.close(); if(ps!=null) ps.close(); } catch (Exception e2) { e2.printStackTrace(); } } return check; } }// class
true
831a04073f93de59e161c9aed94fcc11989b15b2
Java
onmax/Algoritmos-y-estructura-de-datos
/practica8/src/aed/cache/CacheCell.java
UTF-8
962
2.6875
3
[]
no_license
package aed.cache; import es.upm.aedlib.Position; public class CacheCell<Key,Value> { private Value value; private boolean dirty; private Position<Key> pos; public CacheCell(Value value, boolean dirty, Position<Key> pos) { this.value = value; this.dirty = dirty; this.pos = pos; } public Value getValue() { return this.value; } public boolean getDirty() { return this.dirty; } public Position<Key> getPos() { return this.pos; } public void setValue(Value value) { this.value = value; } public void setDirty(boolean dirty) { this.dirty = dirty; } public void setPos(Position<Key> pos) { this.pos = pos; } public String toString() { String valueString="null"; String posString="null"; if (value != null) valueString = value.toString(); if (pos != null) posString = pos.toString(); return "<value="+valueString+",dirty="+dirty+",pos="+posString+">"; } }
true
35a28ae4cf2eb59629b44ff978b87cb172589c19
Java
JQhotel/Test
/game_store/game_mysql/src/com/demo/controller/DemoController.java
UTF-8
3,598
2.25
2
[]
no_license
package com.demo.controller; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.demo.entity.TDemo; import com.demo.service.DemoService; import com.demo.util.Page; @Controller @RequestMapping("/demo") public class DemoController { @Resource private DemoService demoService; @RequestMapping("queryDemo.do") public String query(ModelMap map,Page page,String findname) throws Exception{ if(page==null){ page=new Page(); } if(findname==null){ findname=""; } page.setSize(demoService.queryDemoCount(findname,"")); if(page.getSize()>0){ page.setPagecount(page.getPagecount()); if(page.getPageindex()<=0){ page.setPageindex(1); } if(page.getPageindex()>page.getPagecount()){ page.setPageindex(page.getPagecount()); } } List<TDemo> list = demoService.queryDemos(page, findname,""); map.put("items", list); return "/demoMgr.jsp"; } @RequestMapping("queryShowDemo.do") public String queryShowdemo(ModelMap map,Page page,String findname,String goodsKind) throws Exception{ if(page==null){ page=new Page(); } if(findname==null){ findname=""; } if(goodsKind==null){ goodsKind=""; } page.setPagesize(6); page.setSize(demoService.queryDemoCount(findname,goodsKind)); if(page.getSize()>0){ page.setPagecount(page.getPagecount()); if(page.getPageindex()<=0){ page.setPageindex(1); } if(page.getPageindex()>page.getPagecount()){ page.setPageindex(page.getPagecount()); } } List<TDemo> list = demoService.queryDemos(page, findname,goodsKind); map.put("items", list); map.put("goodsKind", goodsKind); return "/main.jsp"; } @RequestMapping("toAddDemo.do") public String toAdddemo(ModelMap map) throws Exception{ return "/addDemo.jsp"; } @RequestMapping("toUpdDemo.do") public String toUpdDemo(ModelMap map,TDemo demo) throws Exception{ demo = demoService.queryDemoById(demo.getId()); map.put("demo", demo); return "/updDemo.jsp"; } @RequestMapping(value="addDemo.do") public String addDemo(ModelMap map, @RequestParam(value = "imgFile") MultipartFile demoImgFile, TDemo demo ) throws Exception{ int count = demoService.queryDemoCountByName(demo.getName()); if(count==0) { demoService.addDemo(demo,demoImgFile); return "redirect:queryDemo.do"; }else { map.put("errorMsg", "名字重复,请修改"); return "/addDemo.jsp"; } } @RequestMapping(value="updDemo.do") public String upddemo(ModelMap map, @RequestParam(value = "imgFile",required=false) MultipartFile demoImgFile, TDemo demo ) throws Exception{ if(demo.getOldName().equals(demo.getName())) { demoService.updDemo(demo, demoImgFile); return "redirect:queryDemo.do"; }else { int count = demoService.queryDemoCountByName(demo.getName()); if(count==0) { demoService.updDemo(demo,demoImgFile); return "redirect:queryDemo.do"; }else { map.put("errorMsg", "名字重复,请修改"); return "/updDemo.jsp"; } } } @RequestMapping("delDemo.do") public String delDemo(ModelMap map,int id) throws Exception{ demoService.deleteDemoById(id); return "redirect:queryDemo.do"; } }
true
82d1ebb05614d2e24933fc5826047b1848ea910b
Java
sagargoyal96/Taxi-Aggregator-service
/MyLinkedList.java
UTF-8
413
2.859375
3
[]
no_license
class MyLinkedList { //vertex obj=new vertex(); vertex first=null; vertex last=null; public void insert(vertex a) { if(first==null) { first=a; last=first; } else { last.next=a; last=a; } } /*public boolean Ismember(X a) { vertex trav; trav=this.first; while(trav!=null) { if(trav.data==a) return true; trav=trav.next; } return false; }*/ }
true
e23ae3ac02f4c0550df72f8b5a704d025afa34ac
Java
xiaozengtest01/shoppingStore
/后端BookStores/src/com/dianbenshu/entiy/ShoppingCar.java
UTF-8
1,951
2.15625
2
[]
no_license
package com.dianbenshu.entiy; public class ShoppingCar { int ShoppingCarId; int UserId; int BooksId; int Num; int Status; String CreateTime; String UpdateTime; String CartMessages; public int getShoppingCarId() { return ShoppingCarId; } public void setShoppingCarId(int shoppingCarId) { ShoppingCarId = shoppingCarId; } public int getUserId() { return UserId; } public void setUserId(int userId) { UserId = userId; } public int getBooksId() { return BooksId; } public void setBooksId(int booksId) { BooksId = booksId; } public int getNum() { return Num; } public void setNum(int num) { Num = num; } public int getStatus() { return Status; } public void setStatus(int status) { Status = status; } public String getCreateTime() { return CreateTime; } public void setCreateTime(String createTime) { CreateTime = createTime; } public String getUpdateTime() { return UpdateTime; } public void setUpdateTime(String updateTime) { UpdateTime = updateTime; } public String getCartMessages() { return CartMessages; } public void setCartMessages(String cartMessages) { CartMessages = cartMessages; } public ShoppingCar(int shoppingCarId, int userId, int booksId, int num, int status, String createTime, String updateTime,String cartMessages) { super(); ShoppingCarId = shoppingCarId; UserId = userId; BooksId = booksId; Num = num; Status = status; CreateTime = createTime; UpdateTime = updateTime; CartMessages = cartMessages; } public ShoppingCar() { } public ShoppingCar(int shoppingCarId,int booksId, int num) { super(); ShoppingCarId = shoppingCarId; BooksId = booksId; Num = num; } public ShoppingCar(int userId, int booksId, int num, int status, String createTime, String cartMessages) { super(); UserId = userId; BooksId = booksId; Num = num; Status = status; CreateTime = createTime; CartMessages = cartMessages; } }
true
a9e166707c4760f8de72404361b0071eee4fc73f
Java
hotHeart48156/smart
/users/users-app/src/main/java/org/users/commandhandle/aggre/GrowthCommandHandle.java
UTF-8
699
1.84375
2
[]
no_license
package org.users.commandhandle.aggre; import lombok.Value; import org.axonframework.commandhandling.CommandHandler; import org.axonframework.modelling.command.AggregateLifecycle; import org.springframework.beans.factory.annotation.Autowired; import org.users.cache.CacheService; import org.users.domain.repository.UserRepository; import org.users.domainevent.aggevent.GrowthEvent; import org.users.executor.command.aggre.GrowthCommand; @Value public class GrowthCommandHandle{ @Autowired UserRepository repository; @Autowired CacheService cacheService; @CommandHandler public void on (GrowthCommand Command){ AggregateLifecycle.apply(new GrowthEvent(Command.getGrowthDto())); }}
true
cc0c4f7a696ec457e0432208416dfa1005161bda
Java
doEinstein/test-java
/src/main/java/br/com/blz/testjava/domain/api/response/InventoryResponse.java
UTF-8
353
1.914063
2
[]
no_license
package br.com.blz.testjava.domain.api.response; import br.com.blz.testjava.domain.api.request.InventoryRequest; public class InventoryResponse extends InventoryRequest { private Long quantity; public Long getQuantity() { return quantity; } public void setQuantity(Long quantity) { this.quantity = quantity; } }
true
59d8aa4ed260b794cbc96fdb5cbc16f4c7caa045
Java
RaulBR/Bookyourlesson
/book-your-lesson/src/main/java/ro/bydl/service/ScheduleService.java
UTF-8
3,538
2.953125
3
[]
no_license
package ro.bydl.service; import java.util.Calendar; import java.util.Collection; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ro.bydl.dao.ScheduleDAO; import ro.bydl.domain.Schedule; import ro.bydl.exceptions.ValidationException; /** * Service class for schedules * * @author Raul * */ @Service public class ScheduleService { private static final Logger LOGGER = LoggerFactory.getLogger(ScheduleService.class); @Autowired ScheduleDAO dao; /** * Returners an arrey of strings format type dd.MM.yyyy * * @param week * @return String[] week days */ public String[] getDays(int week) { CalendarHelper calHelp = new CalendarHelper(); return calHelp.getDays(week); } /** * validation method for type schedule (empty) * * @param schedule * @throws ValidationException */ public void validate(Schedule schedule) throws ValidationException { } /** * method gets all schedules form the DB. * * @return Collection<Schedule> */ public Collection<Schedule> getScheduels() { return dao.getAll(); } /** * Method adds schedules to the Db * * @param schedule */ public long save(Schedule schedule) { LOGGER.debug("Saving: " + schedule); return dao.insert(schedule); } /** * Method delletss schedules to the Db * * @param schedule */ public long delete(Schedule schedule) { LOGGER.debug("Deleting: " + schedule); return dao.delete(schedule); } /** * Method returns number of schedules form db. * * @param id * @return int */ public int countSchedules(long id) { return (dao.searchByStudentId(id).size() * 100 / 30); } /** * method updates schedule * * @param schedule * @return */ public Schedule update(Schedule schedule) { return dao.update(schedule); } /** * returnes schedules based on theacher id * * @param teahcerId * @return Collection<Schedule> */ public Collection<Schedule> searchByTeacherId(long teahcerId) { return dao.searchByTeacherId(teahcerId); } /** * returns scheduled based on student id * * @param id * @return Collection<Schedule> */ public Collection<Schedule> searchByStudentId(int id) { return dao.searchByStudentId(id); } public int pending(long id) { int nr = 0; for (Schedule s : dao.searchByStudentId(id)) { if (s.getStatus().equals("pending") || s.getStatus().equals("booked")) { nr++; } } return (nr * 100 / 15); } public int absent(long id) { int nr = 0; for (Schedule s : dao.searchByStudentId(id)) { if (s.getStatus().equals("absent")) { nr++; } } return (nr * 100 / 10); } public int done(long id) { int nr = 0; for (Schedule s : dao.searchByStudentId(id)) { if (s.getStatus().equals("done")) { nr++; } } return (nr * 100 / 30); } public Collection<Schedule> searchByStudentId(long l, long teacherId) { return dao.searchByStudentId(l, teacherId); } public boolean dateHasPased(Schedule schedule) { Date date = new Date(); if (setTime(schedule).before(date)) { return true; } return false; } private Date setTime(Schedule schedule) { Calendar cal = Calendar.getInstance(); cal.setTime(schedule.getDate()); cal.set(Calendar.HOUR_OF_DAY, schedule.getStartHour()); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } }
true
e175017226ea2e97523527321c7778176eef05db
Java
ningjm/zsyc
/zsyc-service/src/main/java/com/zsyc/goods/mapper/GoodsStorePriceMapper.java
UTF-8
4,048
1.796875
2
[]
no_license
package com.zsyc.goods.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.zsyc.goods.bo.GoodsAndPriceBO; import com.zsyc.goods.bo.GoodsBarginRecommendPriceBO; import com.zsyc.goods.bo.GoodsStorePriceBO; import com.zsyc.goods.bo.GoodsStorePriceListBO; import com.zsyc.goods.entity.GoodsInfo; import com.zsyc.goods.entity.GoodsStorePrice; import com.zsyc.goods.vo.GoodsStorePriceSearchVO; import org.apache.ibatis.annotations.Param; import java.util.List; /** * <p> * 商品价格表 Mapper 接口 * </p> * * @author MP * @since 2019-01-31 */ public interface GoodsStorePriceMapper extends BaseMapper<GoodsStorePrice> { IPage<GoodsStorePriceListBO> selectGoodsPriceAndName(Page page, @Param("is_del")Integer isNotDel, @Param("status")String onSale, @Param("store_id")Long storeId); GoodsStorePriceBO selectGoodsPriceVO(@Param("sku")String sku, @Param("store_id")Long storeId, @Param("is_del")Integer isNotDel, @Param("status")String onSale); IPage<GoodsAndPriceBO> selectGoodsPriceAndNameByCategory(Page page, @Param("is_del")Integer isNotDel, @Param("status")String onSale, @Param("store_id")Long storeId,@Param("category_id")Long categoryId,@Param("category_type")String category_type); List<GoodsInfo> selectStoreSkuList(@Param("spu")String spu, @Param("store_id")Long storeId, @Param("is_del")Integer isNotDel, @Param("status")String onSale); List<GoodsBarginRecommendPriceBO> selectStoreGoodsPriceList(@Param("page_num")Long pageNum,@Param("page_size")Long pageSize, @Param("store_id")Long storeId, @Param("is_del")Integer isNotDel, @Param("status")String onSale, @Param("is_bargain_price")Integer is_bargain_price,@Param("is_recommend")Integer is_recommend,@Param("goods_style")Integer goods_style,@Param("goods_type")Integer goods_type); Integer goodsBarginPriceCount(@Param("store_id")Long storeId, @Param("is_del")Integer isNotDel, @Param("status")String onSale, @Param("is_bargain_price")Integer is_bargain_price,@Param("is_recommend")Integer is_recommend,@Param("goods_style")Integer goods_style,@Param("goods_type")Integer goods_type); List<GoodsBarginRecommendPriceBO> selectGoodsCookBookList(@Param("page_num")Long pageNum, @Param("page_size")Long pageSize, @Param("store_id")Long storeId, @Param("is_del")Integer isNotDel, @Param("status")String onSale, @Param("goods_style")Integer normal, @Param("category_type")String category_type,@Param("is_recommend")Integer is_recommend); Integer selectGoodsCookBookCount(@Param("store_id")Long storeId, @Param("is_del")Integer isNotDel, @Param("status")String onSale, @Param("goods_style")Integer normal, @Param("category_type")String category_type, @Param("is_recommend")Integer isRecommend); IPage<GoodsAndPriceBO> selectGoodsListByName(Page page, @Param("is_del")Integer isNotDel, @Param("status")String onSale, @Param("store_id")Long storeId, @Param("goods_name")String goodsName,@Param("goods_type")Integer goods_type,@Param("goods_style")Integer goods_style); IPage<GoodsAndPriceBO> selectWaterOrGasPriceList(Page page, @Param("is_del")Integer isNotDel, @Param("status")String onSale, @Param("store_id")Long storeId,@Param("category_id")Long categoryId); IPage<GoodsStorePriceListBO> getGoodsVipPriceList(Page page, @Param("store_price_search")GoodsStorePriceSearchVO goodsStorePriceSearchVO, @Param("is_del")Integer isNotDel,@Param("goods_type")Integer goods_type); IPage<GoodsStorePriceListBO> selectGoodsChildPriceAndName(Page page, @Param("is_del")Integer isNotDel, @Param("status")String onSale, @Param("store_id")Long storeId,@Param("goods_type")Integer goods_type,@Param("goods_style")Integer goods_style); IPage<GoodsStorePriceListBO> selectGoodsIngredientPriceAndName(Page page, @Param("is_del")Integer isNotDel, @Param("status")String onSale, @Param("store_id")Long storeId,@Param("goods_type")Integer goods_type,@Param("goods_style")Integer goods_style); }
true
98f9821b281bceaffa7300276b2f35b8942e5a96
Java
atul-vyshnav/2021_IBM_Code_Challenge_StockIT
/src/StockIT-v1-release_source_from_JADX/sources/com/airbnb/lottie/animation/content/FillContent.java
UTF-8
5,637
2.046875
2
[ "Apache-2.0" ]
permissive
package com.airbnb.lottie.animation.content; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import com.airbnb.lottie.C0692L; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.LottieProperty; import com.airbnb.lottie.animation.LPaint; import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation; import com.airbnb.lottie.animation.keyframe.ColorKeyframeAnimation; import com.airbnb.lottie.animation.keyframe.ValueCallbackKeyframeAnimation; import com.airbnb.lottie.model.KeyPath; import com.airbnb.lottie.model.content.ShapeFill; import com.airbnb.lottie.model.layer.BaseLayer; import com.airbnb.lottie.utils.MiscUtils; import com.airbnb.lottie.value.LottieValueCallback; import java.util.ArrayList; import java.util.List; public class FillContent implements DrawingContent, BaseKeyframeAnimation.AnimationListener, KeyPathElementContent { private final BaseKeyframeAnimation<Integer, Integer> colorAnimation; private BaseKeyframeAnimation<ColorFilter, ColorFilter> colorFilterAnimation; private final boolean hidden; private final BaseLayer layer; private final LottieDrawable lottieDrawable; private final String name; private final BaseKeyframeAnimation<Integer, Integer> opacityAnimation; private final Paint paint = new LPaint(1); private final Path path = new Path(); private final List<PathContent> paths = new ArrayList(); public FillContent(LottieDrawable lottieDrawable2, BaseLayer baseLayer, ShapeFill shapeFill) { this.layer = baseLayer; this.name = shapeFill.getName(); this.hidden = shapeFill.isHidden(); this.lottieDrawable = lottieDrawable2; if (shapeFill.getColor() == null || shapeFill.getOpacity() == null) { this.colorAnimation = null; this.opacityAnimation = null; return; } this.path.setFillType(shapeFill.getFillType()); BaseKeyframeAnimation<Integer, Integer> createAnimation = shapeFill.getColor().createAnimation(); this.colorAnimation = createAnimation; createAnimation.addUpdateListener(this); baseLayer.addAnimation(this.colorAnimation); BaseKeyframeAnimation<Integer, Integer> createAnimation2 = shapeFill.getOpacity().createAnimation(); this.opacityAnimation = createAnimation2; createAnimation2.addUpdateListener(this); baseLayer.addAnimation(this.opacityAnimation); } public void onValueChanged() { this.lottieDrawable.invalidateSelf(); } public void setContents(List<Content> list, List<Content> list2) { for (int i = 0; i < list2.size(); i++) { Content content = list2.get(i); if (content instanceof PathContent) { this.paths.add((PathContent) content); } } } public String getName() { return this.name; } public void draw(Canvas canvas, Matrix matrix, int i) { if (!this.hidden) { C0692L.beginSection("FillContent#draw"); this.paint.setColor(((ColorKeyframeAnimation) this.colorAnimation).getIntValue()); this.paint.setAlpha(MiscUtils.clamp((int) ((((((float) i) / 255.0f) * ((float) this.opacityAnimation.getValue().intValue())) / 100.0f) * 255.0f), 0, 255)); BaseKeyframeAnimation<ColorFilter, ColorFilter> baseKeyframeAnimation = this.colorFilterAnimation; if (baseKeyframeAnimation != null) { this.paint.setColorFilter(baseKeyframeAnimation.getValue()); } this.path.reset(); for (int i2 = 0; i2 < this.paths.size(); i2++) { this.path.addPath(this.paths.get(i2).getPath(), matrix); } canvas.drawPath(this.path, this.paint); C0692L.endSection("FillContent#draw"); } } public void getBounds(RectF rectF, Matrix matrix, boolean z) { this.path.reset(); for (int i = 0; i < this.paths.size(); i++) { this.path.addPath(this.paths.get(i).getPath(), matrix); } this.path.computeBounds(rectF, false); rectF.set(rectF.left - 1.0f, rectF.top - 1.0f, rectF.right + 1.0f, rectF.bottom + 1.0f); } public void resolveKeyPath(KeyPath keyPath, int i, List<KeyPath> list, KeyPath keyPath2) { MiscUtils.resolveKeyPath(keyPath, i, list, keyPath2, this); } public <T> void addValueCallback(T t, LottieValueCallback<T> lottieValueCallback) { if (t == LottieProperty.COLOR) { this.colorAnimation.setValueCallback(lottieValueCallback); } else if (t == LottieProperty.OPACITY) { this.opacityAnimation.setValueCallback(lottieValueCallback); } else if (t == LottieProperty.COLOR_FILTER) { BaseKeyframeAnimation<ColorFilter, ColorFilter> baseKeyframeAnimation = this.colorFilterAnimation; if (baseKeyframeAnimation != null) { this.layer.removeAnimation(baseKeyframeAnimation); } if (lottieValueCallback == null) { this.colorFilterAnimation = null; return; } ValueCallbackKeyframeAnimation valueCallbackKeyframeAnimation = new ValueCallbackKeyframeAnimation(lottieValueCallback); this.colorFilterAnimation = valueCallbackKeyframeAnimation; valueCallbackKeyframeAnimation.addUpdateListener(this); this.layer.addAnimation(this.colorFilterAnimation); } } }
true
95e964f8a98dafc2c1f8cedf1ee7fc77d7af378d
Java
KpdsK/QC1G
/src/main/java/ar/utn/frba/dds/tpAnual2015/java8/CondicionPreexistente.java
UTF-8
934
2.859375
3
[]
no_license
package ar.utn.frba.dds.tpAnual2015.java8; abstract class CondicionPreexistente { private String nombre; /** * @param nombre */ public CondicionPreexistente(String nombre) { super(); this.nombre = nombre; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } protected boolean tieneDefinidoAlgunAlimentoPreferidoUsuario(Usuario usuario) { return ! usuario.getAlimentosPreferidos().isEmpty(); } //Metodos publicos funcionalidad de la Clase (interface) //Solución que depende de la tecnologia, no lo resuelve el diseño. public abstract boolean superaLimitacionElUsuario( Usuario usuario ); public abstract boolean subsanaCondicionPreexistenteUsuario( Usuario usuario ); public abstract boolean esAdecuadaLaReceta( Receta receta ); @Override public String toString() { return "CondicionPreexistente [nombre=" + nombre + "]"; } }
true
813234d1cdcad63fa291e6fdfcda0743ebbd5a3c
Java
JiByungKyu/Gusto
/app/src/main/java/com/example/byungkyu/myapplication/BandGraphActivity.java
UTF-8
12,116
2.25
2
[]
no_license
package com.example.byungkyu.myapplication; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.LinearLayout; import com.scichart.charting.model.dataSeries.XyDataSeries; import com.scichart.charting.modifiers.LegendModifier; import com.scichart.charting.modifiers.ModifierGroup; import com.scichart.charting.modifiers.SourceMode; import com.scichart.charting.visuals.SciChartSurface; import com.scichart.charting.visuals.axes.IAxis; import com.scichart.charting.visuals.pointmarkers.EllipsePointMarker; import com.scichart.charting.visuals.renderableSeries.IRenderableSeries; import com.scichart.core.annotations.Orientation; import com.scichart.core.framework.UpdateSuspender; import com.scichart.drawing.utility.ColorUtil; import com.scichart.extensions.builders.SciChartBuilder; import java.util.Collections; import java.util.HashMap; import java.util.Timer; import java.util.TimerTask; public class BandGraphActivity extends AppCompatActivity implements SocketActivity { private String[] strings; private Timer timer; CommunicationManager communicationManager = CommunicationManager.getInstance(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); communicationManager.setSocketActivity(this); communicationManager.graphReceived=false; communicationManager.stopReceived=false; communicationManager.sendMsg(); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setContentView(R.layout.activity_band_graph); // Sci 차트의 도면을 생성한다. final SciChartSurface surface = new SciChartSurface(this); // "activity_band_graph.xml" by id 를 가져온다 LinearLayout chartLayout = (LinearLayout) findViewById(R.id.band_graph); /*Toolbar toolbar = (Toolbar) findViewById(R.id.graph_toolbar); toolbar.setContentInsetsAbsolute(0,0); setSupportActionBar(toolbar);*/ // Chart를 그릴 Layout에다 Sci 차트 도면을 추가한다. chartLayout.addView(surface); // SciChartBuilder 생성자를 해당 엑티비티로 초기화 시킴 SciChartBuilder.init(this); // 엑티비티로 초기화 된 빌더로 Instance를 얻어냄 final SciChartBuilder sciChartBuilder = SciChartBuilder.instance(); // 도면에 그릴 X축의 값들을 설정한다. final IAxis xAxis = sciChartBuilder.newNumericAxis() .withAxisTitle("Time") // X축 명 .withVisibleRange(0, 10)// 한눈에 보여질 X 범위 .build(); // 도면에 그릴 Y축의 값들을 설정한다. final IAxis yAxis = sciChartBuilder.newNumericAxis() .withAxisTitle("Data").withVisibleRange(0, 2).build(); // 그래프를 조작하는 기능들을 설정한다. (줌 기능) ModifierGroup chartModifiers = sciChartBuilder.newModifierGroup() .withPinchZoomModifier().withReceiveHandledEvents(true).build() .withZoomPanModifier().withReceiveHandledEvents(true).build() .build(); // Y축과 Y축에 설정된 값들을 추가한다. Collections.addAll(surface.getYAxes(), yAxis); // X축과 X축에 설정된 값들을 추가한다. Collections.addAll(surface.getXAxes(), xAxis); // 생성된 수정 기능들을 모두 추가한다. Collections.addAll(surface.getChartModifiers(), chartModifiers); //라인 시리즈 추가 // 이전 데이터의 버퍼 용량을 설정해줌 final int fifoCapacity = 500; // X축의 형식과 Y축의 형식을 설정한 뒤 생성 final XyDataSeries EngineRPM = sciChartBuilder.newXyDataSeries(Integer.class, Double.class).withSeriesName("EngineRPM").withFifoCapacity(100).build(); final XyDataSeries EngineOil = sciChartBuilder.newXyDataSeries(Integer.class, Double.class).withSeriesName("EngineOil").withFifoCapacity(100).build(); final XyDataSeries FuelT = sciChartBuilder.newXyDataSeries(Integer.class, Double.class).withSeriesName("FuelT").withFifoCapacity(100).build(); final XyDataSeries FPumpP = sciChartBuilder.newXyDataSeries(Integer.class, Double.class).withSeriesName("FPumpP").withFifoCapacity(100).build(); final XyDataSeries RPumpP = sciChartBuilder.newXyDataSeries(Integer.class, Double.class).withSeriesName("RPumpP").withFifoCapacity(100).build(); final XyDataSeries Pump1P = sciChartBuilder.newXyDataSeries(Integer.class, Double.class).withSeriesName("Pump1P").withFifoCapacity(100).build(); final XyDataSeries Pump2P = sciChartBuilder.newXyDataSeries(Integer.class, Double.class).withSeriesName("Pump2P").withFifoCapacity(100).build(); final XyDataSeries PumpV1 = sciChartBuilder.newXyDataSeries(Integer.class, Double.class).withSeriesName("PumpV1").withFifoCapacity(100).build(); final XyDataSeries PumpV2 = sciChartBuilder.newXyDataSeries(Integer.class, Double.class).withSeriesName("PumpV2").withFifoCapacity(100).build(); final XyDataSeries CoolFenV = sciChartBuilder.newXyDataSeries(Integer.class, Double.class).withSeriesName("CoolFenV").withFifoCapacity(100).build(); final XyDataSeries ControlV = sciChartBuilder.newXyDataSeries(Integer.class, Double.class).withSeriesName("ControlV").withFifoCapacity(100).build(); // 그래프에 쓰일 라인 설정을 하면서 생성 final IRenderableSeries rs1 = sciChartBuilder.newLineSeries() .withDataSeries(EngineRPM) .withStrokeStyle(ColorUtil.Gold, 2f, true) .build(); final IRenderableSeries rs2 = sciChartBuilder.newLineSeries() .withDataSeries(EngineOil) .withStrokeStyle(ColorUtil.Green, 2f, true) .build(); final IRenderableSeries rs3 = sciChartBuilder.newLineSeries() .withDataSeries(FuelT) .withStrokeStyle(ColorUtil.Cyan, 2f, true) .build(); final IRenderableSeries rs4 = sciChartBuilder.newLineSeries() .withDataSeries(FPumpP) .withStrokeStyle(ColorUtil.Brown, 2f, true) .build(); final IRenderableSeries rs5 = sciChartBuilder.newLineSeries() .withDataSeries(RPumpP) .withStrokeStyle(ColorUtil.Blue, 2f, true) .build(); final IRenderableSeries rs6 = sciChartBuilder.newLineSeries() .withDataSeries(Pump1P) .withStrokeStyle(ColorUtil.Red, 2f, true) .build(); final IRenderableSeries rs7 = sciChartBuilder.newLineSeries() .withDataSeries(Pump2P) .withStrokeStyle(ColorUtil.Grey, 2f, true) .build(); final IRenderableSeries rs8 = sciChartBuilder.newLineSeries() .withDataSeries(PumpV1) .withStrokeStyle(ColorUtil.Maroon, 2f, true) .build(); final IRenderableSeries rs9 = sciChartBuilder.newLineSeries() .withDataSeries(PumpV2) .withStrokeStyle(ColorUtil.Navy, 2f, true) .build(); final IRenderableSeries rs10 = sciChartBuilder.newLineSeries() .withDataSeries(CoolFenV) .withStrokeStyle(ColorUtil.Purple, 2f, true) .build(); final IRenderableSeries rs11 = sciChartBuilder.newLineSeries() .withDataSeries(ControlV) .withStrokeStyle(ColorUtil.Olive, 2f, true) .build(); // 그래프에 쓰일 포인터를 설정하면서 생성 EllipsePointMarker pointMarker = sciChartBuilder .newPointMarker(new EllipsePointMarker()) .withFill(ColorUtil.LightBlue) .withStroke(ColorUtil.Green, 2f) .withSize(10) .build(); // 도면에 그래를 추가시킴 surface.getRenderableSeries().add(rs1); surface.getRenderableSeries().add(rs2); surface.getRenderableSeries().add(rs3); surface.getRenderableSeries().add(rs4); surface.getRenderableSeries().add(rs5); surface.getRenderableSeries().add(rs6); surface.getRenderableSeries().add(rs7); surface.getRenderableSeries().add(rs8); surface.getRenderableSeries().add(rs9); surface.getRenderableSeries().add(rs10); surface.getRenderableSeries().add(rs11); // 레전드 추가(기록들 보기) - 처음부터 가릴수가 없다. LegendModifier legendModifier = new LegendModifier(this); legendModifier.setShowLegend(true); legendModifier.setShowSeriesMarkers(true); legendModifier.setSourceMode(SourceMode.AllVisibleSeries); legendModifier.setOrientation(Orientation.VERTICAL); // Add the modifier to the surface surface.getChartModifiers().add(legendModifier); TimerTask updateDataTask = new TimerTask() { private int x = 0; @Override public void run() { //스레드가 돌아가면서 데이터가 저장되지 않았을 때 업데이트하는 것을 방지해주는 서스펜더 클래스 UpdateSuspender.using(surface, new Runnable() { @Override public void run() { EngineRPM.append(x, Double.parseDouble(strings[0])); EngineOil.append(x, Double.parseDouble(strings[1])); FuelT.append(x, Double.parseDouble(strings[2])); FPumpP.append(x, Double.parseDouble(strings[3])); RPumpP.append(x, Double.parseDouble(strings[4])); Pump1P.append(x, Double.parseDouble(strings[5])); Pump2P.append(x, Double.parseDouble(strings[6])); PumpV1.append(x, Double.parseDouble(strings[7])); PumpV2.append(x, Double.parseDouble(strings[8])); CoolFenV.append(x, Double.parseDouble(strings[9])); ControlV.append(x, Double.parseDouble(strings[10])); // Zoom series to fit the viewport surface.zoomExtents(); ++x; } }); } }; //다이터를 설정하여 지속저인 스케쥴링을 할 수 잇도록 해준다. timer = new Timer(); long delay = 0; long interval = 10; timer.schedule(updateDataTask, delay, interval); //그려진 그래프 부분으로 이동시켜 보여줌 //surface.zoomExtents(); } @Override public void receiveMsg(final HashMap<Byte, Object> dataSet) { if (dataSet.containsKey(Data.ANALOG)) { CommunicationManager.graphReceived = true; Message msg= Message.obtain(); msg.what=Data.ANALOG; strings = (String[]) dataSet.get(Data.ANALOG); msg.obj=strings; Log.i("그래프", strings[0]); msgHandler.sendMessage(msg); } } Handler msgHandler = new Handler() { public void handleMessage(Message msg) { strings= (String[])msg.obj; Log.i("그래프",strings[0]); //bundle.putStringArray("data",strings); } }; @Override protected void onDestroy(){ super.onDestroy(); Log.i("종료","하자"); timer.cancel(); CommunicationManager.graphReceived=true; CommunicationManager.stopReceived=true; communicationManager.sendMsg(); getDelegate().onDestroy(); } public void receiveConnect(){ } }
true
31caefd03b3776462198e2c6f2618be74a2cfc29
Java
Exzmerald/EntityCulling-Fabric
/src/main/java/dev/tr7zw/entityculling/mixin/EntityMixin.java
UTF-8
1,046
2.078125
2
[ "MIT" ]
permissive
package dev.tr7zw.entityculling.mixin; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import dev.tr7zw.entityculling.access.DataTrackerAccessor; import dev.tr7zw.entityculling.access.EntityAccessor; import net.minecraft.entity.Entity; import net.minecraft.entity.data.DataTracker; import net.minecraft.entity.data.TrackedData; import net.minecraft.world.World; @Mixin(Entity.class) public class EntityMixin implements EntityAccessor { @Shadow private boolean glowing; @Shadow private World world; @Shadow private DataTracker dataTracker; @Shadow private static TrackedData<Byte> FLAGS; @Override public boolean isUnsafeGlowing() { return this.glowing || this.world.isClient && this.getUnsafeFlag(6); } private boolean getUnsafeFlag(int index) { Byte flagValues = ((DataTrackerAccessor) dataTracker).getUnsafe(FLAGS); if (flagValues == null) return false; return ((Byte) flagValues & 1 << index) != 0; } }
true
1dd9bf201a267010c3145bc0c48fde6de1a9e36c
Java
companieshouse/company-accounts.web.ch.gov.uk
/src/main/java/uk/gov/companieshouse/web/accounts/model/directorsreport/PrincipalActivities.java
UTF-8
761
2.03125
2
[ "MIT" ]
permissive
package uk.gov.companieshouse.web.accounts.model.directorsreport; import javax.validation.constraints.NotBlank; import uk.gov.companieshouse.web.accounts.validation.ValidationMapping; import uk.gov.companieshouse.web.accounts.validation.ValidationModel; @ValidationModel public class PrincipalActivities { @NotBlank(message = "{directorsReport.principalActivities.details.missing}") @ValidationMapping("$.statements.principal_activities") private String principalActivitiesDetails; public String getPrincipalActivitiesDetails() { return principalActivitiesDetails; } public void setPrincipalActivitiesDetails(String principalActivitiesDetails) { this.principalActivitiesDetails = principalActivitiesDetails; } }
true
ca9a238019b589f3b6f87a655cf03be7d27f60f4
Java
Firoz121/TrainingManagmentSystem
/TraningManagementUpdated1-master/TrainingManagementSystem/main-web/src/main/java/com/practice/scms/controller/UserController.java
UTF-8
1,266
2.359375
2
[]
no_license
package com.practice.scms.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.practice.scms.model.User; import com.practice.scms.serviceImpl.UserRegisterServiceImpl; @Controller public class UserController { @Autowired UserRegisterServiceImpl userRegistration; @RequestMapping("/registrationform") public ModelAndView showdetails(Model model) { User registration = new User(); model.addAttribute("registration", registration); return new ModelAndView("registerform"); } @RequestMapping(value="/register", method=RequestMethod.POST) public ModelAndView processRegister(@ModelAttribute("registration")User user ,BindingResult result) { System.out.println(user.getUsername()); if(result.hasErrors()) { System.out.println(result); } userRegistration.registerUser(user); return new ModelAndView("registrationsuccess"); } }
true
91a02e01247933e742c61956d450eb28c497f64f
Java
elphinkuo/lightDroid
/framework/util/acd/BindingFinder.java
UTF-8
2,513
2.34375
2
[ "Apache-2.0" ]
permissive
package com.elphin.framework.util.acd; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; /** * Created with IntelliJ IDEA. * User: guangongbo * Date: 13-6-25 * Time: 下午11:07 */ class BindingFinder { private static final HashMap<Class, BindingBean[]> bindingTableCache = new HashMap<Class, BindingBean[]>(); BindingFinder() { } BindingBean[] finding(Class<?> target) { BindingBean[] contents = null; synchronized (bindingTableCache) { contents = bindingTableCache.get(target); } if (contents != null) { return contents; } ArrayList<BindingBean> bindingBeans = new ArrayList<BindingBean>(); Class<?> cls = target; boolean found = false; do { String name = cls.getCanonicalName(); if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("android.")) { break; } Method[] methods = cls.getDeclaredMethods(); for (int i = 0, len = methods.length; i < len; ++i) { Binding binding = methods[i].getAnnotation(Binding.class); if (binding == null) { continue; } Id[] value = binding.value(); if (value == null || value.length == 0) { continue; } Class<?>[] parameterTypes = methods[i].getParameterTypes(); Class<?>[] targetTypes = ActionParamsMap.ACTION_PARAM_TYPES.get(binding.type()); if (Arrays.equals(parameterTypes, targetTypes)) { bindingBeans.add(new BindingBean(methods[i], binding)); found = true; } else { throw new IllegalStateException("参数类型匹配失败 -> \n\t" + Arrays.toString(parameterTypes) + " not match \n\t" + Arrays.toString(targetTypes)); } } cls = cls.getSuperclass(); } while (cls != null); if (!found) { throw new IllegalStateException("There is no binding method in " + target.getCanonicalName()); } contents = new BindingBean[bindingBeans.size()]; bindingBeans.toArray(contents); synchronized (bindingTableCache) { bindingTableCache.put(target, contents); } return contents; } }
true
55ab818f7a56cc697b04c01b82dfca8274820353
Java
Ellie111/github
/JavaDataBaseDemo/src/com/jdbcEntity/query/Pattern.java
GB18030
7,006
3.109375
3
[]
no_license
package com.jdbcEntity.query; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @ClassName: Pattern : дPattern * @Description: ƥļģʽ * @author * @date */ public final class Pattern implements Serializable { /** * @Fields serialVersionUID : TODO(һ仰ʾʲô) */ private static final long serialVersionUID = 1L; // ȫƥ public static final Integer ALL_REGEX_MATCH = 0; // ƥ public static final Integer LEFT_REGEX_MATCH = 1; // ƥ public static final Integer RIGHT_REGEX_MATCH = 2; // ģƥ public static final Integer FUZZY_REGEX_MACTH = 3; Map<String, Integer> patternMap = new HashMap<String, Integer>(); private Pattern() { } private Pattern(String key, Integer num) { patternMap.put(key, num); } public static Pattern compile(String key, Integer num) { if (!getPatternList().contains(num)) { System.out.println("error:ѡƥȷģʽ!"); return null; } return new Pattern(key, num); } public static Pattern compile(String key) { return new Pattern(key, Pattern.FUZZY_REGEX_MACTH); } private static List<Integer> getPatternList() { List<Integer> list = new ArrayList<Integer>(); list.add(ALL_REGEX_MATCH); list.add(LEFT_REGEX_MATCH); list.add(RIGHT_REGEX_MATCH); list.add(FUZZY_REGEX_MACTH); return list; } /** * @Title: getPatternData * @Description: TODO(һ仰) * @param @param pattern * @param @param intList * @param @param list * @param @param getOr * @param @return ˵ * @return List<Object[]> * @throws */ public List<Object[]> getPatternData(Pattern pattern,List<Integer> intList, List<Object[]> list,String getOr) { List<Object[]> result = new ArrayList<Object[]>(); for (Map.Entry<String, Integer> entry : pattern.patternMap.entrySet()) { switch (entry.getValue()) { case 0: result = this.getAllRegexMatch(entry.getKey(), intList, list,getOr); break; case 1: result = this.getLeftRegexMatch(entry.getKey(), intList, list,getOr); break; case 2: result = this.getRightRegexMatch(entry.getKey(), intList, list,getOr); break; case 3: result = this.getFuzzyRegexMatch(entry.getKey(), intList, list,getOr); break; } } return result; } /** * @Title: getAllRegexMatch * @Description: ȫƥ * @param @return ˵ * @return List<Object[]> * @throws */ public List<Object[]> getAllRegexMatch(String keyValue,List<Integer> intList, List<Object[]> list,String getOr){ List<Object[]> result = new ArrayList<Object[]>(); for(Object[] object : list){ //ȫƥжǷȫͬ if(intList.size() == 1){ if(keyValue.equals(object[intList.get(0)].toString())){ result.add(object); } }else{ if(keyValue.equals(object[intList.get(0)].toString()) && keyValue.equals(object[intList.get(1)].toString()) && getOr == null){ result.add(object); } if( getOr != null){ if(keyValue.equals(object[intList.get(0)].toString()) || keyValue.equals(object[intList.get(1)].toString())){ result.add(object); } } } } return result; } /** * @Title: getLeftRegexMatch * @Description: ƥ * @param @param keyValue * @param @param intList * @param @param list * @param @param getOr * @param @return ˵ * @return List<Object[]> * @throws */ public List<Object[]> getLeftRegexMatch(String keyValue,List<Integer> intList, List<Object[]> list,String getOr){ List<Object[]> result = new ArrayList<Object[]>(); for(Object[] object : list){ if(intList.size() == 1){ String str = object[intList.get(0)].toString(); if(str.length() < keyValue.length()){ continue; } String value = str.substring(0, keyValue.length()); if(keyValue.equals(value)){ result.add(object); } } else{ String str = object[intList.get(0)].toString(); String str1 = object[intList.get(1)].toString(); if(str.length() < keyValue.length() || str1.length() < keyValue.length()){ continue; } String value = str.substring(0, keyValue.length()); String value1 = str1.substring(0, keyValue.length()); if(keyValue.equals(value) && keyValue.equals(value1) && getOr == null){ result.add(object); } if( getOr != null){ if(keyValue.equals(value) || keyValue.equals(value1)){ result.add(object); } } } } return result; } /** * @Title: getRightRegexMatch * @Description: ƥ * @param @param keyValue * @param @param intList * @param @param list * @param @param getOr * @param @return ˵ * @return List<Object[]> * @throws */ public List<Object[]> getRightRegexMatch(String keyValue,List<Integer> intList, List<Object[]> list,String getOr){ List<Object[]> result = new ArrayList<Object[]>(); for(Object[] object : list){ if(intList.size() == 1){ String str = object[intList.get(0)].toString(); if(str.length() < keyValue.length()){ continue; } String value = str.substring(str.length()-keyValue.length(), str.length()); if(keyValue.equals(value)){ result.add(object); } } else{ String str = object[intList.get(0)].toString(); String str1 = object[intList.get(1)].toString(); if(str.length() < keyValue.length() || str1.length() < keyValue.length()){ continue; } String value = str.substring(str.length()-keyValue.length(), str.length()); String value1 = str1.substring(str1.length()-keyValue.length(), str1.length()); if(keyValue.equals(value) && keyValue.equals(value1) && getOr == null){ result.add(object); } if( getOr != null){ if(keyValue.equals(value) || keyValue.equals(value1)){ result.add(object); } } } } return result; } /** * @Title: getFuzzyRegexMatch * @Description: ģƥ * @param @param keyValue * @param @param intList * @param @param list * @param @param getOr * @param @return ˵ * @return List<Object[]> * @throws */ public List<Object[]> getFuzzyRegexMatch(String keyValue,List<Integer> intList, List<Object[]> list,String getOr){ List<Object[]> result = new ArrayList<Object[]>(); for(Object[] object : list){ if(intList.size() == 1){ if(object[intList.get(0)].toString().indexOf(keyValue) != -1){ result.add(object); } }else{ if(object[intList.get(0)].toString().indexOf(keyValue) != -1 && object[intList.get(1)].toString().indexOf(keyValue) != -1 && getOr == null){ result.add(object); } if( getOr != null){ if(object[intList.get(0)].toString().indexOf(keyValue) != -1 || object[intList.get(1)].toString().indexOf(keyValue) != -1){ result.add(object); } } } } return result; } }
true
4fcc165de24cfa7fb52c5024538683562380e6cf
Java
ClaudePlos/VOrders
/src/main/java/pl/vendi/ui/config/products/WndUnitsProducts.java
UTF-8
6,796
1.929688
2
[]
no_license
/* * 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 pl.vendi.ui.config.products; import com.vaadin.data.Property; import com.vaadin.data.util.BeanContainer; import com.vaadin.data.util.BeanItem; import com.vaadin.data.util.BeanItemContainer; import com.vaadin.event.ItemClickEvent; import com.vaadin.ui.ComboBox; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Table; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Window; import java.util.List; import javax.xml.registry.infomodel.Organization; import pl.vendi.ui.VOLookup; import pl.vendi.ui.common.ComboBoxOrganisationUnit; import pl.vendi.ui.common.VoExceptionHandler; import pl.vo.exceptions.VOWrongDataException; import pl.vo.organisation.model.OrganisationUnit; import pl.vo.products.api.UnitsProductsApi; import pl.vo.products.model.Product; import pl.vo.products.model.UnitsProducts; /** * * @author Piotr */ public class WndUnitsProducts extends Window { BeanItemContainer<UnitsProducts> cntUnitsProducts = new BeanItemContainer<UnitsProducts>(UnitsProducts.class); List<Product> allProducts; List<UnitsProducts> unitProducts; BeanItemContainer< Product> cntProductsToAdd = new BeanItemContainer<Product>(Product.class); VerticalLayout vboxMain = new VerticalLayout(); HorizontalLayout hboxTop = new HorizontalLayout(); HorizontalLayout hboxTables = new HorizontalLayout(); Table tabProductsToAdd = new Table("Towary do przypięcia"); Table tabProductsAdded = new Table("Towary przypisane"); ComboBoxOrganisationUnit cmbSelectObject = new ComboBoxOrganisationUnit("Wybierz obiekt"); private OrganisationUnit selectedUnit; private UnitsProductsApi unitsProductsApi; public WndUnitsProducts(){ super("Towary w obiektach"); unitsProductsApi = VOLookup.lookupUnitsProductsApi(); this.setContent( vboxMain); vboxMain.setSizeFull(); vboxMain.setMargin( true ); vboxMain.addComponent( hboxTop ); vboxMain.addComponent( hboxTables ); hboxTop.addComponent(cmbSelectObject); hboxTables.addComponent( tabProductsToAdd); hboxTables.addComponent( tabProductsAdded ); vboxMain.setExpandRatio( hboxTables, 1); hboxTables.setWidth("100%"); hboxTables.setExpandRatio( tabProductsAdded, 0.5f); hboxTables.setExpandRatio( tabProductsToAdd,0.5f); tabProductsAdded.setWidth("100%"); tabProductsToAdd.setWidth("100%"); hboxTables.setSpacing( true ); hboxTables.setSizeFull(); tabProductsAdded.setContainerDataSource( cntUnitsProducts ); tabProductsToAdd.setContainerDataSource( cntProductsToAdd ); cntProductsToAdd.addNestedContainerProperty("measureUnit.name"); tabProductsToAdd.setVisibleColumns(new String[]{"id","abbr", "indexNumber", "measureUnit.name"}); cntUnitsProducts.addNestedContainerProperty("product.measureUnit"); cntUnitsProducts.addNestedContainerProperty("product.abbr"); cntUnitsProducts.addNestedContainerProperty("product.name"); cntUnitsProducts.addNestedContainerProperty("product.indexNumber"); cntUnitsProducts.addNestedContainerProperty("product.measureUnit.name"); tabProductsAdded.setVisibleColumns(new String[]{"id","product.abbr", "product.indexNumber","product.measureUnit.name"}); tabProductsToAdd.setSelectable( true ); tabProductsToAdd.addItemClickListener( new ItemClickEvent.ItemClickListener() { @Override public void itemClick(ItemClickEvent event) { if (event.isDoubleClick() ) { BeanItem<Product> biProd= ( BeanItem<Product>) event.getItem(); addProductToUnit( (Product) biProd.getBean() ); } }}); tabProductsAdded.setSelectable( true ); tabProductsAdded.addItemClickListener( new ItemClickEvent.ItemClickListener() { @Override public void itemClick(ItemClickEvent event) { if (event.isDoubleClick() ) { BeanItem<UnitsProducts> biProd= ( BeanItem<UnitsProducts>) event.getItem(); removeProductFromUnit( biProd.getBean() ); } }}); readAllProducts(); cmbSelectObject.addValueChangeListener(new Property.ValueChangeListener() { @Override public void valueChange(Property.ValueChangeEvent event) { selectedUnit = ( OrganisationUnit ) event.getProperty().getValue(); onSelectedUnitChange(); } }); } private void readAllProducts() { allProducts = VOLookup.lookupProductsApi().findAll(); } private void onSelectedUnitChange ( ) { cntUnitsProducts.removeAllItems(); cntProductsToAdd.removeAllItems(); if ( selectedUnit != null ) { unitProducts = unitsProductsApi.findForUnit( selectedUnit.getId() ); cntUnitsProducts.addAll( unitProducts); // parse products for (Product prod : allProducts ) { Boolean fContains = false; for ( UnitsProducts upr : unitProducts ){ if ( upr.getProduct().getId().equals( prod.getId() )) fContains = true ; } if ( !fContains ) { cntProductsToAdd.addItem( prod ); } } } } private void addProductToUnit( Product prod ) { try { UnitsProducts up = unitsProductsApi.addProductToUnit( prod.getId(), selectedUnit.getId()); cntProductsToAdd.removeItem( prod ); cntUnitsProducts.addItem( up ) ; } catch( VOWrongDataException wre){ VoExceptionHandler.handleException(wre); } } private void removeProductFromUnit( UnitsProducts up ) { try { unitsProductsApi.delete( up ); cntProductsToAdd.addItem( up.getProduct()); cntUnitsProducts.removeItem( up ); } catch( VOWrongDataException wre){ VoExceptionHandler.handleException(wre); } } }
true
cddaba8e2d7ca5e401c7a5f0b62948f165801eaf
Java
epsstan/kata2go
/kata2go-executor/src/main/java/com/goldmansachs/kata2go/executor/runner/StdOutStdErrCapturingKataRunner.java
UTF-8
3,352
2.390625
2
[ "Apache-2.0" ]
permissive
/* Copyright 2017 Goldman Sachs. 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.goldmansachs.kata2go.executor.runner; import com.goldmansachs.kata2go.executor.compiler.ByteArrayFileObject; import junit.framework.JUnit4TestAdapter; import junit.framework.TestResult; import junit.textui.TestRunner; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.NoTestsRemainException; import java.util.Map; /* Wrapper around the standard Junit runner. */ public class StdOutStdErrCapturingKataRunner { public static synchronized KataJunitTestResult run(Map<String, ByteArrayFileObject> classes, String testClassName) { return run(classes, testClassName, Filter.ALL); } public static synchronized KataJunitTestResult run(Map<String, ByteArrayFileObject> classes, String testClassName, String testName) { return run(classes, testClassName, new MethodNameFilter(testName)); } /* This method has to be static synchronized to serialize access to the JVM's stdout and stderr streams This method does the following : 1) Capture the JVM's stdout and stderr 2) Reset the JVM's stdout and stderr with new streams 3) Runs the input test class 4) Reset the JVM's stdout and stderr with the streams from step 1) 5) Returns the Junit test result along with the stdout and stderr step 2) */ private static synchronized KataJunitTestResult run(Map<String, ByteArrayFileObject> classes, String testClassName, Filter testFilter) { StreamsCaptor.Pair streamsPair = StreamsCaptor.captureAndResetSystemStreams(); try { ManagedClassLoader managedClassLoader = new ManagedClassLoader(classes); Class<?> testClass = null; try { testClass = managedClassLoader.findClass(testClassName); } catch (ClassNotFoundException e) { // TODO: handle exception e.printStackTrace(); } JUnit4TestAdapter adapter = new JUnit4TestAdapter(testClass); try { adapter.filter(testFilter); } catch (NoTestsRemainException e) { // TODO: handle exception e.printStackTrace(); } TestResult testResult = new TestRunner().doRun(adapter, false); return ImmutableKataJunitTestResult.builder() .junitResult(testResult) .stdOut(streamsPair.newStreams.getStdOutByteArray().toString()) .stdErr(streamsPair.newStreams.getStdErrByteArray().toString()) .build(); } finally { streamsPair.restoreSystemStreams(); } } }
true
04c5a17c8454c021573d08a5e5818c15b3192cd1
Java
vytautasphp/src
/Uzduotis23/Main.java
UTF-8
1,167
3.109375
3
[]
no_license
package Uzduotis23; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; public class Main { static final long LOOP = 100; public static void main(String... args) throws InterruptedException { List<Integer> list = Collections.synchronizedList(new ArrayList<>()); for (int y = 0; y < 10; y++) { // Create Thread class Thread temp = new Thread(() -> { for (int i = 0; i < LOOP; i++) { Random rand = new Random(); int x = rand.nextInt(100) + 1; list.add(x); } }); temp.start(); try { temp.join(10); } catch (InterruptedException e) { e.printStackTrace(); } } Map<Integer, Long> lista = list.stream() .collect(Collectors.groupingBy( Function.identity(), Collectors.counting())); System.out.println(lista); } }
true
ada60c1c1cc55ac19fb4ded654e7cbe0d2ef54e3
Java
vladRak/crm-system
/src/main/java/jcrm/pp/ua/crmsystem/domain/entity/Lead.java
UTF-8
1,257
2.125
2
[]
no_license
package jcrm.pp.ua.crmsystem.domain.entity; import jcrm.pp.ua.crmsystem.domain.BaseClientImplImpl; import jcrm.pp.ua.crmsystem.domain.BaseTaskTargetImpl; import jcrm.pp.ua.crmsystem.listeners.event.RootAware; import lombok.Data; import lombok.EqualsAndHashCode; import javax.persistence.*; import java.math.BigDecimal; import static javax.persistence.CascadeType.MERGE; @Entity @Table(name = "lead") //@DiscriminatorValue("lead") @EqualsAndHashCode(callSuper = true) //@Audited @Data public class Lead extends BaseTaskTargetImpl implements RootAware<BaseClientImplImpl> { private static final long serialVersionUID = 1L; private String leadName; private String leadStatus; private BigDecimal budget; @ManyToOne(cascade = {CascadeType.PERSIST, MERGE}) @JoinColumn(name = "client_id") private BaseClientImplImpl client; @Override public BaseClientImplImpl root() { return client; } public Lead() { } public void setClient(BaseClientImplImpl client) { setClient(client, true); } public void setClient(BaseClientImplImpl client, boolean add) { this.client = client; if (client != null && add) { client.addLead(this, false); } } }
true
6679bd745070b8706d36a2e38aa68c8e4884fab0
Java
agreea/Des-Forges
/src/com/example/radr/backend/EventLoader.java
UTF-8
990
2.34375
2
[]
no_license
package com.example.radr.backend; import java.util.List; import android.content.Context; import android.util.Log; import com.example.radr.AleppoEvent; import com.example.radr.backend.database.RadarDataHelper; import com.example.radr.backend.util.ListLoader; import com.example.radr.util.LogTags; public class EventLoader extends ListLoader<AleppoEvent> { // TODO: Put this in an xml resource private static final int DEFAULT_NUM_EVENTS = 1000; private final int mNumEvents; Context c; public EventLoader(Context context) { this(context, DEFAULT_NUM_EVENTS); } public EventLoader(Context context, int numEvents) { super(context); c = context; mNumEvents = numEvents; Log.v(LogTags.BACKEND_LOAD, "Constructing EventLoader with mNumEvents=" + mNumEvents); } @Override protected List<AleppoEvent> getData() { Log.v(LogTags.BACKEND_LOAD, "Retrieving ranked events with mNumEvents=" + mNumEvents); return (new RadarDataHelper(c)).getRankedEvents(mNumEvents); } }
true
96335811cdd3ca25b18e13a20a2128b54d977fdf
Java
jimmy-he/asterisk-java-unifor-yvens
/WebAppConvergence/src/servlets/ListAgentServlet.java
UTF-8
2,289
2.390625
2
[]
no_license
package servlets; import java.io.IOException; import java.util.List; 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 model.queues.Agent; import asterisk.AgentHandler; /** * Servlet implementation class ListAgentServlet */ @WebServlet("/ListAgentServlet") public class ListAgentServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ListAgentServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String error = ""; String feedback = ""; String forward = "/Pages/Application/tableAgent.jsp"; try { AgentHandler handler = new AgentHandler(); if(request.getParameter("remover") != null){ //Manda o comando para remover o WaitQueue que possua a tag recebida pela URL String id = request.getParameter("id"); Agent agent = handler.getAgent(Integer.parseInt(id)); boolean remocao = handler.deleteAgent(agent); if(remocao){ feedback = "Agente removido com sucesso!"; }else{ error = "Algum outro usuário está alterando o arquivo, por favor, tente novamente!"; } } //Preenchendo o feedback de alteração de plano if (request.getAttribute("feedback") != null){ feedback = (String) request.getAttribute("feedback"); } List<Agent> list = handler.listAgent(); request.setAttribute("list", list); } catch (Exception e) { error = e.getMessage(); e.printStackTrace(); } finally { request.setAttribute("feedback", feedback); request.setAttribute("error", error); getServletContext().getRequestDispatcher(forward).forward(request, response); } } }
true
54ecd4518a262a7656968e327be46c1f59a0db38
Java
LDawns/java20-homework
/8-Generics/王浩天-181860093/generics/Calabash_Brothers.java
UTF-8
447
3.046875
3
[]
no_license
package generics; public class Calabash_Brothers<T extends Myinteger> extends Human { Calabash_Brothers(T i,String na){ this.value=i; this.name=na; } boolean compare_val(Calabash_Brothers<T> a) { if(this.value.compareTo(a.value)<0)return true; else return false; } void swap(Calabash_Brothers<T> a) { Myinteger tem_val=a.getval(); String tem_nam=a.getname(); a.change(value, name); this.change( tem_val, tem_nam); } }
true
aecb857860362a7d0b6290bfabc96418d49e0d24
Java
gretchenfrage/BDT
/src/bdt/variabletypes/ByteVar.java
UTF-8
730
3.03125
3
[]
no_license
package bdt.variabletypes; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import bdt.Variable; public class ByteVar implements Variable { private byte value; public ByteVar(byte valueIn) { value = valueIn; } public ByteVar(InputStream stream) { try { value = (byte) stream.read(); } catch (IOException e) { throw new RuntimeException(); } } public byte getValue() { return value; } public void setValue(byte valueIn) { value = valueIn; } @Override public void writeTo(OutputStream stream) { try { stream.write(value); } catch (IOException e) { throw new RuntimeException(); } } public String toString() { return value + "b"; } }
true
f4bbd5f8cbae37f754469de880078c74f3b8109d
Java
zvorygin/graphql-over-sql
/graphql-sql/src/main/java/graphql/sql/core/StaticFieldExecutor.java
UTF-8
462
2.28125
2
[ "MIT" ]
permissive
package graphql.sql.core; import javax.annotation.Nonnull; import java.sql.Connection; import java.sql.SQLException; import java.util.Map; class StaticFieldExecutor implements FieldExecutor { private final Object value; public StaticFieldExecutor(Object value) { this.value = value; } @Nonnull @Override public Object execute(Connection conn, Map<String, Object> variables) throws SQLException { return value; } }
true
eb443497a1d66140016cb3d2cc1b01ba2319be81
Java
JulienAlauzet/IUT
/AS/TPs - POO/tp3-JulienAlauzet/src/main/java/fr/umontpellier/iut/exo1/Etudiant.java
UTF-8
1,002
2.71875
3
[]
no_license
package fr.umontpellier.iut.exo1; import java.time.LocalDate; public class Etudiant { private String nom; private String prenom; private LocalDate dob; private String adresseMail; private String adressePostale; public Etudiant(String nom, String prenom, LocalDate dob, String adresseMail, String adressePostale) { this.nom = nom; this.prenom = prenom; this.dob = dob; this.adresseMail = adresseMail; this.adressePostale = adressePostale; } @Override public String toString() { return "Etudiant{" + "nom='" + nom + '\'' + ", prenom='" + prenom + '\'' + ", dob=" + dob + ", adresseMail='" + adresseMail + '\'' + ", adressePostale='" + adressePostale + '\'' + '}'; } public void setNom(String nom, String prenom) { this.nom = nom; this.prenom = prenom; } }
true
7699c0a0b07e912fd3c6ceaf09fe9df81ed980c0
Java
williammeger/hacker-rank
/30-Days-of-Code/06-Lets-Review/Solution.java
UTF-8
829
3.890625
4
[]
no_license
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { int stringCount = sc.nextInt(); sc.nextLine(); for (int a = 0; a <= stringCount; a++) { String str = sc.next(); printEvenOdd(str); } } } public static void printEvenOrOdd (String s) { StringBuffer even = new StringBuffer(); StringBuffer odd = new StringBuffer(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); // bitwise operation check on odd/even indices if ((i & 1) == 0) { even.append(c); } else { odd.append(c); } } System.out.println(even + " " + odd); } }
true
47efcc91dc109678b870006dac61909de12c76f3
Java
alexoooo/datamine-ai
/ai-model/src/main/java/ao/ai/model/ml/classify/hypothesis/classifier/grid/BinGridBinClassifier.java
UTF-8
318
1.523438
2
[]
no_license
package ao.ai.model.ml.classify.hypothesis.classifier.grid; import ao.ai.model.common.data.BinGrid; import ao.ai.model.ml.classify.hypothesis.classifier.bin.BinClassifier; /** * User: alex * Date: 4-May-2010 * Time: 11:00:37 PM */ public interface BinGridBinClassifier extends BinClassifier<BinGrid> { }
true
87458d0428bab15118f8e24c9b456cc656771507
Java
wanghkzzz/MegaMart
/app/src/main/java/com/benben/megamart/adapter/MyAccountAdapter.java
UTF-8
2,354
2.34375
2
[]
no_license
package com.benben.megamart.adapter; import android.app.Activity; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.benben.commoncore.utils.DateUtils; import com.benben.megamart.R; import com.benben.megamart.bean.AccountListBean; import butterknife.BindView; import butterknife.ButterKnife; public class MyAccountAdapter extends AFinalRecyclerViewAdapter<AccountListBean.UserBalanceBean> { private Activity mActivity; public MyAccountAdapter(Context ctx) { super(ctx); mActivity = (Activity) ctx; } @Override protected BaseRecyclerViewHolder onCreateCustomerViewHolder(ViewGroup parent, int viewType) { return new MyAccountListViewHoler(m_Inflater.inflate(R.layout.item_my_account, parent, false)); } @Override protected void onBindCustomerViewHolder(BaseRecyclerViewHolder holder, int position) { ((MyAccountListViewHoler) holder).setContent(getItem(position), position); } public class MyAccountListViewHoler extends BaseRecyclerViewHolder { @BindView(R.id.tv_money) TextView tvMoney; @BindView(R.id.tv_title) TextView tvTitle; @BindView(R.id.tv_time) TextView tvTime; public MyAccountListViewHoler(View view) { super(view); ButterKnife.bind(this, view); } private void setContent(AccountListBean.UserBalanceBean mUserBalanceBean, int position) { if("1".equals(mUserBalanceBean.getType())){ tvTitle.setText(m_Context.getResources().getString(R.string.recharge)); tvMoney.setText("-$" + mUserBalanceBean.getChange_money()); }else if("2".equals(mUserBalanceBean.getType())){ tvTitle.setText(m_Context.getResources().getString(R.string.consumption)); tvMoney.setText("-$" + mUserBalanceBean.getChange_money()); }else { tvTitle.setText(m_Context.getResources().getString(R.string.refunds)); tvMoney.setText("+$" + mUserBalanceBean.getChange_money()); } // tvTitle.setText(mUserBalanceBean.getBal_title()); tvTime.setText(DateUtils.stampToDate(String.valueOf(mUserBalanceBean.getChange_time()))); } } }
true
ae85f449cbf1d2feb86b5e7dd595b1c9359875f3
Java
KAILASH27/Spring-Practice
/SpringWeb/src/main/java/com/opentext/SptingWeb/controller/SpringWebController.java
UTF-8
982
2.3125
2
[]
no_license
package com.opentext.SptingWeb.controller; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.opentext.SpringWeb.model.ModelClass; @Controller public class SpringWebController { @RequestMapping(path = "/LoginForm", method = RequestMethod.GET) public String loginForm() throws IOException { return "LoginForm"; }// End of loginform() @RequestMapping(path = "/authenticate", method = RequestMethod.POST) public String authenticate(HttpServletRequest req) throws IOException { String username = req.getParameter("username"); String password = req.getParameter("password"); ModelClass model = new ModelClass(); if (model.authenticate(username, password)) { return "HomePage"; } return "LoginPage"; }// End of authenticate }// End of Controller
true
c27c84e03159b560d66a41dc2fa9de48a1867e57
Java
bizhan-laripour/PDF
/src/main/java/net/dpco/pdf/service/impl/DependantServiceImpl.java
UTF-8
1,080
2.21875
2
[]
no_license
package net.dpco.pdf.service.impl; import net.dpco.pdf.dao.DependantDao; import net.dpco.pdf.entity.Applicant; import net.dpco.pdf.entity.Dependant; import net.dpco.pdf.service.DependantService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class DependantServiceImpl implements DependantService { private DependantDao dependantDao; @Autowired public DependantServiceImpl(DependantDao dependantDao){ this.dependantDao = dependantDao; } @Override public Dependant save(Dependant dependant) throws Exception { try{ return dependantDao.save(dependant); }catch (Exception ex){ throw new Exception(ex.getMessage()); } } @Override public List<Dependant> findByApplicant(Applicant applicant) throws Exception { try{ return dependantDao.findByApplicant(applicant); }catch (Exception ex){ throw new Exception(ex.getMessage()); } } }
true
85ed0df6b83b2ea9979ebdbd6e32745bdc872512
Java
brunoallison/classificadorDePalavras
/src/Principal/Main.java
UTF-8
1,686
3.109375
3
[]
no_license
package Principal; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in)); // objeto para leitura da palavra Palavra palavra = new Palavra("peteca"); //instanciando um objeto do tipo palavra e fazendo a leitura palavra.AnalisarPalavra(); /*System.out.println("###############################"); Palavra palavra1 = new Palavra("caneta"); palavra1.AnalisarPalavra(); System.out.println("###############################"); Palavra palavra2 = new Palavra("borracha"); palavra2.AnalisarPalavra(); System.out.println("###############################"); Palavra palavra3 = new Palavra("caderno"); palavra3.AnalisarPalavra(); System.out.println("###############################"); Palavra palavra4 = new Palavra("livro"); palavra4.AnalisarPalavra(); System.out.println("###############################"); Palavra palavra5 = new Palavra("estojo"); palavra5.AnalisarPalavra(); System.out.println("###############################"); Palavra palavra6 = new Palavra("cola"); palavra6.AnalisarPalavra(); System.out.println("###############################"); Palavra palavra7 = new Palavra("pasta"); palavra7.AnalisarPalavra(); System.out.println("###############################"); Palavra palavra8 = new Palavra("sulfite"); palavra8.AnalisarPalavra(); System.out.println("###############################"); Palavra palavra9 = new Palavra("canetinha"); palavra9.AnalisarPalavra();*/ } }
true
b21e8c668303dc3eae2b2a1a2c87c8feddceaadf
Java
agrasso87/RealEstateListingDatabase
/IndustrialProperty.java
UTF-8
2,387
3.609375
4
[]
no_license
package M1Homework; /** * The IndustrialProperty Class is a child class of the Property class * that can be listed in the Real Estate Listing database. * * In addition to the instance data variables of Property, IndustrialProperty * also has an instance data variable that describes the manufacturing type that * the Industrial Property houses. * * @author Alex * */ public class IndustrialProperty extends Property { private String manufactType; public static final double I_MORTGAGE = .0525; public static final double I_TAX = .016; public static final double I_COMMISSION = .04; public IndustrialProperty(String a, int v, int ln, String m) { super(a, v, ln); manufactType = m; } public IndustrialProperty () { this(null, 0, 0, null); } public void setManufacturing(String b) { manufactType = b; } public String getManufacturing() { return manufactType; } @Override public String toString() { return super.toString() + "\r\nThe manufacturing type is: " + manufactType; } @Override public boolean equals(Object otherProperty) { IndustrialProperty other = (IndustrialProperty) otherProperty; if (this.equals(other) && other.manufactType.equals(manufactType)) return true; else return false; } /** * This method overrides the parent mortgageCalculator() method and provides * an estimated value for the monthly mortgage based on historical industrial * mortgage rates * * @return estimated monthly mortgage */ @Override public double mortgageCalculator() { return ((this.getValue() + (this.getValue() * IndustrialProperty.I_MORTGAGE))/30); } /** * This method overrides the parent taxCalculator() method and provides * an estimated value for the annual property tax based on historical industrial * property tax rates * * @return estimated annual property tax */ @Override public double taxCalculator() { return (this.getValue() * IndustrialProperty.I_TAX); } /** * This method overrides the parent commissionCalculator() method and provides * an estimated value for the percent commission on the * sale of the property by a broker based on the historical industrial broker commissions. * * @return estimated broker's commission */ @Override public double commissionCalculator() { return (this.getValue() * IndustrialProperty.I_COMMISSION); } }
true
7f73e3ebd2b6d0e1cbe85950ac5010b881680688
Java
kshdreams/social-api
/library/src/main/java/com/android/sebiya/net/social/instagram/InstagramApiImpl.java
UTF-8
2,944
2.25
2
[ "Apache-2.0" ]
permissive
package com.android.sebiya.net.social.instagram; import com.android.sebiya.net.SimpleRetrofit; import com.android.sebiya.net.social.instagram.response.Response; import com.android.sebiya.net.social.instagram.response.media.Comment; import com.android.sebiya.net.social.instagram.response.media.UserMedia; import com.android.sebiya.net.social.instagram.response.user.UserInfo; import io.reactivex.Single; import io.reactivex.SingleSource; import java.util.List; import java.util.concurrent.Callable; public class InstagramApiImpl implements InstagramApi { private InstagramApi mApi; public InstagramApi getApi() { if (mApi == null) { // TODO : make okhttp client if you want to add interceptors mApi = SimpleRetrofit.create(InstagramUrls.API_URL, InstagramApi.class); } return mApi; } @Override public Single<Response<List<Comment>>> mediaComments(final String mediaId, final String token) { return Single.defer(new Callable<SingleSource<? extends Response<List<Comment>>>>() { @Override public SingleSource<? extends Response<List<Comment>>> call() throws Exception { return getApi().mediaComments(mediaId, token); } }); } @Override public Single<Response<UserInfo>> userSelf(final String token) { return Single.defer(new Callable<SingleSource<? extends Response<UserInfo>>>() { @Override public SingleSource<? extends Response<UserInfo>> call() throws Exception { return getApi().userSelf(token); } }); } @Override public Single<Response<List<UserMedia>>> userSelfRecentMedia(final String token) { return Single.defer(new Callable<SingleSource<? extends Response<List<UserMedia>>>>() { @Override public SingleSource<? extends Response<List<UserMedia>>> call() throws Exception { return getApi().userSelfRecentMedia(token); } }); } @Override public Single<Response<List<UserMedia>>> userSelfRecentMedia(final String token, final String maxId, final String minId, final int count) { return Single.defer(new Callable<SingleSource<? extends Response<List<UserMedia>>>>() { @Override public SingleSource<? extends Response<List<UserMedia>>> call() throws Exception { return getApi().userSelfRecentMedia(token, maxId, minId, count); } }); } @Override public Single<Response<List<UserMedia>>> userSelfRecentMediaNext(final String url) { return Single.defer(new Callable<SingleSource<? extends Response<List<UserMedia>>>>() { @Override public SingleSource<? extends Response<List<UserMedia>>> call() { return getApi().userSelfRecentMediaNext(url); } }); } }
true
0d58f876ec279ff49abab02810d42f7217a5ac5b
Java
pathakashish/Generic
/src/com/aviras/generic/BaseLoaderCallbacks.java
UTF-8
840
1.984375
2
[]
no_license
package com.aviras.generic; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.Loader; public class BaseLoaderCallbacks<D> implements LoaderCallbacks<D> { @Override public Loader<D> onCreateLoader(int arg0, Bundle arg1) { // TODO Auto-generated method stub return null; } @Override public void onLoadFinished(Loader<D> arg0, D arg1) { // TODO Auto-generated method stub } @Override public void onLoaderReset(Loader<D> arg0) { // TODO Auto-generated method stub } public void useLoader(FragmentActivity a, int id, Bundle args, boolean checkInternet) { Loader<D> loader = a.getSupportLoaderManager().initLoader(id, args, this); loader.forceLoad(); } }
true
ada7da08a97fbdfb34d14daf32a0825dc059635b
Java
winklesen/Petani
/app/src/main/java/com/samuelbernard147/soag/fragment/ChiliFragment.java
UTF-8
6,473
2.015625
2
[]
no_license
package com.samuelbernard147.soag.fragment; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import com.samuelbernard147.soag.Helper.PlantHelper; import com.samuelbernard147.soag.R; import com.samuelbernard147.soag.preference.TimerPreference; public class ChiliFragment extends Fragment implements View.OnClickListener { private TimerPreference pref; private PlantHelper helper; private CountDownTimer timer; private Boolean isRunning = false; private ProgressBar pbCircle; private TextView tvTime; private TextView tvDateEnd; private SwipeRefreshLayout refresh; private Button btnStart, btnHistory; public ChiliFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_cabai, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); pbCircle = view.findViewById(R.id.pb_circle_chili); tvTime = view.findViewById(R.id.tv_time_chili); tvDateEnd = view.findViewById(R.id.tv_date_end_chili); btnStart = view.findViewById(R.id.btn_start_chili); btnHistory = view.findViewById(R.id.btn_history_chili); btnStart.setOnClickListener(this); btnHistory.setOnClickListener(this); if (getActivity() != null) { helper = new PlantHelper(getActivity()); pref = new TimerPreference(getActivity()); } refresh = view.findViewById(R.id.refresh_chili); refresh.setColorSchemeResources(R.color.colorAccent); refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { checkPlant(); refresh.setRefreshing(false); } }, 2000); //4000 millisecond = 4 detik } }); checkPlant(); } @Override public void onStart() { super.onStart(); if (pref.getStatus(TimerPreference.CHILI)) { checkPlant(); } } @Override public void onResume() { super.onResume(); if (pref.getStatus(TimerPreference.CHILI)) { checkPlant(); } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_start_chili: helper.postStatus(TimerPreference.CHILI, "on"); pref.setStatus(TimerPreference.CHILI, true); pref.setInterval(TimerPreference.CHILI_INTERVAL, 600); tvTime.clearAnimation(); tvTime.animate().cancel(); startTimer(); btnStart.setEnabled(false); break; case R.id.btn_history_chili: showDialog(); break; } } private void startTimer() { isRunning = true; btnStart.setEnabled(false); final int second = pref.getInterval(TimerPreference.CHILI_INTERVAL); timer = new CountDownTimer(second * 1000, 500) { @Override public void onTick(long leftTimeInMilliseconds) { long seconds = leftTimeInMilliseconds / 1000; pbCircle.setProgress((int) seconds); tvDateEnd.setText(getResources().getString(R.string.perkiraan_panen)); tvTime.setText(helper.timeConverter(leftTimeInMilliseconds)); } @Override public void onFinish() { btnStart.setEnabled(true); pref.setStatus(TimerPreference.CHILI, false); pref.setInterval(TimerPreference.CHILI_INTERVAL, 0); tvDateEnd.setText(getResources().getString(R.string.selesai)); tvTime.setText(getResources().getString(R.string.siap_panen)); helper.showNotification( getActivity(), getResources().getString(R.string.panen_title), String.format(getResources().getString(R.string.panen_desc), "Cabai"), 1 ); blink(500); helper.postStatus(TimerPreference.CHILI, "off"); isRunning = false; } }.start(); } private void blink(final int time) { Animation anim = new AlphaAnimation(0.0f, 1.0f); anim.setDuration(time); //You can manage the time of the blink with this parameter anim.setStartOffset(20); anim.setRepeatMode(Animation.REVERSE); anim.setRepeatCount(Animation.INFINITE); tvTime.startAnimation(anim); } private void checkPlant() { helper.loadPlant(TimerPreference.CHILI, TimerPreference.CHILI_INTERVAL); if (pref.getStatus(TimerPreference.CHILI)) { if (isRunning) { timer.cancel(); } startTimer(); btnStart.setEnabled(false); } else { if (isRunning) { timer.cancel(); } pbCircle.setProgress(0); tvDateEnd.setText(getResources().getString(R.string.belum_dipanen)); tvTime.setText(getResources().getString(R.string.time)); btnStart.setEnabled(true); } } private void showDialog() { BottomSheetFragment bottomSheetFragment = new BottomSheetFragment(); Bundle bundle = new Bundle(); bundle.putString("TAG",TimerPreference.CHILI); bottomSheetFragment.setArguments(bundle); bottomSheetFragment.show(getChildFragmentManager(), bottomSheetFragment.getTag()); } }
true
763b812b56795a03836dad2ead9635bd6995730f
Java
maximinetto/media-app-backend
/src/main/java/com/mitocode/dao/IPacienteDAO.java
UTF-8
710
2.0625
2
[]
no_license
package com.mitocode.dao; import java.util.List; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import com.mitocode.model.Paciente; public interface IPacienteDAO extends JpaRepository<Paciente, Integer>{ // @Query("SELECT p FROM Paciente p WHERE UPPER(CONCAT(p.nombres, ' ',p.apellidos)) LIKE %:busqueda%") List<Paciente> obtenerPacientePorBusqueda(@Param("busqueda")String busqueda, Pageable pageable); @Query("SELECT p FROM Paciente p ORDER BY p.idPaciente desc") List<Paciente> obtenerUltimoPaciente(Pageable pageable); }
true
0e764cd3cadfcbb5f6fab2ee3db4863a58aec785
Java
abramovvicz/bookshopII
/src/main/java/dao/BookDAO.java
UTF-8
2,360
2.8125
3
[]
no_license
package dao; import enums.FileTypes; import model.Author; import model.Book; import utils.CheckApplicationState; import utils.UserInput; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class BookDAO { private UserInput userInput = new UserInput(); private CheckApplicationState checkApplicationState = CheckApplicationState.getInstance(); public void deleteBookByID(List<Book> bookList) { if (bookList.isEmpty()) { System.out.println("Book list is empty"); } else { System.out.println("Enter book ID to delete"); List<Book> copyOfBookList = new ArrayList<>(bookList); boolean flag = true; while (flag) { int idEnteredByUser = getBookIdFromUser(); for (Book book : copyOfBookList) { if (book.getId() == idEnteredByUser) { bookList.remove(book); System.out.println("Remove successful"); checkApplicationState.setStatus(true); flag = false; } } if (flag) { System.out.println("Did`int find any ids. Renter ID:"); } } } } public void deleteBookByIdStream(List<Book> bookList) { if (bookList.isEmpty()) { System.out.println("Book list is empty"); } else { System.out.println("Enter book ID to delete"); List<Book> copyOfBookList = new ArrayList<>(bookList); while (true) { int idBook = userInput.getNumberFromUser(); Optional<Book> first = copyOfBookList.stream().filter(x -> idBook == x.getId()).findFirst(); if (first.isPresent()) { bookList.remove(first.get()); checkApplicationState.setStatus(true); System.out.println("Successfully remove book of if: " + idBook); break; } else { System.out.println("Did`int find any ids. Renter ID:"); } } } } private int getBookIdFromUser() { return userInput.getNumberFromUser(); } }
true
175bd742336fe28647daf2fca36403188c1ccae7
Java
WislieZhu/java-
/src/chapter_interface/Processor.java
UTF-8
159
1.890625
2
[]
no_license
package chapter_interface; /** * Created by wislie on 2018/10/29. */ public interface Processor { String getName(); Object process(Object obj); }
true
07817e945c55353956f6547626f32b9b6febdc29
Java
xiaosong-git/weixin
/src/main/java/com/company/project/service/impl/UserServiceImpl.java
UTF-8
34,576
1.78125
2
[]
no_license
package com.company.project.service.impl; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.company.project.compose.Status; import com.company.project.compose.TableList; import com.company.project.core.AbstractService; import com.company.project.core.Result; import com.company.project.core.ResultGenerator; import com.company.project.dao.*; import com.company.project.model.*; import com.company.project.service.*; import com.company.project.util.*; import com.company.project.weixin.MyWxServiceImpl; import com.soecode.wxtools.api.IService; import com.soecode.wxtools.exception.WxErrorException; import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.interceptor.TransactionAspectSupport; import tk.mybatis.mapper.entity.Condition; import javax.annotation.Resource; import java.io.File; import java.net.URLDecoder; import java.text.SimpleDateFormat; import java.util.*; /** * Created by CodeGenerator on 2019/10/09. */ @Service @Transactional public class UserServiceImpl extends AbstractService<User> implements UserService { @Resource private UserMapper tblUserMapper; private final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); @Resource private PasswordService passwordService; @Resource private ParamService paramService; @Resource private CodeService codeService; @Resource private UserAccountService userAccountService; @Resource private KeyService keyService; @Resource private CompanyService companyService; @Resource private OrgService orgService; @Resource private UserAuthMapper userAuthMapper; @Resource private UserMapper userMapper; @Resource private CompanyMapper companyMapper; @Resource private VisitRecordMapper visitRecordMapper; @Resource private OtherOpenidMapper otherOpenidMapper; @Resource private OtherWxMapper otherWxMapper; @Resource private OtherOpenidService otherOpenidService; @Value("${imgUrl}") private String imgUrl; private IService iService = new MyWxServiceImpl(); /** * 检测用户是否存在 * * @param realName * @param phone * @return java.util.List<com.company.project.model.User> * @throws Exception * @author cwf * @date 2019/10/13 17:10 */ @Override public List<User> findByNamePhone(String realName, String phone) { Condition condition = new Condition(User.class); condition.createCriteria().andEqualTo("realname", realName).andEqualTo("phone", phone); condition.selectProperties("id"); List<User> list = super.findByCondition(condition); // System.out.println(list.get(0).getCompanyId()); // System.out.println(list); return list; } @Override public Result login(String phone, String password, String openId) throws Exception { User user = findBy("phone", phone); if (user == null) { return ResultGenerator.genFailResult("用户不存在"); } long userId = user.getId(); //判断密码输入次数是否超出限制,超出无法登录 if (passwordService.isErrInputOutOfLimit(String.valueOf(userId), Status.PWD_TYPE_SYS)) { String limitTime = paramService.findValueByName("errorInputSyspwdWaitTime"); codeService.sendMsg(user.getLoginname() + "", 2, null, null, null, null); return ResultGenerator.genFailResult("由于您多次输入错误密码,为保证您的账户与资金安全," + limitTime + "分钟内无法登录", "fail"); } UserAccount userAccount = userAccountService.findByUserId(userId); if (userAccount == null) { return ResultGenerator.genFailResult("找不到用户的账户信息", "fail"); } String dbPassword = userAccount.getSyspwd() + "";//正确密码 if (password.equals(dbPassword)) { //重置允许用户输入错误密码次数 passwordService.resetPwdInputNum(String.valueOf(userId), Status.PWD_TYPE_SYS); String cstatus = userAccount.getCstatus() + ""; if ("normal".equals(cstatus)) { User userUpdate = new User(); userUpdate.setId(userId); userUpdate.setToken(UUID.randomUUID().toString()); userUpdate.setWxOpenId(openId); this.update(userUpdate); user = this.findById(userId); //更新缓存中的Token,实人 String token = user.getToken(); String isAuth = user.getIsauth(); updateRedisTokenAndAuth(String.valueOf(user.getId()), token, isAuth); //获取密钥 String workKey = keyService.findKeyByStatus(TableList.KEY_STATUS_NORMAL); if (workKey != null) { user.setWorkkey(workKey); } return ResultGenerator.genSuccessResult(user); } else { //返回登录失败事由 String handleCause = userAccount.getHandlecause(); return ResultGenerator.genFailResult(handleCause); } } else { Long leftInputNum = passwordService.addErrInputNum(String.valueOf(userId), Status.PWD_TYPE_SYS); return ResultGenerator.genFailResult("密码错误:剩余" + leftInputNum + "次输入机会", "fail"); } } @Override public void updateRedisTokenAndAuth(String userId, String token, String isAuth) throws Exception { if (StringUtils.isBlank(userId) || StringUtils.isBlank(token) || StringUtils.isBlank(isAuth)) { return; } Integer apiNewAuthCheckRedisDbIndex = Integer.valueOf(paramService.findValueByName("apiNewAuthCheckRedisDbIndex"));//存储在缓存中的位置 Integer expire = Integer.valueOf(paramService.findValueByName("apiAuthCheckRedisExpire"));//过期时间(分钟) //redis修改 RedisUtil.setStr(userId + "_token", token, apiNewAuthCheckRedisDbIndex, expire * 60); //redis修改 RedisUtil.setStr(userId + "_isAuth", isAuth, apiNewAuthCheckRedisDbIndex, expire * 60); } //更新实人 @Override public void updateRedisAuth(String userId, String isAuth) throws Exception { if (StringUtils.isBlank(userId) || StringUtils.isBlank(isAuth)) { return; } Integer apiNewAuthCheckRedisDbIndex = Integer.valueOf(paramService.findValueByName("apiNewAuthCheckRedisDbIndex"));//存储在缓存中的位置 Integer expire = Integer.valueOf(paramService.findValueByName("apiAuthCheckRedisExpire"));//过期时间(分钟) //redis修改 RedisUtil.setStr(userId + "_isAuth", isAuth, apiNewAuthCheckRedisDbIndex, expire * 60); } //更新微信号 @Override public void updateRedisOpenId(String userId, String openId) throws Exception { if (StringUtils.isBlank(userId) || StringUtils.isBlank(openId)) { return; } //36 Integer apiNewAuthCheckRedisDbIndex = Integer.valueOf(paramService.findValueByName("wxOpenIdCheckRedisDbindex"));//存储在缓存中的位置 Integer expire = Integer.valueOf(paramService.findValueByName("apiAuthCheckRedisExpire"));//过期时间(分钟) //redis修改 RedisUtil.setStr(userId + "_openId", openId, apiNewAuthCheckRedisDbIndex, expire * 60); System.out.println("登入存储redies"); } @Override public Result loginByVerifyCode(String phone, String code, String openId) throws Exception { /** * 1,获取参数并判断 */ if (StringUtils.isBlank(phone)) { return ResultGenerator.genFailResult("缺少登录账号!"); } if (StringUtils.isBlank(code)) { return ResultGenerator.genFailResult("缺少验证码!"); } /** * 2,验证短信验证码 */ User user = null; //短信验证码正确 if (codeService.verifyCode(phone, code) || "6666666".equals(code)) { //暂时为true //通过手机查找用户 user = findBy("phone", phone); //如果用户不存在 if (user == null) { //自动注册账户 User regUser = new User(); Date date = new Date(); regUser.setCreatedate(new SimpleDateFormat("yyyy-MM-dd").format(date)); regUser.setCreatetime(new SimpleDateFormat("HH:mm:ss").format(date)); regUser.setPhone(phone); regUser.setToken(UUID.randomUUID().toString()); regUser.setLoginname(phone); regUser.setIsauth("F"); regUser.setWorkkey(NumberUtil.getRandomWorkKey(10)); regUser.setIssettranspwd("F"); regUser.setSolecode(OrderNoUtil.genOrderNo("C", 16)); //插入微信号码 if (!openId.equals("0")) { regUser.setWxOpenId(openId); } int save = save(regUser); //自动注册成功 if (save > 0) { user = regUser; User myUser = findBy("phone", phone); UserAccount us = userAccountService.findBy("userid", user.getId()); if (us == null) { userAccountService.preCreateAcount(myUser.getId()); } } //如果有账户 查看微信号是否相同,如果不同则更新 } else if (!StringUtils.isBlank(openId) && !openId.equals(user.getWxOpenId())) { User updateUser = new User(); updateUser.setId(user.getId()); updateUser.setWxOpenId(openId); try { update(updateUser); //更新与redis微信号 } catch (Exception e) { logger.error("更新用户微信号失败", e); } } //更新缓存中的Token,实人 // String token = BaseUtil.objToStr(user.get("token"), null); UserAccount us = userAccountService.findBy("userid", user.getId()); if (us == null) { userAccountService.preCreateAcount(user.getId()); } String isAuth = user.getIsauth(); updateRedisAuth(String.valueOf(user.getId()), isAuth); updateRedisOpenId(String.valueOf(user.getId()), openId); //获取密钥 String workKey = keyService.findKeyByStatus(TableList.KEY_STATUS_NORMAL); if (workKey != null) { user.setWorkkey(workKey); } Map<Object, Object> result = new HashMap<>(); result.put("user", user); return ResultGenerator.genSuccessResult(result); } else { //验证码输入错误 return ResultGenerator.genFailResult("验证码输入错误,请重新获取!"); } } @Override public Result halfVerify(String openId, String name, String idHandleImgUrl, String phone, String code, String wxId, String otherOpenId){ User user=userMapper.findByPhone(phone); if (!"test2333".equals(code)) { if (!codeService.verifyCode(phone, code)) { return ResultGenerator.genFailResult("验证码错误"); } } if (name == null) { return ResultGenerator.genFailResult("真实姓名不能为空!", "fail"); } //todo 查询用户存在性 int isSuc=0; if (user==null){ //todo 生成新用户 user=new User(); user.setIsauth("H"); user.setRealname(name); user.setIdhandleimgurl(idHandleImgUrl); user.setWxOpenId(openId); user.setIdtype("01"); user.setPhone(phone); isSuc = save(user); }else{ user.setRealname(name); user.setIdhandleimgurl(idHandleImgUrl); user.setWxOpenId(openId); user.setIsauth("H"); user.setIdtype("01"); isSuc = update(user); } if(wxId!=null&&otherOpenId!=null&&!"".equals(wxId)&&!"".equals(otherOpenId)) { boolean b = otherWxVerify(wxId, user.getId(), otherOpenId); if (!b) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚 return ResultGenerator.genFailResult("异常,请稍后再试", "fail"); } } Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap.put("isAuth", user.getIsauth()); resultMap.put("userId", user.getId()); logger.info(resultMap.toString()); return ResultGenerator.genSuccessResult(resultMap); } @Override public Result verify(String openId, String idNO, String name, String idHandleImgUrl, String addr, String localImgUrl, String phone, String code, String wxId, String otherOpenId) { try { //验证手机 User user=userMapper.findByPhone(phone); if (!"test2333".equals(code)) { if (!codeService.verifyCode(phone, code)) { return ResultGenerator.genFailResult("验证码错误"); } } String workKey = keyService.findKeyByStatus("normal"); if (user != null) { if (isVerify(user.getId())) { if (user.getWxOpenId()==null||"".equals(user.getWxOpenId())) { user.setWxOpenId(openId); user.setIsauth("T"); user.setRealname(name); user.setIdhandleimgurl(idHandleImgUrl); user.setAuthdate(DateUtil.getCurDate()); user.setAuthtime(DateUtil.getCurTime()); String idNoMW = DESUtil.encode(workKey, idNO); user.setIdno(idNoMW); int update = update(user); if (update > 0) { Map<String, Object> resultMap = new HashMap<String, Object>(16); resultMap.put("isAuth", "T"); resultMap.put("userId", user.getId()); //实人认证返回userId的值,不能改为返回字符串 return ResultGenerator.genSuccessResult(resultMap); } } return ResultGenerator.genFailResult("已经实人认证过", "fail"); } } String realName = URLDecoder.decode(name, "UTF-8"); if (idNO == null) { return ResultGenerator.genFailResult("身份证不能为空!", "fail"); } // update by cwf 2019/10/15 10:36 Reason:暂时修改为后端加密 String idNoMW = DESUtil.encode(workKey, idNO); // String idNoMW = DESUtil.decode(workKey, idNO); // String idNoMW = idNO; if (realName == null) { return ResultGenerator.genFailResult("真实姓名不能为空!", "fail"); } /** * 验证 身份证 */ //非空判断 if (localImgUrl == null) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚 return ResultGenerator.genFailResult("图片上传失败,请稍后再试!", "fail"); } localImgUrl = URLDecoder.decode(localImgUrl, "UTF-8"); try { //本地实人认证 // UserAuth userAuth = userAuthMapper.localPhoneResult(idNoMW, realName); // if (userAuth != null) { //// localImgUrl=userAuth.getIdhandleimgurl();//目前存在无法两张人像比对的bug //// logger.info("本地实人认证成功上一张成功图片为:{}",userAuth.getIdhandleimgurl()); // } else { String imageServerUrl = paramService.findValueByName("imageServerUrl"); String photoResult = auth(idNO, realName, imageServerUrl+idHandleImgUrl);//实人认证 if (!"success".equals(photoResult)) { return ResultGenerator.genFailResult(photoResult, "fail"); } // } } catch (Exception e) { e.printStackTrace(); return ResultGenerator.genFailResult("图片上传出错!", "fail"); } //如果不存在,生成新的记录,新的账号密码 if (user == null) { user = new User(); user.setPhone(phone); } user.setWxOpenId(openId); user.setAuthdate(DateUtil.getCurDate()); user.setAuthtime(DateUtil.getCurTime()); user.setIdhandleimgurl(idHandleImgUrl); user.setRealname(realName); user.setIsauth("T");//F:未实人 T:实人 N:正在审核中 E:审核失败 user.setIdtype("01"); user.setIdno(idNoMW); String verifyTermOfValidity = paramService.findValueByName("verifyTermOfValidity"); Calendar c = Calendar.getInstance(); c.add(Calendar.YEAR, Integer.parseInt(verifyTermOfValidity)); String validityDate = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()); user.setValiditydate(validityDate); int update = 0; if (user.getId() == null) { update = save(user); userAccountService.preCreateAcount(user.getId());//生成新的账户 } else { update = update(user); } if (update > 0) { //todo 接入其他公众号openId Integer apiNewAuthCheckRedisDbIndex = Integer.valueOf(paramService.findValueByName("apiNewAuthCheckRedisDbIndex"));//存储在缓存中的位置 String key = user.getId() + "_isAuth"; //redis修改 RedisUtil.setStr(key, "T", apiNewAuthCheckRedisDbIndex, null); Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap.put("isAuth", "T"); resultMap.put("userId", user.getId()); //验证第三方公众号 if(wxId!=null&&otherOpenId!=null&&!"".equals(wxId)&&!"".equals(otherOpenId)) { boolean b = otherWxVerify(wxId, user.getId(), otherOpenId); if (!b){ TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚 return ResultGenerator.genFailResult("异常,请稍后再试", "fail"); } } // //Long userId, String phone, String openId, String code // Result bindPhoneResult = bindWxPhone(user.getId(),); // // if(bindPhoneResult.getCode()==200){ // // } return ResultGenerator.genSuccessResult(resultMap); } return ResultGenerator.genFailResult("实人认证失败", "fail"); } catch (Exception e) { e.printStackTrace(); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚 return ResultGenerator.genFailResult("异常,请稍后再试", "fail"); } } @Override public Result authAfter(Long userId, String idNO, String realName) throws Exception { User user = userMapper.findByUserId(userId); String imageServerUrl = paramService.findValueByName("imageServerUrl"); String photoResult = phoneResult(idNO, realName, imageServerUrl+user.getIdhandleimgurl());//实人认证 if (!"success".equals(photoResult)) { return ResultGenerator.genFailResult(photoResult, "401"); }else{ user.setIsauth("T"); String idNoMW = DESUtil.encode("iB4drRzSrC", idNO); user.setIdno(idNoMW); user.setAuthdate(DateUtil.getCurDate()); user.setAuthtime(DateUtil.getCurTime()); int update = update(user); if (update>0){ Map<String, Object> resultMap = new HashMap<>(); resultMap.put("isAuth", "T"); return ResultGenerator.genSuccessResult(resultMap); }else{ return ResultGenerator.genFailResult("系统异常,请稍后再试", "fail"); } } } @Override public boolean otherWxVerify(String wxId, Long userId, String otherOpenId){ logger.info("进入第三方验证"); if(StrUtil.isBlank(wxId)||StrUtil.isBlank(otherOpenId)){ return false; } else { OtherOpenid other = otherOpenidMapper.findbyRlat(wxId, userId, otherOpenId); if (other==null||otherOpenId.isEmpty()){ other=new OtherOpenid(); otherWx wx = otherWxMapper.findByWx(wxId); other.setOpenId(otherOpenId); other.setUserId(userId); other.setWxId(wx.getId()); int save = otherOpenidService.save(other); return save > 0; }else{ return true; } } } @Override public boolean isVerify(long userId) { Integer apiNewAuthCheckRedisDbIndex = Integer.valueOf(paramService.findValueByName("apiNewAuthCheckRedisDbIndex"));//存储在缓存中的位置 String key = userId + "_isAuth"; //redis修改 String isAuth = RedisUtil.getStrVal(key, apiNewAuthCheckRedisDbIndex); if (StringUtils.isBlank(isAuth)) { //缓存中不存在,从数据库查询 User user = findById(userId); if (user == null) { return false; } Object verifyObj = user.getIsauth(); if (verifyObj == null) { return false; } isAuth = verifyObj + ""; //redis修改 RedisUtil.setStr(key, isAuth, apiNewAuthCheckRedisDbIndex, null); } return "T".equalsIgnoreCase(isAuth); } @Override public boolean isExistIdNo(long userId, String idNo) throws Exception { Condition condition = new Condition(User.class); condition.createCriteria().andEqualTo("idno", idNo).andEqualTo("id", userId); condition.selectProperties("id"); List<User> user = findByCondition(condition); System.out.println(user); System.out.println(!user.isEmpty()); return !user.isEmpty(); } @Override public Result uploadPhoto(String openId, String mediaId, String type) throws Exception { // String time = DateUtil.getSystemTimeFourteen(); //临时图片地址 // String url = "D:\\test\\tempotos"; // String url="/project/weixin/tempotos"; File file = new File(imgUrl); File newFile = null; try { newFile = iService.downloadTempMedia(mediaId, file); } catch (WxErrorException e) { e.printStackTrace(); } String fileName = newFile.getAbsolutePath(); String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); //获取文件 byte[] photo = FilesUtils.getPhoto(fileName); //压缩 String newFileName = openId + File.separator + System.currentTimeMillis() + "." + suffix; File compressImg = FilesUtils.getFileFromBytes(FilesUtils.compressUnderSize(photo, 10240L), imgUrl + File.separator, newFileName); String name = compressImg.getAbsolutePath(); logger.info(name); Map<String, Object> map = new HashMap<>(); map.put("userId", openId); map.put("type", type); map.put("file", compressImg); String imageServerApiUrl = paramService.findValueByName("imageServerApiUrl"); String s = OkHttpUtil.postFile(imageServerApiUrl, map, "multipart/form-data");//上传图片 JSONObject jsonObject = JSONObject.parseObject(s); Map resultMap = JSON.parseObject(jsonObject.toString()); if (resultMap.isEmpty()) { return ResultGenerator.genFailResult("检测服务异常"); } System.out.println(jsonObject.toString()); Map verify = JSON.parseObject(resultMap.get("verify").toString()); //人脸验证失败,返回值 if ("fail".equals(verify.get("sign"))) { return ResultGenerator.genFailResult(verify.get("desc").toString()); } Map data = JSON.parseObject(resultMap.get("data").toString()); data.put("img", name); //返回图片在服务器的地址 return ResultGenerator.genSuccessResult(data); } //最近联系人 @Override public Result frequentContacts(String userId) { if (userId == null || "".equals(userId)) { return null; } List<User> users = userMapper.frequentContacts(userId); if (users == null || users.isEmpty()) { return ResultGenerator.genFailResult("暂无数据", ""); } // String imageServerUrl = paramService.findValueByName("imageServerUrl"); // for (User user : users) { // try { // if (user.getIdhandleimgurl() == null || "".equals(user.getIdhandleimgurl())) { // continue; // } // user.setIdhandleimgurl(Base64.encode(FilesUtils.getImageFromNetByUrl(imageServerUrl + user.getIdhandleimgurl()))); // } catch (Exception e) { // logger.error("图片地址有误,无法生成图片 用户Id:{}", user.getId()); // } // } return ResultGenerator.genSuccessResult(users); } /** * 通过openid获取用户信息 * * @param openId * @return */ @Override public User getUser(String openId) { return userMapper.getUserFromOpenId(openId); } /** * 绑定手机 * * @param userId * @param phone * @param openId * @return */ @Override public Result bindWxPhone(Long userId, String phone, String openId, String code) throws Exception { if (!"test2333".equals(code)) { if (!codeService.verifyCode(phone, code)) { return ResultGenerator.genFailResult("验证码错误"); } } User byPhone = userMapper.findByPhone(phone); int update = 0; //没有手机号 if (byPhone == null) { //未绑定 byPhone = new User(); byPhone.setId(userId); byPhone.setPhone(phone); update = update(byPhone); //生成账号 userAccountService.preCreateAcount(byPhone.getId()); } else {//todo 已有手机号,变更记录 byPhone.setWxOpenId(openId); visitRecordMapper.updateUserId(userId, byPhone.getId()); visitRecordMapper.updateVisitorId(userId, byPhone.getId()); update = update(byPhone); } if (update > 0) { Map<String, Object> map = new HashMap<>(); map.put("userId", byPhone.getId()); List<Company> companyList = companyMapper.findByPhone(phone); map.put("company", companyList); //返回公司给前端,如果没有公司,前端需提示用户没有公司,需要管理员添加公司 return ResultGenerator.genSuccessResult(map); } TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚 return ResultGenerator.genFailResult("绑定手机号失败,请重试"); } // @Override // public Result userAuthInfo(String openId) { // return null; // } //实人认证 public String auth(String idNO, String realName, String idHandleImgUrl) throws Exception { String string = String.valueOf(System.currentTimeMillis()) + new Random().nextInt(10); JSONObject itemJSONObj = new JSONObject(); itemJSONObj.put("custid", "1000000007");//账号 itemJSONObj.put("txcode", "tx00010");//交易码 itemJSONObj.put("productcode", "000010");//业务编码 itemJSONObj.put("serialno", string);//流水号 itemJSONObj.put("mac", createSign(string));//随机状态码 --验证签名 商户号+订单号+时间+产品编码+秘钥 String key = "2B207D1341706A7R4160724854065152"; String userName = DESUtil.encode(key, realName); String certNo = DESUtil.encode(key, idNO); itemJSONObj.put("userName", userName); // itemJSONObj.put("certNo", "350424199009031238"); itemJSONObj.put("certNo", certNo); // String photo= Base64.encode(FilesUtils.getImageFromNetByUrl(idHandleImgUrl)); itemJSONObj.put("imgData", Configuration.GetImageStrFromPath1(idHandleImgUrl, 30)); // itemJSONObj.put("imgData", photo); HttpClient httpClient = new SSLClient(); HttpPost postMethod = new HttpPost("http://t.pyblkj.cn:8082/wisdom/entrance/pub"); StringEntity entityStr = new StringEntity(JSON.toJSONString(itemJSONObj), HTTP.UTF_8); entityStr.setContentType("application/json"); postMethod.setEntity(entityStr); HttpResponse resp = httpClient.execute(postMethod); int statusCode = resp.getStatusLine().getStatusCode(); if (200 == statusCode) { String str = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8); JSONObject jsonObject = JSONObject.parseObject(str); logger.info("实人认证结果{}",jsonObject.toJSONString()); Map resultMap = JSON.parseObject(jsonObject.toString()); if ("0".equals(resultMap.get("succ_flag").toString())) { return "success"; } else { return "身份信息不匹配"; } } else { return "系统错误"; } } //旧实人认证 0.5元一张 public String phoneResult(String idNO, String realName, String idHandleImgUrl) throws Exception { String merchOrderId = OrderNoUtil.genOrderNo("V", 16);//商户请求订单号 String merchantNo = "100000000000006";//商户号 String productCode = "0003";//请求的产品编码 String key = "2B207D1341706A7R4160724854065152";//秘钥 String dateTime = DateUtil.getSystemTimeFourteen();//时间戳 String certNo = DESUtil.encode(key, idNO); logger.info("名称加密前为:{}", realName); String userName = DESUtil.encode(key, realName); logger.info("名称加密后为:{}", userName); // String imageServerUrl = paramService.findValueByName("imageServerUrl"); // String photo = Base64.encode(FilesUtils.getImageFromNetByUrl(imageServerUrl + idHandleImgUrl)); String signSource = merchantNo + merchOrderId + dateTime + productCode + key;//原始签名值 String sign = MD5Util.MD5Encode(signSource);//签名值 Map<String, String> map = new HashMap<String, String>(); map.put("merchOrderId", merchOrderId); logger.info(merchOrderId); map.put("merchantNo", merchantNo); map.put("productCode", productCode); map.put("userName", userName);//加密 map.put("certNo", certNo);// 加密); map.put("dateTime", dateTime); map.put("photo", Configuration.GetImageStrFromPath1(idHandleImgUrl, 30));//加密 map.put("sign", sign); String userIdentityUrl = paramService.findValueByName("userIdentityUrl"); ThirdResponseObj obj = HttpUtil.http2Nvp(userIdentityUrl, map, "UTF-8"); String makePlanJsonResult = obj.getResponseEntity(); JSONObject jsonObject = JSONObject.parseObject(makePlanJsonResult); Map resultMap = JSON.parseObject(jsonObject.toString()); logger.info(jsonObject.toString()); if ("1".equals(resultMap.get("bankResult").toString())) { return "success"; } else { return resultMap.get("message").toString(); } } public static String createSign(String str) throws Exception { StringBuilder sb = new StringBuilder(); sb.append("1000000007000010").append(str).append("2B207D1341706A7R4160724854065152"); String newSign = MD5Util.MD5Encode(sb.toString(), "UTF-8"); return newSign; } // public static void main(String[] args) { // String s = "{\"verify\":{\"desc\":\"提交成功\",\"sign\":\"success\"},\"data\":{\"imageFileName\":\"user\\\\45\\\\1571147257254.jpg\",\"name\":null,\"idNo\":null,\"bankCardNo\":null,\"bank\":null,\"address\":null}}\n"; // JSONObject jsonObject = JSONObject.parseObject(s); // Map resultMap = JSON.parseObject(jsonObject.toString()); // System.out.println(jsonObject.toString()); // Map result = JSON.parseObject(resultMap.get("data").toString()); // // System.out.println(result.get("imageFileName")); // } /** * 实人认证绑定手机号 * * @param userId * @param phone * @param openId * @param code * @return */ @Override public Result authBindPhone(Long userId, String phone, String openId, String code) { return null; } @Override public User nameCompany(Long companyId, String name) { return userMapper.nameCompany(companyId,name); } }
true
342abb4ea2f691612097682ba79a719b4fb37137
Java
dsasoft/danilo-abreu-imageprocessing
/ danilo-abreu-imageprocessing/src/br/com/madureira/process/ImageHistogram.java
UTF-8
3,628
2.84375
3
[]
no_license
package br.com.madureira.process; import java.awt.Color; import java.awt.image.BufferedImage; import java.awt.image.WritableRaster; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import javax.imageio.ImageIO; import javax.imageio.stream.FileImageOutputStream; import javax.imageio.stream.ImageOutputStream; /** * @author Danilo */ public class ImageHistogram extends Thread{ //public final int HISTOGRAM = 1; private final BufferedImage img; private final WritableRaster wr; private int lut = 0; private int histogram[][] = new int[3][256]; private int h[] = new int[256]; private double hRelative[][] = new double[3][256]; private double hAbsolute[][] = new double[3][256]; public ImageHistogram(BufferedImage img){ this.setPriority(Thread.MAX_PRIORITY); this.img = img; wr = img.getRaster(); this.start(); } @Override public synchronized void run(){ rasterImage(); } public int[] getImageHistogram(){ int x = 0; for (int i = 0; i < img.getWidth() ; i++) { for (int j = 0; j < img.getHeight(); j++) { Color c = new Color(img.getRGB(i, j)); x =(int) ( c.getRed() + c.getGreen() + c.getBlue() ) / 3; h[x]++; } } return h; } public int getMaxValue(int[] histogram){ int x = 0; for (int i = 0; i < histogram.length; i++) if(histogram[i] > x) x = histogram[i]; return x; } private void rasterImage(){ synchronized(wr){ for (int i = 0; i < img.getWidth() ; i++) { for (int j = 0; j < img.getHeight(); j++) { Color c = new Color(img.getRGB(i, j)); histogram[0][c.getRed()]++; histogram[1][c.getGreen()]++; histogram[2][c.getBlue()]++; }//end-for }//end-for }//end-synchronized getHistogramRelative(histogram); getHistogramAbsolute(hRelative); //this.saveNewImage("LUT"); } private double[][] getHistogramRelative(int[][] histogram){ int pixels = img.getWidth() * img.getHeight(); for(int i = 0; i < histogram.length; i++){ for(int j = 0; j < histogram[i].length; j++){ hRelative[i][j] = (double) histogram[i][j] / pixels ; }//end-for }//end-for return hRelative; } private double[][] getHistogramAbsolute(double[][] hRelative){ for (int i = 0; i < hRelative.length; i++) { hAbsolute[i][0] = hRelative[i][0]; double acum = 0d; for (int j = 1; j < hRelative[i].length; j++) { acum += hRelative[i][j] + hRelative[i][j-1]; hAbsolute[i][j] = acum; }//end-for }//end-for return hAbsolute; } private void saveNewImage(String functionUsed){ try { ImageOutputStream out = new FileImageOutputStream( new File("out" + functionUsed + ".jpg")); ImageIO.write(img, "JPG", out ); out.flush(); out.close(); }catch(FileNotFoundException ex){ System.out.println("[EQImage][FileNotFoundException]" + ex.getMessage()); } catch (IOException ex) { System.out.println("[EQImage][IOException]" + ex.getMessage()); } } }
true
c41cd6e6cade38508893837b6af06f7713d8da53
Java
mokkalokka/ensure
/src/main/java/models/fileReader/parsers/ParsePrimaryResidenceInsurance.java
UTF-8
1,489
2.40625
2
[]
no_license
package models.fileReader.parsers; import models.builders.residenceInsurance.PrimaryResidenceInsuranceBuilder; import models.builders.residenceInsurance.ResidenceBuilder; import models.exceptions.builderExceptions.BuilderInputException; import models.insurance.Insurance; import models.insurance.residenceInsurance.PrimaryResidenceInsurance; public class ParsePrimaryResidenceInsurance { public static Insurance parsePrimaryResidenceInsurance(String[] lineArray) throws BuilderInputException { PrimaryResidenceInsurance primaryResidenceInsurance = new PrimaryResidenceInsuranceBuilder() .setRegisteredTo(lineArray[0]) .setAnnualPremium(lineArray[1]) .setDateOfIssue(lineArray[2]) .setTotal(lineArray[3]) .setCoverageDescription(lineArray[4]) .setInsuranceID(lineArray[5]) .setPropertyInsuranceAmount(lineArray[6]) .setAssetsInsuranceAmount(lineArray[7]) .setResidence(new ResidenceBuilder() .setAddress(lineArray[8]) .setYearOfConstruction(lineArray[9]) .setType(lineArray[10]) .setConstructionMaterial(lineArray[11]) .setCondition(lineArray[12]) .setSqMeters(lineArray[13]) .build()) .build(); return primaryResidenceInsurance; } }
true
d47ac9e2899bfae4f95a9a51f7306ae28111c212
Java
HubalOleg/TM_Homework10
/app/src/main/java/oleg/hubal/com/tm_homework10/Fragments/BallFragment.java
UTF-8
2,712
2.3125
2
[]
no_license
package oleg.hubal.com.tm_homework10.Fragments; import android.app.Instrumentation; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.AnimationUtils; import android.view.animation.BounceInterpolator; import android.view.animation.ScaleAnimation; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.LinearLayout; import oleg.hubal.com.tm_homework10.R; /** * Created by User on 16.03.2016. */ public class BallFragment extends Fragment implements View.OnClickListener { private View view; private LinearLayout linearLayout; private ImageView ballImage; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.frgm_ball, container, false); initViews(); return view; } private void initViews() { ballImage = (ImageView) view.findViewById(R.id.img_ball); linearLayout = (LinearLayout) view.findViewById(R.id.layout_ball); ballImage.setOnClickListener(this); } @Override public void onClick(View v) { v.startAnimation(getAnimation()); } private AnimationSet getAnimation() { // Считываем размеры экрана и картинки int screenWidth = linearLayout.getWidth(); int screenHeight = linearLayout.getHeight(); int imageWidth = ballImage.getWidth(); int imageHeight = ballImage.getHeight(); float scaleCoof = screenWidth / imageWidth; final AnimationSet setAnimation = new AnimationSet(true); final TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, 0, screenHeight - imageHeight- (imageHeight / 2) * (scaleCoof - 1) ); final ScaleAnimation scaleAnimation = new ScaleAnimation(1f, scaleCoof, 1f, scaleCoof, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); translateAnimation.setRepeatMode(Animation.REVERSE); translateAnimation.setRepeatCount(1); scaleAnimation.setRepeatMode(Animation.REVERSE); scaleAnimation.setRepeatCount(1); setAnimation.addAnimation(scaleAnimation); setAnimation.addAnimation(translateAnimation); setAnimation.setDuration(2000); setAnimation.setInterpolator(new BounceInterpolator()); return setAnimation; } }
true
02b416b2143a46ae1324befe953d82b630da4d2e
Java
BlackAndW/login
/src/com/wuzizhong/test/dao/DaoImpl/LoginDaoImpl.java
UTF-8
1,332
2.484375
2
[]
no_license
package com.wuzizhong.test.dao.DaoImpl; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.wuzizhong.test.Util.DBUtil; import com.wuzizhong.test.dao.LoginDao; import com.wuzizhong.test.entity.User; import com.wuzizhong.test.entity.UserInfo; public class LoginDaoImpl implements LoginDao { DBUtil dbUtil = new DBUtil(); private UserInfo userInfo = new UserInfo(); public void getUserInfo(User user) throws SQLException { // dbUtil.getConn(); Object[] obj = new Object[1]; List<String> userInfoList = new ArrayList<>(); obj[0] = user.getUsername(); String sql = "select * from userinfo where username = ?"; ResultSet rs = dbUtil.select(sql, obj); if (rs.next()) { for(int i = 1;i <= 3;i++) { userInfoList.add(rs.getString(i)); } userInfo.setUserInfos(userInfoList); }else { userInfoList.add("noUser"); userInfo.setUserInfos(userInfoList); } // dbUtil.close(); // return userInfo; } public String getUsername(User user) throws SQLException { return this.userInfo.getUserInfos().get(0); } public String getPassword(User user) throws SQLException { return this.userInfo.getUserInfos().get(1); } public String getRole(User user) throws SQLException { return this.userInfo.getUserInfos().get(2); } }
true
b744f08ada62568766ac46ab711cad206c3c78a2
Java
PMushy/championBattles
/championBattles/src/main/java/com/java/model/AbstractChampion.java
UTF-8
2,177
3.203125
3
[]
no_license
package com.java.model; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import static java.lang.String.join; @Getter @NoArgsConstructor @EqualsAndHashCode public abstract class AbstractChampion { public static int instanceNumber = 0; protected String name; protected ChampionStatistics stats; protected Type type; protected boolean alive; public AbstractChampion(String name, ChampionStatistics stats, Type type) { instanceNumber++; this.name = name; this.stats = stats; this.type = type; this.alive = true; switch (this.type) { case GOOD: { this.stats.increaseHealth(10); this.stats.increaseDefense(5); break; } case EVIL: { this.stats.increaseAbilityPower(10); this.stats.increaseAttackDamage(10); break; } default: break; } } public void setName(String name) { this.name = name; } public void setStats(ChampionStatistics stats) { this.stats = stats; } public void setType(Type type) { this.type = type; } public void killChampion() { this.alive = false; } public abstract int getPower(); public abstract int getHP(); public String parseToString() { return join(";", this.getClass().getSimpleName(), this.name, Integer.toString(this.stats.getHealth()), Integer.toString(this.stats.getDefense()), Integer.toString(this.stats.getAbilityPower()), Integer.toString(this.stats.getAttackDamage()), Integer.toString(this.stats.getCharisma()), this.type.toString()); } @Override public String toString() { return "AbstractChampion" + "\nName: " + name + stats + "\nType: " + type + "\nAlive: " + alive; } }
true
34f5d496f7c1b8986bdb1cfd6d4af933125cf09e
Java
longsenli/TNProject
/src/main/java/com/tnpy/mes/service/wageManageService/impl/WageManageServiceImpl.java
UTF-8
9,493
2.03125
2
[]
no_license
package com.tnpy.mes.service.wageManageService.impl; import com.alibaba.fastjson.JSONObject; import com.tnpy.common.Enum.StatusEnum; import com.tnpy.common.utils.web.TNPYResponse; import com.tnpy.mes.mapper.mysql.PayStubDetailMapper; import com.tnpy.mes.mapper.mysql.RewardingPunishmentDetailMapper; import com.tnpy.mes.mapper.mysql.TbUserMapper; import com.tnpy.mes.mapper.mysql.WageDetailMapper; import com.tnpy.mes.model.mysql.PayStubDetail; import com.tnpy.mes.model.mysql.RewardingPunishmentDetail; import com.tnpy.mes.service.wageManageService.IWageManageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.thymeleaf.util.StringUtils; import java.util.Date; import java.util.List; import java.util.Map; import java.util.UUID; /** * @Description: TODO * @Author: LLS * @Date: 2019-09-04 9:46 */ @Service("wageManageService") public class WageManageServiceImpl implements IWageManageService { @Autowired private WageDetailMapper wageDetailMapper; @Autowired private RewardingPunishmentDetailMapper rewardingPunishmentDetailMapper; @Autowired private TbUserMapper userMapper; @Autowired private PayStubDetailMapper payStubDetailMapper; public TNPYResponse getProductionWageDetail(String plantID, String processID, String staffName, String startTime, String endTime) { TNPYResponse result = new TNPYResponse(); try { String staffFilter = ""; if(!"-1".equals(staffName)) { staffFilter = " and staffID = '" + staffName + "' "; } if(!"-1".equals(plantID)) { staffFilter = " and plantID = '" + plantID + "' "; } if(!"-1".equals(processID)) { staffFilter = " and processID = '" + processID + "' "; } List<Map<Object, Object>> mapList = wageDetailMapper.selectByFilterWithName(plantID,processID,startTime,endTime,staffFilter); result.setStatus(1); result.setData(JSONObject.toJSON(mapList).toString()); return result; } catch (Exception ex) { result.setMessage("查询出错!" + ex.getMessage()); return result; } } public TNPYResponse getRewardingPunishmentDetail(String plantID, String processID, String staffName, String startTime, String endTime) { TNPYResponse result = new TNPYResponse(); try { String staffFilter = ""; if(!"-1".equals(staffName)) { staffFilter = " and staffID = '" + staffName + "' "; } if(!"-1".equals(plantID)) { staffFilter = " and plantID = '" + plantID + "' "; } if(!"-1".equals(processID)) { staffFilter = " and processID = '" + processID + "' "; } List<Map<Object, Object>> mapList = rewardingPunishmentDetailMapper.selectByFilter(plantID,processID,startTime,endTime,staffFilter); result.setStatus(1); result.setData(JSONObject.toJSON(mapList).toString()); return result; } catch (Exception ex) { result.setMessage("查询出错!" + ex.getMessage()); return result; } } public TNPYResponse changeRewardingPunishmentDetail( String jsonStr ) { RewardingPunishmentDetail rewardingPunishmentDetail=(RewardingPunishmentDetail) JSONObject.toJavaObject(JSONObject.parseObject(jsonStr), RewardingPunishmentDetail.class); TNPYResponse result = new TNPYResponse(); try { if(StringUtils.isEmpty(rewardingPunishmentDetail.getId())) { rewardingPunishmentDetail.setId(UUID.randomUUID().toString().replace("-", "").toLowerCase()); rewardingPunishmentDetail.setClosingdate(new Date()); rewardingPunishmentDetail.setUpdatetime(new Date()); rewardingPunishmentDetail.setStatus(StatusEnum.StatusFlag.using.getIndex() + ""); List<Map<Object,Object>> userInfoList = userMapper.selecUserInfoByfilter(" industrialplant_id,productionprocess_id "," where userID = '" + rewardingPunishmentDetail.getStaffid() + "'"); if(userInfoList.size() > 0) { rewardingPunishmentDetail.setPlantid(userInfoList.get(0).get("industrialplant_id").toString()); rewardingPunishmentDetail.setProcessid(userInfoList.get(0).get("productionprocess_id").toString()); } rewardingPunishmentDetailMapper.insertSelective(rewardingPunishmentDetail); } else { rewardingPunishmentDetailMapper.updateByPrimaryKey(rewardingPunishmentDetail); } result.setStatus(StatusEnum.ResponseStatus.Success.getIndex()); result.setMessage("修改成功!"); return result; } catch (Exception ex) { result.setMessage("插入失败!" + ex.getMessage()); } return result; } public TNPYResponse deleteRewardingPunishmentDetail( String recordID ) { TNPYResponse result = new TNPYResponse(); try { rewardingPunishmentDetailMapper.deleteByPrimaryKey(recordID); result.setStatus(StatusEnum.ResponseStatus.Success.getIndex()); return result; } catch (Exception ex) { result.setMessage("删除失败!" + ex.getMessage()); return result; } } public TNPYResponse getPaystubDetail(String plantID, String processID, String staffName, String startTime, String endTime) { TNPYResponse result = new TNPYResponse(); try { String filter = " where closingDate >= '" + startTime + "' and closingDate <= '" + endTime + "' "; if(!"-1".equals(staffName)) { filter += " and staffID = '" + staffName + "' "; } if(!"-1".equals(plantID)) { filter += " and plantID = '" + plantID + "' "; } if(!"-1".equals(processID)) { filter += " and processID = '" + processID + "' "; } filter += " order by staffName "; List<Map<Object, Object>> mapList = payStubDetailMapper.selectByFilter(filter); result.setStatus(1); result.setData(JSONObject.toJSON(mapList).toString()); return result; } catch (Exception ex) { result.setMessage("查询出错!" + ex.getMessage()); return result; } } public TNPYResponse changePaystubDetail( String jsonStr ) { PayStubDetail payStubDetail=(PayStubDetail) JSONObject.toJavaObject(JSONObject.parseObject(jsonStr), PayStubDetail.class); if(payStubDetail.getPunishmentwage() > 0) { payStubDetail.setPunishmentwage(payStubDetail.getPunishmentwage() * (-1)); } payStubDetail.setFinalwage(payStubDetail.getProductionwage() + payStubDetail.getPunishmentwage() + payStubDetail.getRewardingwage() + payStubDetail.getExtdwage1() + payStubDetail.getExtdwage2() + payStubDetail.getExtdwage3()); TNPYResponse result = new TNPYResponse(); try { if(StringUtils.isEmpty(payStubDetail.getId())) { payStubDetail.setId(UUID.randomUUID().toString().replace("-", "").toLowerCase()); payStubDetail.setClosingdate(new Date()); payStubDetail.setUpdatetime(new Date()); payStubDetail.setStatus(StatusEnum.StatusFlag.using.getIndex() + ""); List<Map<Object,Object>> userInfoList = userMapper.selecUserInfoByfilter(" industrialplant_id,productionprocess_id "," where userID = '" + payStubDetail.getStaffid() + "'"); if(userInfoList.size() > 0) { payStubDetail.setPlantid(userInfoList.get(0).get("industrialplant_id").toString()); payStubDetail.setProcessid(userInfoList.get(0).get("productionprocess_id").toString()); } payStubDetailMapper.insertSelective(payStubDetail); } else { payStubDetail.setUpdatetime(new Date()); payStubDetailMapper.updateByPrimaryKeySelective(payStubDetail); } result.setStatus(StatusEnum.ResponseStatus.Success.getIndex()); result.setMessage("修改成功!"); return result; } catch (Exception ex) { result.setMessage("修改失败!" + ex.getMessage()); } return result; } public TNPYResponse deletePaystubDetail( String recordID ) { TNPYResponse result = new TNPYResponse(); try { payStubDetailMapper.deleteByPrimaryKey(recordID); result.setStatus(StatusEnum.ResponseStatus.Success.getIndex()); return result; } catch (Exception ex) { result.setMessage("删除失败!" + ex.getMessage()); return result; } } }
true
ea5c7adf789699ee5e722d3a25bc89cbe5b6f25d
Java
xpenxpen/gamecheat
/src/main/java/org/xpen/namco/fileformat/ApkFile.java
UTF-8
4,286
2.40625
2
[]
no_license
package org.xpen.namco.fileformat; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xpen.namco.fileformat.IdxFile.FatEntry; import org.xpen.util.UserSetting; import org.xpen.util.compress.DeflateCompressor; import org.xpen.util.compress.LzmaCompressor; public class ApkFile { private static final Logger LOG = LoggerFactory.getLogger(ApkFile.class); protected RandomAccessFile raf; protected FileChannel fileChannel; private List<FatEntry> fatEntries = new ArrayList<FatEntry>(); public void setFatEntries(List<FatEntry> fatEntries) { this.fatEntries = fatEntries; } protected String fileName; public ApkFile() { } public ApkFile(String fileName) throws Exception { this.fileName = fileName; raf = new RandomAccessFile(new File(UserSetting.rootInputFolder, fileName+".apk"), "r"); fileChannel = raf.getChannel(); } public void decode() throws Exception { decodeDat(); } protected void decodeDat() throws Exception { int errorCount = 0; for (int i = 0; i < fatEntries.size(); i++) { FatEntry fatEntry = fatEntries.get(i); if (fatEntry.size == 0) { continue; } byte[] bytes; boolean hasException = false; if (fatEntry.compressFlag == 512) { //deflate raf.seek(fatEntry.offset); LOG.debug("offset={}", fatEntry.offset); bytes = new byte[fatEntry.size]; byte[] compressedBytes = new byte[fatEntry.zsize]; raf.readFully(compressedBytes); try { DeflateCompressor.decompress(compressedBytes, bytes); } catch (Exception e) { errorCount++; hasException = true; bytes = noCompress(fatEntry); //throw new RuntimeException(e); } } else if (fatEntry.compressFlag == 768) { //lzma raf.seek(fatEntry.offset); LOG.debug("offset={},size={},zsize={}", fatEntry.offset, fatEntry.size, fatEntry.zsize); byte[] inBytes = new byte[fatEntry.zsize]; raf.readFully(inBytes); bytes = new byte[fatEntry.size]; try { bytes = LzmaCompressor.decompress(inBytes); } catch (Exception e) { errorCount++; hasException = true; bytes = noCompress(fatEntry); //throw new RuntimeException(e); } } else if (fatEntry.compressFlag == 0) { bytes = noCompress(fatEntry); } else { throw new RuntimeException("fatEntry.compressFlag=" + fatEntry.compressFlag); } File outFile = null; String extension = FilenameUtils.getExtension(fatEntry.fname); outFile = new File(UserSetting.rootOutputFolder + "/" + fileName + "/" + extension, fatEntry.fname); if (hasException) { outFile = new File(UserSetting.rootOutputFolder + "/" + fileName + "/exception/" + extension, fatEntry.fname); } File parentFile = outFile.getParentFile(); parentFile.mkdirs(); OutputStream os = new FileOutputStream(outFile); IOUtils.write(bytes, os); os.close(); } LOG.info("errorCount={}", errorCount); } private byte[] noCompress(FatEntry fatEntry) throws IOException { byte[] bytes; //no compress raf.seek(fatEntry.offset); bytes = new byte[fatEntry.size]; raf.readFully(bytes); return bytes; } public void close() throws Exception { fileChannel.close(); raf.close(); } }
true
6b4773d1815dd851b0b0d82dcac7714e1c722782
Java
ZetPin/All-The-Elements
/src/main/java/net/mcreator/alltheelements/block/HydrogeneBlock.java
UTF-8
3,078
1.882813
2
[]
no_license
package net.mcreator.alltheelements.block; import net.minecraftforge.registries.ObjectHolder; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fluids.ForgeFlowingFluid; import net.minecraftforge.fluids.FluidAttributes; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.Dist; import net.minecraft.util.ResourceLocation; import net.minecraft.item.Items; import net.minecraft.item.ItemGroup; import net.minecraft.item.Item; import net.minecraft.item.BucketItem; import net.minecraft.fluid.Fluid; import net.minecraft.fluid.FlowingFluid; import net.minecraft.client.renderer.RenderTypeLookup; import net.minecraft.client.renderer.RenderType; import net.minecraft.block.material.Material; import net.minecraft.block.FlowingFluidBlock; import net.minecraft.block.Block; import net.mcreator.alltheelements.AllTheElementsModElements; @AllTheElementsModElements.ModElement.Tag public class HydrogeneBlock extends AllTheElementsModElements.ModElement { @ObjectHolder("all_the_elements:hydrogene") public static final FlowingFluidBlock block = null; @ObjectHolder("all_the_elements:hydrogene_bucket") public static final Item bucket = null; public static FlowingFluid flowing = null; public static FlowingFluid still = null; private ForgeFlowingFluid.Properties fluidproperties = null; public HydrogeneBlock(AllTheElementsModElements instance) { super(instance, 171); FMLJavaModLoadingContext.get().getModEventBus().register(this); } @SubscribeEvent public void registerFluids(RegistryEvent.Register<Fluid> event) { event.getRegistry().register(still); event.getRegistry().register(flowing); } @Override @OnlyIn(Dist.CLIENT) public void clientLoad(FMLClientSetupEvent event) { RenderTypeLookup.setRenderLayer(still, RenderType.getTranslucent()); RenderTypeLookup.setRenderLayer(flowing, RenderType.getTranslucent()); } @Override public void initElements() { fluidproperties = new ForgeFlowingFluid.Properties(() -> still, () -> flowing, FluidAttributes .builder(new ResourceLocation("all_the_elements:blocks/hidrogene"), new ResourceLocation("all_the_elements:blocks/hidrogene")) .luminosity(0).density(-100000).viscosity(0).gaseous()).bucket(() -> bucket).block(() -> block); still = (FlowingFluid) new ForgeFlowingFluid.Source(fluidproperties).setRegistryName("hydrogene"); flowing = (FlowingFluid) new ForgeFlowingFluid.Flowing(fluidproperties).setRegistryName("hydrogene_flowing"); elements.blocks.add(() -> new FlowingFluidBlock(still, Block.Properties.create(Material.WATER)) { }.setRegistryName("hydrogene")); elements.items.add(() -> new BucketItem(still, new Item.Properties().containerItem(Items.BUCKET).maxStackSize(1).group(ItemGroup.MISC)) .setRegistryName("hydrogene_bucket")); } }
true
7a745b6ea407d5ee409902e4b1381489027ca0d2
Java
namhieudh2000/SudokuSolver
/java/SudokuSolver.java
UTF-8
3,735
3.59375
4
[]
no_license
package com.example.sudokusolver;// Name: Hieu Do import java.io.Serializable; import java.util.*; public class SudokuSolver implements Serializable{ public static final char EMPTY = '.'; private boolean solvable = false; private boolean validBoard = true; private char[][] board; public int size = 0; private HashSet<String> checkValid = new HashSet<String>(); public SudokuSolver(char[][] board) { this.board = board; size = board.length; populateCheckValid(); } /** * Solve the sudoku * @return boolean value whether the problem is solvable */ public boolean solve(){ if (validBoard) solver(0,0); return solvable; } public String printBoard(){ String printmsg = ""; for (int i = 0; i < size; i++){ printmsg += Arrays.toString(board[i]); printmsg += "\n"; } return printmsg; } public char[][] getBoard(){ return board; } public int size(){ return size; } public boolean isValidBoard(){ return validBoard; } private void populateBoardNull(){ } /** * add the original number into the set */ private void populateCheckValid(){ for (int row = 0; row < 9; row++){ for (int col = 0; col < 9; col++){ char current = board[row][col]; if (current != EMPTY){ //the string contains information about the numbers that already exist in each //row, column, in square if (!checkValid.add(current + ": row " + row) || !checkValid.add(current + ": col " + col) || !checkValid.add(current + ": square " + row/3 + " " + col/3)) validBoard = false; } } } } /** * check whether this number satisfies the sudoku rule * @param row * @param col * @param current the current number * @return boolean value whether it satisfies the sudoku rule */ private boolean checkValidNum(int row, int col, char current){ return !checkValid.contains(current + ": row " + row) && !checkValid.contains(current + ": col " + col) && !checkValid.contains(current + ": square " + row/3 + " " + col/3); } private void add(int row, int col, char current){ board[row][col] = current; checkValid.add(current + ": row " + row); checkValid.add(current + ": col " + col); checkValid.add(current + ": square " + row/3 + " " + col/3); } private void remove(int row, int col){ char current = board[row][col]; board[row][col] = EMPTY; checkValid.remove(current + ": row " + row); checkValid.remove(current + ": col " + col); checkValid.remove(current + ": square " + row/3 + " " + col/3); } /** * Solver acts as the main backtracking recursive function * if there is an unfilled cell, it will try to find if there exists any number from 1 to 9 that * satisfies the sudoku rule. Otherwise, it backtracks to the previous empty cell and try a * different number. * @param row: current row position of the cell * @param col: current column position of the cell */ private void solver(int row, int col){ if (!solvable && row < size){ if (board[row][col] != EMPTY){ if (col == size - 1) solver(row + 1, 0); else solver(row, col + 1); } else{ for (int i = 1; i < 10; i++){ char current = (char) (i + '0'); if (checkValidNum(row, col, current)){ //System.out.println("Add row & col: " + row + " " + col + ": " + current); add(row, col, current); if (col == size - 1) solver(row + 1, 0); else solver(row, col + 1); //System.out.println("Remove row & col: " + row + " " + col + ": " + board[row][col]); if (!solvable) remove(row, col); } } } } if (row == size) solvable = true; } }
true
c73db8f3023212e6e776203efc0e2e5313e910b6
Java
ojama/NewRetail
/newretail-manager/newretail-manager-pojo/src/main/java/com/newretail/pojo/custom/MerchantActivities.java
UTF-8
1,824
2.15625
2
[]
no_license
package com.newretail.pojo.custom; public class MerchantActivities { private String attribute; private String description; private String icon_color; private String icon_name; private int id; private boolean is_exclusive_with_food_activity; private String name; private String tips; private int type; public void setAttribute(String attribute) { this.attribute = attribute; } public String getAttribute() { return attribute; } public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } public void setIcon_color(String icon_color) { this.icon_color = icon_color; } public String getIcon_color() { return icon_color; } public void setIcon_name(String icon_name) { this.icon_name = icon_name; } public String getIcon_name() { return icon_name; } public void setId(int id) { this.id = id; } public int getId() { return id; } public void setIs_exclusive_with_food_activity(boolean is_exclusive_with_food_activity) { this.is_exclusive_with_food_activity = is_exclusive_with_food_activity; } public boolean getIs_exclusive_with_food_activity() { return is_exclusive_with_food_activity; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setTips(String tips) { this.tips = tips; } public String getTips() { return tips; } public void setType(int type) { this.type = type; } public int getType() { return type; } }
true
9e32797caf7ba9ad6244cb248eb11b7cf9af0a8a
Java
thombergs/coderadar
/server/coderadar-webapp/src/test/java/org/wickedsource/coderadar/commit/domain/DateCoordinatesTest.java
UTF-8
1,795
2.71875
3
[ "MIT" ]
permissive
package org.wickedsource.coderadar.commit.domain; import org.junit.Test; import java.util.Calendar; import java.util.Date; import java.util.Locale; import static org.assertj.core.api.Assertions.assertThat; public class DateCoordinatesTest { @Test public void lastWeekOfPreviousYearDE() { DateCoordinates coordinates = new DateCoordinates(); coordinates.updateFromDate(date(2016, 1, 1), Locale.GERMAN); assertThat(coordinates.getDayOfMonth()).isEqualTo(1); assertThat(coordinates.getMonth()).isEqualTo(1); assertThat(coordinates.getWeekOfYear()).isEqualTo(53); assertThat(coordinates.getYear()).isEqualTo(2016); assertThat(coordinates.getYearOfWeek()).isEqualTo(2015); coordinates.updateFromDate(date(2015, 12, 30), Locale.GERMAN); assertThat(coordinates.getDayOfMonth()).isEqualTo(30); assertThat(coordinates.getMonth()).isEqualTo(12); assertThat(coordinates.getWeekOfYear()).isEqualTo(53); assertThat(coordinates.getYear()).isEqualTo(2015); assertThat(coordinates.getYearOfWeek()).isEqualTo(2015); } @Test public void firstWeekOfCurrentYearDE() { DateCoordinates coordinates = new DateCoordinates(); coordinates.updateFromDate(date(2016, 1, 4), Locale.GERMAN); assertThat(coordinates.getDayOfMonth()).isEqualTo(4); assertThat(coordinates.getMonth()).isEqualTo(1); assertThat(coordinates.getWeekOfYear()).isEqualTo(1); assertThat(coordinates.getYear()).isEqualTo(2016); assertThat(coordinates.getYearOfWeek()).isEqualTo(2016); } private Date date(int year, int month, int day) { Calendar c = Calendar.getInstance(); c.set(year, month - 1, day); return c.getTime(); } }
true
3ff78e5dbd423ce1d28c79524560b64152baabec
Java
hzkkkk/wolf-material-manage
/src/main/java/com/wolf/material/controller/SoftwareController.java
UTF-8
1,765
2.59375
3
[]
no_license
/** * @Title: SoftwareController * @Description: 软件组成员表与前端交换数据处 * @author 黄彦钊 * @date 2019/9/23 **/ package com.wolf.material.controller; import com.wolf.material.pojo.SoftwareInfo; import com.wolf.material.service.SoftwareInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController//返回数据直接显示,而不是跳转 @CrossOrigin(origins = "*",maxAge = 3600)//实现跨域注解 @RequestMapping("/software")//拦截有software的url public class SoftwareController { @Autowired//自动注入service层 private SoftwareInfoService softwareInfoService; //页面访问localhost:8080/software/findAll,返回数据库软件组所有人数据 @RequestMapping("findAll")//拦截有findAll的url public List<SoftwareInfo> findAll() throws Exception{//抛出异常 List<SoftwareInfo> softwareInfo = softwareInfoService.findAll();//调用service类方法 System.out.println(softwareInfo); return softwareInfo;//返回json数据 } //页面访问localhost:8080/software/findOne,接收网页传来的json中id属性,到数据库查询id相同的人员信息并返回 @RequestMapping(value="findOne", method = RequestMethod.GET, produces = "application/json;charset=UTF-8") //拦截有jsonInteractive的url,拦截该访问路径的json数据 public List<SoftwareInfo> findOne(@RequestParam(value="id") Integer id) throws Exception{//拦截一个key为id的json数据,并注入定义的变量 List<SoftwareInfo> softwareInfo = softwareInfoService.findOne(id);//调用service类方法 return softwareInfo;//返回json数据 } }
true
417e01aa55698d834ae14cfa6370695b983f297d
Java
anassaeed72/Android
/MassEmailS/src/com/anassaeed/massemails/SetAccount.java
UTF-8
2,539
2.21875
2
[]
no_license
package com.anassaeed.massemails; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class SetAccount extends Activity { Button btnSetAccount; EditText username; EditText password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.setaccount); btnSetAccount = (Button) findViewById(R.id.btnSetAccount); username = (EditText) findViewById(R.id.username); password = (EditText) findViewById(R.id.password); btnSetAccount.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String usernameString = username.getText().toString(); String passwordString = password.getText().toString(); Mail mail = new Mail(); mail.setUsername(usernameString); mail.setPassword(passwordString); SharedPreferences shfObject = getSharedPreferences(MainActivity.databaseName, Context.MODE_PRIVATE); SharedPreferences.Editor shfEditorObject=shfObject.edit(); shfEditorObject.putString(MainActivity.usernameDB,usernameString); shfEditorObject.putString(MainActivity.passwordDB,passwordString); shfEditorObject.commit(); Toast.makeText(SetAccount.this, "Account Info Saved", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(SetAccount.this, MainActivity.class); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
true
d554e6fca40750658adc1d5c6ad217b3a7f2ce3e
Java
Kavrese/SinemaApp
/app/src/main/java/com/example/sinemaapp/classes/Errors.java
UTF-8
2,149
2.421875
2
[]
no_license
package com.example.sinemaapp.classes; import android.content.Context; import android.util.Log; import android.widget.Toast; import com.example.sinemaapp.model.FullinfoVideo; import com.example.sinemaapp.model.ModelMain; import org.json.JSONObject; import retrofit2.Response; public class Errors { public Errors (Response<ModelMain> responseM, Response<FullinfoVideo> responseF, String mode, Context context,String from) { Response response = null; if(mode.equals("ModelMain")) response = responseM; else if(mode.equals("FullVideoApi")) response = responseF; else if(mode.equals("No full info")){ Toast.makeText(context, "Error info: No info", Toast.LENGTH_SHORT).show(); Log.e("error","Error info: No info"); return; }else if(mode.equals("loading new videos")){ Toast.makeText(context, "Error loading: Restart loading new videos" + " - "+from, Toast.LENGTH_SHORT).show(); Log.e("error","Error loading: Restart loading new videos"+" - "+from); return; } if (response.errorBody() != null) { try { JSONObject jObjError = new JSONObject(response.errorBody().string()); Log.e("error", jObjError.getJSONObject("error").getString("message")); if (jObjError.getJSONObject("error").getString("message").equals("The request cannot be completed because you have exceeded your <a href=\"/youtube/v3/getting-started#quota\">quota</a>.")) { Toast.makeText(context, "Error "+mode+" : Закончились квоты на api. Подождите до полуночи, пока они обновляются, и попробуйте еще раз. Is in " + from, Toast.LENGTH_LONG).show(); } } catch (Exception e) { Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show(); } } } public Errors(Throwable t,Context context,String from){ Toast.makeText(context, t.getMessage() + " - is in "+from, Toast.LENGTH_LONG).show(); } }
true
dee55775dcc06dce72baab6f18574fe1351be7a1
Java
chatrolavivek/learning-java-programming
/JavaPrograms/src/practice/ContinueDemo.java
UTF-8
264
3.46875
3
[]
no_license
package practice; public class ContinueDemo { public static void main(String[] args) { // WAP to display the following output // 1 2 3 4 6 7 8 9 10 for (int i = 1; i <= 10; i++) { if (i == 5) { continue; } System.out.print(i + " "); } } }
true
9602501fc6f2948dffe2384ddbc08f02fbe7511d
Java
meeteor-13/core
/src/main/java/com/github/meeteor13/core/controller/IntersectionController.java
UTF-8
1,502
2.0625
2
[]
no_license
package com.github.meeteor13.core.controller; import com.github.meeteor13.core.domain.Intersection; import com.github.meeteor13.core.repository.IntersectionRepository; import lombok.RequiredArgsConstructor; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; @RestController @RequestMapping("/api/v1/intersections") @RequiredArgsConstructor public class IntersectionController { private final IntersectionRepository intersectionRepository; @PreAuthorize("hasRole('INTERSECTION_READ')") @GetMapping( produces = { MediaType.APPLICATION_JSON_UTF8_VALUE, MediaType.APPLICATION_STREAM_JSON_VALUE } ) public Flux<Intersection> findAll() { return intersectionRepository.findAll(); } @PreAuthorize("hasRole('INTERSECTION_READ')") @GetMapping( params = { "userId" }, produces = { MediaType.APPLICATION_JSON_UTF8_VALUE, MediaType.APPLICATION_STREAM_JSON_VALUE } ) public Flux<Intersection> findAllByUserId(@RequestParam Long userId) { return intersectionRepository.findAllByUsersContains(userId); } }
true
bb8197590fde60c136cce436bbff01ea3abe63f0
Java
hanhanzhang/algorithm-java
/src/main/java/com/sdu/algorithm/leetcode/LT208.java
UTF-8
2,047
3.34375
3
[ "Apache-2.0" ]
permissive
package com.sdu.algorithm.leetcode; public class LT208 { private static class TrieNode { char val; // 标识是否有结束的单词 boolean hasWord; TrieNode[] children; TrieNode(char val) { this.val = val; this.children = new TrieNode[26]; } } private static class Trie { TrieNode[] root; Trie() { root = new TrieNode[26]; } private static void buildTrie(TrieNode[] roots, String word, int start) { char c = word.charAt(start); int pos = c - 'a'; if (roots[pos] == null) { roots[pos] = new TrieNode(c); } if (start + 1 < word.length()) { buildTrie(roots[pos].children, word, start + 1); } else { roots[pos].hasWord = true; } } void insert(String word) { buildTrie(root, word, 0); } private static boolean childrenEmpty(TrieNode[] children) { for (TrieNode child : children) { if (child != null) { return false; } } return true; } private static boolean dfs(TrieNode[] roots, String word, int start, boolean prefixMatch) { int pos = word.charAt(start) - 'a'; TrieNode cur = roots[pos]; if (cur == null) { return false; } if (start + 1 < word.length()) { return dfs(roots[pos].children, word, start + 1, prefixMatch); } if (prefixMatch) { return true; } if (roots[pos].hasWord) { return true; } return childrenEmpty(roots[pos].children); } boolean search(String word) { return dfs(root, word, 0, false); } boolean startsWith(String prefix) { return dfs(root, prefix, 0, true); } } public static void main(String[] args) { Trie trie = new Trie(); trie.insert("apple"); System.out.println(trie.search("apple")); System.out.println(trie.search("app")); System.out.println(trie.startsWith("app")); trie.insert("app"); System.out.println(trie.search("app")); } }
true
169ceea991011af96d5a6ff2ab252c081a217d4e
Java
modoundongo/forage
/forage-dao/src/test/java/sn/ndongoinformatique/forage/IDaoFactureImplTest.java
UTF-8
1,286
2.03125
2
[]
no_license
package sn.ndongoinformatique.forage; import static org.junit.Assert.*; import org.junit.Ignore; import org.junit.Test; public class IDaoFactureImplTest { Village village = new Village(10000, "Dakar", 12000); ClientForage client = new ClientForage("5020", "ouseynou", "Sene", village); Compteur compteur = new Compteur("3000", 100, 200); Abonnement abonnement = new Abonnement(1500, client, compteur, "actif"); Facture facture = new Facture(12, abonnement); IDaoAbonnementImpl daoAbonnementImpl=new IDaoAbonnementImpl(); IDaoClientForageImpl daoClientImpl=new IDaoClientForageImpl(); IDaoVillageImpl daoVillage=new IDaoVillageImpl(); IDaoCompteurImpl daoCompteur=new IDaoCompteurImpl(); IDaoFactureImpl daoFacture=new IDaoFactureImpl(); @Test public void testCreate() { daoVillage.create(village); daoClientImpl.create(client); daoCompteur.create(compteur); daoAbonnementImpl.create(abonnement); daoFacture.create(facture); } @Test public void testUpdate() { daoFacture.update(facture); } @Test public void testList() { daoFacture.list(); } @Test public void testDelete() { daoFacture.delete(facture); daoAbonnementImpl.delete(abonnement); daoCompteur.delete(compteur); daoClientImpl.delete(client); daoVillage.delete(village); } }
true
656b14653f764345f56f7d26b92a93082291cb87
Java
jasobimDevelopers/jasobim
/src/com/my/spring/DAOImpl/AtttenceLogDaoImpl.java
UTF-8
12,358
2.15625
2
[]
no_license
package com.my.spring.DAOImpl; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import org.hibernate.transform.Transformers; import org.hibernate.type.StandardBasicTypes; import org.springframework.stereotype.Repository; import com.my.spring.DAO.AttenceLogDao; import com.my.spring.DAO.BaseDao; import com.my.spring.enums.ErrorCodeEnum; import com.my.spring.model.AttenceForgetFactLogs; import com.my.spring.model.AttenceLog; import com.my.spring.model.AttenceLogs; import com.my.spring.utils.DataWrapper; @Repository public class AtttenceLogDaoImpl extends BaseDao<AttenceLog> implements AttenceLogDao { @Override public boolean addAttenceLog(AttenceLog am) { // TODO Auto-generated method stub return save(am); } @Override public boolean deleteAttenceLog(Long id) { // TODO Auto-generated method stub return delete(get(id)); } @Override public boolean updateAttenceLog(AttenceLog am) { // TODO Auto-generated method stub return update(am); } @Override public AttenceLog getAttenceLogById(Long id) { // TODO Auto-generated method stub return get(id); } @SuppressWarnings("unchecked") @Override public DataWrapper<List<AttenceLogs>> getAttenceLogsList(Integer pageIndex, Integer pageSize,AttenceLog am,Integer year,Integer month) { // TODO Auto-generated method stub /*if(pageIndex==null){ pageIndex=1; } if(pageSize==null){ pageSize=10; }*/ DataWrapper<List<AttenceLogs>> dataWrapper=new DataWrapper<List<AttenceLogs>>(); String sql = "select e.user_id,sum(e.late_num) as late_nums,sum(e.leave_early_num) as leave_early_nums from" +" (select sum(late) as late_num,sum(leave_early) as leave_early_num,1 as clock_flag,user_id from attence_log " +"where (start_work_time is not null and end_work_time is not null) and project_id="+ +am.getProjectId()+" and create_date BETWEEN '"+String.valueOf(year)+"-"+String.valueOf(month)+"-01"+"' and '" +String.valueOf(year)+"-"+String.valueOf(month+1)+"-01"+"' GROUP BY user_id UNION " +"select sum(late) as late_num,sum(leave_early) as leave_early_num,2 as clock_flag,user_id from attence_log" +" where (start_work_time is null or end_work_time is null) and project_id=" +am.getProjectId()+" and create_date BETWEEN '"+String.valueOf(year)+"-"+String.valueOf(month)+"-01" +"' and '"+String.valueOf(year)+"-"+String.valueOf(month+1)+"-01"+"' GROUP BY user_id) e GROUP BY e.user_id"; /*if(pageIndex!=-1){ sql = sql +" limit "+(pageSize*pageIndex-pageSize)+","+pageSize; }*/ Session session=getSession(); try{ Query query = session.createSQLQuery(sql) .addScalar("user_id", StandardBasicTypes.LONG) .addScalar("late_nums", StandardBasicTypes.INTEGER) .addScalar("leave_early_nums", StandardBasicTypes.INTEGER) .setResultTransformer(Transformers.aliasToBean(AttenceLogs.class)); dataWrapper.setData(query.list()); }catch(Exception e){ e.printStackTrace(); } /* result.setData(ret); result.setTotalNumber(totalItemNum); result.setCurrentPage(pageIndex); result.setTotalPage(totalPageNum); result.setNumberPerPage(pageSize);*/ return dataWrapper; } @SuppressWarnings("unchecked") @Override public DataWrapper<List<AttenceLogs>> getAttenceLogsList(Integer pageIndex, Integer pageSize,AttenceLog am,String start,String end) { DataWrapper<List<AttenceLogs>> dataWrapper=new DataWrapper<List<AttenceLogs>>(); String sql = "select e.user_id,sum(e.late_num) as late_nums,sum(e.leave_early_num) as leave_early_nums from" +" (select sum(late) as late_num,sum(leave_early) as leave_early_num,1 as clock_flag,user_id from attence_log " +"where (start_work_time is not null and end_work_time is not null) and project_id="+ +am.getProjectId()+" and user_id="+am.getUserId()+" and create_date BETWEEN '"+start+"' and '" +end+"' GROUP BY user_id UNION " +"select sum(late) as late_num,sum(leave_early) as leave_early_num,2 as clock_flag,user_id from attence_log" +" where (start_work_time is null or end_work_time is null) and project_id=" +am.getProjectId()+" and user_id="+am.getUserId()+" and create_date BETWEEN '"+start +"' and '"+end+"' GROUP BY user_id) e GROUP BY e.user_id"; Session session=getSession(); try{ Query query = session.createSQLQuery(sql) .addScalar("user_id", StandardBasicTypes.LONG) .addScalar("late_nums", StandardBasicTypes.INTEGER) .addScalar("leave_early_nums", StandardBasicTypes.INTEGER) .setResultTransformer(Transformers.aliasToBean(AttenceLogs.class)); dataWrapper.setData(query.list()); }catch(Exception e){ e.printStackTrace(); } return dataWrapper; } @SuppressWarnings("unchecked") @Override public DataWrapper<List<AttenceLogs>> getAttenceLogsUserList(Integer pageIndex, Integer pageSize,AttenceLog am,Integer year,Integer month) { DataWrapper<List<AttenceLogs>> dataWrapper=new DataWrapper<List<AttenceLogs>>(); String sql = "select DATE_FORMAT(a.create_date,'%Y-%m') as month,a.* from attence_log a " +" where project_id="+am.getProjectId()+" group by user_id"; Session session=getSession(); try{ Query query = session.createSQLQuery(sql) .addScalar("month", StandardBasicTypes.DATE) .addScalar("id", StandardBasicTypes.LONG) .addScalar("start_work_time", StandardBasicTypes.STRING) .addScalar("end_work_time", StandardBasicTypes.STRING) .addScalar("user_id", StandardBasicTypes.LONG) .addScalar("project_id", StandardBasicTypes.LONG) .addScalar("late", StandardBasicTypes.INTEGER) .addScalar("lat", StandardBasicTypes.DOUBLE) .addScalar("lng", StandardBasicTypes.DOUBLE) .addScalar("attence_model_id", StandardBasicTypes.LONG) .addScalar("create_date", StandardBasicTypes.DATE) .addScalar("clock_flag", StandardBasicTypes.INTEGER) .setResultTransformer(Transformers.aliasToBean(AttenceLogs.class)); dataWrapper.setData(query.list()); }catch(Exception e){ e.printStackTrace(); } return dataWrapper; } @Override public DataWrapper<Void> deleteAttenceLogByProjectId(Long id) { DataWrapper<Void> dataWrapper = new DataWrapper<Void>(); String sql="delete * from attence_log where project_id="+id; Session session=getSession(); try{ @SuppressWarnings("unused") Query query=session.createSQLQuery(sql); session.getTransaction().commit(); session.flush(); }catch(Exception e){ e.printStackTrace(); session.getTransaction().rollback(); dataWrapper.setErrorCode(ErrorCodeEnum.Target_Not_Existed); } return dataWrapper; } @Override public DataWrapper<List<AttenceLog>> getAttenceLogList(Integer pageIndex, Integer pageSize, AttenceLog am) { // TODO Auto-generated method stub return null; } @SuppressWarnings("unchecked") @Override public AttenceLog getAttenceLogByInfos(Long id, Date nowDate, Long projectId) { List<AttenceLog> ret = new ArrayList<AttenceLog>(); Session session = getSession(); Criteria criteria = session.createCriteria(AttenceLog.class); if(id!=null){ criteria.add(Restrictions.eq("userId", id)); } if(nowDate!=null){ criteria.add(Restrictions.eq("createDate",nowDate)); } if(projectId!=null){ criteria.add(Restrictions.eq("projectId", projectId)); } try { ret = criteria.list(); }catch (Exception e){ e.printStackTrace(); } if (ret != null && ret.size() > 0) { return ret.get(0); } return null; } @SuppressWarnings("unchecked") @Override public AttenceLog getAttenceLogListByIds(AttenceLog ps) { List<AttenceLog> ret = new ArrayList<AttenceLog>(); Session session = getSession(); Criteria criteria = session.createCriteria(AttenceLog.class); if(ps!=null){ if(ps.getUserId()!=null){ criteria.add(Restrictions.eq("userId", ps.getUserId())); } if(ps.getProjectId()!=null){ criteria.add(Restrictions.eq("projectId", ps.getProjectId())); } if(ps.getCreateDate()!=null){ criteria.add(Restrictions.eq("createDate", ps.getCreateDate())); } try { ret = criteria.list(); }catch (Exception e){ e.printStackTrace(); } if (ret != null && ret.size() > 0) { return ret.get(0); } } return null; } @SuppressWarnings("unchecked") @Override public DataWrapper<List<AttenceForgetFactLogs>> getForgetFactNumsList(Integer pageIndex, Integer pageSize,AttenceLog am,Integer year,Integer month) { DataWrapper<List<AttenceForgetFactLogs>> dataWrapper=new DataWrapper<List<AttenceForgetFactLogs>>(); String sql = "select e.user_id,sum(e.fact_num) as fact_nums,sum(e.forget_num) as forget_nums from " +"(select count(1) as fact_num ,0 as forget_num,1 as clock_flag,user_id from attence_log" +" where (start_work_time is not null and end_work_time is not null) and project_id="+ +am.getProjectId()+" and create_date BETWEEN '"+String.valueOf(year)+"-"+String.valueOf(month)+"-01"+"' and '" +String.valueOf(year)+"-"+String.valueOf(month+1)+"-01"+"' GROUP BY user_id" +" UNION select 0 as fact_num,count(1) as forget_num,2 as clock_flag,user_id from attence_log" +" where (start_work_time is null or end_work_time is null) and project_id=" +am.getProjectId()+" and create_date BETWEEN '"+String.valueOf(year)+"-"+String.valueOf(month)+"-01" +"' and '"+String.valueOf(year)+"-"+String.valueOf(month+1)+"-01"+"' GROUP BY user_id) e GROUP BY e.user_id"; Session session=getSession(); try{ Query query = session.createSQLQuery(sql) .addScalar("forget_nums", StandardBasicTypes.INTEGER) .addScalar("fact_nums", StandardBasicTypes.INTEGER) .addScalar("user_id", StandardBasicTypes.LONG) .setResultTransformer(Transformers.aliasToBean(AttenceForgetFactLogs.class)); dataWrapper.setData(query.list()); }catch(Exception e){ e.printStackTrace(); } return dataWrapper; } @SuppressWarnings("unchecked") @Override public DataWrapper<List<AttenceForgetFactLogs>> getForgetFactNumsList(Integer pageIndex, Integer pageSize,AttenceLog am,String start,String end) { DataWrapper<List<AttenceForgetFactLogs>> dataWrapper=new DataWrapper<List<AttenceForgetFactLogs>>(); String sql = "select e.user_id,sum(e.fact_num) as fact_nums,sum(e.forget_num) as forget_nums from " +"(select count(1) as fact_num ,0 as forget_num,1 as clock_flag,user_id from attence_log" +" where (start_work_time is not null and end_work_time is not null) and project_id="+ +am.getProjectId()+" and user_id="+am.getUserId()+" and create_date BETWEEN '"+start+"' and '" +end+"' GROUP BY user_id" +" UNION select 0 as fact_num,count(1) as forget_num,2 as clock_flag,user_id from attence_log" +" where (start_work_time is null or end_work_time is null) and project_id=" +am.getProjectId()+" and user_id="+am.getUserId()+" and create_date BETWEEN '"+start +"' and '"+end+"' GROUP BY user_id) e GROUP BY e.user_id"; /*if(pageIndex!=-1){ sql = sql +" limit "+(pageSize*pageIndex-pageSize)+","+pageSize; }*/ Session session=getSession(); try{ Query query = session.createSQLQuery(sql) .addScalar("forget_nums", StandardBasicTypes.INTEGER) .addScalar("fact_nums", StandardBasicTypes.INTEGER) .addScalar("user_id", StandardBasicTypes.LONG) .setResultTransformer(Transformers.aliasToBean(AttenceForgetFactLogs.class)); dataWrapper.setData(query.list()); }catch(Exception e){ e.printStackTrace(); } return dataWrapper; } }
true
34a9603ae303112ad4b6336dfed92d31c8c53077
Java
sammysauce/java
/src/com/RahulShetty/Constructor/constructDemo.java
UTF-8
414
2.734375
3
[]
no_license
package com.RahulShetty.Constructor; public class constructDemo { public constructDemo() { System.out.println("I am the constructor demo"); System.out.println("I am the constructor demo lecture 1"); } public void getData() { System.out.println("I am the method "); } public static void main(String[] args) { constructDemo cd = new constructDemo(); } }
true
065fe67020d1d8905aa882ae58f6ce657162b059
Java
lucas-puebla/CC4102-tarea2
/src/main/java/com/cc4102/stringDict/TSTreeNode.java
UTF-8
3,624
3.234375
3
[ "MIT" ]
permissive
package com.cc4102.stringDict; import java.util.ArrayList; class TSTreeNode { private char key; private ArrayList<Integer> values1; private ArrayList<Integer> values2; private TSTreeNode left, right, son; private boolean empty; TSTreeNode() { empty = true; key = 0; values1 = values2 = null; left = right = son = null; } private void initNode(char key) { empty = false; this.key = key; left = new TSTreeNode(); right = new TSTreeNode(); son = new TSTreeNode(); } private void initLeaf(char key, int value, int text) { initNode(key); values1 = new ArrayList<Integer>(); values2 = new ArrayList<Integer>(); addValue(value, text); } public ArrayList<Integer> search(String word, int text) { if (empty) // not found return new ArrayList<Integer>(); // empty char first = word.charAt(0); if (first == key) { // word found if (word.length() == 1) return getValues(text); // recursive calls return son.search(word.substring(1), text); } else if (first < key) { return left.search(word, text); } else { return right.search(word, text); } } private ArrayList<Integer> getValues(int text) { if (text == 0) return values1; else return values2; } public void insert(String word, int pos, int text) { char first = word.charAt(0); // initialize empty nodes if (empty) { if (word.length() == 1) { initLeaf(first, pos, text); return; } else { initNode(first); } } if (first == key) { // word already in if (word.length() == 1) { addValue(pos, text); return; } // recursive calls son.insert(word.substring(1), pos, text); } else if (first < key) { left.insert(word, pos, text); } else { right.insert(word, pos, text); } } private void addValue(int pos, int text) { if (text == 0) values1.add(pos); else values2.add(pos); } public int getSize() { if (empty) return 0; return 1 + son.getSize() + left.getSize() + right.getSize(); } void getKeys(String prefix, ArrayList<String> keys) { if (empty) return; if (values1 != null) keys.add(prefix); left.getKeys(prefix, keys); son.getKeys(prefix + String.valueOf(key), keys); right.getKeys(prefix, keys); } void getSimilarity(double[] sums) { if (empty) return; if (values1 != null) { sums[0] += Math.abs(values1.size() - values2.size()); sums[1] += values1.size() + values2.size(); } left.getSimilarity(sums); son.getSimilarity(sums); right.getSimilarity(sums); } @Override /** * este metodo se usa solo para debuggear */ public String toString() { return toString("").trim(); } /** * este metodo se usa solo para debuggear */ private String toString(String pre) { StringBuilder sb = new StringBuilder(); sb.append(key); if (values1 != null) { sb.append(" "); sb.append(values1); sb.append(", "); sb.append(values2); } sb.append("\n"); String newpre = pre + " "; if (!son.empty) { sb.append(newpre); sb.append("son: "); sb.append(son.toString(newpre)); } if (!left.empty) { sb.append(newpre); sb.append("left: "); sb.append(left.toString(newpre)); } if (!right.empty) { sb.append(newpre); sb.append("right: "); sb.append(right.toString(newpre)); } return sb.toString(); } }
true
a49a14393f1cf46a320193acfdf735bdfea45040
Java
nablarch/nablarch-core
/src/main/java/nablarch/core/text/NumberFormatter.java
UTF-8
3,691
3.28125
3
[ "Apache-2.0" ]
permissive
package nablarch.core.text; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Locale; /** * 数値をフォーマットするクラス。 * * @author Ryota Yoshinouchi */ public class NumberFormatter implements Formatter<Number> { /** * フォーマッタの名前 */ private String formatterName = "number"; /** * デフォルトのフォーマットパターン */ private String defaultPattern = "#,###.###"; @Override public Class<Number> getFormatClass() { return Number.class; } @Override public String getFormatterName() { return formatterName; } /** * デフォルトの書式で数値をフォーマットする。 * フォーマット対象がnullの場合はnullを返却する。 * * @param input フォーマット対象 * @return フォーマットされた文字列 */ @Override public String format(Number input) { return format(input, defaultPattern); } /** * 指定された書式で数値をフォーマットする。 * 指定するフォーマットは{@link DecimalFormat}の仕様に準拠すること。 * フォーマット対象がnullの場合はnullを返却する。 * * @param input フォーマット対象 * @param pattern フォーマットの書式 * @return フォーマットされた文字列 */ @Override public String format(Number input, String pattern) { if (pattern == null) { throw new IllegalArgumentException("pattern must not be null."); } if (input == null) { return null; } Locale locale = Locale.getDefault(); DecimalFormat decimalFormat; //Javadocにある以下の記載をもとにDecimalFormatのインスタンスを取得している。 //https://docs.oracle.com/javase/jp/9/docs/api/java/text/NumberFormat.html より //> フォーマットや解析をさらに制御したい場合、あるいはこのような制御をユーザーが使えるようにしたい場合は、 //> ファクトリ・メソッドから得られるNumberFormatをDecimalFormatにキャストすることもできます。 //> これはほとんどのロケールで有効ですが、有効にならないロケールの場合に備えて、これはtryブロックに指定してください。 try { decimalFormat = (DecimalFormat) NumberFormat.getInstance(locale); } catch (RuntimeException e) { //NumberFormat.getInstanceにthrowsの宣言がないためRuntimeExceptionをcatchしている throw new IllegalArgumentException("invalid locale for DecimalFormat, locale = " + locale, e); } try { decimalFormat.applyPattern(pattern); return decimalFormat.format(input); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( String.format("format failed. input = [%s] pattern = [%s] locale = [%s]", input, pattern, locale), e); } } /** * フォーマッタの名前を設定する。 * * @param formatterName フォーマッタの名前 */ public void setFormatterName(String formatterName) { this.formatterName = formatterName; } /** * フォーマットのデフォルトの書式を設定する。 * * @param defaultPattern デフォルトの書式 */ public void setDefaultPattern(String defaultPattern) { this.defaultPattern = defaultPattern; } }
true
aab5bb30d7365c01b5dcd303a711720db6b407f1
Java
wanbing/VivoFramework
/Vivo_y93/src/main/java/android/graphics/drawable/VivoAnimatedStateListDrawable.java
UTF-8
2,300
2.0625
2
[]
no_license
package android.graphics.drawable; import android.content.res.Resources; import android.graphics.drawable.DrawableContainer.DrawableContainerState; public class VivoAnimatedStateListDrawable extends AnimatedStateListDrawable { private static final String TAG = "VivoAnimatedStateListDrawable"; private float globaltheme; private boolean mMutated; private VivoAnimatedStateListState mState; static class VivoAnimatedStateListState extends AnimatedStateListState { VivoAnimatedStateListState(AnimatedStateListState orig, AnimatedStateListDrawable owner, Resources res) { super(orig, owner, res); } public Drawable newDrawable() { return new VivoAnimatedStateListDrawable(this, null, null); } public Drawable newDrawable(Resources res) { return new VivoAnimatedStateListDrawable(this, res, null); } } /* synthetic */ VivoAnimatedStateListDrawable(AnimatedStateListState state, Resources res, VivoAnimatedStateListDrawable -this2) { this(state, res); } VivoAnimatedStateListDrawable() { this(null, null); this.globaltheme = Resources.getSystem().getDimension(51118202); } protected boolean onStateChange(int[] stateSet) { boolean changed = super.onStateChange(stateSet); if (this.globaltheme == 0.0f) { jumpToCurrentState(); } return changed; } public Drawable mutate() { if (!this.mMutated && super.mutate() == this) { this.mState.mutate(); this.mMutated = true; } return this; } public void clearMutated() { super.clearMutated(); this.mMutated = false; } protected void setConstantState(DrawableContainerState state) { super.setConstantState(state); if (state instanceof VivoAnimatedStateListState) { this.mState = (VivoAnimatedStateListState) state; } } private VivoAnimatedStateListDrawable(AnimatedStateListState state, Resources res) { this.globaltheme = Resources.getSystem().getDimension(51118202); setConstantState(new VivoAnimatedStateListState(state, this, res)); onStateChange(getState()); jumpToCurrentState(); } }
true
b9a793aeacd4e2c89fcd12027c586819e8c61962
Java
jotayc/GAOP
/app/src/main/java/ugr/lsi/ui/ArtGridActivity.java
UTF-8
2,199
1.976563
2
[]
no_license
package ugr.lsi.ui; import android.content.Intent; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.GridLayout; import android.widget.GridView; import android.widget.Toast; import java.util.ArrayList; import ph.edu.dlsu.cmt.CameraActivity; import ph.edu.dlsu.cmt.Data; import ph.edu.dlsu.cmt.R; import ugr.lsi.ui.Adapters.ArtAdapter; import ugr.lsi.ui.Model.Art; public class ArtGridActivity extends AppCompatActivity { private GridView gridView; private ArrayList<Art> artList; private FloatingActionButton floatBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_art_grid); gridView = (GridView) findViewById(R.id.gridVw); artList = (ArrayList<Art>) Data.artList; floatBtn = (FloatingActionButton) findViewById(R.id.floatBtn); ArtAdapter adapter = new ArtAdapter(this, (ArrayList) Data.artList); gridView.setAdapter(adapter); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent i = new Intent(ArtGridActivity.this, CameraActivity.class); i.putExtra(Data.INFO_ID, position); i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); startActivity(i); //Toast.makeText(ArtGridActivity.this, "Pulsada obra: "+ Data.artList.get(position).getName(), Toast.LENGTH_SHORT).show(); } }); floatBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(ArtGridActivity.this, QrActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); startActivity(i); } }); } public void showLog(String msg){ Log.i("GAOP", msg); } }
true
2364ca73250c8039785f31d32845951110a31862
Java
cckmit/pnlb
/client/Src/org/compiere/apps/RecordInfo.java
UTF-8
10,546
1.765625
2
[]
no_license
/******************************************************************************* * The contents of this file are subject to the Compiere License Version 1.1 * ("License"); You may not use this file except in compliance with the License * You may obtain a copy of the License at http://www.compiere.org/license.html * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. The * Original Code is Compiere ERP & CRM Business Solution The Initial Developer * of the Original Code is Jorg Janke and ComPiere, Inc. Portions created by * Jorg Janke are Copyright (C) 1999-2005 Jorg Janke, parts created by ComPiere * are Copyright (C) ComPiere, Inc.; All Rights Reserved. Contributor(s): * ______________________________________. ******************************************************************************/ package org.compiere.apps; import java.awt.*; import java.awt.event.*; import java.math.*; import java.sql.*; import java.text.*; import java.util.*; import java.util.logging.*; import javax.swing.table.*; import org.compiere.grid.*; import org.compiere.model.*; import org.compiere.swing.*; import org.compiere.util.*; /** * Record Info (Who) With Change History * * @author Jorg Janke * @version $Id: RecordInfo.java,v 1.5 2005/11/14 02:10:58 jjanke Exp $ */ public class RecordInfo extends CDialog { /** * Record Info * @param owner owner * @param title title * @param dse data status event */ public RecordInfo (Frame owner, String title, DataStatusEvent dse) { super (owner, title, true); try { jbInit ( dynInit(dse, title) ); } catch (Exception e) { log.log(Level.SEVERE, "", e); } AEnv.positionCenterWindow (owner, this); } // RecordInfo private CPanel mainPanel = new CPanel (new BorderLayout(0,0)); private CPanel northPanel = new CPanel (); private CScrollPane scrollPane = new CScrollPane (); private VTable table = new VTable (); private ConfirmPanel confirmPanel = new ConfirmPanel (false); /** Logger */ protected CLogger log = CLogger.getCLogger(getClass()); /** The Data */ private Vector<Vector<String>> m_data = new Vector<Vector<String>>(); /** Info */ private StringBuffer m_info = new StringBuffer(); /** Date Time Format */ private SimpleDateFormat m_dateTimeFormat = DisplayType.getDateFormat (DisplayType.DateTime, Env.getLanguage(Env.getCtx())); /** Date Format */ private SimpleDateFormat m_dateFormat = DisplayType.getDateFormat (DisplayType.DateTime, Env.getLanguage(Env.getCtx())); /** Number Format */ private DecimalFormat m_numberFormat = DisplayType.getNumberFormat (DisplayType.Number, Env.getLanguage(Env.getCtx())); /** Amount Format */ private DecimalFormat m_amtFormat = DisplayType.getNumberFormat (DisplayType.Amount, Env.getLanguage(Env.getCtx())); /** Number Format */ private DecimalFormat m_intFormat = DisplayType.getNumberFormat (DisplayType.Integer, Env.getLanguage(Env.getCtx())); /** * Static Layout * @throws Exception */ private void jbInit (boolean showTable) throws Exception { getContentPane().add(mainPanel); CTextArea info = new CTextArea(m_info.toString()); info.setReadWrite(false); info.setOpaque(false); // transparent info.setForeground(Color.blue); info.setBorder(null); // if (showTable) { mainPanel.add (info, BorderLayout.NORTH); mainPanel.add (scrollPane, BorderLayout.CENTER); scrollPane.getViewport().add(table); scrollPane.setPreferredSize(new Dimension(500,100)); } else { info.setPreferredSize(new Dimension(400,75)); mainPanel.add (info, BorderLayout.CENTER); } // mainPanel.add (confirmPanel, BorderLayout.SOUTH); confirmPanel.addActionListener(this); } // jbInit /** * Dynamic Init * @param dse data status event * @param title title * @return true if table initialized */ private boolean dynInit(DataStatusEvent dse, String title) { if (dse.CreatedBy == null) return false; // Info MUser user = MUser.get(Env.getCtx(), dse.CreatedBy.intValue()); m_info.append(" ") .append(Msg.translate(Env.getCtx(), "CreatedBy")) .append(": ").append(user.getName()) .append(" - ").append(m_dateTimeFormat.format(dse.Created)).append("\n"); if (!dse.Created.equals(dse.Updated) || !dse.CreatedBy.equals(dse.UpdatedBy)) { if (!dse.CreatedBy.equals(dse.UpdatedBy)) user = MUser.get(Env.getCtx(), dse.UpdatedBy.intValue()); m_info.append(" ") .append(Msg.translate(Env.getCtx(), "UpdatedBy")) .append(": ").append(user.getName()) .append(" - ").append(m_dateTimeFormat.format(dse.Updated)).append("\n"); } if (dse.Info != null && dse.Info.length() > 0) m_info.append("\n (").append(dse.Info).append(")"); // Title if (dse.AD_Table_ID != 0) { M_Table table = M_Table.get (Env.getCtx(), dse.AD_Table_ID); setTitle(title + " - " + table.getName()); } // Only Client Preference can view Change Log if (!MRole.PREFERENCETYPE_Client.equals(MRole.getDefault().getPreferenceType())) return false; int Record_ID = 0; if (dse.Record_ID instanceof Integer) Record_ID = ((Integer)dse.Record_ID).intValue(); else log.info("dynInit - Invalid Record_ID=" + dse.Record_ID); if (Record_ID == 0) return false; // Data String sql = "SELECT AD_Column_ID, Updated, UpdatedBy, OldValue, NewValue " + "FROM AD_ChangeLog " + "WHERE AD_Table_ID=? AND Record_ID=? " + "ORDER BY Updated DESC"; PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement (sql, null); pstmt.setInt (1, dse.AD_Table_ID); pstmt.setInt (2, Record_ID); ResultSet rs = pstmt.executeQuery (); while (rs.next ()) { addLine (rs.getInt(1), rs.getTimestamp(2), rs.getInt(3), rs.getString(4), rs.getString(5)); } rs.close (); pstmt.close (); pstmt = null; } catch (Exception e) { log.log(Level.SEVERE, sql, e); } try { if (pstmt != null) pstmt.close (); pstmt = null; } catch (Exception e) { pstmt = null; } // Vector<String> columnNames = new Vector<String>(); columnNames.add(Msg.translate(Env.getCtx(), "AD_Column_ID")); columnNames.add(Msg.translate(Env.getCtx(), "NewValue")); columnNames.add(Msg.translate(Env.getCtx(), "OldValue")); columnNames.add(Msg.translate(Env.getCtx(), "UpdatedBy")); columnNames.add(Msg.translate(Env.getCtx(), "Updated")); DefaultTableModel model = new DefaultTableModel(m_data, columnNames); table.setModel(model); table.autoSize(false); return true; } // dynInit /** * Add Line * @param AD_Column_ID column * @param Updated updated * @param UpdatedBy user * @param OldValue old * @param NewValue new */ private void addLine (int AD_Column_ID, Timestamp Updated, int UpdatedBy, String OldValue, String NewValue) { Vector<String> line = new Vector<String>(); // Column M_Column column = M_Column.get (Env.getCtx(), AD_Column_ID); line.add(column.getName()); // if (OldValue != null && OldValue.equals(MChangeLog.NULL)) OldValue = null; String showOldValue = OldValue; if (NewValue != null && NewValue.equals(MChangeLog.NULL)) NewValue = null; String showNewValue = NewValue; // try { if (DisplayType.isText (column.getAD_Reference_ID ())) ; else if (column.getAD_Reference_ID() == DisplayType.YesNo) { if (OldValue != null) { boolean yes = OldValue.equals("true") || OldValue.equals("Y"); showOldValue = Msg.getMsg(Env.getCtx(), yes ? "Y" : "N"); } if (NewValue != null) { boolean yes = NewValue.equals("true") || NewValue.equals("Y"); showNewValue = Msg.getMsg(Env.getCtx(), yes ? "Y" : "N"); } } else if (column.getAD_Reference_ID() == DisplayType.Amount) { if (OldValue != null) showOldValue = m_amtFormat .format (new BigDecimal (OldValue)); if (NewValue != null) showNewValue = m_amtFormat .format (new BigDecimal (NewValue)); } else if (column.getAD_Reference_ID() == DisplayType.Integer) { if (OldValue != null) showOldValue = m_intFormat.format (new Integer (OldValue)); if (NewValue != null) showNewValue = m_intFormat.format (new Integer (NewValue)); } else if (DisplayType.isNumeric (column.getAD_Reference_ID ())) { if (OldValue != null) showOldValue = m_numberFormat.format (new BigDecimal (OldValue)); if (NewValue != null) showNewValue = m_numberFormat.format (new BigDecimal (NewValue)); } else if (column.getAD_Reference_ID() == DisplayType.Date) { if (OldValue != null) showOldValue = m_dateFormat.format (Timestamp.valueOf (OldValue)); if (NewValue != null) showNewValue = m_dateFormat.format (Timestamp.valueOf (NewValue)); } else if (column.getAD_Reference_ID() == DisplayType.DateTime) { if (OldValue != null) showOldValue = m_dateTimeFormat.format (Timestamp.valueOf (OldValue)); if (NewValue != null) showNewValue = m_dateTimeFormat.format (Timestamp.valueOf (NewValue)); } else if (DisplayType.isLookup(column.getAD_Reference_ID ())) { MLookup lookup = MLookupFactory.get (Env.getCtx(), 0, AD_Column_ID, column.getAD_Reference_ID(), Env.getLanguage(Env.getCtx()), column.getColumnName(), column.getAD_Reference_Value_ID(), column.isParent(), null); if (OldValue != null) { Object key = OldValue; if (column.getAD_Reference_ID() != DisplayType.List) key = new Integer(OldValue); NamePair pp = lookup.get(key); if (pp != null) showOldValue = pp.getName(); } if (NewValue != null) { Object key = NewValue; if (column.getAD_Reference_ID() != DisplayType.List) key = new Integer(NewValue); NamePair pp = lookup.get(key); if (pp != null) showNewValue = pp.getName(); } } else if (DisplayType.isLOB (column.getAD_Reference_ID ())) ; } catch (Exception e) { log.log(Level.WARNING, OldValue + "->" + NewValue, e); } // line.add(showNewValue); line.add(showOldValue); // UpdatedBy MUser user = MUser.get(Env.getCtx(), UpdatedBy); line.add(user.getName()); // Updated line.add(m_dateFormat.format(Updated)); m_data.add(line); } // addLine /** * ActionListener * @param e event */ public void actionPerformed(ActionEvent e) { dispose(); } // actionPerformed } // RecordInfo
true
2410c627dd4b12720715795fa61a82dadfab7260
Java
hnkaustubh/datastructures-general-operations
/Stack/PostfixEvaluationUsingStack.java
UTF-8
1,239
3.515625
4
[]
no_license
package org.launchcode; import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter an arithmetic expression"); String str = scanner.next(); System.out.println(postfixEvaluation(str)); } public static int postfixEvaluation(String str){ char[] strArray = str.toCharArray(); Stack<Integer> stack = new Stack(); for(char c:strArray) { if(Character.isDigit(c)) stack.push(c - '0'); else{ int op1 = stack.pop(); int op2 = stack.pop(); switch (c) { case '+' : stack.push(op2 + op1); break; case '-' : stack.push(op2 - op1); break; case '*' : stack.push(op2 * op1); break; case '/' : stack.push(op2 / op1); break; } } } return stack.pop(); } }
true
d0ad2d5db49742f5865c646f969f63d404ebfa05
Java
oguzhanyrdmc/hashtable
/src/Read.java
ISO-8859-9
669
3.078125
3
[]
no_license
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Read { public void readStory(HashTable table) { // dosyadan inputtxt dosyas okunuyor File file = new File("story.txt"); Scanner scanner, line; try { scanner = new Scanner(file); while (scanner.hasNextLine()) { // read line by line line = new Scanner(scanner.nextLine()); while (line.hasNext()) { //read word by word String word = line.next(); table.put(word); //okunan deper hemen table yerletiriliyor } } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
true
9bae2506901527af0c62153eb783d35ebd872554
Java
AyrtonGonsallo/E-banking
/src/main/java/com/projetJEE/Ebanking/EBankingApplication.java
UTF-8
12,827
2.109375
2
[]
no_license
package com.projetJEE.Ebanking; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import com.projetJEE.Ebanking.Dao.AdminRepository; import com.projetJEE.Ebanking.Dao.AgenceRepository; import com.projetJEE.Ebanking.Dao.AgentRepository; import com.projetJEE.Ebanking.Dao.ClientRepository; import com.projetJEE.Ebanking.Dao.CompteRepository; import com.projetJEE.Ebanking.Dao.DeviseRepository; import com.projetJEE.Ebanking.Dao.OperateurRepository; import com.projetJEE.Ebanking.Dao.OperationRepository; import com.projetJEE.Ebanking.Dao.RechargeRepository; import com.projetJEE.Ebanking.Dao.VirementRepository; import com.projetJEE.Ebanking.entities.Admin; import com.projetJEE.Ebanking.entities.Agence; import com.projetJEE.Ebanking.entities.Agent; import com.projetJEE.Ebanking.entities.Client; import com.projetJEE.Ebanking.entities.Compte; import com.projetJEE.Ebanking.entities.Devise; import com.projetJEE.Ebanking.entities.Operateur; import com.projetJEE.Ebanking.entities.Operation; import com.projetJEE.Ebanking.entities.Recharge; import com.projetJEE.Ebanking.entities.Virement; import net.bytebuddy.utility.RandomString; @SpringBootApplication public class EBankingApplication implements CommandLineRunner { @Autowired private AgenceRepository agenceR; @Autowired private ClientRepository clientR; @Autowired private CompteRepository compteR; @Autowired private AgentRepository agentR; @Autowired private AdminRepository adminR; @Autowired private DeviseRepository deviseR; @Autowired private RechargeRepository rechargeR; @Autowired private VirementRepository virementR; @Autowired private OperateurRepository operateurR; @Autowired private OperationRepository operationR; //pour recuperer le id des articles @Autowired private RepositoryRestConfiguration rrc; public static void main(String[] args) { SpringApplication.run(EBankingApplication.class, args); } @Override public void run(String... args) throws Exception { String[] noms={"Dark","Allen","Jones",RandomString.make(12),RandomString.make(12),RandomString.make(12),RandomString.make(12)}; String[] prenoms={"Marco","Paul","Alain",RandomString.make(12),RandomString.make(12),RandomString.make(12),RandomString.make(12)}; String[] usernames={"admin","allen","jones",RandomString.make(12),RandomString.make(12),RandomString.make(12),RandomString.make(12)}; String[] passwords={"madagascar","allen","jones",RandomString.make(12),RandomString.make(12),RandomString.make(12),RandomString.make(12)}; //pour recuperer le id des articles rrc.exposeIdsFor(Client.class,Compte.class,Agent.class,Virement.class,Agence.class,Operation.class,Operateur.class); List<Client>clients=new ArrayList<Client>(); List<Agent>agents=new ArrayList<Agent>(); List<Compte>comptes1=new ArrayList<Compte>(); List<Compte>comptes2=new ArrayList<Compte>(); List<Compte>comptes3=new ArrayList<Compte>(); List<Compte>comptes4=new ArrayList<Compte>(); List<Compte>comptes5=new ArrayList<Compte>(); List<Compte>comptes6=new ArrayList<Compte>(); List<Compte>comptes7=new ArrayList<Compte>(); List<List<Compte>>comptes=new ArrayList<List<Compte>>(); comptes.add(comptes1); comptes.add(comptes2); comptes.add(comptes3); comptes.add(comptes4); comptes.add(comptes5); comptes.add(comptes6); comptes.add(comptes7); List<Virement>virements_envoyés1=new ArrayList<Virement>(); List<Virement>virements_envoyés2=new ArrayList<Virement>(); List<Virement>virements_envoyés3=new ArrayList<Virement>(); List<Virement>virements_recus1=new ArrayList<Virement>(); List<Virement>virements_recus2=new ArrayList<Virement>(); List<Virement>virements_recus3=new ArrayList<Virement>(); List<Operation>operations1=new ArrayList<Operation>(); List<Operation>operations2=new ArrayList<Operation>(); List<Operation>operations3=new ArrayList<Operation>(); List<Recharge>recharges1=new ArrayList<Recharge>(); List<Recharge>recharges2=new ArrayList<Recharge>(); List<Recharge>recharges3=new ArrayList<Recharge>(); //creer les client for(int i=0;i<noms.length;i++){ Client c=new Client("oui",null,null,null); c.setNom(noms[i]); c.setAdresse(RandomString.make(15)); c.setEmail(RandomString.make(10)+"@gmail.com"); c.setPrenom(prenoms[i]); c.setPassword(passwords[i]); c.setCin("MM"+RandomString.make(10)); c.setUsername(usernames[i]); c.setRole("client"); c.setComptes(comptes.get(i)); clientR.save(c); clients.add(c); } //un admin Admin admin1=new Admin(); admin1.setPassword("admin"); admin1.setNom("Caleta Car"); admin1.setPrenom("Duje"); admin1.setAdresse("rue du man"); admin1.setEmail("iezae@gmail.com"); admin1.setTelephone("+212 67876787"); admin1.setUsername("root"); admin1.setRole("admin"); //un admin2 Admin admin2=new Admin(); admin2.setPassword("password"); admin2.setNom("Drake"); admin2.setPrenom("Domen"); admin2.setAdresse("rue du louvre"); admin2.setEmail("iefdsfsd@gmail.com"); admin2.setTelephone("+212 67886787"); admin2.setUsername("user"); admin2.setRole("admin"); adminR.save(admin1); adminR.save(admin2); //creer une agence Agence agence1=new Agence(1L,"principale","sidi abbad","+2127837278","663253","agence1@gmail.com",admin1,null,clients); //creer des agents String[] nomsA={"karl","Allen","Jonzdzes",RandomString.make(12),RandomString.make(12),RandomString.make(12),RandomString.make(12)}; String[] prenomsA={"marcos","Paul","dqsn",RandomString.make(12),RandomString.make(12),RandomString.make(12),RandomString.make(12)}; String[] usernamesA={"alain","sddallen","jonesdss",RandomString.make(12),RandomString.make(12),RandomString.make(12),RandomString.make(12)}; String[] passwordsA={"delon","dssallen","dsjones",RandomString.make(12),RandomString.make(12),RandomString.make(12),RandomString.make(12)}; for(int i=0;i<nomsA.length;i++){ Agent agent=new Agent(null,null); agent.setPassword(passwordsA[i]); agent.setNom(nomsA[i]); agent.setPrenom(prenomsA[i]); agent.setUsername(usernamesA[i]); agent.setRole("agent"); agents.add(agent); agentR.save(agent); } agence1.setAgents(agents); agenceR.save(agence1); for(Agent ag:agents){ ag.setAgence(agence1); ag.setCreationAdmin(admin2); agentR.save(ag); } //creer les comptes //devise Devise d=new Devise(1L,"USD","Dollar","english","@66576","ISO 3166","B65657","US",null,admin2,null,admin1); Devise d2=new Devise(2L,"INR","Roupie","english","@6767'","ISO 3366","B65657","IN",null,admin2,null,admin1); Devise d3=new Devise(3L,"EUR","Euro","francais","@766767","ISO 3266","B65657","EU",null,admin2,null,admin1); Devise d4=new Devise(4L,"DEM","Deutshe Mark","allemand","@76767","ISO 3162","B65657","DE",null,admin2,null,admin1); deviseR.save(d); deviseR.save(d2); deviseR.save(d3); deviseR.save(d4); Compte compte=new Compte(1L,RandomString.make(10),"epargne",5000.0,d,null,clients.get(0),agents.get(1),null,null,null,null); comptes1.add(compte); clients.get(0).setComptes(comptes1); clients.get(0).setAgence(agence1); clients.get(0).setCreationAgent(agents.get(0)); clientR.save(clients.get(0)); Compte compte2=new Compte(2L,RandomString.make(10),"epargne",9000.0,d2,null,clients.get(1),agents.get(1),null,null,null,null); Compte compte2_2=new Compte(3L,RandomString.make(10),"courant",2000.0,d2,null,clients.get(1),agents.get(0),null,null,null,null); Compte compte2_3=new Compte(4L,RandomString.make(10),"credit",3000.0,d2,null,clients.get(1),agents.get(2),null,null,null,null); comptes2.add(compte2); comptes2.add(compte2_2); comptes2.add(compte2_3); clients.get(1).setComptes(comptes2); clients.get(1).setAgence(agence1); clients.get(1).setCreationAgent(agents.get(1)); clientR.save(clients.get(1)); Compte compte3=new Compte(5L,RandomString.make(10),"epargne",4000.0,d3,null,clients.get(2),agents.get(2),null,null,null,null); comptes3.add(compte3); clients.get(2).setComptes(comptes3); clients.get(2).setAgence(agence1); clients.get(2).setCreationAgent(agents.get(2)); clientR.save(clients.get(2)); for (int j=3;j<clients.size();j++){ Compte nv_compte=new Compte((long)6+j,RandomString.make(10),"epargne",2000.0*j,d,null,clients.get(j),agents.get(1),null,null,null,null); comptes.get(j).add(nv_compte); clients.get(j).setComptes(comptes.get(j)); clients.get(j).setAgence(agence1); clients.get(j).setCreationAgent(agents.get(0)); clientR.save(clients.get(j)); } //Virement Virement v1=new Virement(1L,compte,compte3,null,1200.0,1200.0); Virement v2=new Virement(2L,compte,compte2,null,1500.0,1500.0); v1.setDate(LocalDateTime.now()); v2.setDate(LocalDateTime.now()); virementR.save(v1); virementR.save(v2); //operation Operation op1=new Operation(1L,compte,null,2000.0,1999.0,"Versement",d); Operation op2=new Operation(2L,compte,null,3000.0,2999.0,"Retrait",d2); Operation op3=new Operation(3L,compte,null,4000.0,3999.0,"Versement",d3); Operation op4=new Operation(4L,compte2,null,2000.0,1999.0,"Versement",d); Operation op5=new Operation(5L,compte3,null,2000.0,1999.0,"Versement",d); operations1.add(op1); operations1.add(op2); operations1.add(op3); operations2.add(op4); operations3.add(op5); virements_envoyés1.add(v1); virements_envoyés1.add(v2); virements_recus2.add(v2); virements_recus3.add(v1); compte.setVirementsEnvoyes(virements_envoyés1); compte2.setVirementsRecus(virements_recus2); compte3.setVirementsRecus(virements_recus3); compte.setOperations(operations1); compte2.setOperations(operations2); compte3.setOperations(operations3); operationR.save(op1); operationR.save(op2); operationR.save(op3); operationR.save(op4); operationR.save(op5); Operateur o1=new Operateur(); o1.setRole(RandomString.make(10)); o1.setUsername(RandomString.make(10)); o1.setPassword(RandomString.make(10)); o1.setNom("Miller"); o1.setEmail("op1@gmail.com"); o1.setAdresse("foire au saucisses"); o1.setTelephone("+2120998998889"); operateurR.save(o1); //comptes des operateurs List<Compte>comptes_operateur1=new ArrayList<Compte>(); Compte compte_operateur1=new Compte(20L,RandomString.make(10),"epargne",5000.0,d,null,o1,agents.get(1),null,null,null,null); compteR.save(compte_operateur1); comptes_operateur1.add(compte_operateur1); o1.setComptes(comptes_operateur1); o1.setAgence(agence1); o1.setCreationAgent(agents.get(0)); Operateur o2=new Operateur(); o2.setRole(RandomString.make(10)); o2.setNom("Morris"); o2.setEmail("op2@gmail.com"); o2.setAdresse("rue du man"); o2.setTelephone("+2120998998989"); o2.setUsername(RandomString.make(10)); o2.setPassword(RandomString.make(10)); o1.setCin(RandomString.make(15)); o2.setCin(RandomString.make(15)); Operateur o3=new Operateur(); o3.setRole(RandomString.make(10)); o3.setNom("Zineb"); o3.setEmail("op3@gmail.com"); o3.setAdresse("rue du loup"); o3.setTelephone("+2120933998989"); o3.setUsername(RandomString.make(10)); o3.setPassword(RandomString.make(10)); o3.setCin(RandomString.make(15)); Operateur o4=new Operateur(); o4.setRole(RandomString.make(10)); o4.setNom("AL Rezanhi"); o4.setEmail("op4@gmail.com"); o4.setAdresse("rue du louvre"); o4.setTelephone("+2120998998939"); o4.setUsername(RandomString.make(10)); o4.setPassword(RandomString.make(10)); o4.setCin(RandomString.make(15)); operateurR.save(o1); operateurR.save(o2); operateurR.save(o3); operateurR.save(o4); Recharge r1=new Recharge(1L,3000.0,2950.0,d2,"+212 7668733",LocalDateTime.now(),compte,o1); Recharge r2=new Recharge(2L,9000.0,8950.0,d3,"+212 7128733",LocalDateTime.now(),compte,o1); Recharge r3=new Recharge(3L,5000.0,4950.0,d,"+212 7228733",LocalDateTime.now(),compte3,o1); Recharge r4=new Recharge(4L,4000.0,3950.0,d4,"+212 7662233",LocalDateTime.now(),compte2,o1); rechargeR.save(r1); rechargeR.save(r2); rechargeR.save(r3); rechargeR.save(r4); recharges1.add(r1); recharges1.add(r2); recharges2.add(r4); recharges3.add(r3); compteR.save(compte); compteR.save(compte3); compteR.save(compte2); //http://localhost:4200/client/:1/accountForm }}
true
4d52bc6edd4a9153c5f3b3faab46c85294add766
Java
zackattacknyu/BLI_ProbePathRender
/JMonkeyEngine/LibGeneral_GeometryToolkit/src/org/zrd/geometryToolkit/meshDataStructure/MeshEdgeTriangles.java
UTF-8
1,404
3.328125
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.zrd.geometryToolkit.meshDataStructure; /** * * @author Zach */ public class MeshEdgeTriangles { private MeshTriangle triangle1; private MeshTriangle triangle2; public MeshEdgeTriangles(){ triangle1 = null; triangle2 = null; } public void addTriangle(MeshTriangle triangle){ if(triangle1 == null){ triangle1 = triangle; }else if(triangle2 == null && !triangle.equals(triangle1)){ triangle2 = triangle; } } public MeshTriangle getOtherTriangle(MeshTriangle currentTriangle){ if(currentTriangle.equals(triangle1)){ return triangle2; }else{ return triangle1; } } public int numTriangles(){ if(triangle1==null){ return 0; }else if(triangle2 == null){ return 1; }else{ return 2; } } public MeshTriangle getTriangle1() { return triangle1; } public MeshTriangle getTriangle2() { return triangle2; } @Override public String toString() { return "MeshEdgeTriangles{" + "triangle1=" + triangle1 + ", triangle2=" + triangle2 + '}'; } }
true
a20eb03c7899d251a5d2669c9c908709d3f8c034
Java
eProsima/RPC
/fastrpcgen/src/com/eprosima/fastrpc/rpcddsgen.java
UTF-8
1,069
2.1875
2
[ "Apache-2.0" ]
permissive
package com.eprosima.fastrpc; import com.eprosima.fastrpc.fastrpcgen; import com.eprosima.fastrpc.exceptions.BadArgumentException; import com.eprosima.log.ColorMessage; public class rpcddsgen extends fastrpcgen { public rpcddsgen(String[] args) throws BadArgumentException { super(args); } public static void main(String[] args) throws Exception { ColorMessage.load(); if(loadPlatforms()) { try { rpcddsgen.m_protocol = PROTOCOL.DDS; rpcddsgen.m_appName = "rpcddsgen"; rpcddsgen.m_appProduct = "rpcdds"; rpcddsgen.m_appEnv = "RPCDDSHOME"; rpcddsgen main = new rpcddsgen(args); if(main.execute()) System.exit(0); } catch(BadArgumentException ex) { System.out.println(ColorMessage.error("BadArgumentException") + ex.getMessage()); printHelp(); } } System.exit(-1); } }
true
e10607e5bf23710b39467de0477b6fbc08b73e05
Java
HugoKeung/5_a_day_tracker_android
/5adayTracker/MyApplication/app/src/main/java/com/example/hugo/myapplication/MainActivity.java
UTF-8
525
1.679688
2
[]
no_license
package com.example.hugo.myapplication; import android.content.Intent; import android.os.Bundle; import com.example.hugo.myapplication.notification.DayChangeBroadcastReceiver; public class MainActivity extends BaseActivityCamera { DayChangeBroadcastReceiver broadcastReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); broadcastReceiver = new DayChangeBroadcastReceiver(); } }
true
8f5e74ead4637ab3c7ff148b9a8f2f91075aad4f
Java
xutongle/AutoHomen
/app/src/main/java/com/l000phone/daojia/myentitis/Entity.java
UTF-8
72,875
1.984375
2
[]
no_license
package com.l000phone.daojia.myentitis; import org.xutils.db.annotation.Column; import org.xutils.db.annotation.Table; import java.util.List; /** * Created by Administrator on 2016/11/18/018. */ @Table(name ="Entity") public class Entity { /** * status : 200 * result : {"tags":[{"Id":"38","Title":"猪肉","Url":"haodourecipe://haodou * .com/goods/searchResult/?tagName=猪肉&TagId=38","Goods":{"GoodsId":"6278", * "Title":"【温州特产】猪油渣","DealPrice":"69.00","CoverUrl":"http://pimg3.hoto * .cn/goods/2016/11/09/6278_582303b7c4313_336_336.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=6278"}},{"Id":"42", * "Title":"饼干","Url":"haodourecipe://haodou * .com/goods/searchResult/?tagName=饼干&TagId=42","Goods":{"GoodsId":"6281", * "Title":"【Emily的美好时光】蛋黄酥 低糖白莲蓉味(六个礼盒装)","DealPrice":"79.00", * "CoverUrl":"http://pimg3.hoto.cn/goods/2016/11/08/6281_5821a8fdc0ed1_336_336 * .jpg","OpenUrl":"haodourecipe://haodou.com/goods/detail?id=6281"}},{"Id":"37", * "Title":"牛羊肉","Url":"haodourecipe://haodou * .com/goods/searchResult/?tagName=牛羊肉&TagId=37","Goods":{"GoodsId":"1285", * "Title":"【2份包邮】限时促销精品罐装飘香秘制风味牙签牛肉","DealPrice":"65.00","CoverUrl":"http://pimg2 * .hoto.cn/goods/2016/11/17/1285_582d6d880edee_336_336.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1285"}},{"Id":"34", * "Title":"辣椒酱","Url":"haodourecipe://haodou * .com/goods/searchResult/?tagName=辣椒酱&TagId=34","Goods":{"GoodsId":"6255", * "Title":"正宗重庆香辣红油","DealPrice":"25.80","CoverUrl":"http://pimg1.hoto * .cn/goods/2016/10/12/6255_57fdd8d5ba1d3_336_336.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=6255"}},{"Id":"57", * "Title":"腌制品","Url":"haodourecipe://haodou * .com/goods/searchResult/?tagName=腌制品&TagId=57","Goods":{"GoodsId":"2122", * "Title":"醉血蛤","DealPrice":"45.00","CoverUrl":"http://pimg2.hoto * .cn/goods/2016/10/30/2122_581581a266f86_336_336.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=2122"}},{"Id":"33", * "Title":"螃蟹","Url":"haodourecipe://haodou * .com/goods/searchResult/?tagName=螃蟹&TagId=33","Goods":{"GoodsId":"6259", * "Title":"麻辣醉蟹钳","DealPrice":"35.00","CoverUrl":"http://pimg2.hoto * .cn/goods/2016/10/13/6259_57ffa260a1659_336_336.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=6259"}},{"Id":"64", * "Title":"养颜","Url":"haodourecipe://haodou * .com/goods/searchResult/?tagName=养颜&TagId=64","Goods":{"GoodsId":"1859", * "Title":"川贝柠檬膏","DealPrice":"45.00","CoverUrl":"http://pimg3.hoto * .cn/goods/2016/11/18/1859_582ea2601acb4_336_336.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1859"}},{"Id":"43", * "Title":"鸡鸭鱼肉","Url":"haodourecipe://haodou * .com/goods/searchResult/?tagName=鸡鸭鱼肉&TagId=43","Goods":{"GoodsId":"6145", * "Title":"厨鲜生 | 固城湖咸鸭蛋65g×20颗礼盒装","DealPrice":"39.90","CoverUrl":"http://pimg2 * .hoto.cn/goods/2016/07/07/6145_577e060a41c3f_336_336.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=6145"}}], * "CateList":[{"CateId":"58","CateName":"家传秘制","ImgUrl":"http://img1.hoto * .cn/mall/mall_ad/2015/08/1438411987.jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=58&CateName=家传秘制"},{"CateId":"59", * "CateName":"肉禽蛋类","ImgUrl":"http://img1.hoto.cn/mall/mall_ad/2015/08/1438412006 * .jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=59&CateName=肉禽蛋类"},{"CateId":"60", * "CateName":"烘焙面点","ImgUrl":"http://img1.hoto.cn/mall/mall_ad/2015/08/1438412017 * .jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=60&CateName=烘焙面点"},{"CateId":"61", * "CateName":"水产海鲜","ImgUrl":"http://img1.hoto.cn/mall/mall_ad/2015/08/1438412028 * .jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=61&CateName=水产海鲜"},{"CateId":"62", * "CateName":"腌腊制品","ImgUrl":"http://img1.hoto.cn/mall/mall_ad/2015/08/1438412038 * .jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=62&CateName=腌腊制品"},{"CateId":"63", * "CateName":"调味酱料","ImgUrl":"http://img1.hoto.cn/mall/mall_ad/2015/08/1438412074 * .jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=63&CateName=调味酱料"},{"CateId":"64", * "CateName":"养生养颜","ImgUrl":"http://img1.hoto.cn/mall/mall_ad/2015/08/1438412060 * .jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=64&CateName=养生养颜"},{"CateId":"65", * "CateName":"小吃零嘴","ImgUrl":"http://img1.hoto.cn/mall/mall_ad/2015/08/1438412048 * .jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=65&CateName=小吃零嘴"},{"CateId":"66", * "CateName":"冲调饮品","ImgUrl":"http://img1.hoto.cn/mall/mall_ad/2015/11/1447986571 * .jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=66&CateName=冲调饮品"},{"CateId":"67", * "CateName":"生鲜果蔬","ImgUrl":"http://img1.hoto.cn/mall/mall_ad/2015/11/1448422666 * .jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=67&CateName=生鲜果蔬"}], * "DailySpecialGoods":{"Label":"","Title":"今日特价","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460520351.jpg","Price":"¥9.90","IsAuto":0, * "OpenUrl":"haodourecipe://haodou.com/goods/subjectlist/?id=173"}, * "DailyFirstGoods":{"Label":"美食研究所","Title":"新品推荐","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/03/1457419342.jpg","Price":"¥0.00","IsAuto":0, * "OpenUrl":"haodourecipe://haodou.com/goods/dailyfirst?type=new"}, * "OneHourGoods":{"Label":"明星店铺","Title":"俊哥的小店儿","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460099180.jpg","Price":"¥0.00","IsAuto":2, * "OpenUrl":"haodourecipe://haodou.com/store/?id=610"}, * "FoodieFavoriteGoods":[{"Title":"日式汤料","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460599417.jpg","Price":"¥9.90","HomePosition":1, * "GoodsId":5549},{"Title":"阿胶糕","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460342044.jpg","Price":"¥89.90","HomePosition":2, * "GoodsId":2786},{"Title":"核桃曲奇","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460342069.jpg","Price":"¥29.90","HomePosition":3, * "GoodsId":556},{"Title":"红肠","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460599176.jpg","Price":"¥31.90","HomePosition":4, * "GoodsId":1910},{"Title":"糖蒜","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460342883.jpg","Price":"¥16.90","HomePosition":5, * "GoodsId":5268},{"Title":"山楂果酱","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460342151.jpg","Price":"¥32.00","HomePosition":6, * "GoodsId":4364},{"Title":"酸角糕","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460342322.jpg","Price":"¥16.80","HomePosition":7, * "GoodsId":1155},{"Title":"香蕉酥","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460342343.jpg","Price":"¥35.00","HomePosition":8, * "GoodsId":5172},{"Title":"香辣腊肉干","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460342371.jpg","Price":"¥48.00","HomePosition":9, * "GoodsId":985}],"BrandStore":{"InsertionUrl":"http://m.haodou.com/mall/index * .php?r=wap/brand/home-page-recommend","OpenURL":"haodourecipe://haodou * .com/opentopic/?id=471515&store_id=167","Title":"【夏日美食】一骑红尘荔枝蜜~", * "ImgUrl":"http://img1.hoto.cn/mall/mall_ad/2016/06/1466748684.jpg"}, * "NewsRecommendGood":{"Goods":{"GoodsId":4786,"Title":"买5冷面赠2凉皮한국냉면 매우맛있다", * "DealPrice":"¥14.90","CoverUrl":"http://pimg2.hoto * .cn/goods/2016/02/24/4786_56cda5464f937_336_336.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=4786"}, * "UserName":"好豆到家品鉴员","ImgUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460341662.jpg","Tags":["好吃不贵"],"Content":"好豆到家", * "Info":"冷面,面条劲道且富有弹性,是看得见的Q * ,看得见的弹!!酸溜溜的,甜滋滋的汤汁,浓郁到让你的舌头欲罢不能,火红的油辣子带来了不仅是满满的诚意而且更多幸福感。真空包装,卫生和干净都看得见。"}, * "count":200,"list":[{"StoreId":149,"StoreTitle":"靓家货", * "StoreLogoUrl":"http://pimg2.hoto.cn/store/2015/07/31/55bb6ac68d05a.jpg", * "UserId":"8190340","UserName":"Leslie靓靓","GoodsId":271,"Title":"【肘爷】酱肘子", * "SubTitle":"【肘爷】酱肘子,肉质细腻","DealPrice":"¥150.00","ShippingInfo":"配送上门/全国快递", * "CoverUrl":"http://pimg2.hoto.cn/goods/2015/07/31/271_55bb72af0a680_680_450 * .jpg","OpenUrl":"haodourecipe://haodou.com/goods/detail?id=271", * "LikeCount":2485,"Stock":100,"IsShippingFree":1,"IsLike":0,"CartNum":0, * "Labels":[],"Weight":"1000克","Price":"¥168.00"},{"StoreId":4174, * "StoreTitle":"小钱包的美好生活","StoreLogoUrl":"http://pimg3.hoto * .cn/store/2015/11/19/564db750f35db.jpg","UserId":"8927449","UserName":"钱包妈", * "GoodsId":1917,"Title":"哈尔滨农大风干肠300克","SubTitle":"黑猪肉灌制而成 佐餐及零食佳品", * "DealPrice":"¥32.80","ShippingInfo":"全国快递","CoverUrl":"http://pimg1.hoto * .cn/goods/2015/11/25/1917_56551cf4d9142_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1917","LikeCount":202, * "Stock":128,"IsShippingFree":2,"IsLike":0,"CartNum":0,"Labels":["新人价","包邮"], * "Weight":"300克","Price":"¥48.00"},{"StoreId":7161,"StoreTitle":"荤爷的店", * "StoreLogoUrl":"http://pimg3.hoto.cn/store/2016/03/21/56efbcd89b255.jpg", * "UserId":"9049464","UserName":"斯坦福桥的破车","GoodsId":5676, * "Title":"好豆金牌卖家热卖关东煮汤料200ml","SubTitle":"200ml.日本风味.安全放心无添加","DealPrice":"¥33 * .90","ShippingInfo":"全国快递","CoverUrl":"http://pimg1.hoto * .cn/goods/2016/04/07/5676_5705dcd7d69a5_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=5676","LikeCount":184, * "Stock":31,"IsShippingFree":1,"IsLike":0,"CartNum":0,"Labels":[], * "Weight":"500克","Price":"¥49.99"},{"StoreId":166,"StoreTitle":"然妈烘焙", * "StoreLogoUrl":"http://pimg3.hoto.cn/store/2015/08/09/55c6ba6389638.jpg", * "UserId":"20500","UserName":"尚志李波","GoodsId":312,"Title":"蔓越莓饼干(40片)", * "SubTitle":"纯手工制作健康无添加饼干","DealPrice":"¥35.00","ShippingInfo":"配送上门/全国快递", * "CoverUrl":"http://pimg1.hoto.cn/goods/2015/10/16/312_5620372fe06ed_680_450 * .jpg","OpenUrl":"haodourecipe://haodou.com/goods/detail?id=312", * "LikeCount":1541,"Stock":25,"IsShippingFree":2,"IsLike":0,"CartNum":0, * "Labels":["包邮"],"Weight":"230克","Price":"¥38.00"},{"StoreId":176, * "StoreTitle":"双双爱烘焙","StoreLogoUrl":"http://pimg1.hoto * .cn/store/2015/08/02/55bcff516fbf5.jpg","UserId":"8749","UserName":"love双双", * "GoodsId":337,"Title":"(当家菜)台湾风味脆皮肠 纯手工自制(100克装)","SubTitle":"双双自制零添加美食", * "DealPrice":"¥12.80","ShippingInfo":"全国快递","CoverUrl":"http://pimg2.hoto * .cn/goods/2015/08/04/337_55bf9cbf5384b_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=337","LikeCount":3497, * "Stock":100,"IsShippingFree":1,"IsLike":0,"CartNum":0,"Labels":[], * "Weight":"100克","Price":"¥13.80"},{"StoreId":3976,"StoreTitle":"淼冉妈七彩面点手工坊", * "StoreLogoUrl":"http://pimg2.hoto.cn/store/2015/11/05/563afb18a8936.jpg", * "UserId":"8111886","UserName":"淼冉妈","GoodsId":1309,"Title":"纯手工空心面手工挂面500克", * "SubTitle":"百年工艺纯手工制作空心面","DealPrice":"¥20.00","ShippingInfo":"配送上门/全国快递", * "CoverUrl":"http://pimg2.hoto.cn/goods/2016/01/19/1309_569ded18ecc46_680_450 * .jpg","OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1309", * "LikeCount":387,"Stock":4242,"IsShippingFree":2,"IsLike":0,"CartNum":0, * "Labels":["包邮"],"Weight":"500克","Price":"¥40.00"},{"StoreId":166, * "StoreTitle":"然妈烘焙","StoreLogoUrl":"http://pimg3.hoto * .cn/store/2015/08/09/55c6ba6389638.jpg","UserId":"20500","UserName":"尚志李波", * "GoodsId":465,"Title":"杂粮煎饼15张(500克)","SubTitle":"东北纯手工杂粮煎饼","DealPrice":"¥35 * .00","ShippingInfo":"配送上门/全国快递","CoverUrl":"http://pimg1.hoto * .cn/goods/2015/09/07/465_55ed2423e0056_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=465","LikeCount":1514, * "Stock":46,"IsShippingFree":2,"IsLike":0,"CartNum":0,"Labels":["包邮"], * "Weight":"500克","Price":"¥40.00"},{"StoreId":3595,"StoreTitle":"婷婷美食", * "StoreLogoUrl":"http://pimg3.hoto.cn/store/2015/10/28/56304265088d2.jpg", * "UserId":"8835271","UserName":"婷婷手工美食","GoodsId":1501, * "Title":"江米条寸枣500g炸糖婷婷美食年货过年料","SubTitle":"食味⑨久","DealPrice":"¥29.90", * "ShippingInfo":"配送上门/同城快递","CoverUrl":"http://pimg2.hoto * .cn/goods/2015/11/12/1501_5643dcd8200e3_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1501","LikeCount":284, * "Stock":4909,"IsShippingFree":2,"IsLike":0,"CartNum":0,"Labels":["新人价","包邮"], * "Weight":"500克","Price":"¥68.00"},{"StoreId":3976,"StoreTitle":"淼冉妈七彩面点手工坊", * "StoreLogoUrl":"http://pimg2.hoto.cn/store/2015/11/05/563afb18a8936.jpg", * "UserId":"8111886","UserName":"淼冉妈","GoodsId":1348,"Title":"新疆大个核桃薄皮核桃1000克", * "SubTitle":"手可以直接剥开食用哦!个大,皮薄,肉鲜!","DealPrice":"¥49.00", * "ShippingInfo":"配送上门/全国快递","CoverUrl":"http://pimg2.hoto * .cn/goods/2015/11/09/1348_564002d330acf_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1348","LikeCount":200, * "Stock":3307,"IsShippingFree":2,"IsLike":0,"CartNum":0,"Labels":["包邮"], * "Weight":"1000克","Price":"¥78.00"},{"StoreId":610,"StoreTitle":"俊哥的小店儿", * "StoreLogoUrl":"http://pimg1.hoto.cn/store/2016/03/25/56f54ab590ccb.jpg", * "UserId":"8307326","UserName":"俊哥黄瓜","GoodsId":360, * "Title":"【爆款】俊哥牌俊少脆皮黄瓜(荐)(400克)","SubTitle":"吃了俊哥瓜、忘了那个他(她)!","DealPrice":"¥25 * .00","ShippingInfo":"配送上门/全国快递","CoverUrl":"http://pimg1.hoto * .cn/goods/2016/01/05/360_568aa7f3db62c_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=360","LikeCount":1879, * "Stock":28,"IsShippingFree":1,"IsLike":0,"CartNum":0,"Labels":[], * "Weight":"400克","Price":"¥35.00"},{"StoreId":1645,"StoreTitle":"麻辣小面", * "StoreLogoUrl":"http://pimg1.hoto.cn/store/2016/01/08/568f2605e81bd.jpg", * "UserId":"8466351","UserName":"华曜餐饮","GoodsId":705,"Title":"【窝窝侠】麻辣面2份/盒", * "SubTitle":"凑合?滚粗!","DealPrice":"¥25.80","ShippingInfo":"全国快递", * "CoverUrl":"http://pimg1.hoto.cn/goods/2016/06/17/705_57635906f3689_680_450 * .jpg","OpenUrl":"haodourecipe://haodou.com/goods/detail?id=705", * "LikeCount":1411,"Stock":299,"IsShippingFree":2,"IsLike":0,"CartNum":0, * "Labels":["包邮"],"Weight":"470克","Price":"¥39.00"},{"StoreId":176, * "StoreTitle":"双双爱烘焙","StoreLogoUrl":"http://pimg1.hoto * .cn/store/2015/08/02/55bcff516fbf5.jpg","UserId":"8749","UserName":"love双双", * "GoodsId":338,"Title":"黑胡椒脆皮(100克装)纯手工自制","SubTitle":"双双自制零添加美食 健康美味 早餐首选", * "DealPrice":"¥12.80","ShippingInfo":"全国快递","CoverUrl":"http://pimg3.hoto * .cn/goods/2015/08/04/338_55c02b80b8a91_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=338","LikeCount":2462, * "Stock":100,"IsShippingFree":1,"IsLike":0,"CartNum":0,"Labels":[], * "Weight":"100克"},{"StoreId":3475,"StoreTitle":"红蛋蛋","StoreLogoUrl":"http://pimg3 * .hoto.cn/store/2015/12/04/5661243a1b012.jpg","UserId":"3729569", * "UserName":"红蛋蛋来也","GoodsId":886,"Title":"开胃红油蟹黄咸鸭蛋20只", * "SubTitle":"天热不想吃饭?来一只鸭蛋,开胃消食,蟹黄味哦!","DealPrice":"¥39.80", * "ShippingInfo":"配送上门/全国快递","CoverUrl":"http://pimg2.hoto * .cn/goods/2015/11/06/886_563c0b0e0e280_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=886","LikeCount":399, * "Stock":103,"IsShippingFree":2,"IsLike":0,"CartNum":0,"Labels":["活动价","包邮"], * "Weight":"1400克","Price":"¥80.00"},{"StoreId":3712,"StoreTitle":"飘香美食铺", * "StoreLogoUrl":"http://pimg3.hoto.cn/store/2015/10/30/56338e99214c7.jpg", * "UserId":"8843844","UserName":"爱美食滴加菲猫","GoodsId":2402, * "Title":"【限时促销】精品罐装秘制酒鬼花生","SubTitle":"好豆爆款,买5份赠送1份。","DealPrice":"¥12.50", * "ShippingInfo":"配送上门/全国快递","CoverUrl":"http://pimg3.hoto * .cn/goods/2015/12/02/2402_565f0efb074d6_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=2402","LikeCount":218, * "Stock":50,"IsShippingFree":1,"IsLike":0,"CartNum":0,"Labels":["活动价"], * "Weight":"250克","Price":"¥25.00"},{"StoreId":2920,"StoreTitle":"海阔凭鱼跃", * "StoreLogoUrl":"http://pimg2.hoto.cn/store/2015/11/17/564ae6c5c982b.jpg", * "UserId":"8288073","UserName":"辰妈私房美食","GoodsId":1354,"Title":"野生红娘鱼即食鱼干原味", * "SubTitle":"原生态天然滋补海鲜","DealPrice":"¥18.00","ShippingInfo":"全国快递", * "CoverUrl":"http://pimg2.hoto.cn/goods/2016/04/09/1354_57086a8225173_680_450 * .jpg","OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1354", * "LikeCount":204,"Stock":88,"IsShippingFree":2,"IsLike":0,"CartNum":0, * "Labels":["包邮"],"Weight":"100克","Price":"¥38.00"},{"StoreId":3976, * "StoreTitle":"淼冉妈七彩面点手工坊","StoreLogoUrl":"http://pimg2.hoto * .cn/store/2015/11/05/563afb18a8936.jpg","UserId":"8111886","UserName":"淼冉妈", * "GoodsId":1346,"Title":"淼冉妈手工蔬菜面条7种口味混合装","SubTitle":"七种口味混合装,七彩面宝宝面条宝宝副食", * "DealPrice":"¥19.90","ShippingInfo":"配送上门/全国快递","CoverUrl":"http://pimg3.hoto * .cn/goods/2015/11/09/1346_563ffd64c8c91_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1346","LikeCount":385, * "Stock":178,"IsShippingFree":2,"IsLike":0,"CartNum":0,"Labels":["包邮"], * "Weight":"250克","Price":"¥41.00"},{"StoreId":3872,"StoreTitle":"颜大叔", * "StoreLogoUrl":"http://pimg3.hoto.cn/store/2015/11/03/5638a32b7ea6c.jpg", * "UserId":"8879952","UserName":"颜大叔","GoodsId":1139,"Title":"颜大叔|宁波水磨年糕 1斤", * "SubTitle":"百搭食材,口感柔嫩Q弹","DealPrice":"¥7.90","ShippingInfo":"配送上门/全国快递", * "CoverUrl":"http://pimg3.hoto.cn/goods/2015/11/04/1139_56396b3c5b251_680_450 * .jpg","OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1139", * "LikeCount":624,"Stock":308,"IsShippingFree":1,"IsLike":0,"CartNum":0, * "Labels":[],"Weight":"500克","Price":"¥15.90"},{"StoreId":3051, * "StoreTitle":"香聚源食品店","StoreLogoUrl":"http://pimg1.hoto * .cn/store/2015/10/16/5620fa05630a3.jpg","UserId":"8754144","UserName":"香聚源食品店", * "GoodsId":683,"Title":"山东特产手撕风琴鱿鱼片","SubTitle":"吃出苗条身材","DealPrice":"¥13.90", * "ShippingInfo":"全国快递","CoverUrl":"http://pimg3.hoto * .cn/goods/2015/10/20/683_562597c64f2f6_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=683","LikeCount":481, * "Stock":300,"IsShippingFree":2,"IsLike":0,"CartNum":0,"Labels":["新人价","包邮"], * "Weight":"200克","Price":"¥25.00"},{"StoreId":3712,"StoreTitle":"飘香美食铺", * "StoreLogoUrl":"http://pimg3.hoto.cn/store/2015/10/30/56338e99214c7.jpg", * "UserId":"8843844","UserName":"爱美食滴加菲猫","GoodsId":1136, * "Title":"【限时促销】湖南特色猪血丸子包邮(640g左右)","SubTitle":"香糯爽口 腊味十足(满49包邮)", * "DealPrice":"¥26.00","ShippingInfo":"配送上门/全国快递","CoverUrl":"http://pimg3.hoto * .cn/goods/2015/11/03/1136_5638d2788a847_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1136","LikeCount":243, * "Stock":30,"IsShippingFree":2,"IsLike":0,"CartNum":0,"Labels":["活动价","包邮"], * "Weight":"640克","Price":"¥50.00"},{"StoreId":4269,"StoreTitle":"乡下家源", * "StoreLogoUrl":"http://pimg1.hoto.cn/store/2016/07/21/57902a0260183.jpg", * "UserId":"8931711","UserName":"乡下家源","GoodsId":1643,"Title":"自制腐竹段原价38元", * "SubTitle":"非转基因黄豆自制腐竹段全国包邮(新疆、海南、西藏除外)","DealPrice":"¥31.00", * "ShippingInfo":"配送上门/全国快递","CoverUrl":"http://pimg3.hoto * .cn/goods/2015/11/14/1643_5646c85a9318e_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1643","LikeCount":132, * "Stock":300,"IsShippingFree":2,"IsLike":0,"CartNum":0,"Labels":["包邮"], * "Weight":"370克","Price":"¥38.00"}],"CartTotalNum":0} */ @Column(name = "id", isId = true) private int id; @Column(name ="result" ) private int status; private ResultBean result; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public ResultBean getResult() { return result; } public void setResult(ResultBean result) { this.result = result; } public static class ResultBean { /** * tags : [{"Id":"38","Title":"猪肉","Url":"haodourecipe://haodou * .com/goods/searchResult/?tagName=猪肉&TagId=38","Goods":{"GoodsId":"6278", * "Title":"【温州特产】猪油渣","DealPrice":"69.00","CoverUrl":"http://pimg3.hoto * .cn/goods/2016/11/09/6278_582303b7c4313_336_336.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=6278"}},{"Id":"42", * "Title":"饼干","Url":"haodourecipe://haodou * .com/goods/searchResult/?tagName=饼干&TagId=42","Goods":{"GoodsId":"6281", * "Title":"【Emily的美好时光】蛋黄酥 低糖白莲蓉味(六个礼盒装)","DealPrice":"79.00", * "CoverUrl":"http://pimg3.hoto.cn/goods/2016/11/08/6281_5821a8fdc0ed1_336_336 * .jpg","OpenUrl":"haodourecipe://haodou.com/goods/detail?id=6281"}}, * {"Id":"37","Title":"牛羊肉","Url":"haodourecipe://haodou * .com/goods/searchResult/?tagName=牛羊肉&TagId=37","Goods":{"GoodsId":"1285", * "Title":"【2份包邮】限时促销精品罐装飘香秘制风味牙签牛肉","DealPrice":"65.00", * "CoverUrl":"http://pimg2.hoto.cn/goods/2016/11/17/1285_582d6d880edee_336_336 * .jpg","OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1285"}}, * {"Id":"34","Title":"辣椒酱","Url":"haodourecipe://haodou * .com/goods/searchResult/?tagName=辣椒酱&TagId=34","Goods":{"GoodsId":"6255", * "Title":"正宗重庆香辣红油","DealPrice":"25.80","CoverUrl":"http://pimg1.hoto * .cn/goods/2016/10/12/6255_57fdd8d5ba1d3_336_336.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=6255"}},{"Id":"57", * "Title":"腌制品","Url":"haodourecipe://haodou * .com/goods/searchResult/?tagName=腌制品&TagId=57","Goods":{"GoodsId":"2122", * "Title":"醉血蛤","DealPrice":"45.00","CoverUrl":"http://pimg2.hoto * .cn/goods/2016/10/30/2122_581581a266f86_336_336.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=2122"}},{"Id":"33", * "Title":"螃蟹","Url":"haodourecipe://haodou * .com/goods/searchResult/?tagName=螃蟹&TagId=33","Goods":{"GoodsId":"6259", * "Title":"麻辣醉蟹钳","DealPrice":"35.00","CoverUrl":"http://pimg2.hoto * .cn/goods/2016/10/13/6259_57ffa260a1659_336_336.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=6259"}},{"Id":"64", * "Title":"养颜","Url":"haodourecipe://haodou * .com/goods/searchResult/?tagName=养颜&TagId=64","Goods":{"GoodsId":"1859", * "Title":"川贝柠檬膏","DealPrice":"45.00","CoverUrl":"http://pimg3.hoto * .cn/goods/2016/11/18/1859_582ea2601acb4_336_336.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1859"}},{"Id":"43", * "Title":"鸡鸭鱼肉","Url":"haodourecipe://haodou * .com/goods/searchResult/?tagName=鸡鸭鱼肉&TagId=43","Goods":{"GoodsId":"6145", * "Title":"厨鲜生 | 固城湖咸鸭蛋65g×20颗礼盒装","DealPrice":"39.90", * "CoverUrl":"http://pimg2.hoto.cn/goods/2016/07/07/6145_577e060a41c3f_336_336 * .jpg","OpenUrl":"haodourecipe://haodou.com/goods/detail?id=6145"}}] * CateList : [{"CateId":"58","CateName":"家传秘制","ImgUrl":"http://img1.hoto * .cn/mall/mall_ad/2015/08/1438411987.jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=58&CateName=家传秘制"},{"CateId":"59", * "CateName":"肉禽蛋类","ImgUrl":"http://img1.hoto * .cn/mall/mall_ad/2015/08/1438412006.jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=59&CateName=肉禽蛋类"},{"CateId":"60", * "CateName":"烘焙面点","ImgUrl":"http://img1.hoto * .cn/mall/mall_ad/2015/08/1438412017.jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=60&CateName=烘焙面点"},{"CateId":"61", * "CateName":"水产海鲜","ImgUrl":"http://img1.hoto * .cn/mall/mall_ad/2015/08/1438412028.jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=61&CateName=水产海鲜"},{"CateId":"62", * "CateName":"腌腊制品","ImgUrl":"http://img1.hoto * .cn/mall/mall_ad/2015/08/1438412038.jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=62&CateName=腌腊制品"},{"CateId":"63", * "CateName":"调味酱料","ImgUrl":"http://img1.hoto * .cn/mall/mall_ad/2015/08/1438412074.jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=63&CateName=调味酱料"},{"CateId":"64", * "CateName":"养生养颜","ImgUrl":"http://img1.hoto * .cn/mall/mall_ad/2015/08/1438412060.jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=64&CateName=养生养颜"},{"CateId":"65", * "CateName":"小吃零嘴","ImgUrl":"http://img1.hoto * .cn/mall/mall_ad/2015/08/1438412048.jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=65&CateName=小吃零嘴"},{"CateId":"66", * "CateName":"冲调饮品","ImgUrl":"http://img1.hoto * .cn/mall/mall_ad/2015/11/1447986571.jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=66&CateName=冲调饮品"},{"CateId":"67", * "CateName":"生鲜果蔬","ImgUrl":"http://img1.hoto * .cn/mall/mall_ad/2015/11/1448422666.jpg","OpenUrl":"haodourecipe://haodou * .com/goods/searchResult/?CateId=67&CateName=生鲜果蔬"}] * DailySpecialGoods : {"Label":"","Title":"今日特价","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460520351.jpg","Price":"¥9.90","IsAuto":0, * "OpenUrl":"haodourecipe://haodou.com/goods/subjectlist/?id=173"} * DailyFirstGoods : {"Label":"美食研究所","Title":"新品推荐","CoverUrl":"http://img1 * .hoto.cn/mall/mall_ad/2016/03/1457419342.jpg","Price":"¥0.00","IsAuto":0, * "OpenUrl":"haodourecipe://haodou.com/goods/dailyfirst?type=new"} * OneHourGoods : {"Label":"明星店铺","Title":"俊哥的小店儿","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460099180.jpg","Price":"¥0.00","IsAuto":2, * "OpenUrl":"haodourecipe://haodou.com/store/?id=610"} * FoodieFavoriteGoods : [{"Title":"日式汤料","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460599417.jpg","Price":"¥9.90","HomePosition":1, * "GoodsId":5549},{"Title":"阿胶糕","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460342044.jpg","Price":"¥89.90","HomePosition":2, * "GoodsId":2786},{"Title":"核桃曲奇","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460342069.jpg","Price":"¥29.90","HomePosition":3, * "GoodsId":556},{"Title":"红肠","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460599176.jpg","Price":"¥31.90","HomePosition":4, * "GoodsId":1910},{"Title":"糖蒜","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460342883.jpg","Price":"¥16.90","HomePosition":5, * "GoodsId":5268},{"Title":"山楂果酱","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460342151.jpg","Price":"¥32.00","HomePosition":6, * "GoodsId":4364},{"Title":"酸角糕","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460342322.jpg","Price":"¥16.80","HomePosition":7, * "GoodsId":1155},{"Title":"香蕉酥","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460342343.jpg","Price":"¥35.00","HomePosition":8, * "GoodsId":5172},{"Title":"香辣腊肉干","CoverUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460342371.jpg","Price":"¥48.00","HomePosition":9, * "GoodsId":985}] * BrandStore : {"InsertionUrl":"http://m.haodou.com/mall/index * .php?r=wap/brand/home-page-recommend","OpenURL":"haodourecipe://haodou * .com/opentopic/?id=471515&store_id=167","Title":"【夏日美食】一骑红尘荔枝蜜~", * "ImgUrl":"http://img1.hoto.cn/mall/mall_ad/2016/06/1466748684.jpg"} * NewsRecommendGood : {"Goods":{"GoodsId":4786,"Title":"买5冷面赠2凉皮한국냉면 매우맛있다", * "DealPrice":"¥14.90","CoverUrl":"http://pimg2.hoto * .cn/goods/2016/02/24/4786_56cda5464f937_336_336.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=4786"}, * "UserName":"好豆到家品鉴员","ImgUrl":"http://img1.hoto * .cn/mall/mall_ad/2016/04/1460341662.jpg","Tags":["好吃不贵"],"Content":"好豆到家", * "Info":"冷面,面条劲道且富有弹性,是看得见的Q * ,看得见的弹!!酸溜溜的,甜滋滋的汤汁,浓郁到让你的舌头欲罢不能,火红的油辣子带来了不仅是满满的诚意而且更多幸福感。真空包装,卫生和干净都看得见。"} * count : 200 * list : [{"StoreId":149,"StoreTitle":"靓家货","StoreLogoUrl":"http://pimg2.hoto * .cn/store/2015/07/31/55bb6ac68d05a.jpg","UserId":"8190340", * "UserName":"Leslie靓靓","GoodsId":271,"Title":"【肘爷】酱肘子", * "SubTitle":"【肘爷】酱肘子,肉质细腻","DealPrice":"¥150.00","ShippingInfo":"配送上门/全国快递", * "CoverUrl":"http://pimg2.hoto.cn/goods/2015/07/31/271_55bb72af0a680_680_450 * .jpg","OpenUrl":"haodourecipe://haodou.com/goods/detail?id=271", * "LikeCount":2485,"Stock":100,"IsShippingFree":1,"IsLike":0,"CartNum":0, * "Labels":[],"Weight":"1000克","Price":"¥168.00"},{"StoreId":4174, * "StoreTitle":"小钱包的美好生活","StoreLogoUrl":"http://pimg3.hoto * .cn/store/2015/11/19/564db750f35db.jpg","UserId":"8927449","UserName":"钱包妈", * "GoodsId":1917,"Title":"哈尔滨农大风干肠300克","SubTitle":"黑猪肉灌制而成 佐餐及零食佳品", * "DealPrice":"¥32.80","ShippingInfo":"全国快递","CoverUrl":"http://pimg1.hoto * .cn/goods/2015/11/25/1917_56551cf4d9142_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1917","LikeCount":202, * "Stock":128,"IsShippingFree":2,"IsLike":0,"CartNum":0,"Labels":["新人价","包邮"], * "Weight":"300克","Price":"¥48.00"},{"StoreId":7161,"StoreTitle":"荤爷的店", * "StoreLogoUrl":"http://pimg3.hoto.cn/store/2016/03/21/56efbcd89b255.jpg", * "UserId":"9049464","UserName":"斯坦福桥的破车","GoodsId":5676, * "Title":"好豆金牌卖家热卖关东煮汤料200ml","SubTitle":"200ml.日本风味.安全放心无添加", * "DealPrice":"¥33.90","ShippingInfo":"全国快递","CoverUrl":"http://pimg1.hoto * .cn/goods/2016/04/07/5676_5705dcd7d69a5_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=5676","LikeCount":184, * "Stock":31,"IsShippingFree":1,"IsLike":0,"CartNum":0,"Labels":[], * "Weight":"500克","Price":"¥49.99"},{"StoreId":166,"StoreTitle":"然妈烘焙", * "StoreLogoUrl":"http://pimg3.hoto.cn/store/2015/08/09/55c6ba6389638.jpg", * "UserId":"20500","UserName":"尚志李波","GoodsId":312,"Title":"蔓越莓饼干(40片)", * "SubTitle":"纯手工制作健康无添加饼干","DealPrice":"¥35.00","ShippingInfo":"配送上门/全国快递", * "CoverUrl":"http://pimg1.hoto.cn/goods/2015/10/16/312_5620372fe06ed_680_450 * .jpg","OpenUrl":"haodourecipe://haodou.com/goods/detail?id=312", * "LikeCount":1541,"Stock":25,"IsShippingFree":2,"IsLike":0,"CartNum":0, * "Labels":["包邮"],"Weight":"230克","Price":"¥38.00"},{"StoreId":176, * "StoreTitle":"双双爱烘焙","StoreLogoUrl":"http://pimg1.hoto * .cn/store/2015/08/02/55bcff516fbf5.jpg","UserId":"8749","UserName":"love双双", * "GoodsId":337,"Title":"(当家菜)台湾风味脆皮肠 纯手工自制(100克装)","SubTitle":"双双自制零添加美食", * "DealPrice":"¥12.80","ShippingInfo":"全国快递","CoverUrl":"http://pimg2.hoto * .cn/goods/2015/08/04/337_55bf9cbf5384b_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=337","LikeCount":3497, * "Stock":100,"IsShippingFree":1,"IsLike":0,"CartNum":0,"Labels":[], * "Weight":"100克","Price":"¥13.80"},{"StoreId":3976,"StoreTitle":"淼冉妈七彩面点手工坊", * "StoreLogoUrl":"http://pimg2.hoto.cn/store/2015/11/05/563afb18a8936.jpg", * "UserId":"8111886","UserName":"淼冉妈","GoodsId":1309,"Title":"纯手工空心面手工挂面500克", * "SubTitle":"百年工艺纯手工制作空心面","DealPrice":"¥20.00","ShippingInfo":"配送上门/全国快递", * "CoverUrl":"http://pimg2.hoto.cn/goods/2016/01/19/1309_569ded18ecc46_680_450 * .jpg","OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1309", * "LikeCount":387,"Stock":4242,"IsShippingFree":2,"IsLike":0,"CartNum":0, * "Labels":["包邮"],"Weight":"500克","Price":"¥40.00"},{"StoreId":166, * "StoreTitle":"然妈烘焙","StoreLogoUrl":"http://pimg3.hoto * .cn/store/2015/08/09/55c6ba6389638.jpg","UserId":"20500","UserName":"尚志李波", * "GoodsId":465,"Title":"杂粮煎饼15张(500克)","SubTitle":"东北纯手工杂粮煎饼", * "DealPrice":"¥35.00","ShippingInfo":"配送上门/全国快递","CoverUrl":"http://pimg1 * .hoto.cn/goods/2015/09/07/465_55ed2423e0056_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=465","LikeCount":1514, * "Stock":46,"IsShippingFree":2,"IsLike":0,"CartNum":0,"Labels":["包邮"], * "Weight":"500克","Price":"¥40.00"},{"StoreId":3595,"StoreTitle":"婷婷美食", * "StoreLogoUrl":"http://pimg3.hoto.cn/store/2015/10/28/56304265088d2.jpg", * "UserId":"8835271","UserName":"婷婷手工美食","GoodsId":1501, * "Title":"江米条寸枣500g炸糖婷婷美食年货过年料","SubTitle":"食味⑨久","DealPrice":"¥29.90", * "ShippingInfo":"配送上门/同城快递","CoverUrl":"http://pimg2.hoto * .cn/goods/2015/11/12/1501_5643dcd8200e3_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1501","LikeCount":284, * "Stock":4909,"IsShippingFree":2,"IsLike":0,"CartNum":0,"Labels":["新人价", * "包邮"],"Weight":"500克","Price":"¥68.00"},{"StoreId":3976, * "StoreTitle":"淼冉妈七彩面点手工坊","StoreLogoUrl":"http://pimg2.hoto * .cn/store/2015/11/05/563afb18a8936.jpg","UserId":"8111886","UserName":"淼冉妈", * "GoodsId":1348,"Title":"新疆大个核桃薄皮核桃1000克","SubTitle":"手可以直接剥开食用哦!个大,皮薄,肉鲜!", * "DealPrice":"¥49.00","ShippingInfo":"配送上门/全国快递","CoverUrl":"http://pimg2 * .hoto.cn/goods/2015/11/09/1348_564002d330acf_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1348","LikeCount":200, * "Stock":3307,"IsShippingFree":2,"IsLike":0,"CartNum":0,"Labels":["包邮"], * "Weight":"1000克","Price":"¥78.00"},{"StoreId":610,"StoreTitle":"俊哥的小店儿", * "StoreLogoUrl":"http://pimg1.hoto.cn/store/2016/03/25/56f54ab590ccb.jpg", * "UserId":"8307326","UserName":"俊哥黄瓜","GoodsId":360, * "Title":"【爆款】俊哥牌俊少脆皮黄瓜(荐)(400克)","SubTitle":"吃了俊哥瓜、忘了那个他(她)!", * "DealPrice":"¥25.00","ShippingInfo":"配送上门/全国快递","CoverUrl":"http://pimg1 * .hoto.cn/goods/2016/01/05/360_568aa7f3db62c_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=360","LikeCount":1879, * "Stock":28,"IsShippingFree":1,"IsLike":0,"CartNum":0,"Labels":[], * "Weight":"400克","Price":"¥35.00"},{"StoreId":1645,"StoreTitle":"麻辣小面", * "StoreLogoUrl":"http://pimg1.hoto.cn/store/2016/01/08/568f2605e81bd.jpg", * "UserId":"8466351","UserName":"华曜餐饮","GoodsId":705,"Title":"【窝窝侠】麻辣面2份/盒", * "SubTitle":"凑合?滚粗!","DealPrice":"¥25.80","ShippingInfo":"全国快递", * "CoverUrl":"http://pimg1.hoto.cn/goods/2016/06/17/705_57635906f3689_680_450 * .jpg","OpenUrl":"haodourecipe://haodou.com/goods/detail?id=705", * "LikeCount":1411,"Stock":299,"IsShippingFree":2,"IsLike":0,"CartNum":0, * "Labels":["包邮"],"Weight":"470克","Price":"¥39.00"},{"StoreId":176, * "StoreTitle":"双双爱烘焙","StoreLogoUrl":"http://pimg1.hoto * .cn/store/2015/08/02/55bcff516fbf5.jpg","UserId":"8749","UserName":"love双双", * "GoodsId":338,"Title":"黑胡椒脆皮(100克装)纯手工自制","SubTitle":"双双自制零添加美食 健康美味 早餐首选", * "DealPrice":"¥12.80","ShippingInfo":"全国快递","CoverUrl":"http://pimg3.hoto * .cn/goods/2015/08/04/338_55c02b80b8a91_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=338","LikeCount":2462, * "Stock":100,"IsShippingFree":1,"IsLike":0,"CartNum":0,"Labels":[], * "Weight":"100克"},{"StoreId":3475,"StoreTitle":"红蛋蛋", * "StoreLogoUrl":"http://pimg3.hoto.cn/store/2015/12/04/5661243a1b012.jpg", * "UserId":"3729569","UserName":"红蛋蛋来也","GoodsId":886,"Title":"开胃红油蟹黄咸鸭蛋20只", * "SubTitle":"天热不想吃饭?来一只鸭蛋,开胃消食,蟹黄味哦!","DealPrice":"¥39.80", * "ShippingInfo":"配送上门/全国快递","CoverUrl":"http://pimg2.hoto * .cn/goods/2015/11/06/886_563c0b0e0e280_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=886","LikeCount":399, * "Stock":103,"IsShippingFree":2,"IsLike":0,"CartNum":0,"Labels":["活动价","包邮"], * "Weight":"1400克","Price":"¥80.00"},{"StoreId":3712,"StoreTitle":"飘香美食铺", * "StoreLogoUrl":"http://pimg3.hoto.cn/store/2015/10/30/56338e99214c7.jpg", * "UserId":"8843844","UserName":"爱美食滴加菲猫","GoodsId":2402, * "Title":"【限时促销】精品罐装秘制酒鬼花生","SubTitle":"好豆爆款,买5份赠送1份。","DealPrice":"¥12.50", * "ShippingInfo":"配送上门/全国快递","CoverUrl":"http://pimg3.hoto * .cn/goods/2015/12/02/2402_565f0efb074d6_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=2402","LikeCount":218, * "Stock":50,"IsShippingFree":1,"IsLike":0,"CartNum":0,"Labels":["活动价"], * "Weight":"250克","Price":"¥25.00"},{"StoreId":2920,"StoreTitle":"海阔凭鱼跃", * "StoreLogoUrl":"http://pimg2.hoto.cn/store/2015/11/17/564ae6c5c982b.jpg", * "UserId":"8288073","UserName":"辰妈私房美食","GoodsId":1354,"Title":"野生红娘鱼即食鱼干原味", * "SubTitle":"原生态天然滋补海鲜","DealPrice":"¥18.00","ShippingInfo":"全国快递", * "CoverUrl":"http://pimg2.hoto.cn/goods/2016/04/09/1354_57086a8225173_680_450 * .jpg","OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1354", * "LikeCount":204,"Stock":88,"IsShippingFree":2,"IsLike":0,"CartNum":0, * "Labels":["包邮"],"Weight":"100克","Price":"¥38.00"},{"StoreId":3976, * "StoreTitle":"淼冉妈七彩面点手工坊","StoreLogoUrl":"http://pimg2.hoto * .cn/store/2015/11/05/563afb18a8936.jpg","UserId":"8111886","UserName":"淼冉妈", * "GoodsId":1346,"Title":"淼冉妈手工蔬菜面条7种口味混合装","SubTitle":"七种口味混合装,七彩面宝宝面条宝宝副食", * "DealPrice":"¥19.90","ShippingInfo":"配送上门/全国快递","CoverUrl":"http://pimg3 * .hoto.cn/goods/2015/11/09/1346_563ffd64c8c91_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1346","LikeCount":385, * "Stock":178,"IsShippingFree":2,"IsLike":0,"CartNum":0,"Labels":["包邮"], * "Weight":"250克","Price":"¥41.00"},{"StoreId":3872,"StoreTitle":"颜大叔", * "StoreLogoUrl":"http://pimg3.hoto.cn/store/2015/11/03/5638a32b7ea6c.jpg", * "UserId":"8879952","UserName":"颜大叔","GoodsId":1139,"Title":"颜大叔|宁波水磨年糕 1斤", * "SubTitle":"百搭食材,口感柔嫩Q弹","DealPrice":"¥7.90","ShippingInfo":"配送上门/全国快递", * "CoverUrl":"http://pimg3.hoto.cn/goods/2015/11/04/1139_56396b3c5b251_680_450 * .jpg","OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1139", * "LikeCount":624,"Stock":308,"IsShippingFree":1,"IsLike":0,"CartNum":0, * "Labels":[],"Weight":"500克","Price":"¥15.90"},{"StoreId":3051, * "StoreTitle":"香聚源食品店","StoreLogoUrl":"http://pimg1.hoto * .cn/store/2015/10/16/5620fa05630a3.jpg","UserId":"8754144", * "UserName":"香聚源食品店","GoodsId":683,"Title":"山东特产手撕风琴鱿鱼片","SubTitle":"吃出苗条身材", * "DealPrice":"¥13.90","ShippingInfo":"全国快递","CoverUrl":"http://pimg3.hoto * .cn/goods/2015/10/20/683_562597c64f2f6_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=683","LikeCount":481, * "Stock":300,"IsShippingFree":2,"IsLike":0,"CartNum":0,"Labels":["新人价","包邮"], * "Weight":"200克","Price":"¥25.00"},{"StoreId":3712,"StoreTitle":"飘香美食铺", * "StoreLogoUrl":"http://pimg3.hoto.cn/store/2015/10/30/56338e99214c7.jpg", * "UserId":"8843844","UserName":"爱美食滴加菲猫","GoodsId":1136, * "Title":"【限时促销】湖南特色猪血丸子包邮(640g左右)","SubTitle":"香糯爽口 腊味十足(满49包邮)", * "DealPrice":"¥26.00","ShippingInfo":"配送上门/全国快递","CoverUrl":"http://pimg3 * .hoto.cn/goods/2015/11/03/1136_5638d2788a847_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1136","LikeCount":243, * "Stock":30,"IsShippingFree":2,"IsLike":0,"CartNum":0,"Labels":["活动价","包邮"], * "Weight":"640克","Price":"¥50.00"},{"StoreId":4269,"StoreTitle":"乡下家源", * "StoreLogoUrl":"http://pimg1.hoto.cn/store/2016/07/21/57902a0260183.jpg", * "UserId":"8931711","UserName":"乡下家源","GoodsId":1643,"Title":"自制腐竹段原价38元", * "SubTitle":"非转基因黄豆自制腐竹段全国包邮(新疆、海南、西藏除外)","DealPrice":"¥31.00", * "ShippingInfo":"配送上门/全国快递","CoverUrl":"http://pimg3.hoto * .cn/goods/2015/11/14/1643_5646c85a9318e_680_450.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=1643","LikeCount":132, * "Stock":300,"IsShippingFree":2,"IsLike":0,"CartNum":0,"Labels":["包邮"], * "Weight":"370克","Price":"¥38.00"}] * CartTotalNum : 0 */ private DailySpecialGoodsBean DailySpecialGoods; private DailyFirstGoodsBean DailyFirstGoods; private OneHourGoodsBean OneHourGoods; private BrandStoreBean BrandStore; private NewsRecommendGoodBean NewsRecommendGood; private int count; private int CartTotalNum; private List<TagsBean> tags; private List<CateListBean> CateList; private List<FoodieFavoriteGoodsBean> FoodieFavoriteGoods; private List<ListBean> list; public DailySpecialGoodsBean getDailySpecialGoods() { return DailySpecialGoods; } public void setDailySpecialGoods(DailySpecialGoodsBean DailySpecialGoods) { this.DailySpecialGoods = DailySpecialGoods; } public DailyFirstGoodsBean getDailyFirstGoods() { return DailyFirstGoods; } public void setDailyFirstGoods(DailyFirstGoodsBean DailyFirstGoods) { this.DailyFirstGoods = DailyFirstGoods; } public OneHourGoodsBean getOneHourGoods() { return OneHourGoods; } public void setOneHourGoods(OneHourGoodsBean OneHourGoods) { this.OneHourGoods = OneHourGoods; } public BrandStoreBean getBrandStore() { return BrandStore; } public void setBrandStore(BrandStoreBean BrandStore) { this.BrandStore = BrandStore; } public NewsRecommendGoodBean getNewsRecommendGood() { return NewsRecommendGood; } public void setNewsRecommendGood(NewsRecommendGoodBean NewsRecommendGood) { this.NewsRecommendGood = NewsRecommendGood; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getCartTotalNum() { return CartTotalNum; } public void setCartTotalNum(int CartTotalNum) { this.CartTotalNum = CartTotalNum; } public List<TagsBean> getTags() { return tags; } public void setTags(List<TagsBean> tags) { this.tags = tags; } public List<CateListBean> getCateList() { return CateList; } public void setCateList(List<CateListBean> CateList) { this.CateList = CateList; } public List<FoodieFavoriteGoodsBean> getFoodieFavoriteGoods() { return FoodieFavoriteGoods; } public void setFoodieFavoriteGoods(List<FoodieFavoriteGoodsBean> FoodieFavoriteGoods) { this.FoodieFavoriteGoods = FoodieFavoriteGoods; } public List<ListBean> getList() { return list; } public void setList(List<ListBean> list) { this.list = list; } public static class DailySpecialGoodsBean { /** * Label : * Title : 今日特价 * CoverUrl : http://img1.hoto.cn/mall/mall_ad/2016/04/1460520351.jpg * Price : ¥9.90 * IsAuto : 0 * OpenUrl : haodourecipe://haodou.com/goods/subjectlist/?id=173 */ private String Label; private String Title; private String CoverUrl; private String Price; private int IsAuto; private String OpenUrl; public String getLabel() { return Label; } public void setLabel(String Label) { this.Label = Label; } public String getTitle() { return Title; } public void setTitle(String Title) { this.Title = Title; } public String getCoverUrl() { return CoverUrl; } public void setCoverUrl(String CoverUrl) { this.CoverUrl = CoverUrl; } public String getPrice() { return Price; } public void setPrice(String Price) { this.Price = Price; } public int getIsAuto() { return IsAuto; } public void setIsAuto(int IsAuto) { this.IsAuto = IsAuto; } public String getOpenUrl() { return OpenUrl; } public void setOpenUrl(String OpenUrl) { this.OpenUrl = OpenUrl; } } public static class DailyFirstGoodsBean { /** * Label : 美食研究所 * Title : 新品推荐 * CoverUrl : http://img1.hoto.cn/mall/mall_ad/2016/03/1457419342.jpg * Price : ¥0.00 * IsAuto : 0 * OpenUrl : haodourecipe://haodou.com/goods/dailyfirst?type=new */ private String Label; private String Title; private String CoverUrl; private String Price; private int IsAuto; private String OpenUrl; public String getLabel() { return Label; } public void setLabel(String Label) { this.Label = Label; } public String getTitle() { return Title; } public void setTitle(String Title) { this.Title = Title; } public String getCoverUrl() { return CoverUrl; } public void setCoverUrl(String CoverUrl) { this.CoverUrl = CoverUrl; } public String getPrice() { return Price; } public void setPrice(String Price) { this.Price = Price; } public int getIsAuto() { return IsAuto; } public void setIsAuto(int IsAuto) { this.IsAuto = IsAuto; } public String getOpenUrl() { return OpenUrl; } public void setOpenUrl(String OpenUrl) { this.OpenUrl = OpenUrl; } } public static class OneHourGoodsBean { /** * Label : 明星店铺 * Title : 俊哥的小店儿 * CoverUrl : http://img1.hoto.cn/mall/mall_ad/2016/04/1460099180.jpg * Price : ¥0.00 * IsAuto : 2 * OpenUrl : haodourecipe://haodou.com/store/?id=610 */ private String Label; private String Title; private String CoverUrl; private String Price; private int IsAuto; private String OpenUrl; public String getLabel() { return Label; } public void setLabel(String Label) { this.Label = Label; } public String getTitle() { return Title; } public void setTitle(String Title) { this.Title = Title; } public String getCoverUrl() { return CoverUrl; } public void setCoverUrl(String CoverUrl) { this.CoverUrl = CoverUrl; } public String getPrice() { return Price; } public void setPrice(String Price) { this.Price = Price; } public int getIsAuto() { return IsAuto; } public void setIsAuto(int IsAuto) { this.IsAuto = IsAuto; } public String getOpenUrl() { return OpenUrl; } public void setOpenUrl(String OpenUrl) { this.OpenUrl = OpenUrl; } } public static class BrandStoreBean { /** * InsertionUrl : http://m.haodou.com/mall/index * .php?r=wap/brand/home-page-recommend * OpenURL : haodourecipe://haodou.com/opentopic/?id=471515&store_id=167 * Title : 【夏日美食】一骑红尘荔枝蜜~ * ImgUrl : http://img1.hoto.cn/mall/mall_ad/2016/06/1466748684.jpg */ private String InsertionUrl; private String OpenURL; private String Title; private String ImgUrl; public String getInsertionUrl() { return InsertionUrl; } public void setInsertionUrl(String InsertionUrl) { this.InsertionUrl = InsertionUrl; } public String getOpenURL() { return OpenURL; } public void setOpenURL(String OpenURL) { this.OpenURL = OpenURL; } public String getTitle() { return Title; } public void setTitle(String Title) { this.Title = Title; } public String getImgUrl() { return ImgUrl; } public void setImgUrl(String ImgUrl) { this.ImgUrl = ImgUrl; } } public static class NewsRecommendGoodBean { /** * Goods : {"GoodsId":4786,"Title":"买5冷面赠2凉皮한국냉면 매우맛있다","DealPrice":"¥14 * .90","CoverUrl":"http://pimg2.hoto * .cn/goods/2016/02/24/4786_56cda5464f937_336_336.jpg", * "OpenUrl":"haodourecipe://haodou.com/goods/detail?id=4786"} * UserName : 好豆到家品鉴员 * ImgUrl : http://img1.hoto.cn/mall/mall_ad/2016/04/1460341662.jpg * Tags : ["好吃不贵"] * Content : 好豆到家 * Info : * 冷面,面条劲道且富有弹性,是看得见的Q,看得见的弹!!酸溜溜的,甜滋滋的汤汁,浓郁到让你的舌头欲罢不能,火红的油辣子带来了不仅是满满的诚意而且更多幸福感。真空包装,卫生和干净都看得见。 */ private GoodsBean Goods; private String UserName; private String ImgUrl; private String Content; private String Info; private List<String> Tags; public GoodsBean getGoods() { return Goods; } public void setGoods(GoodsBean Goods) { this.Goods = Goods; } public String getUserName() { return UserName; } public void setUserName(String UserName) { this.UserName = UserName; } public String getImgUrl() { return ImgUrl; } public void setImgUrl(String ImgUrl) { this.ImgUrl = ImgUrl; } public String getContent() { return Content; } public void setContent(String Content) { this.Content = Content; } public String getInfo() { return Info; } public void setInfo(String Info) { this.Info = Info; } public List<String> getTags() { return Tags; } public void setTags(List<String> Tags) { this.Tags = Tags; } public static class GoodsBean { /** * GoodsId : 4786 * Title : 买5冷面赠2凉皮한국냉면 매우맛있다 * DealPrice : ¥14.90 * CoverUrl : http://pimg2.hoto * .cn/goods/2016/02/24/4786_56cda5464f937_336_336.jpg * OpenUrl : haodourecipe://haodou.com/goods/detail?id=4786 */ private int GoodsId; private String Title; private String DealPrice; private String CoverUrl; private String OpenUrl; public int getGoodsId() { return GoodsId; } public void setGoodsId(int GoodsId) { this.GoodsId = GoodsId; } public String getTitle() { return Title; } public void setTitle(String Title) { this.Title = Title; } public String getDealPrice() { return DealPrice; } public void setDealPrice(String DealPrice) { this.DealPrice = DealPrice; } public String getCoverUrl() { return CoverUrl; } public void setCoverUrl(String CoverUrl) { this.CoverUrl = CoverUrl; } public String getOpenUrl() { return OpenUrl; } public void setOpenUrl(String OpenUrl) { this.OpenUrl = OpenUrl; } } } public static class TagsBean { /** * Id : 38 * Title : 猪肉 * Url : haodourecipe://haodou.com/goods/searchResult/?tagName=猪肉&TagId=38 * Goods : {"GoodsId":"6278","Title":"【温州特产】猪油渣","DealPrice":"69.00", * "CoverUrl":"http://pimg3.hoto.cn/goods/2016/11/09/6278_582303b7c4313_336_336.jpg","OpenUrl":"haodourecipe://haodou.com/goods/detail?id=6278"} */ private String Id; private String Title; private String Url; private GoodsBeanX Goods; public String getId() { return Id; } public void setId(String Id) { this.Id = Id; } public String getTitle() { return Title; } public void setTitle(String Title) { this.Title = Title; } public String getUrl() { return Url; } public void setUrl(String Url) { this.Url = Url; } public GoodsBeanX getGoods() { return Goods; } public void setGoods(GoodsBeanX Goods) { this.Goods = Goods; } public static class GoodsBeanX { /** * GoodsId : 6278 * Title : 【温州特产】猪油渣 * DealPrice : 69.00 * CoverUrl : http://pimg3.hoto.cn/goods/2016/11/09/6278_582303b7c4313_336_336.jpg * OpenUrl : haodourecipe://haodou.com/goods/detail?id=6278 */ private String GoodsId; private String Title; private String DealPrice; private String CoverUrl; private String OpenUrl; public String getGoodsId() { return GoodsId; } public void setGoodsId(String GoodsId) { this.GoodsId = GoodsId; } public String getTitle() { return Title; } public void setTitle(String Title) { this.Title = Title; } public String getDealPrice() { return DealPrice; } public void setDealPrice(String DealPrice) { this.DealPrice = DealPrice; } public String getCoverUrl() { return CoverUrl; } public void setCoverUrl(String CoverUrl) { this.CoverUrl = CoverUrl; } public String getOpenUrl() { return OpenUrl; } public void setOpenUrl(String OpenUrl) { this.OpenUrl = OpenUrl; } } @Override public String toString() { return "TagsBean{" + "Id='" + Id + '\'' + ", Title='" + Title + '\'' + ", Url='" + Url + '\'' + ", Goods=" + Goods + '}'; } } public static class CateListBean { /** * CateId : 58 * CateName : 家传秘制 * ImgUrl : http://img1.hoto.cn/mall/mall_ad/2015/08/1438411987.jpg * OpenUrl : haodourecipe://haodou.com/goods/searchResult/?CateId=58&CateName=家传秘制 */ private String CateId; private String CateName; private String ImgUrl; private String OpenUrl; public String getCateId() { return CateId; } public void setCateId(String CateId) { this.CateId = CateId; } public String getCateName() { return CateName; } public void setCateName(String CateName) { this.CateName = CateName; } public String getImgUrl() { return ImgUrl; } public void setImgUrl(String ImgUrl) { this.ImgUrl = ImgUrl; } public String getOpenUrl() { return OpenUrl; } public void setOpenUrl(String OpenUrl) { this.OpenUrl = OpenUrl; } @Override public String toString() { return "CateListBean{" + "CateId='" + CateId + '\'' + ", CateName='" + CateName + '\'' + ", ImgUrl='" + ImgUrl + '\'' + ", OpenUrl='" + OpenUrl + '\'' + '}'; } } public static class FoodieFavoriteGoodsBean { /** * Title : 日式汤料 * CoverUrl : http://img1.hoto.cn/mall/mall_ad/2016/04/1460599417.jpg * Price : ¥9.90 * HomePosition : 1 * GoodsId : 5549 */ private String Title; private String CoverUrl; private String Price; private int HomePosition; private int GoodsId; public String getTitle() { return Title; } public void setTitle(String Title) { this.Title = Title; } public String getCoverUrl() { return CoverUrl; } public void setCoverUrl(String CoverUrl) { this.CoverUrl = CoverUrl; } public String getPrice() { return Price; } public void setPrice(String Price) { this.Price = Price; } public int getHomePosition() { return HomePosition; } public void setHomePosition(int HomePosition) { this.HomePosition = HomePosition; } public int getGoodsId() { return GoodsId; } public void setGoodsId(int GoodsId) { this.GoodsId = GoodsId; } } public static class ListBean { /** * StoreId : 149 * StoreTitle : 靓家货 * StoreLogoUrl : http://pimg2.hoto.cn/store/2015/07/31/55bb6ac68d05a.jpg * UserId : 8190340 * UserName : Leslie靓靓 * GoodsId : 271 * Title : 【肘爷】酱肘子 * SubTitle : 【肘爷】酱肘子,肉质细腻 * DealPrice : ¥150.00 * ShippingInfo : 配送上门/全国快递 * CoverUrl : http://pimg2.hoto.cn/goods/2015/07/31/271_55bb72af0a680_680_450.jpg * OpenUrl : haodourecipe://haodou.com/goods/detail?id=271 * LikeCount : 2485 * Stock : 100 * IsShippingFree : 1 * IsLike : 0 * CartNum : 0 * Labels : [] * Weight : 1000克 * Price : ¥168.00 */ private int StoreId; private String StoreTitle; private String StoreLogoUrl; private String UserId; private String UserName; private int GoodsId; private String Title; private String SubTitle; private String DealPrice; private String ShippingInfo; private String CoverUrl; private String OpenUrl; private int LikeCount; private int Stock; private int IsShippingFree; private int IsLike; private int CartNum; private String Weight; private String Price; private List<?> Labels; public int getStoreId() { return StoreId; } public void setStoreId(int StoreId) { this.StoreId = StoreId; } public String getStoreTitle() { return StoreTitle; } public void setStoreTitle(String StoreTitle) { this.StoreTitle = StoreTitle; } public String getStoreLogoUrl() { return StoreLogoUrl; } public void setStoreLogoUrl(String StoreLogoUrl) { this.StoreLogoUrl = StoreLogoUrl; } public String getUserId() { return UserId; } public void setUserId(String UserId) { this.UserId = UserId; } public String getUserName() { return UserName; } public void setUserName(String UserName) { this.UserName = UserName; } public int getGoodsId() { return GoodsId; } public void setGoodsId(int GoodsId) { this.GoodsId = GoodsId; } public String getTitle() { return Title; } public void setTitle(String Title) { this.Title = Title; } public String getSubTitle() { return SubTitle; } public void setSubTitle(String SubTitle) { this.SubTitle = SubTitle; } public String getDealPrice() { return DealPrice; } public void setDealPrice(String DealPrice) { this.DealPrice = DealPrice; } public String getShippingInfo() { return ShippingInfo; } public void setShippingInfo(String ShippingInfo) { this.ShippingInfo = ShippingInfo; } public String getCoverUrl() { return CoverUrl; } public void setCoverUrl(String CoverUrl) { this.CoverUrl = CoverUrl; } public String getOpenUrl() { return OpenUrl; } public void setOpenUrl(String OpenUrl) { this.OpenUrl = OpenUrl; } public int getLikeCount() { return LikeCount; } public void setLikeCount(int LikeCount) { this.LikeCount = LikeCount; } public int getStock() { return Stock; } public void setStock(int Stock) { this.Stock = Stock; } public int getIsShippingFree() { return IsShippingFree; } public void setIsShippingFree(int IsShippingFree) { this.IsShippingFree = IsShippingFree; } public int getIsLike() { return IsLike; } public void setIsLike(int IsLike) { this.IsLike = IsLike; } public int getCartNum() { return CartNum; } public void setCartNum(int CartNum) { this.CartNum = CartNum; } public String getWeight() { return Weight; } public void setWeight(String Weight) { this.Weight = Weight; } public String getPrice() { return Price; } public void setPrice(String Price) { this.Price = Price; } public List<?> getLabels() { return Labels; } public void setLabels(List<?> Labels) { this.Labels = Labels; } } @Override public String toString() { return "ResultBean{" + "DailySpecialGoods=" + DailySpecialGoods + ", DailyFirstGoods=" + DailyFirstGoods + ", OneHourGoods=" + OneHourGoods + ", BrandStore=" + BrandStore + ", NewsRecommendGood=" + NewsRecommendGood + ", count=" + count + ", CartTotalNum=" + CartTotalNum + ", tags=" + tags + ", CateList=" + CateList + ", FoodieFavoriteGoods=" + FoodieFavoriteGoods + ", list=" + list + '}'; } } @Override public String toString() { return "Entity{" + "status=" + status + ", result=" + result + '}'; } }
true
9112d3574fcfdcc1457cab365f26f102fe1ce252
Java
prashantrai/Algo_DS_InterviewPrep
/src/test/math/MinimizeSteps.java
UTF-8
1,213
3.875
4
[]
no_license
package test.math; import java.util.Arrays; import java.util.Scanner; public class MinimizeSteps { /** [DP problem with memoization] * http://www.geeksforgeeks.org/minimum-steps-minimize-n-per-given-condition/ Given a number n, count minimum steps to minimize it to 1 according to the following criteria: If n is divisible by 2 then we may reduce n to n/2. If n is divisible by 3 then you may reduce n to n/3. Decrement n by 1. Examples: Input : n = 10 Output : 3 Input : 6 Output : 2 */ public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("RESULT: " + getMinimisedSteps(in.nextInt())); } public static int getMinimisedSteps(int n) { int[] memo = new int[n+1]; Arrays.fill(memo, -1); return getMinimisedSteps(n, memo); } private static int getMinimisedSteps(int n, int[] memo) { if(n == 1) return 0; if(memo[n] != -1) { return memo[n]; } int res = getMinimisedSteps(n-1, memo); if(n%2 == 0) { res = Math.min (res, getMinimisedSteps(n/2, memo)); } if(n%3 == 0) { res = Math.min (res, getMinimisedSteps(n/3, memo)); } memo[n] = 1+res; return memo[n]; } }
true
1856337901dfb80851a77438c43c5a35f900438c
Java
valasruthi/java-keywords-implementation
/src/main/java/com/stackroute/ConditionalStatement.java
UTF-8
1,065
3.921875
4
[]
no_license
package com.stackroute; import java.util.*; public class ConditionalStatement { public static void main(String[] args) { System.out.println("Enter the value of a"); Scanner scanner=new Scanner(System.in); int a=scanner.nextInt(); if (a % 2 == 0) {//if the number is even it prints as even number System.out.println("Even number"); } else if(a%2!=0){ System.out.println("Odd number");//if the number is odd it prints as odd number } else{ System.out.println("Invalid number");//else it prints invalid } //Switch conditional statement switch(a){ case 1:System.out.println("hello");//if the user give the value as 1 case:1 gets printed break; case 2 :System.out.println("welcome");//if the user give the value as 2 case:2 gets printed break; case 3:System.out.println("to stackroute");//if the user give the value as 3 case:3 gets printed break; default:System.out.println("not a valid number");//if the user give the value as some other default gets printed } } }
true
f7e49af6f5a7b237c9407c7c1cef6ad5294ad254
Java
daemonjaejin/jaejin_java_study
/src/main/java/effective/javatwo/noif/PaymentService.java
UTF-8
530
2.390625
2
[]
no_license
package effective.javatwo.noif; /** * Created by Administrator on 2017-10-18. */ public class PaymentService { private Discountable getDiscounter(String discountCode){ if("NAVER".equals(discountCode)){ return new NaverDiscountPolicy(); }else if("DANAWA".equals(discountCode)){ return new DanawaDiscountPolicy(); }else if("FANCAFE".equals(discountCode)){ return new FancafeDiscountPolicy(); }else{ return Discountable.NONE; } } }
true
0558325f5e30b91b39333adee8cdaebc95e04ebe
Java
patrickucy/learn_java
/13.day60_09.Web51_Hibernate09/src/hibernate/HibernateTest.java
UTF-8
1,587
2.828125
3
[]
no_license
package hibernate; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import entity.FourWheeler; import entity.TwoWheeler; import entity.UserDetails; import entity.Vehicle; public class HibernateTest { public static void main(String[] args) { UserDetails user = new UserDetails(); user.setUserName("Test User"); SessionFactory sessionFactory = HibernateSessionFactory.getSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); // begin to create table and insert data /** * if you don't do this process, hibernate will not save this data to db for you * thus it will be a transient object, if you save it. then it will be a persisted * object */ session.save(user); user.setUserName("1 Another tested user"); user.setUserName("2 Another tested user"); user.setUserName("3 Another tested user"); user.setUserName("4 Another tested user"); /** * hibernate will update this change for us automatically; what if you have multiple * modifications here? in fact the hibernate will only save the last operation to database. * it will not do every alteration while you modifying the object */ user.setUserName("last Another tested user"); session.getTransaction().commit(); session.close(); /* * once close, it it will be a detached object, it was persisted before, now it is no longer it. * right now it just the same as transient object */ user.setUserName("After session close test user"); } }
true
d407a84f2e93fe6b5c6ccb099dbcb18d28114df2
Java
orispencer/JuegoRol
/src/models/Aldeano.java
UTF-8
634
2.625
3
[]
no_license
package models; public class Aldeano extends Personaje{ public static final int ataqueAldeanoBase=5; public Aldeano(String nombre){ super(Personaje.vidaMax, ataqueAldeanoBase, nombre); } public Aldeano(int pt_vida, int pt_ataque, String nombre) { super(pt_vida, pt_ataque, nombre); } @Override public void setPt_vida(int pt_vida) { super.setPt_vida(pt_vida); //modo berserker if(this.getPt_vida()>0 && this.getPt_vida()<=20){ this.setPt_ataque(this.getPt_ataque() * 4); } } }
true
1a8633b2720686a3d5917afc41e69f58acc73c26
Java
usernamegemaoa/EC
/ec/src/test/java/njuse/ec/service/FileServiceTest.java
UTF-8
829
2.125
2
[ "Apache-2.0" ]
permissive
package njuse.ec.service; import static org.junit.Assert.assertEquals; import java.io.File; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * 文件测试. * @author 丞 * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext.xml") public class FileServiceTest { /** * 文件service. */ @Autowired private FileService fileService; /** * 测试上传函数. */ @Test public final void testUpload() { // assertEquals(1, fileService.upload(null).getResultCode()); // assertEquals(0, fileService.upload(new File("aaa")).getResultCode()); } }
true
ad8930212d32a7620dbc65ec04f87594f0243d25
Java
psychozaur/springmvc_tutorial_javasolutions
/src/main/java/part1/controller/LoginController.java
UTF-8
921
2.15625
2
[]
no_license
package main.java.part1.controller; import main.java.part1.pojo.User; import main.java.part1.validator.UserValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; @Controller @SessionAttributes("loggedUser") public class LoginController { @PostMapping(value = "/login") public String postLogin(Model model, @ModelAttribute("user") User user){ model.addAttribute("loggedUser", user); return "redirect:user_page"; } @GetMapping(value = "/login") public String login (Model model){ model.addAttribute("user", new User()); return "login"; } }
true
ca08d595b3b48dfd28248e717e67e7f2d10c2b25
Java
leohinterlang/argFace
/src/main/java/com/fidelis/argface/ArgPattern.java
UTF-8
21,054
2.484375
2
[ "Apache-2.0" ]
permissive
/** *+ * ArgPattern.java * 1.0.0 May 6, 2014 Leo Hinterlang *- */ package com.fidelis.argface; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; /** * ArgFace Pattern Generation and Matching. * * @version 1.0.0 * @author Leo Hinterlang * */ public class ArgPattern { private ArgList argList; private List<String> nonOptionList; private boolean patternWatch; private String patternMatch; private ArgHelp help; private Deque<ArgList> listStack = new ArrayDeque<ArgList>(); private List<ArgNode> patternList = new ArrayList<ArgNode>(); private List<ArgNode> saveList = new ArrayList<ArgNode>(); private int prevIndex; private ArgNode failBase; private ArgNode failNode; private ArgNode lastBase; private ArgNode lastFail; private int patternMin; private int patternMax; private List<ArgOperand> targetOperands = new ArrayList<ArgOperand>(); /** * Sets the reference to the {@code ArgHelp} object. * * @param help the ArgHelp reference */ public void setHelp (ArgHelp help) { this.help = help; } /** * Sets the arguments list. * * @param argList the argument list */ public void setArgList (ArgList argList) { this.argList = argList; } /** * Sets the non option list. * * @param nonOptionList the non option list */ public void setNonOptionList (List<String> nonOptionList) { this.nonOptionList = nonOptionList; } /** * Sets the pattern watch operating mode. * * @param patternWatch {@code true} enables pattern watch mode */ public void setPatternWatch (boolean patternWatch) { this.patternWatch = patternWatch; } /** * Returns the target operands list. * * @return the target operands list */ public List<ArgOperand> getTargetOperands () { return targetOperands; } /** * Returns the matching pattern text. * * @return the matching pattern text */ public String getPatternMatch () { return patternMatch; } /** * Returns true if the non options match a usage pattern. * * @param usageNode the node that starts the usage definition * @return {@code true} if a match is found */ public boolean matchUsage (ArgNode usageNode) { // Get the number of operands. // If zero, return success. int argCount = nonOptionList.size(); if (argCount == 0) { return true; } // Pattern loop. patternMatch = null; ArgNode start = usageNode.getEast(); for (String pat = first(start); pat != null; pat = next(start)) { if (pat.isEmpty()) { break; } String text = String.format("%d-%d (%d) %-30.30s %s", patternMin, patternMax, argCount, patternSpec(pat), pat); trace("pattern", text); if (patternWatch) { if (patternMin <= argCount && argCount <= patternMax) { System.out.println("Try pattern: " + patternSpec(pat)); } } if (match(pat)) { patternMatch = patternSpec(pat); if (patternWatch) { System.out.println("Pattern match found"); } addTargetOperands(pat); return true; } else if (failBase == null) { break; } } help.addProblem(usageNode, "No matching operand pattern"); return false; } private String first (ArgNode start) { StringBuilder sb = new StringBuilder(); patternList.clear(); patternMin = 0; patternMax = 0; String pattern = buildPattern(start, sb); if (patternMax == 0) { patternMax = patternMin; } return pattern; } private String next (ArgNode start) { StringBuilder sb = new StringBuilder(); String pattern = null; nextInit(); for (boolean done = false; !done; ) { pattern = rebuildPattern(start, sb); if (pattern == null) { if (lastBase == null) { return null; } trace("next no pat", lastFail.brief()); failBase = lastBase; failNode = lastFail; sb.setLength(0); nextInit(); } else { done = true; } } if (patternMax == 0) { patternMax = patternMin; } return pattern; } private void nextInit () { saveList.clear(); saveList.addAll(patternList); patternList.clear(); patternMin = 0; patternMax = 0; lastBase = null; lastFail = null; prevIndex = 0; } private boolean match (String pattern) { trace("match", pattern); for (ArgNode node : patternList) { if (node == null) { trace("patternList", "null"); } else if (node.isOperand()) { trace("patternList", node.toString()); } else if (node.isGroup()) { trace("patternList", node.brief()); } } int argIndex = 0; int argCount = nonOptionList.size(); ArgNode node = null; String arg = null; failBase = null; failNode = null; int nodeIndex = 0; for (int n = 0; n < pattern.length(); n++) { char c = pattern.charAt(n); // Literal. if (c == 'L') { // Get the literal text. node = patternList.get(nodeIndex++); ArgOperand operand = node.getOperand(); String literal = operand.getName(); // Next non-option argument. if (argIndex >= argCount) { failNode = node; if (failBase == null) { failBase = failNode; } return false; } arg = nonOptionList.get(argIndex++); trace("compare", literal + " to " + arg); // Ignore case. Not a match. if (!arg.equalsIgnoreCase(literal)) { failNode = node; if (failBase == null) { failBase = failNode; } return false; } } // Variable. else if (c == 'V') { // Get the variable node. node = patternList.get(nodeIndex++); // Accept the next non-option argument. if (argIndex >= argCount) { failNode = node; if (failBase == null) { failBase = failNode; } return false; } arg = nonOptionList.get(argIndex++); trace("Variable", arg); } // Base node. else if (c == 'b') { failBase = patternList.get(nodeIndex++); } // Group node. else if (c == 'g') { ++nodeIndex; } // Reduced optional argument. else if (c == 'x') { ++nodeIndex; } } if (patternMin > argCount || argCount > patternMax) { failBase = patternList.get(0); failNode = failBase; return false; } return true; } private String buildPattern (ArgNode start, StringBuilder sb) { argList.setCurrent(start); for (ArgNode node = start; node != null; node = argList.goEast()) { if (node.isOperand()) { buildOperand(node, sb); } else if (node.isGroup()) { buildGroup(node, sb, false); } } return sb.toString(); } private String rebuildPattern (ArgNode start, StringBuilder sb) { if (failBase == null) { trace("rebuild no base", "none"); } else { trace("rebuild Base", failBase.brief()); } if (failNode == null) { trace("rebuild no fail", "none"); } else { trace("rebuild Fail", failNode.brief()); } boolean showNext = false; argList.setCurrent(start); ArgOperand operand = null; for (ArgNode node = start; node != null; node = argList.goEast()) { if (showNext) { showNext = false; trace("next node", node.brief()); } if (node == failBase) { trace("fail Base", failBase.brief()); if (failNode == null) { trace("fail Node", "NULL"); } else { trace("fail Node", failNode.brief()); } ArgNode south = failNode.getSouth(); if (south != null) { trace("fail south", south.brief()); if (south.isOperand()) { buildOperand(south, sb, failBase); } else if (south.isGroup()) { trace("fail group", sb.toString()); buildGroup(south, sb, true); } } // South is null. else { trace("south is NULL", failNode.brief()); // Fail node optional? if (failNode.isOptional()) { trace("end alternatives", sb.toString()); showNext = true; buildBase(failBase, sb); buildReduce(failNode, sb); continue; } return null; } } // Not the fail base node. else { if (node.isOperand()) { trace("not fail base", node.brief()); operand = node.getOperand(); if (operand.isLiteral()) { if (operand.getName().equalsIgnoreCase("options")) { continue; } lastBase = node; lastFail = node; ArgNode prevBase = null; ArgNode prevNode = null; trace("prevIndex", "" + prevIndex); if (saveList.size() > prevIndex + 1) { prevBase = saveList.get(prevIndex); prevNode = saveList.get(prevIndex + 1); if (prevBase == null) { trace("prev Base", null); } else { trace("prev Base", prevBase.brief()); } if (prevNode == null) { trace("prev Node", null); } else { trace("prev Node", prevNode.brief()); } } if (prevBase == node) { buildBase(prevBase, sb); buildLiteral(prevNode, sb); } else { buildBase(node, sb); buildLiteral(node, sb); } } else { if (node.isOptional()) { trace("optional", node.brief()); lastBase = node; lastFail = node; } buildVariable(node, sb); } } else if (node.isGroup()) { lastBase = node; lastFail = node; ArgNode prevGroup = null; if (saveList.size() > prevIndex) { prevGroup = saveList.get(prevIndex); lastFail = prevGroup; trace("prev Group", prevGroup.brief()); } String pattern = null; if (prevGroup == node) { pattern = buildGroup(node, sb, true); } else { pattern = buildGroup(prevGroup, sb, true); } trace("rebuild group", pattern); if (pattern == null) { return null; } } } } return sb.toString(); } private void buildOperand (ArgNode node, StringBuilder sb) { // Get the operand. ArgOperand operand = node.getOperand(); // Literal operands are preceded by a base node. // Initially, the base node is the same as the literal node that follows. if (operand.isLiteral()) { // Literal operand named "options" is not part of the pattern. if (operand.getName().equalsIgnoreCase("options")) { return; } buildBase(node, sb); buildLiteral(node, sb); } else { buildVariable(node, sb); } } private void buildOperand (ArgNode node, StringBuilder sb, ArgNode base) { // Get the operand. ArgOperand operand = node.getOperand(); // Literal operands are preceded by a base node. // On a rebuild, the base may not be the same as the node. if (operand.isLiteral()) { // Literal operand named "options" is not part of the pattern. if (operand.getName().equalsIgnoreCase("options")) { return; } buildBase(base, sb); buildLiteral(node, sb); } else { buildVariable(node, sb); } } private void buildBase (ArgNode node, StringBuilder sb) { patternList.add(node); sb.append('b'); ++prevIndex; } private void buildLiteral (ArgNode node, StringBuilder sb) { ArgOperand operand = node.getOperand(); boolean ender = false; if (operand.getName().equals("$END$")) { ender = true; trace("literal end", node.toString()); } patternList.add(node); if (ender) { sb.append('x'); } else { sb.append('L'); adjustCount(node); } ++prevIndex; } private void buildReduce (ArgNode node, StringBuilder sb) { ArgOperand operand = new ArgOperand().literal(); operand.setName("$END$"); ArgNode reduce = new ArgNode(operand); patternList.add(reduce); sb.append('x'); ++prevIndex; } private void buildVariable (ArgNode node, StringBuilder sb) { patternList.add(node); sb.append('V'); adjustCount(node); ++prevIndex; } private void adjustCount (ArgNode node) { ++patternMin; if (node.isRepeat()) { patternMax = 999; } } private String buildGroup (ArgNode node, StringBuilder sb, boolean rebuild) { patternList.add(node); sb.append('g'); ++prevIndex; ArgList group = node.getGroup(); listStack.push(argList); argList = group; String pattern = null; if (rebuild) { pattern = rebuildPattern(argList.goHome(), sb); } else { pattern = buildPattern(argList.goHome(), sb); } argList = listStack.pop(); return pattern; } private char remLast (StringBuilder sb) { int last = sb.length() - 1; if (last < 0) { return '\0'; } char c = sb.charAt(last); sb.setLength(last); return c; } private String patternSpec (String pattern) { StringBuilder sb = new StringBuilder(); ArgOperand operand = null; int n = 0; for (ArgNode node : patternList) { char c = pattern.charAt(n++); boolean trailers = false; if (c == 'L') { if (node.isOptional()) { sb.append('['); } operand = node.getOperand(); String literal = operand.getName(); sb.append(literal); trailers = true; } else if (c == 'V') { if (node.isOptional()) { sb.append('['); } operand = node.getOperand(); String name = operand.getName(); sb.append('<'); sb.append(name); sb.append('>'); trailers = true; } if (trailers) { if (node.isOptional()) { sb.append(']'); } if (node.isRepeat()) { sb.append("..."); } sb.append(' '); } } remLast(sb); return sb.toString(); } private void addTargetOperands (String pattern) { int argIndex = 0; String arg = null; ArgNode node = null; Debug.trace("PATTERN: " + pattern); for (int n = 0; n < pattern.length(); n++) { node = null; char c = pattern.charAt(n); if (c == 'L') { node = patternList.remove(0); } else if (c == 'V') { node = patternList.remove(0); } else if (c == 'b' || c == 'x' || c == 'g') { patternList.remove(0); } if (node != null) { ArgOperand operand = node.getOperand(); if (operand != null) { if (operand.isRepeat()) { int argsLeft = nonOptionList.size() - argIndex; int operandsLeft = patternMin - argIndex; while (argsLeft >= operandsLeft) { --argsLeft; arg = nonOptionList.get(argIndex++); Debug.trace(String.format("rep: %15.15s -> %s", arg, operand)); takeOperand(operand, arg); } } else { arg = nonOptionList.get(argIndex++); Debug.trace(String.format("arg: %15.15s -> %s", arg, operand)); takeOperand(operand, arg); } } } } } private boolean takeOperand (ArgOperand operand, String arg) { if (operand.isVariable()) { operand.setHas(true); operand.setValue(arg); operand.setCount(operand.getCount() + 1); if (operand.isRepeat()) { operand.addList(arg); } targetOperands.add(operand); return true; } else if (operand.isLiteral()) { if (operand.getName().equalsIgnoreCase(arg)) { operand.setHas(true); operand.setValue(arg); operand.setCount(operand.getCount() + 1); targetOperands.add(operand); return true; } } return false; } private void trace (String id, String text) { Debug.trace(String.format("%15.15s : %s", id, text)); } }
true
48ce41273c6a725e02bbd0a85fa1808271d932ef
Java
muhammaddjulfikar/PBO3-10117086-Latihan37-ObjectOrientedProgramRata-RataNilai
/src/pbo3/pkg10117086/latihan37/objectorientedprogramrata/ratanilai/PBO310117086Latihan37ObjectOrientedProgramRataRataNilai.java
UTF-8
1,121
3
3
[]
no_license
/* * 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 pbo3.pkg10117086.latihan37.objectorientedprogramrata.ratanilai; import java.util.Scanner; /** * * @author Lenovo * NAMA : RD Muhammad Djulfikar BU * KELAS : IF3 * NIM : 10117086 * DESKRIPSI PROGRAM : Mencari Rata-rataNilai */ public class PBO310117086Latihan37ObjectOrientedProgramRataRataNilai { /** * @param args the command line arguments */ public static void main(String[] args) { Rata rata = new Rata(); Scanner scn = new Scanner(System.in); int n; System.out.print("Masukkan Banyaknya Mahasiswa : "); n = scn.nextInt(); rata.HitungTotal(rata.nilaiMhs, n); rata.HitungRataRataNilaiMhs(rata.totalNilaiMhs, n); System.out.println("\nMaka, Rata-rata Nilainya adalah : "+rata.HitungRataRataNilaiMhs(rata.totalNilaiMhs,n)); System.out.println("Developed by : DJ BU"); } }
true
ee6773c1e8f5039e5fcf5a62d4dc95a97130bb7e
Java
keteik/java-game-project
/Tysiac/src/window/App.java
UTF-8
7,707
2.546875
3
[]
no_license
package window; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import game.Card; import game.Deck; import game.Rules; import network.Client; import network.Server; public class App extends CardIcon{ static int firstPlayerScore = 0; static int secondPlayerScore = 0; static int bid; static Server server = null; static Client client = null; final static Deck deck = new Deck(); Rules rules = new Rules(); ImagePath path = new ImagePath(); final static TrickAction trickAction = new TrickAction(); final static GameWindow firstPlayerWindow = new GameWindow(); final static GameWindow secondPlayerWindow = new GameWindow(); final static BiddingWindow firstPlayerBiddingWindow = new BiddingWindow(); final static BiddingWindow secondPlayerBiddingWindow = new BiddingWindow(); static boolean trick = false; static int counter = 0; static boolean firstPlayerWin = false; public static ArrayList<Card> firstPlayerWinCards = new ArrayList<Card>(10); public static ArrayList<Card> secondPlayerWinCards = new ArrayList<Card>(10); protected void finalize() throws IOException{ client.closeConnection(); server.closeConnection(); } public void takeTrick() { firstPlayerWindow.firstCard.setEnabled(false); firstPlayerWindow.secondCard.setEnabled(false); firstPlayerWindow.thirdCard.setEnabled(false); firstPlayerWindow.fourthCard.setEnabled(false); firstPlayerWindow.fifthCard.setEnabled(false); firstPlayerWindow.sixthCard.setEnabled(false); firstPlayerWindow.seventhCard.setEnabled(false); firstPlayerWindow.eighthCard.setEnabled(false); firstPlayerWindow.ninthCard.setEnabled(false); firstPlayerWindow.tenthCard.setEnabled(false); secondPlayerWindow.firstCard.setEnabled(false); secondPlayerWindow.secondCard.setEnabled(false); secondPlayerWindow.thirdCard.setEnabled(false); secondPlayerWindow.fourthCard.setEnabled(false); secondPlayerWindow.fifthCard.setEnabled(false); secondPlayerWindow.sixthCard.setEnabled(false); secondPlayerWindow.seventhCard.setEnabled(false); secondPlayerWindow.eighthCard.setEnabled(false); secondPlayerWindow.ninthCard.setEnabled(false); secondPlayerWindow.tenthCard.setEnabled(false); firstPlayerWindow.firstTrickButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { trickAction.getTrick(firstPlayerWindow, secondPlayerWindow, "first_trick", deck.firstPlayerHand, deck.firstTrick); } }); firstPlayerWindow.secondTrickButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { trickAction.getTrick(firstPlayerWindow, secondPlayerWindow, "second_trick", deck.firstPlayerHand, deck.secondTrick); } }); secondPlayerWindow.firstTrickButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { trickAction.getTrick(secondPlayerWindow, firstPlayerWindow, "first_trick", deck.secondPlayerHand, deck.firstTrick); } }); secondPlayerWindow.secondTrickButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { trickAction.getTrick(secondPlayerWindow, firstPlayerWindow, "second_trick", deck.secondPlayerHand, deck.secondTrick); } }); } public static void main(String[] args) throws IOException { final App app = new App(); deck.resetDeck(); deck.dealCards(); Thread serverThread = new Thread(new Runnable(){ @Override public void run() { server = new Server(5000); final BiddingAction biddingAction = new BiddingAction(); final DealingAction dealingAction = new DealingAction(); setPlayerCardIcon(firstPlayerWindow, deck.firstPlayerHand); setTrickCardIcon(firstPlayerWindow, deck.firstTrick, deck.secondTrick); firstPlayerWindow.frmTysiac.setTitle("Player 1"); firstPlayerWindow.frmTysiac.setVisible(true); firstPlayerWindow.frmTysiac.setEnabled(false); firstPlayerBiddingWindow.setTitle("Player 1 binding"); firstPlayerBiddingWindow.setVisible(true); biddingAction.bidServer(server, firstPlayerBiddingWindow, firstPlayerWindow); int tmp = biddingAction.getClientBid(server); if(tmp > bid ) bid = tmp; firstPlayerWindow.frmTysiac.setVisible(true); firstPlayerWindow.frmTysiac.setEnabled(true); app.takeTrick(); dealingAction.giveCardServer(firstPlayerWindow, server, deck.firstPlayerHand, trick); firstPlayerWin = dealingAction.checkFirstPlayerWin(server); server.serverWriteString("start"); while(!deck.firstPlayerHand.isEmpty()) { if(firstPlayerWin) { firstPlayerWindow.frmTysiac.setVisible(true); dealingAction.giveCardServer(firstPlayerWindow, server, deck.firstPlayerHand, trick); firstPlayerWin = dealingAction.checkFirstPlayerWin(server); } else { dealingAction.showCardsServer(firstPlayerWindow, server, deck.firstPlayerHand, deck.secondPlayerHand, firstPlayerWinCards, secondPlayerWinCards); } } } }); serverThread.start(); Thread clientThread = new Thread(new Runnable(){ @Override public void run() { final App app = new App(); final DealingAction dealingAction = new DealingAction(); final BiddingAction biddingAction = new BiddingAction(); String state; client = new Client(2, "127.0.0.1", 5000); secondPlayerWindow.frmTysiac.setTitle("Player 2"); secondPlayerBiddingWindow.setTitle("Player 2 binding"); setPlayerCardIcon(secondPlayerWindow, deck.secondPlayerHand); setTrickCardIcon(secondPlayerWindow, deck.firstTrick, deck.secondTrick); bid = biddingAction.getServerBid(client); if(bid == 0) { app.takeTrick(); secondPlayerWindow.frmTysiac.setEnabled(true); secondPlayerWindow.frmTysiac.setVisible(true); } else { secondPlayerWindow.frmTysiac.setVisible(true); secondPlayerWindow.frmTysiac.setEnabled(false); secondPlayerBiddingWindow.setEnabled(true); secondPlayerBiddingWindow.setVisible(true); biddingAction.bidClient(client, secondPlayerBiddingWindow, secondPlayerWindow, bid); } dealingAction.showCardsClient(secondPlayerWindow, client, deck.secondPlayerHand, deck.firstPlayerHand, secondPlayerWinCards, firstPlayerWinCards); state = client.clientReadString(); while(!deck.secondPlayerHand.isEmpty()) { secondPlayerScore = dealingAction.getPoints(secondPlayerWinCards); System.out.println(secondPlayerScore); if(!firstPlayerWin) { secondPlayerWindow.frmTysiac.setVisible(true); dealingAction.giveCardClient(secondPlayerWindow, client, deck.secondPlayerHand, trick); firstPlayerWin = dealingAction.checkSecondPlayerWin(client); } else dealingAction.showCardsClient(secondPlayerWindow, client, deck.secondPlayerHand, deck.firstPlayerHand,secondPlayerWinCards, firstPlayerWinCards); if(deck.secondPlayerHand.isEmpty()) { secondPlayerScore = dealingAction.getPoints(secondPlayerWinCards); System.out.println(secondPlayerScore); } } } }); clientThread.start(); } }
true
6a04e3ae6825a7fda0fa8fa24a6ce962c8718e32
Java
savitrasapre/RestApp
/src/main/java/com/LearningJava/restservice/RestApp/Repository/AuthRepository.java
UTF-8
488
1.992188
2
[]
no_license
package com.LearningJava.restservice.RestApp.Repository; import com.LearningJava.restservice.RestApp.Model.User; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface AuthRepository extends MongoRepository<User,String> { @Query("{'email' : ?0}") public Optional<User> findByEmail(String email); }
true
d9aedff6f8e8e8c943f8e446e888331edd5fc5b8
Java
oronpaz/Java_To_Spring_Convertor
/Medium_Spring_Examples/Hash_password/Spring/src/main/java/Main.java
UTF-8
559
2.15625
2
[]
no_license
import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfiguration.class); RegisterManager registerManager = ctx.getBean("registerManager", RegisterManager.class); try { registerManager.run(); } catch (Exception ex) { System.out.println(ex.getMessage()); } } }
true
270fd6c9b3a788196ff93d66d8e7e52849a1ede0
Java
Vishnupriya7575/Practice
/ValidateIPAddress.java
UTF-8
921
3.296875
3
[]
no_license
package Programs; import org.apache.commons.validator.routines.InetAddressValidator; // Java program to validate <tt>IPv4</tt> and <tt>IPv6</tt> address class ValidateIPAddress { // an IPv4 address private static final String INET4ADDRESS = "172.8.9.28"; // an IPv6 address private static final String INET6ADDRESS = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"; public static void main(String[] args) { InetAddressValidator validator = new InetAddressValidator(); if(validator.isValid(INET4ADDRESS)) { System.out.println("The IP Address is" + INET4ADDRESS + "is valid"); } else { System.out.println("The IP Address is" + INET4ADDRESS + "not valid"); } if(validator.isValidInet4Address(INET6ADDRESS)) { System.out.println("The IP Address is" + INET6ADDRESS + "is valid"); } else { System.out.println("The IP Address is" + INET6ADDRESS + "is not valid"); } } }
true
4e6973ab1d896f54c35e2756af0e443c08f29c40
Java
RyanTech/android-apk-parser
/src/main/java/com/broadwave/android/content/pm/PackageItemInfo.java
UTF-8
2,627
2.25
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2007 The Android Open Source Project * * 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.broadwave.android.content.pm; import java.awt.Image; /** * Base class containing information common to all package items held by the * package manager. This provides a very common basic set of attributes: a * label, icon, and meta-data. This class is not intended to be used by itself; * it is simply here to share common definitions between all items returned by * the package manager. As such, it does not itself implement Parcelable, but * does provide convenience methods to assist in the implementation of * Parcelable in subclasses. */ public class PackageItemInfo { /** * Public name of this item. From the "android:name" attribute. */ public String name; /** * Name of the package that this item is in. */ public String packageName; /** * A string resource identifier (in the package's resources) of this * component's label. From the "label" attribute or, if not set, 0. */ public int labelRes; /** * label string resource read from APK. */ public CharSequence localizedLabel; /** * The string provided in the AndroidManifest file, if any. You probably * don't want to use this. You probably want * {@link PackageManager#getApplicationLabel} */ public CharSequence nonLocalizedLabel; /** * A drawable resource identifier (in the package's resources) of this * component's icon. From the "icon" attribute or, if not set, 0. */ public int icon; /** * Buffered Image read from APK. */ public Image iconImage; // /** // * A drawable resource identifier (in the package's resources) of this // * component's logo. Logos may be larger/wider than icons and are // * displayed by certain UI elements in place of a name or name/icon // * combination. From the "logo" attribute or, if not set, 0. // */ // public int logo; }
true
11b2792827a35a597e6357f46b9dfe8bc0df0258
Java
ksenia-vyushkova/KseniiaViushkova
/src/main/java/base/BasicTestBase.java
UTF-8
261
1.976563
2
[]
no_license
package base; import org.testng.annotations.BeforeSuite; public class BasicTestBase { @BeforeSuite(alwaysRun = true) public void beforeSuite() { System.setProperty("webdriver.chrome.driver", "src\\main\\resources\\chromedriver.exe"); } }
true
6cbc24cf95f91f30654091f55ac28bd6cb1bed36
Java
twintial/DisneyLandSimulation
/src/disney/place/shop/goods/PackageFactory.java
UTF-8
479
2.5625
3
[]
no_license
package disney.place.shop.goods; import disney.constant.PackageName; import java.util.HashMap; //用到的设计模式有 原型模式 /** * {@PackageFactory} class 是用于创建包装袋的方法 */ public class PackageFactory { public static HashMap<PackageName, Package> packageMap; static { //initiate packageMap } public static Package getPackage(PackageName packageName){ return (Package) packageMap.get(packageName).clone(); } }
true
d29c527d20832c8ed08d55afb66bfc0423618ebe
Java
manu2315/Caravana2
/app/src/main/java/calculatuesfuerzo/finsol/com/mx/calcula/providers/Provider.java
UTF-8
5,130
2.375
2
[]
no_license
package calculatuesfuerzo.finsol.com.mx.calcula.providers; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import calculatuesfuerzo.finsol.com.mx.calcula.adapters.Model; public class Provider<V extends Model> { private static final String SLASH = "/"; private static final String NODE_RED_OPERATIVA = "red_operativa"; private static final String NODE_DIVISIONALES = "divisionales"; private static final String NODE_REGIONALES = "regionales"; private static final String NODE_SUCURSALES = "gerentes"; public static final String NODE_USUARIO_LOGIN = "usuarios_login/"; private static final String NODE_PARAM_STRING = "%s"; public static final String NODE_ASESORES = "asesores/"; private static final String DINAMIC_DIVISIONAL = NODE_DIVISIONALES + SLASH + NODE_PARAM_STRING; private static final String DINAMIC_REGIONAL = NODE_REGIONALES + SLASH + NODE_PARAM_STRING; private static final String DINAMIC_SUCURSAL = NODE_SUCURSALES + SLASH + NODE_PARAM_STRING; private static final String DINAMIC_ASESOR = NODE_ASESORES + NODE_PARAM_STRING; public static String getDinamicDivisional(String divisional) { return String.format(DINAMIC_DIVISIONAL, divisional); } public static String getDinamicRegional(String regional) { return String.format(DINAMIC_REGIONAL, regional); } public static String getDinamicSucursal(String sucursal) { return String.format(DINAMIC_SUCURSAL, sucursal); } public static String getDinamicAsesor(String asesor) { return String.format(DINAMIC_ASESOR, asesor); } public static final String PATH_RED_OPERATIVA = NODE_RED_OPERATIVA; private static final FirebaseDatabase mDatabase; static{ mDatabase = FirebaseDatabase.getInstance(); } public static DatabaseReference addValueEventListener(String firebasePath, boolean keepSynced, ValueEventListener valueEventListener) { DatabaseReference ref = mDatabase.getReference(firebasePath); ref.keepSynced(keepSynced); ref.addValueEventListener(valueEventListener); return ref; } public static DatabaseReference addChildEventListener(String firebasePath, boolean keepSynced, ChildEventListener childEventListener) { DatabaseReference ref = mDatabase.getReference(firebasePath); ref.keepSynced(keepSynced); ref.addChildEventListener(childEventListener); return ref; } public static DatabaseReference addListenerForSingleValueEvent(String firebasePath, boolean keepSynced, ValueEventListener valueEventListener) { DatabaseReference ref = mDatabase.getReference(firebasePath); ref.keepSynced(keepSynced); ref.addListenerForSingleValueEvent(valueEventListener); return ref; } public static void updateValue(String path, Object value){ mDatabase.getReference(path).setValue(value); } public static String pushValue(String path, Object value){ DatabaseReference ref = mDatabase.getReference(path).push(); ref.setValue(value); return ref.getKey(); } public static void guardarFirebase(String path, Object value){ DatabaseReference ref = mDatabase.getReference(path).push(); ref.setValue(value); } <T extends Model> T parseDatasnapshot(DataSnapshot dataSnapshot, Class<T> type) { if(dataSnapshot.getValue()!=null){ T t = dataSnapshot.getValue(type); t.setKey(dataSnapshot); return t; }else{ return null; } } private ModelValueEventListener<V> mModelValueEventListener; private Class<V> mType; public Provider(Class<V> type) { this.mType = type; } public DatabaseReference addGenericValueEventListener(String node, ModelValueEventListener<V> modelValueEventListener){ this.mModelValueEventListener = modelValueEventListener; return Provider.addValueEventListener(node, false, new ValueEventListenerImpl()); } class ValueEventListenerImpl implements ValueEventListener { @Override public void onDataChange(DataSnapshot dataSnapshot) { V v = parseDatasnapshot(dataSnapshot, mType); mModelValueEventListener.onDataChange(v); } @Override public void onCancelled(DatabaseError databaseError) { mModelValueEventListener.onCancelled(databaseError); } } public interface ModelChildEventListener<T>{ void onChildAdded(T t); void onChildChanged(T t); void onChildRemoved(T t); void onChildMoved(T t); void onCancelled(DatabaseError databaseError); } public interface ModelValueEventListener<T>{ void onDataChange(T t); void onCancelled(DatabaseError databaseError); } }
true
12817ad2ed9ebf05beca4d01d480858741275ad3
Java
williambernardesf/compasso_avaliacao
/src/main/java/net/javaguides/springboot/controller/DisciplinaController.java
UTF-8
2,951
2.46875
2
[]
no_license
package net.javaguides.springboot.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import net.javaguides.springboot.model.Disciplina; import net.javaguides.springboot.service.DisciplinaFuncao; @Controller @RequestMapping("disciplinas") public class DisciplinaController { @Autowired private DisciplinaFuncao disciplinaFuncao; // display list of employees @GetMapping() public String viewHomePage(Model model) { return findPaginated(1, "nome", "asc", model); } @GetMapping("/mostraNovaDisciplinaForm") public String mostraNovaDisciplinaForm(Model model) { // create model attribute to bind form data Disciplina disciplina = new Disciplina(); model.addAttribute("disciplina", disciplina); return "nova_disciplina"; } @PostMapping("/registraDisciplina") public String registraDisciplina(@ModelAttribute("disciplina") Disciplina disciplina) { // save employee to database disciplinaFuncao.registraDisciplina(disciplina); return "redirect:/disciplinas"; } @GetMapping("/showFormForUpdate/{id}") public String showFormForUpdate(@PathVariable(value = "id") long id, Model model) { // get employee from the service Disciplina disciplina = disciplinaFuncao.listaDisciplinaId(id); // set employee as a model attribute to pre-populate the form model.addAttribute("disciplina", disciplina); return "atualiza_disciplina"; } @GetMapping("/deleteDisciplina/{id}") public String deleteDisciplina(@PathVariable(value = "id") long id) { // call delete employee method this.disciplinaFuncao.excluiDisciplinaId(id); return "redirect:/disciplinas"; } @GetMapping("/page/{pageNo}") public String findPaginated(@PathVariable(value = "pageNo") int pageNo, @RequestParam("sortField") String sortField, @RequestParam("sortDir") String sortDir, Model model) { int pageSize = 5; Page<Disciplina> page = disciplinaFuncao.findPaginated(pageNo, pageSize, sortField, sortDir); List<Disciplina> listDisciplinas = page.getContent(); model.addAttribute("currentPage", pageNo); model.addAttribute("totalPages", page.getTotalPages()); model.addAttribute("totalItems", page.getTotalElements()); model.addAttribute("sortField", sortField); model.addAttribute("sortDir", sortDir); model.addAttribute("reverseSortDir", sortDir.equals("asc") ? "desc" : "asc"); model.addAttribute("listDisciplinas", listDisciplinas); return "index_disciplina"; } }
true