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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
be6f2a2373057b2f0ae84dd9f8586a4e78af1170 | Java | HugoG7/CodeChallenges | /src/main/java/com/hg/challenges/OneEdit.java | UTF-8 | 1,451 | 3.359375 | 3 | [] | no_license | package com.hg.challenges;
/** DONE **/
public class OneEdit {
public static void main(String[] args) {
System.out.println("Is this pair of words 'One edit' away? => " + isOneEdit("cat", "dog") );
System.out.println("Is this pair of words 'One edit' away? => " + isOneEdit("cat", "cats") );
System.out.println("Is this pair of words 'One edit' away? => " + isOneEdit("cat", "cut") );
System.out.println("Is this pair of words 'One edit' away? => " + isOneEdit("cat", "cast") );
System.out.println("Is this pair of words 'One edit' away? => " + isOneEdit("cat", "at") );
System.out.println("Is this pair of words 'One edit' away? => " + isOneEdit("cat", "act") );
System.out.println("Is this pair of words 'One edit' away? => " + isOneEdit("cat", "amo") );
System.out.println("Is this pair of words 'One edit' away? => " + isOneEdit("cat", "cap") );
}
static boolean isOneEdit(String word1, String word2) {
int auxOneCharReplaced = 0;
if(word1.length() != word2.length()) {
//CHAR ADDED OR REMOVED VALIDATION
int diff = word1.length() - word2.length();
//3 - 2 = 1 REMOVED
//3 - 4 = -1 INSERTED
if(!(diff == -1 || diff == 1)) {
return false;
}
}else {
//CHAR REPLACED VALIDATION
for(int i = 0; i < word1.length(); i++) {
auxOneCharReplaced += word1.charAt(i) == word2.charAt(i) ? 0 : 1;
if(auxOneCharReplaced > 1) {
return false;
}
}
}
return true;
}
}
| true |
4f9ff890e1c50f5606726e36de1e1586a1456cf5 | Java | ohtaeg/algorithm-study | /src/main/java/book/part2/binarysearch/component/ComponentBinarySearch.java | UTF-8 | 1,977 | 3.8125 | 4 | [] | no_license | package book.part2.binarysearch.component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
* 부품 찾기
*/
public class ComponentBinarySearch {
private static final String YES = "YES";
private static final String NO = "NO";
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(bufferedReader.readLine());
String[] components = bufferedReader.readLine().split(" ");
int m = Integer.parseInt(bufferedReader.readLine());
String[] targets = bufferedReader.readLine().split(" ");
StringBuilder result = new StringBuilder();
for (String target : targets) {
result.append(find(components, target));
}
System.out.println(result.toString());
bufferedReader.close();
}
private static String find(final String[] array, final String target) {
final int[] components = convertIntegerArray(array);
Arrays.sort(components);
return searchBinary(components, Integer.parseInt(target), 0, components.length - 1);
}
private static int[] convertIntegerArray(final String[] array) {
return Arrays.stream(array)
.mapToInt(Integer::parseInt)
.toArray();
}
private static String searchBinary(final int[] components, final int target, int start, int end) {
if (start > end) {
return NO;
}
int mid = (start + end) / 2;
if (components[mid] == target) {
return YES;
}
if (components[mid] > target) {
return searchBinary(components, target, start, mid - 1);
}
if (components[mid] < target) {
return searchBinary(components, target, mid + 1, end);
}
return NO;
}
}
| true |
6c58bcc8d934a9fceb6b2b0f3cb3e73490f3bac9 | Java | hanjaeguk/WebStudy | /boardmvc/src/com/kitri/action/admin/board/AdminBoardMakeAction.java | UTF-8 | 991 | 2.46875 | 2 | [] | no_license | package com.kitri.action.admin.board;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.kitri.action.Action;
public class AdminBoardMakeAction implements Action {
//싱글톤 패턴
//1.외부에서 생성자접근 못하게 private로 막아라
//2.private static으로 자기자신을 리턴
//3.하나만 만들어되니깐 static으로 객체 생성
//4.외부에서 접근하게 public의 getter
//2.
private static Action adminBoardMakeAction;
//3.
static {
adminBoardMakeAction = new AdminBoardMakeAction();
}
//1.
private AdminBoardMakeAction() {}
//4.
public static Action getAdminBoardMakeAction() {
return adminBoardMakeAction;
}
@Override
public String excute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
return null;
}
}
| true |
c23459b9eca5a06796603fd90e4a4846e5ae2793 | Java | yeo-l/enterprise-manager-server | /src/main/java/org/hispci/enterprisemanager/repositories/employments/employees/StaffPostRepository.java | UTF-8 | 534 | 1.890625 | 2 | [] | no_license | package org.hispci.enterprisemanager.repositories.employments.employees;
import org.hispci.enterprisemanager.domain.employment.employees.Staff;
import org.hispci.enterprisemanager.domain.employment.employees.StaffPost;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import java.util.List;
@RepositoryRestResource
public interface StaffPostRepository extends JpaRepository<StaffPost, Long> {
List<StaffPost> findByStaff(Staff staff);
}
| true |
c43792cff5f171c63a279badba40fda8c1c7a0d2 | Java | trungdeveloper/vuong_project | /src/project/Reference.java | UTF-8 | 578 | 2.59375 | 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 project;
public class Reference extends Book {
public Reference() {
super();
this.category = "Reference";
}
public Reference(String name, String authorName, String publisher, double price, String dateOfPucharse, int rackNumber) {
super(name, authorName, publisher, price, dateOfPucharse, rackNumber);
this.category = "Reference";
}
}
| true |
198e4b627a91f7debc5c01f3954da77814a64354 | Java | efquinajo/FidoTest | /Fido/src/main/java/gob/adsib/fido/BaseKeyStore.java | UTF-8 | 1,184 | 2.046875 | 2 | [] | no_license | package gob.adsib.fido;
import gob.adsib.fido.data.KeyAndCertificate;
import gob.adsib.fido.stores.profiles.AbstractInfo;
import java.security.cert.X509Certificate;
import java.util.List;
/**
*
* @author UID-ADSIB
*/
public abstract class BaseKeyStore {
public abstract AbstractInfo getInfo(long slot) throws Exception;
public abstract void login(String pin,long slot) throws Exception;
public abstract void logout() throws Exception;
public abstract long[] getSlots() throws Exception;
public abstract boolean isAuthenticated();
public abstract KeyAndCertificate getKeyAndCertificate(String alias) throws Exception;
public abstract String updateCertificate(String alias,X509Certificate x509Certificate) throws Exception;
public abstract KeyAndCertificate generateKeyAndCertificate(String alias) throws Exception;
public abstract List<String> getAlieces() throws Exception;
public static String generateRandomAlias(){
String randomAlias = String.valueOf((long)Double.parseDouble(""+Math.random()*100000000000000L));
return randomAlias;
}
public abstract void removeKeyPair(String alias) throws Exception;
} | true |
175a53bad0c7ce64c97b5787bbdcc2f6506159b2 | Java | happy6eve/AppPackager | /02_SourceCode/.svn/pristine/17/175a53bad0c7ce64c97b5787bbdcc2f6506159b2.svn-base | UTF-8 | 3,770 | 1.992188 | 2 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"ISC",
"BSD-3-Clause"
] | permissive | package com.elab.zyzz.user.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.elab.zyzz.user.R;
import com.elab.zyzz.common.ui.BaseActivity;
import com.elab.zyzz.core.utils.ToastUtils;
import com.elab.zyzz.common.utils.StatisticsDataConstant;
import com.elab.zyzz.user.R2;
import com.elab.zyzz.user.listener.ICommonHandleView;
import com.elab.zyzz.user.webservice.UserRequestApi;
import java.util.HashMap;
import java.util.Map;
import butterknife.BindView;
import butterknife.OnClick;
public class ForgetPasswordTwoActivity extends BaseActivity implements ICommonHandleView {
private Context context;
@BindView(R2.id.txt_title)
TextView titView;
@BindView(R2.id.new_password)
EditText setPassword;
@BindView(R2.id.renew_password)
EditText resetPassword;
@BindView(R2.id.reset_submit)
Button submit;
@BindView(R2.id.img_back)
ImageView goBack;
private UserRequestApi userRequestApi;
private String password1, password2, loginid;
private Handler handler = new Handler();
@Override
public void create() {
context = this;
Intent intent = this.getIntent();
loginid = intent.getStringExtra("loginid");
titView.setText("找回密码");
goBack.setVisibility(View.VISIBLE);
statisticsData(StatisticsDataConstant.PageNameConstant.PAGE_00037,StatisticsDataConstant.STATISTICS_TYPE_1);
userRequestApi = new UserRequestApi(this);
}
@Override
public int getContentView() {
return R.layout.layout_forget_step_two;
}
@Override
public void initData() {
}
@Override
public void destroy() {
statisticsData(StatisticsDataConstant.PageNameConstant.PAGE_00037,StatisticsDataConstant.STATISTICS_TYPE_2);
}
@OnClick({R2.id.reset_submit, R2.id.img_back})
public void onClick(View v) {
if(v.getId() == R.id.reset_submit){
submit();
}
if(v.getId() == R.id.img_back){
finishAcMove();
}
}
private void submit(){
password1 = setPassword.getText().toString().trim();
password2 = resetPassword.getText().toString().trim();
if(password1.length() == 0 || password2.length() == 0){
Toast.makeText(context, "密码必须6位以上或者密码过于简单", Toast.LENGTH_SHORT).show();
return;
}
if(password1.length() < 6 || password2.length() < 6){
Toast.makeText(context, "密码必须6位以上或者密码过于简单", Toast.LENGTH_SHORT).show();
return;
}
if(password1.length() != 0 && password2.length() != 0 && !password1.equals(password2)){
Toast.makeText(context, "两次输入密码不一致", Toast.LENGTH_SHORT).show();
return;
}else{
resetPassword();
}
}
private void resetPassword(){
dialog.setMessage("");
dialog.show();
Map<String, String> map = new HashMap<String, String>();
map.put("mobile", loginid);
map.put("password", password1);
userRequestApi.forgetPasswordStep2(map);
}
//忘记密码第二步成功后跳转至密码登录页面
private void startSkip(){
// Intent intent = new Intent(context, LoginByPasswordActivity.class);
// intent.putExtra("front", "two");
// startActivity(intent);
finishAcMove();
}
@Override
public void handleData(boolean bool, int step, String message) {
if(bool) {
ToastUtils.showShort(context, "密码更新成功,赶快去登录吧");
handler.postDelayed(new Runnable() {
@Override
public void run() {
startSkip();
}
}, 200);
}else {
ToastUtils.showShort(context, message);
}
}
}
| true |
a09983bfee85c4f570fe38a17dcf1e364e45c9c4 | Java | openspim/micro-OpenSPIM | /src/main/java/spim/ui/view/component/util/NumberFieldTableCell.java | UTF-8 | 1,677 | 2.546875 | 3 | [] | no_license | package spim.ui.view.component.util;
import javafx.event.EventHandler;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.MouseEvent;
import javafx.util.Callback;
import javafx.util.StringConverter;
import javafx.util.converter.DefaultStringConverter;
/**
* Author: HongKee Moon (moon@mpi-cbg.de), Scientific Computing Facility
* Organization: MPI-CBG Dresden
* Date: July 2019
*/
public class NumberFieldTableCell<S,T> extends TextFieldTableCell<S,T>
{
public static <S> Callback<TableColumn<S,String>, TableCell<S,String>> forTableColumn() {
return forTableColumn(new DefaultStringConverter());
}
public static <S,T> Callback<TableColumn<S,T>, TableCell<S,T>> forTableColumn(
final StringConverter<T> converter) {
return list -> new NumberFieldTableCell<S,T>(converter);
}
static NumberFieldTableCell lastCell;
NumberFieldTableCell(StringConverter<T> converter) {
super(converter);
this.addEventFilter( MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (event.getClickCount() > 1) {
NumberFieldTableCell c = (NumberFieldTableCell) event.getSource();
lastCell = c;
lastCell.startSuperStartEdit();
} else {
if (lastCell != null && !lastCell.equals(event.getSource())) {
lastCell.cancelEdit();
lastCell = null;
}
}
}
});
}
@Override public void startEdit() {
if (! isEditable()
|| ! getTableView().isEditable()
|| ! getTableColumn().isEditable()) {
return;
}
}
void startSuperStartEdit() {
super.startEdit();
}
}
| true |
001ed3a51ce25ad69ac09b72283ed73190785419 | Java | Ash222/DSA | /src/problems/DP/Leetcode22/Solution.java | UTF-8 | 1,643 | 3.875 | 4 | [
"MIT"
] | permissive | package problems.DP.Leetcode22;
/*
Problem Statement : Generate Parenthesis
Given n pairs of parentheses, write a function to generate all combinations of
well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
*/
import java.util.ArrayList;
import java.util.List;
public class Solution {
private static List< String > generateParenthesis( int n ) {
List< String > storage = new ArrayList<>();
parenthesis( storage , "" , n , n );
System.out.println( "Total length : " + storage.size() );
return storage;
}
private static List< String > parenthesis( List< String > storage , String currentString ,
int openBracketCount , int closeBracketCount ) {
// bounding condition.
if ( openBracketCount == 0 && closeBracketCount == 0 ) {
storage.add( currentString );
}
if ( openBracketCount <= closeBracketCount && openBracketCount >= 0 ) {
parenthesis( storage , currentString + "(" ,
openBracketCount - 1 , closeBracketCount );
}
if ( closeBracketCount >= openBracketCount && closeBracketCount >= 0 ) {
parenthesis( storage , currentString + ")" , openBracketCount ,
closeBracketCount - 1 );
}
return storage;
}
public static void main( String[] args ) {
System.out.println( generateParenthesis( 5 ) );
}
}
| true |
3240fc1e3d35798303bbfffebea766bf4a548d7a | Java | vishnudivakar31/Daily-Challenges | /Triplets/src/edu/njit/Main.java | UTF-8 | 1,443 | 3.046875 | 3 | [] | no_license | package edu.njit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
System.out.println(threeSum(new int[] {1, -1, -1, -0}));
}
public static List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> triplets = null;
List<String> tripletCache = new ArrayList<String>();
int sum = 0;
for(int i = 0; i < nums.length - 2; i++) {
sum = nums[i];
triplets = null;
for(int j = i + 1; j < nums.length; j++) {
if(triplets == null) {
triplets = new ArrayList<Integer>();
triplets.add(nums[i]);
}
sum += nums[j];
triplets.add(nums[j]);
if(triplets.size() == 3) {
if(sum == 0) {
Collections.sort(triplets);
if(!tripletCache.contains(triplets.toString())) {
result.add(triplets);
tripletCache.add(triplets.toString());
}
}
triplets = null;
sum = nums[i];
}
}
}
return result;
}
}
| true |
62f9b3b7a591f3fe381a0f9df77f8688560c842e | Java | google-code/apco | /apco-server/src/main/java/org/spbsu/apco/server/taskset/BagOfTasks.java | UTF-8 | 847 | 2.3125 | 2 | [] | no_license | package org.spbsu.apco.server.taskset;
import org.spbsu.apco.common.task.core.TaskDescriptor;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.util.Assert;
import java.util.Set;
/**
* User: mikpan
* Date: 1/21/13
* Time: 7:39 PM
*/
public class BagOfTasks extends BaseTaskSet {
private Set<TaskDescriptor> taskDescriptors;
@Required
public void setTaskDescriptors(Set<TaskDescriptor> taskDescriptors) {
Assert.notEmpty(taskDescriptors, "Bag of taskDescriptors cannot be empty");
this.taskDescriptors = taskDescriptors;
}
@Override
public void initializeTasks() {
for (TaskDescriptor taskDescriptor : taskDescriptors) {
addLeafTask(taskDescriptor.getBaseTask(), taskDescriptor.getInput());
}
}
}
| true |
2d49c39d1836f1d87142e4b03bc9947f27b08ed0 | Java | maxminute/algorithm006-class02 | /Week_02/G20200343030606/LeetCode_589_606.java | UTF-8 | 1,467 | 3.796875 | 4 | [] | no_license | /*
* @lc app=leetcode.cn id=589 lang=java
*
* [589] N叉树的前序遍历
*
* https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/description/
*
* algorithms
* Easy (71.85%)
* Likes: 66
* Dislikes: 0
* Total Accepted: 18.4K
* Total Submissions: 25.5K
* Testcase Example: '[1,null,3,2,4,null,5,6]'
*
* 给定一个 N 叉树,返回其节点值的前序遍历。
*
* 例如,给定一个 3叉树 :
*
*
*
*
*
*
*
* 返回其前序遍历: [1,3,5,6,2,4]。
*
*
*
* 说明: 递归法很简单,你可以使用迭代法完成此题吗?
*/
// @lc code=start
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
private List<Integer> res = new ArrayList<Integer>();
public List<Integer> preorder(Node root) {
helper(root);
return res;
}
public void helper(Node node) {
// 下面节点不存在了结束
if (node == null){
return;
}
// 添加树的节点的值
res.add(node.val);
int size = node.children.size();
for (int i = 0 ; i < size ;i ++){
// 进入树的下一层
helper(node.children.get(i));
}
}
}
// @lc code=end
| true |
03a74469e4d7e32966aae218b62f31e073010747 | Java | BurpSuite03/leetCode | /src/IO/ListTest.java | UTF-8 | 424 | 3.25 | 3 | [] | no_license | package IO;
import java.util.ArrayList;
import java.util.List;
public class ListTest {
public static void main(String args[]) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
int tag =0;
for (int i = 0; i < list.size(); i++) {
if (list.get(i-tag)==2 || list.get(i-tag)==4) {
list.remove(i-tag);
tag++;
}
}
System.out.println(list);
}
}
| true |
28cca008379de72447e019794b0760ab39eca493 | Java | Korman2018/BookLibrary_finalProject | /src/main/java/com/epam/bookLibrary/model/Status.java | UTF-8 | 508 | 2.65625 | 3 | [] | no_license | package com.epam.bookLibrary.model;
import com.epam.bookLibrary.model.abstracts.AbstractEnum;
import java.io.Serializable;
public class Status extends AbstractEnum implements Serializable {
public Status(String description) {
super(description);
}
// по умолчанию статус = запрос
public Status() {
super("запрос");
setId(1);
}
@Override
public String toString() {
return getId() + ". " + getDescription();
}
}
| true |
0c55cd5d57b63de000d54662faf3d08cd788f115 | Java | gskebin/Workspace | /0525/src/parkjugod/Ex03p.java | UTF-8 | 356 | 2.921875 | 3 | [] | no_license | package parkjugod;
import java.util.Scanner;
public class Ex03p {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("숫자를 써라 : ");
int num = s.nextInt();
int n = 1;
int a = 1;
while (num / n != 0) {
System.out.println(a + " / " + n);
a++;
n = n * 10;
}
}
}
| true |
1fee320de2070a96f43fdb2fd8d64ee264700bc7 | Java | JanLiao/LeetCode_Algorithm | /src/com/jan/CS407/exp2/MyHttpServer.java | UTF-8 | 2,651 | 2.953125 | 3 | [] | no_license | package com.jan.CS407.exp2;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author jan
* @data 2019年10月20日 上午11:42:14
*/
public class MyHttpServer {
private static ExecutorService bootstrapExecutor = Executors.newSingleThreadExecutor();
private static ExecutorService taskExecutor;
private static int PORT = 8899;
public static void startHttpServer() {
int nThreads = Runtime.getRuntime().availableProcessors();
taskExecutor =
new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(100),
new ThreadPoolExecutor.DiscardPolicy());
while (true) {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
bootstrapExecutor.submit(new ServerThread(serverSocket));
break;
} catch (Exception e) {
try {
//重试
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
}
bootstrapExecutor.shutdown();
}
private static class ServerThread implements Runnable {
private ServerSocket serverSocket;
public ServerThread(ServerSocket s) throws IOException {
this.serverSocket = s;
}
@Override
public void run() {
while (true) {
try {
System.out.println("start listen--------------");
Socket socket = this.serverSocket.accept();
System.out.println("------------enter ");
HttpTask eventTask = new HttpTask(socket);
taskExecutor.submit(eventTask);
} catch (Exception e) {
e.printStackTrace();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
}
}
}
public static void main(String[] args) {
System.out.println("===========");
SessionThread st = new SessionThread();
Thread thread = new Thread(st);
thread.start();
startHttpServer();
}
}
| true |
a2bdf1ae1302e2cf07c0271abf1e920f47744c8f | Java | mahendrakishore/JavaTution | /JavaTution/src/com/pratice/Grade.java | UTF-8 | 339 | 2.640625 | 3 | [] | no_license | package com.pratice;
public class Grade {
public static void main(String[] args) {
// TODO Auto-generated method stub
double grade = -20.00 ;
if(grade>0 && grade<50){
System.out.println("avg student");
}
else if(grade>50){
System.out.println("grade upper");
}
else{
System.out.println("poor student");
}
}
}
| true |
f1372e32bad6a0e44cf059e95d5471b92aa3b47f | Java | Dp-Android-2018/NabbtaBase | /app/src/main/java/dp/com/nabbtabase/view/viewholder/PaymentViewModel.java | UTF-8 | 792 | 2.203125 | 2 | [] | no_license | package dp.com.nabbtabase.view.viewholder;
import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import android.support.annotation.NonNull;
import dp.com.nabbtabase.servise.model.request.CreateOrderRequest;
import dp.com.nabbtabase.servise.repository.CreateOrderRepository;
public class PaymentViewModel extends AndroidViewModel {
private LiveData<Integer>code;
public PaymentViewModel(@NonNull Application application, CreateOrderRequest request) {
super(application);
System.out.println("enter view Model :"+request.getAddressId());
code=CreateOrderRepository.getInstance().createOrder(application,request);
}
public LiveData<Integer> getCode() {
return code;
}
}
| true |
fcac1100091e318ceee01d84dcbc181628cd076c | Java | Robi02/HomeStudy | /Java/effective3/_12_serialize/Item90.java | UTF-8 | 2,508 | 3.4375 | 3 | [] | no_license | package _12_serialize;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Date;
public class Item90 {
/**
* [Item90] 직렬화된 인스턴스 대신 직렬화 프록시 사용을 검토하라
*
* [핵심]
* 제 3자가 호가장할 수 없는 클래스라면 가능한 한 직렬화 프록시 패턴을 사용하자.
* 이 패턴이 아마도 중요한 불변식을 안정적으로 직렬화해주는 가장 쉬운 방법일 것이다.
* (단, 방어적 복사 때보다 14%정도 느린 성능을 보일 수 있다.)
*
* [한계]
* 1. 클라이언트가 멋대로 확장할 수 있는 클래스에는 적용할 수 없다.
* 2. 객체 그래프에 순환이 있는 클래스에 적용할 수 없다.
*
*/
// Item50의 Period클래스
public static final class Period {
private final Date start;
private final Date end;
public Period(Date start, Date end) {
this.start = new Date(start.getTime());
this.end = new Date(end.getTime());
if (this.start.compareTo(this.end) > 0) {
throw new IllegalArgumentException(
this.start + "가 " + this.end + "보다 늦다.");
}
}
public Date start() {
return new Date(this.start.getTime());
}
public Date end() {
return new Date(this.end.getTime());
}
// 추가됨: 직렬화 프록시 패턴용 writeReplace 메서드
private Object writeReplace() {
return new SerializationProxy(this);
}
// 추가됨: 직렬화 프록시 패턴용 readObject 메서드
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
// 불변식 훼손 시도를 가볍게 막아낼 수 있다
throw new InvalidObjectException("프록시가 필요합니다.");
}
}
public static class SerializationProxy implements Serializable {
private final Date start;
private final Date end;
SerializationProxy(Period p) {
this.start = p.start;
this.end = p.end;
}
// Period.SerializationProxy용 readResolve 메서드
private Object readResolve() {
return new Period(start, end);
}
private static final long serialVersionUID = 2340982438234858285L;
}
} | true |
11a6a1b003c9bee2b724fab98bf173276caedaa7 | Java | tpinkston/discover | /src/discover/vdis/enums/PDU_STATUS_DMI.java | UTF-8 | 1,028 | 2.25 | 2 | [] | no_license | package discover.vdis.enums;
import java.util.List;
/**
* PDU_STATUS_DMI: This class is auto-generated by vdis.EnumGenerator
*/
public final class PDU_STATUS_DMI extends Value {
public static final PDU_STATUS_DMI
GUISE_MODE = new PDU_STATUS_DMI(0, "GUISE_MODE", "Guise Mode", true),
DISGUISE_MODE = new PDU_STATUS_DMI(1, "DISGUISE_MODE", "Disguise Mode", true);
private PDU_STATUS_DMI(int value, String name, String description, boolean known) {
super(value, name, description, known);
cache(this, PDU_STATUS_DMI.class);
}
/** @see Value#values(Class) */
public static List<PDU_STATUS_DMI> values() {
return values(PDU_STATUS_DMI.class);
}
/** @see Value#values(Class, boolean) */
public static List<PDU_STATUS_DMI> values(boolean known) {
return values(PDU_STATUS_DMI.class, known);
}
/** @see Value#get(int, Class) */
public static PDU_STATUS_DMI get(int value) {
return get(value, PDU_STATUS_DMI.class);
}
}
| true |
d1992fda6242ba113c3d82c66d6e25817195b38f | Java | dhileepankruschev/sample-app-service | /src/main/java/com/fse/wttracker/controller/WorkoutTrackerController.java | UTF-8 | 1,566 | 2.390625 | 2 | [] | no_license | package com.fse.wttracker.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
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.RestController;
import com.fse.wttracker.model.Workout;
import com.fse.wttracker.repository.WorkoutRepository;
@RestController
@CrossOrigin
@RequestMapping("/workout")
public class WorkoutTrackerController {
@Autowired
private WorkoutRepository workoutRepository;
@RequestMapping(value = "/fetchall", method = RequestMethod.GET)
public List<Workout> getAllWorkouts() {
/*
* Workout workout1 = new Workout(1, "Morning run for 5 mins from svc");
* Workout workout2 = new Workout(2,
* "Boxing practice for 10 mins from svc"); Workout workout3 = new
* Workout(3, "Chest and tricep workout for 10 mins from svc"); Workout
* workout4 = new Workout(4, "Evening walk for 30 mins from svc");
*
* List<Workout> workoutList = new ArrayList<>();
* workoutList.add(workout1); workoutList.add(workout2);
* workoutList.add(workout3); workoutList.add(workout4);
*/
return workoutRepository.findAll();
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public void saveWorkout(@RequestBody Workout workout) {
workout.setCategoryParent(workout.getCategory());
workoutRepository.save(workout);
}
}
| true |
95894a958156f998da97523b0d45de5e4f0637e7 | Java | AndersonTaday/SistemaFacturacionJugueteriaPagosLinea | /FrmClientes.java | UTF-8 | 37,808 | 2.21875 | 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 Vistas;
import Controlador.Conexion;
import Controlador.Controlador_Persona;
import Controlador.Controlador_Rol;
import Controlador.Controlador_Validar;
import Modelo.Persona;
import Modelo.Rol;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
/**
*
* @author James Romero
*/
public class FrmClientes extends javax.swing.JFrame {
/**
* Creates new form Clientes
*/
Controlador_Rol RolDB = new Controlador_Rol();
Controlador_Persona personadb = new Controlador_Persona();
Controlador_Validar val = new Controlador_Validar();
DefaultTableModel TablaCliente;
Conexion con = new Conexion();
Connection cn = con.conexion();
public FrmClientes() {
initComponents();
inicio();
mostrarDatos("");
}
private boolean ValidarCampos() {
boolean lleno = true;
if (txtNombre.getText().equals("") || txtApellido.getText().equals("") || txtCedula.getText().equals("")
|| txtTelefono.getText().equals("") || txtDireccion.getText().equals("") || txtCorreElectronico.getText().equals("")) {
lleno = false;
} else {
lleno = true;
}
return lleno;
}
private void ModificarTabla() {
JTCliente.getColumnModel().getColumn(0).setMaxWidth(0);
JTCliente.getColumnModel().getColumn(0).setMinWidth(0);
JTCliente.getColumnModel().getColumn(0).setPreferredWidth(0);
JTCliente.getColumnModel().getColumn(1).setPreferredWidth(220);
JTCliente.getColumnModel().getColumn(2).setPreferredWidth(220);
JTCliente.getColumnModel().getColumn(3).setPreferredWidth(220);
JTCliente.getColumnModel().getColumn(4).setPreferredWidth(220);
JTCliente.getColumnModel().getColumn(5).setPreferredWidth(220);
JTCliente.getColumnModel().getColumn(6).setPreferredWidth(220);
JTCliente.getColumnModel().getColumn(7).setPreferredWidth(220);
TablaCliente = (DefaultTableModel) JTCliente.getModel();
TablaCliente.setNumRows(0);
}
private void cargarTabla(String estado) {
List<Persona> lista = null;
lista = personadb.cargarClientes(estado, lista);
for (Persona persona : lista) {
TablaCliente.addRow(new Object[]{
persona.getIdPersona(), persona.getCI(), persona.getNombre(), persona.getApellido(), persona.getTelefono(), persona.getCorreoElectronico(), persona.getDireccion(), persona.getEstado()
});
}
}
private void mostrarDatos(String valor) {
DefaultTableModel modelo = new DefaultTableModel();
modelo.addColumn("Cédula");
modelo.addColumn("Nombre");
modelo.addColumn("Apellido");
modelo.addColumn("Teléfono");
modelo.addColumn("Correo Electrónico");
modelo.addColumn("Dirección");
modelo.addColumn("Estado");
JTCliente.setModel(modelo);
String sql = "";
if(valor.equals("")){
sql = "SELECT * FROM persona";
} else{
sql = "SELECT * FROM persona WHERE CI='"+valor+"'";
}
String[] datos = new String[7];
try {
Statement st = cn.createStatement();
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
datos[0] = rs.getString(2);
datos[1] = rs.getString(7);
datos[2] = rs.getString(3);
datos[3] = rs.getString(8);
datos[4] = rs.getString(4);
datos[5] = rs.getString(5);
datos[6] = rs.getString(6);
modelo.addRow(datos);
}
JTCliente.setModel(modelo);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error" + " " + e.getMessage(), "mensaje", JOptionPane.ERROR_MESSAGE);
}
}
private void inicio() {
ModificarTabla();
cargarTabla("A");
//CAMBIARLA VARIABLE ESTADO A STRING
// cargarTabla("");
}
private void cargarClientes(int id) {
Persona pe = personadb.TraeClienteId(id);
txtCedula.setText(pe.getCI());
txtNombre.setText(pe.getNombre());
txtApellido.setText(pe.getApellido());
txtDireccion.setText(pe.getDireccion());
txtTelefono.setText(pe.getTelefono());
txtCorreElectronico.setText(pe.getCorreoElectronico());
}
private void limpiar() {
txtCedula.setText(" ");
txtNombre.setText("");
txtApellido.setText("");
txtDireccion.setText("");
txtTelefono.setText("");
txtCorreElectronico.setText("");
}
private void buscaCliente(String ced) {
TablaCliente.setNumRows(0);
List<Persona> lis = null;
lis = personadb.buscarPersona(ced, lis);
if (lis.size() > 0) {
for (Persona perLis : lis) {
TablaCliente.addRow(new Object[]{
perLis.getIdPersona(), perLis.getCI(), perLis.getNombre(), perLis.getApellido(), perLis.getTelefono(), perLis.getCorreoElectronico(), perLis.getDireccion(), perLis.getEstado()
});
}
} else {
JOptionPane.showMessageDialog(null, "Cliente no encontrado", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
txtBuscarCedula.requestFocus();
inicio();
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
public void FrmMenu() {
Menu frm = new Menu();
frm.setVisible(true);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
txtBuscarCedula = new java.awt.TextField();
jPanel2 = new javax.swing.JPanel();
txtNombre = new java.awt.TextField();
txtApellido = new java.awt.TextField();
txtCedula = new java.awt.TextField();
txtTelefono = new java.awt.TextField();
jLabel4 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
btnAñadir = new javax.swing.JButton();
btnGuardar = new javax.swing.JButton();
jLabel7 = new javax.swing.JLabel();
txtDireccion = new java.awt.TextField();
jLabel5 = new javax.swing.JLabel();
txtCorreElectronico = new java.awt.TextField();
btnActivar_Desactivar = new javax.swing.JButton();
btnModificar = new javax.swing.JButton();
btnBuscar = new javax.swing.JButton();
btnAtras = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
JTCliente = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Cliente");
jPanel1.setBackground(new java.awt.Color(234, 250, 233));
jLabel6.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
jLabel6.setText("Cédula:");
txtBuscarCedula.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
txtBuscarCedula.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txtBuscarCedulaKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
txtBuscarCedulaKeyTyped(evt);
}
});
jPanel2.setBackground(new java.awt.Color(253, 242, 233));
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Dotos de cliente", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Courier New", 0, 12))); // NOI18N
txtNombre.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtNombreKeyTyped(evt);
}
});
txtApellido.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
txtApellido.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtApellidoKeyTyped(evt);
}
});
txtCedula.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
txtCedula.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtCedulaKeyTyped(evt);
}
});
txtTelefono.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
txtTelefono.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtTelefonoKeyTyped(evt);
}
});
jLabel4.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
jLabel4.setText("Teléfono:");
jLabel3.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
jLabel3.setText("CI:");
jLabel2.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
jLabel2.setText("Apellidos:");
jLabel1.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
jLabel1.setText("Nombres: ");
btnAñadir.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
btnAñadir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/añadir.png"))); // NOI18N
btnAñadir.setText("Añadir");
btnAñadir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAñadirActionPerformed(evt);
}
});
btnGuardar.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/guardar.png"))); // NOI18N
btnGuardar.setText("Guardar");
btnGuardar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnGuardarActionPerformed(evt);
}
});
jLabel7.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
jLabel7.setText("Dirección:");
txtDireccion.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
jLabel5.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
jLabel5.setText("Correo Electronico:");
txtCorreElectronico.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(90, 90, 90)
.addComponent(btnAñadir, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(75, 75, 75)
.addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtCorreElectronico, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(10, 10, 10))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 435, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(48, 48, 48))
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtCedula, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 435, Short.MAX_VALUE)
.addComponent(txtDireccion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtTelefono, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(txtApellido, javax.swing.GroupLayout.PREFERRED_SIZE, 436, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtApellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtCedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel7)
.addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtCorreElectronico, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(20, 20, 20)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnGuardar)
.addComponent(btnAñadir))
.addContainerGap())
);
btnActivar_Desactivar.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
btnActivar_Desactivar.setText("Activar/Desactivar");
btnActivar_Desactivar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnActivar_DesactivarActionPerformed(evt);
}
});
btnModificar.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
btnModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/modificar.png"))); // NOI18N
btnModificar.setText("Modificar");
btnModificar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnModificarActionPerformed(evt);
}
});
btnBuscar.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/buscar.png"))); // NOI18N
btnBuscar.setText("Buscar");
btnBuscar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBuscarActionPerformed(evt);
}
});
btnAtras.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
btnAtras.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/atras.png"))); // NOI18N
btnAtras.setText("Atrás");
btnAtras.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAtrasActionPerformed(evt);
}
});
JTCliente.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Cédula", "Nombre", "Apellido", "Teléfono", "Correo Electrónico", "Dirección", "Estado", "ID"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
JTCliente.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
JTClienteMouseClicked(evt);
}
});
jScrollPane2.setViewportView(JTCliente);
if (JTCliente.getColumnModel().getColumnCount() > 0) {
JTCliente.getColumnModel().getColumn(0).setResizable(false);
}
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtBuscarCedula, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane2))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(btnAtras, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(225, 225, 225))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(80, 80, 80)
.addComponent(btnModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(80, 80, 80)
.addComponent(btnActivar_Desactivar, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnActivar_Desactivar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnModificar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnBuscar, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtBuscarCedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6))
.addGap(12, 12, 12)))
.addGap(30, 30, 30)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addComponent(btnAtras, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnActivar_DesactivarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActivar_DesactivarActionPerformed
try {
int fila = JTCliente.getSelectedRow();
String valor = JTCliente.getValueAt(fila,7).toString();
if(valor.equals("A")){
PreparedStatement pst = cn.prepareStatement("UPDATE persona SET estado='D' WHERE CI='"+txtCedula.getText()+"'");
pst.executeUpdate();
mostrarDatos("");
JOptionPane.showMessageDialog(null, "Los datos se actualizaron correctamente", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
} else {
PreparedStatement pst = cn.prepareStatement("UPDATE persona SET estado='A' WHERE CI='"+txtCedula.getText()+"'");
pst.executeUpdate();
mostrarDatos("");
JOptionPane.showMessageDialog(null, "Los datos se actualizaron correctamente", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
}
} catch (SQLException ex) {
Logger.getLogger(FrmJuguete.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_btnActivar_DesactivarActionPerformed
private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarActionPerformed
try{
PreparedStatement pst = cn.prepareStatement("UPDATE persona SET apellido='"+txtApellido.getText()+"',correoElectronico='"+txtCorreElectronico.getText()+"',direccion='"+txtDireccion.getText()+"',estado='A',nombre='"+txtNombre.getText()+"',telefono='"+txtTelefono.getText()+"' WHERE CI='"+txtCedula.getText()+"'");
pst.executeUpdate();
mostrarDatos("");
JOptionPane.showMessageDialog(null, "Los datos se actualizaron correctamente", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e){
System.out.println(e.getMessage());
}
}//GEN-LAST:event_btnModificarActionPerformed
private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
if (txtBuscarCedula.getText().equals("")) {
JOptionPane.showMessageDialog(null, "LLENAR CAMPO REQUERIDO", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
} else {
mostrarDatos(txtBuscarCedula.getText());
}
}//GEN-LAST:event_btnBuscarActionPerformed
private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
Persona per = null;
if (btnGuardar.getText().equals("Guardar")) {
per = personadb.TraerClientes(txtCedula.getText());
if (per == null) {
if (ValidarCampos() == true) {
per = new Persona();
Rol r = new Rol();
r = RolDB.TraerRoles("Cliente");
per.setRol(r);
per.setCI(txtCedula.getText().trim());
per.setNombre(txtNombre.getText().trim());
per.setApellido(txtApellido.getText().trim());
per.setCorreoElectronico(txtCorreElectronico.getText().trim());
per.setDireccion(txtDireccion.getText().trim());
per.setTelefono(txtTelefono.getText().trim());
per.setEstado("A");
r.getPersonas().add(per);
personadb.Cliente(per);
JOptionPane.showMessageDialog(null, "Cliente Guardado exitoso", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Llenar campos sin escribir", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, "El número de cédula ya existe en el sistema", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
}
}
}//GEN-LAST:event_btnGuardarActionPerformed
private void btnAtrasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAtrasActionPerformed
// TODO add your handling code here:
FrmMenu();
this.dispose();
}//GEN-LAST:event_btnAtrasActionPerformed
private void JTClienteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JTClienteMouseClicked
int fila = JTCliente.getSelectedRow();
if (fila >=0 ){
txtCedula.setText(JTCliente.getValueAt(fila,1).toString());
txtNombre.setText(JTCliente.getValueAt(fila,2).toString());
txtApellido.setText(JTCliente.getValueAt(fila,3).toString());
txtTelefono.setText(JTCliente.getValueAt(fila,4).toString());
txtCorreElectronico.setText(JTCliente.getValueAt(fila,5).toString());
txtDireccion.setText(JTCliente.getValueAt(fila,6).toString());
} else {
JOptionPane.showMessageDialog(null, "Seleccione un juguete");
}
}//GEN-LAST:event_JTClienteMouseClicked
private void btnAñadirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAñadirActionPerformed
// TODO add your handling code here:
if (ValidarCampos() == true) {
inicio();
limpiar();
} else {
JOptionPane.showMessageDialog(null, "Llenar campos sin escribir", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
}
}//GEN-LAST:event_btnAñadirActionPerformed
private void txtNombreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyTyped
// TODO add your handling code here:
val.ValidarLetra(evt, txtNombre, 50);
}//GEN-LAST:event_txtNombreKeyTyped
private void txtApellidoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtApellidoKeyTyped
// TODO add your handling code here:
val.ValidarLetra(evt, txtApellido, 50);
}//GEN-LAST:event_txtApellidoKeyTyped
private void txtCedulaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCedulaKeyTyped
// TODO add your handling code here:
val.ValidarNumero(evt, txtCedula, 10);
}//GEN-LAST:event_txtCedulaKeyTyped
private void txtBuscarCedulaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscarCedulaKeyTyped
// TODO add your handling code here:
val.ValidarNumero(evt, txtBuscarCedula, 10);
}//GEN-LAST:event_txtBuscarCedulaKeyTyped
private void txtTelefonoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTelefonoKeyTyped
// TODO add your handling code here:
val.ValidarNumero(evt, txtTelefono, 10);
}//GEN-LAST:event_txtTelefonoKeyTyped
private void txtBuscarCedulaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscarCedulaKeyPressed
// TODO add your handling code here:
// val.ValidarCedula(txtBuscarCedula.getText(), txtBuscarCedula);
// if (txtBuscarCedula.getText().equals("")) {
// JOptionPane.showMessageDialog(null, "LLENAR CAMPO REQUERIDO", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
// txtBuscarCedula.requestFocus();
// } else {
// buscaCliente(txtBuscarCedula.getText());
// }
}//GEN-LAST:event_txtBuscarCedulaKeyPressed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FrmClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FrmClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FrmClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FrmClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
Logger.getLogger(FrmClientes.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(FrmClientes.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(FrmClientes.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(FrmClientes.class.getName()).log(Level.SEVERE, null, ex);
}
new FrmClientes().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTable JTCliente;
private javax.swing.JButton btnActivar_Desactivar;
private javax.swing.JButton btnAtras;
private javax.swing.JButton btnAñadir;
private javax.swing.JButton btnBuscar;
private javax.swing.JButton btnGuardar;
private javax.swing.JButton btnModificar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane2;
private java.awt.TextField txtApellido;
private java.awt.TextField txtBuscarCedula;
private java.awt.TextField txtCedula;
private java.awt.TextField txtCorreElectronico;
private java.awt.TextField txtDireccion;
private java.awt.TextField txtNombre;
private java.awt.TextField txtTelefono;
// End of variables declaration//GEN-END:variables
}
| true |
b5343530cd3d1c1f1ecde5c2b3df51fe64638275 | Java | jasonxu510/mysummerclub | /src/main/java/com/example/mysummerclub/service/impl/EntryItemServiceImpl.java | UTF-8 | 1,767 | 2.046875 | 2 | [] | no_license | package com.example.mysummerclub.service.impl;
import com.example.mysummerclub.mapper.EntryItemMapper;
import com.example.mysummerclub.pojo.EntryItem;
import com.example.mysummerclub.pojo.EntryItemExample;
import com.example.mysummerclub.service.EntryItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
*
*/
@Service
public class EntryItemServiceImpl implements EntryItemService {
@Autowired
private EntryItemMapper entryItemMapper;
@Override
public void insertEntryItem(EntryItem entryItem) {
entryItemMapper.insert(entryItem);
}
@Override
public void deleteEntryItem(Long id) {
entryItemMapper.deleteByPrimaryKey(id);
}
@Override
public void updateEntryItem(EntryItem entryItem) {
entryItemMapper.updateByPrimaryKeySelective(entryItem);
}
@Override
public EntryItem findEntryItemById(Long id) {
EntryItem entryItem = entryItemMapper.selectByPrimaryKey(id);
return entryItem;
}
@Override
public List<EntryItem> findAllEntryItem() {
EntryItemExample entryItemExample = new EntryItemExample();
entryItemExample.createCriteria()
.getAllCriteria();
List<EntryItem> entryItems = entryItemMapper.selectByExample(entryItemExample);
return entryItems;
}
@Override
public List<EntryItem> findEntryItemByUserId(Long userId) {
EntryItemExample entryItemExample = new EntryItemExample();
entryItemExample.createCriteria()
.andUserIdEqualTo(userId);
List<EntryItem> entryItems = entryItemMapper.selectByExample(entryItemExample);
return entryItems;
}
}
| true |
647c724704d1dbd8252a06b4f12674cbdb03e58a | Java | benjamindotgrey/school | /COSC 1437/Assignment08/CheckboxesTester.java | UTF-8 | 716 | 3.1875 | 3 | [] | no_license | // --------------------------
// Programmer: Hassan Benjamin Shirani
// Course: COSC 1437 Spring 2016
// Semester: Spring 2016
// Assignment #: 08
// Due Date: March 02, 2016
// --------------------------
import javax.swing.JFrame;
public class CheckboxesTester {
/**
* @param args
*/
public static void main(String[] args) {
// instantiate a frame
// from the class JFrame
JFrame frame = new JFrame("Fun with check boxes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// the primary panel is added
// to the frame and made visible
frame.getContentPane().add(new CheckboxesGUI());
frame.pack();
frame.setVisible(true);
} // end method main
} // end class CheckboxesTester
| true |
47099d44354b6667ae5f8a1ac8a8569224ddf1fa | Java | MohamedHELshazly/JavaJunit | /src/junittuts/JunitTuts.java | UTF-8 | 2,467 | 3.53125 | 4 | [] | no_license |
package junittuts;
import java.util.Scanner;
public class JunitTuts {
// input ==> AACD ==> CD , ACD ==> CD, CDEF ==> CDEF , CDAA ==> CDAA
public String truncate(String str){
if(str.length() <= 2){
return str.replace("A", "");
}
String first2 = str.substring(0,2);
String restOfStr = str.substring(2);
return first2.replaceAll("A", "")+ restOfStr;
}
private int [] data = new int[100000];
private int arraySize = 10000;
public void generateRandomArray(){
for (int i = 0; i < data.length; i++) {
data[i] = (int)(Math.random()*10000);
}
}
public void printArray(){
System.out.println("---------------------");
for (int i = 0; i < arraySize; i++) {
System.out.print("|"+i+"|");
System.out.println(data[i]+"|");
System.out.println("---------------------");
}
}
public boolean sameFirstSameLast(String str){
if(str.length() <= 1){
return false;
}else if(str.length() == 2){
return true;
}
String first2 = str.substring(0,2);
String last2= str.substring(str.length()-2);
return first2.equals(last2);
}
public static void main(String[] subs){
JunitTuts j= new JunitTuts();
j.generateRandomArray();
//j.printArray();
j.bubbleSort();
// System.out.print("Enter a string: ");
// String input= "";
// Scanner sc = new Scanner(System.in);
// input = sc.next();
// //System.out.println("the returned value is " + truncate(input));
// sc.close();
}
public void swapValues(int first, int second){
int temp= data[first];
data[second]= temp;
}
public void bubbleSort(){
for (int i = arraySize-1; i > 1; i--) {
for (int j = 0; j < i; j++) {
if (data[j] > data[j+1]) {
swapValues(j, j+1);
}
}
}
printArray();
}
public void selectionSort(){
for (int i = 0; i < arraySize; i++) {
int min = i;
for (int j = i; j < arraySize; j++) {
if (data[min] > data[j]) {
min=j;
}
}
swapValues(i, min);
printArray();
}
}
}
| true |
188b5e3bc0613d713478adb8707e20db477868e0 | Java | jsbhb/cardmanager | /src/main/java/com/card/manager/factory/exception/ServerCenterNullDataException.java | UTF-8 | 632 | 2.328125 | 2 | [] | no_license | /**
* Project Name:cardmanager
* File Name:ServerCenterNullDataException.java
* Package Name:com.card.manager.factory.exception
* Date:Dec 31, 20173:09:30 PM
*
*/
package com.card.manager.factory.exception;
/**
* ClassName: ServerCenterNullDataException <br/>
* Function: TODO ADD FUNCTION. <br/>
* date: Dec 31, 2017 3:09:30 PM <br/>
*
* @author hebin
* @version
* @since JDK 1.7
*/
public class ServerCenterNullDataException extends Exception {
private static final long serialVersionUID = 1L;
public ServerCenterNullDataException(String errorMsg) {
super(errorMsg);
}
}
| true |
46ada3030be695e371a2943c0f35823c0cd4ba84 | Java | cj-china/SecKillService | /wb/src/main/java/CommentServlet.java | UTF-8 | 694 | 2.578125 | 3 | [
"MIT"
] | permissive | import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CommentServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("CommentServlet的service方法");
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out=resp.getWriter();
String content=req.getParameter("content");
out.println("你的看法是:"+content);
}
}
| true |
7330a1f38f80e91242eda5c8992105bdd02b2120 | Java | DeinaK/tankTrouble | /MouseHandler.java | UTF-8 | 3,745 | 2.734375 | 3 | [
"MIT"
] | permissive | import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.RenderingHints;
import java.awt.Dimension;
import java.awt.Image;
import javax.swing.ImageIcon;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.Rectangle2D;
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.AffineTransformOp;
import java.io.*;
import sun.audio.*;
/**
* This class is used to handle mouse events.
*/
public class MouseHandler implements MouseListener, MouseMotionListener
{
private Rectangle2D button1 = new Rectangle(1000,450,300,100); //player1 -> MENU // player1 = PLAY
private Rectangle2D button2 = new Rectangle(1000,150,300,100); //player2 -> MENU // player2 = EXIT
private Rectangle2D button3 = new Rectangle(1000, 300, 300, 100); //credits -> MENU
private Rectangle2D button4 = new Rectangle (500, 600, 300, 100); // menubutton -> CREDITS
private TankTrouble game;
/**
* Constructor of the MouseHandler that takes the game object
* @param tanktrouble Game instance
*/
public MouseHandler (TankTrouble tanktrouble)
{
game = tanktrouble;
}
/**
* This method handles the user's mouse events using game instances methods.
* @param event Mouse event
*/
public void mouseClicked(MouseEvent event)
{
if (game.state == TankTrouble.STATE.MENU){
if(button2.contains(event.getPoint()))
{
game.setGame();
}
if(button1.contains(event.getPoint()))
{
System.exit(0);
}
if(button3.contains(event.getPoint()))
{
game.setCredits();
}
}
if (game.state == TankTrouble.STATE.CREDITS)
{
if(button4.contains(event.getPoint()))
{
game.setMenu();
}
}
}
public void mouseEntered(MouseEvent arg0)
{
}
public void mouseExited(MouseEvent arg0)
{
}
public void mousePressed(MouseEvent arg0)
{
}
public void mouseReleased(MouseEvent arg0){
}
public void mouseDragged(MouseEvent arg0)
{
}
public void mouseMoved(MouseEvent event)
{
if (game.state == TankTrouble.STATE.MENU)
{
if(button2.contains(event.getPoint()))
{
game.getMenu().changePlayer2(true);
}
if(!button2.contains(event.getPoint()))
{
game.getMenu().changePlayer2(false);
}
if(button1.contains(event.getPoint()))
{
game.getMenu().changePlayer1(true);
}
if(!button1.contains(event.getPoint()))
{
game.getMenu().changePlayer1(false);
}
if(button3.contains(event.getPoint()))
{
game.getMenu().gotoCredits(true);
}
if(!button3.contains(event.getPoint()))
{
game.getMenu().gotoCredits(false);
}
}
else if (game.state == TankTrouble.STATE.CREDITS)
{
if (button4.contains(event.getPoint()))
{
game.getCredits().gotoMenu (true);
}
if (!button4.contains(event.getPoint()))
{
game.getCredits().gotoMenu (false);
}
}
}
} | true |
81a820a3e9d7d311d67b5f16f763f7ee9dfeef26 | Java | ajaxkulkarni/hp | /healthplease-webapp/src/main/java/com/rns/healthplease/web/bo/domain/Slot.java | UTF-8 | 1,309 | 2.09375 | 2 | [] | no_license | package com.rns.healthplease.web.bo.domain;
import java.util.Date;
public class Slot {
private Integer id;
private String startTime;
private String endTime;
private Slab slab;
private Date blockedDate;
private String isBooked;
private boolean isBlocked;
private String type;
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public Slab getSlab() {
return slab;
}
public void setSlab(Slab slab) {
this.slab = slab;
}
public Date getBlockedDate() {
return blockedDate;
}
public void setBlockedDate(Date blockedDate) {
this.blockedDate = blockedDate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getIsBooked() {
return isBooked;
}
public void setIsBooked(String isBooked) {
this.isBooked = isBooked;
}
public boolean isBlocked() {
return isBlocked;
}
public void setBlocked(boolean isBlocked) {
this.isBlocked = isBlocked;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| true |
09397bf39d1189cc0605b43696d9c3ccc468ffce | Java | swarnatonse/Compiler_PLP | /src/cop5556sp17/AST/Chain.java | UTF-8 | 415 | 2.625 | 3 | [] | no_license | package cop5556sp17.AST;
import cop5556sp17.Scanner.Token;
import cop5556sp17.AST.Type.TypeName;
public abstract class Chain extends Statement {
TypeName tn;
public boolean isLeft;
public Chain(Token firstToken/*, TypeName tn*/) {
super(firstToken);
//this.tn = tn;
this.isLeft = false;
}
public void setTypeName(TypeName tn){
this.tn = tn;
}
public TypeName getTypeName(){
return tn;
}
}
| true |
0f8d7217eaa509e62da5e1e90131f441a13944ec | Java | 11samype/TicketToRideEurope | /src/gui/factory/JLabelFactory.java | UTF-8 | 619 | 2.9375 | 3 | [] | no_license | package gui.factory;
import gui.DeckSizeLabel;
import java.awt.Font;
import javax.swing.JLabel;
import objects.interfaces.IDeck;
public class JLabelFactory {
public static JLabel createJLabel(String str) {
JLabel lbl = new JLabel(str);
setFont(lbl, "Tahoma", Font.PLAIN, 16);
return lbl;
}
public static DeckSizeLabel createDeckSizeLabel(IDeck<?> deck) {
DeckSizeLabel lbl = new DeckSizeLabel(deck);
setFont(lbl, "Tahoma", Font.PLAIN, 24);
return lbl;
}
public static void setFont(JLabel lbl, String fontName, int fonttype, int size) {
lbl.setFont(new Font(fontName, fonttype, size));
}
}
| true |
fdbfaebd4e60c26fff67dacb12a590cd22c05262 | Java | apache/directory-studio | /plugins/schemaeditor/src/main/java/org/apache/directory/studio/schemaeditor/controller/actions/LinkWithEditorHierarchyViewAction.java | UTF-8 | 6,784 | 1.734375 | 2 | [
"Apache-2.0"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.schemaeditor.controller.actions;
import org.apache.directory.api.ldap.model.schema.AttributeType;
import org.apache.directory.api.ldap.model.schema.ObjectClass;
import org.apache.directory.api.ldap.model.schema.SchemaObject;
import org.apache.directory.studio.schemaeditor.Activator;
import org.apache.directory.studio.schemaeditor.PluginConstants;
import org.apache.directory.studio.schemaeditor.view.editors.attributetype.AttributeTypeEditor;
import org.apache.directory.studio.schemaeditor.view.editors.objectclass.ObjectClassEditor;
import org.apache.directory.studio.schemaeditor.view.views.HierarchyView;
import org.eclipse.jface.action.Action;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.PlatformUI;
/**
* This class implements the Link With Editor Action for the Hierarchy View
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LinkWithEditorHierarchyViewAction extends Action
{
/** The String for storing the checked state of the action */
private static final String LINK_WITH_EDITOR_HIERARCHY_VIEW_DS_KEY = LinkWithEditorHierarchyViewAction.class
.getName()
+ ".dialogsettingkey"; //$NON-NLS-1$
/** The associated view */
private HierarchyView view;
/** The listener listening on changes on editors */
private IPartListener2 editorListener = new IPartListener2()
{
/**
* {@inheritDoc}
*/
public void partVisible( IWorkbenchPartReference partRef )
{
IWorkbenchPart part = partRef.getPart( true );
if ( part instanceof ObjectClassEditor )
{
linkViewWithEditor( ( ( ObjectClassEditor ) part ).getOriginalObjectClass() );
}
else if ( part instanceof AttributeTypeEditor )
{
linkViewWithEditor( ( ( AttributeTypeEditor ) part ).getOriginalAttributeType() );
}
}
/**
* {@inheritDoc}
*/
public void partActivated( IWorkbenchPartReference partRef )
{
}
/**
* {@inheritDoc}
*/
public void partClosed( IWorkbenchPartReference partRef )
{
}
/**
* {@inheritDoc}
*/
public void partDeactivated( IWorkbenchPartReference partRef )
{
}
/**
* {@inheritDoc}
*/
public void partHidden( IWorkbenchPartReference partRef )
{
}
/**
* {@inheritDoc}
*/
public void partInputChanged( IWorkbenchPartReference partRef )
{
}
/**
* {@inheritDoc}
*/
public void partOpened( IWorkbenchPartReference partRef )
{
}
/**
* {@inheritDoc}
*/
public void partBroughtToTop( IWorkbenchPartReference partRef )
{
}
};
/**
* Creates a new instance of LinkWithEditorSchemasView.
*
* @param view
* the associated view
*/
public LinkWithEditorHierarchyViewAction( HierarchyView view )
{
super( Messages.getString( "LinkWithEditorHierarchyViewAction.LinkEditorAction" ), AS_CHECK_BOX ); //$NON-NLS-1$
setToolTipText( Messages.getString( "LinkWithEditorHierarchyViewAction.LinkEditorToolTip" ) ); //$NON-NLS-1$
setImageDescriptor( Activator.getDefault().getImageDescriptor( PluginConstants.IMG_LINK_WITH_EDITOR ) );
setEnabled( true );
this.view = view;
// Setting up the default key value (if needed)
if ( Activator.getDefault().getDialogSettings().get( LINK_WITH_EDITOR_HIERARCHY_VIEW_DS_KEY ) == null )
{
Activator.getDefault().getDialogSettings().put( LINK_WITH_EDITOR_HIERARCHY_VIEW_DS_KEY, false );
}
// Setting state from the dialog settings
setChecked( Activator.getDefault().getDialogSettings().getBoolean( LINK_WITH_EDITOR_HIERARCHY_VIEW_DS_KEY ) );
// Enabling the listeners
if ( isChecked() )
{
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPartService().addPartListener( editorListener );
}
}
/**
* {@inheritDoc}
*/
public void run()
{
setChecked( isChecked() );
Activator.getDefault().getDialogSettings().put( LINK_WITH_EDITOR_HIERARCHY_VIEW_DS_KEY, isChecked() );
if ( isChecked() ) // Enabling the listeners
{
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPartService().addPartListener( editorListener );
IEditorPart activeEditor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.getActiveEditor();
if ( activeEditor instanceof ObjectClassEditor )
{
linkViewWithEditor( ( ( ObjectClassEditor ) activeEditor ).getOriginalObjectClass() );
}
else if ( activeEditor instanceof AttributeTypeEditor )
{
linkViewWithEditor( ( ( AttributeTypeEditor ) activeEditor ).getOriginalAttributeType() );
}
}
else
// Disabling the listeners
{
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPartService().removePartListener( editorListener );
}
}
/**
* Links the view with the right editor
*
* @param schemaElement
* the Schema Element
*/
private void linkViewWithEditor( SchemaObject schemaElement )
{
if ( schemaElement instanceof AttributeType )
{
view.setInput( schemaElement );
}
else if ( schemaElement instanceof ObjectClass )
{
view.setInput( schemaElement );
}
}
}
| true |
b8942f1391c08e41107bfe677f5bd9b85f341b8f | Java | tapate/wolf_ml_mnist | /src/main/java/com/tianyalei/classification/Data2.java | UTF-8 | 4,262 | 2.34375 | 2 | [] | no_license | package com.tianyalei.classification;
import org.datavec.api.records.reader.RecordReader;
import org.datavec.api.records.reader.impl.csv.CSVRecordReader;
import org.datavec.api.split.FileSplit;
import org.deeplearning4j.datasets.datavec.RecordReaderDataSetIterator;
import org.deeplearning4j.eval.Evaluation;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.layers.DenseLayer;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.deeplearning4j.optimize.listeners.ScoreIterationListener;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.dataset.SplitTestAndTrain;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import org.nd4j.linalg.io.ClassPathResource;
import org.nd4j.linalg.learning.config.Nesterovs;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import java.io.File;
import java.io.IOException;
/**
* @author wuweifeng wrote on 2018/6/20.
*/
public class Data2 {
public static void main(String[] args) throws IOException, InterruptedException {
int seed = 123;
double learningRate = 0.005;
int batchSize = 120;
int nEpochs = 10000;
int numInputs = 2;
int numOutputs = 2;
int numHiddenNodes = 28;
String trainPath = new ClassPathResource("/classification/data2.csv").getFile().getPath();
//load the training data
RecordReader recordReader = new CSVRecordReader();
recordReader.initialize(new FileSplit(new File(trainPath)));
//labelIndex是指结果的位置,这个样本结果是第0个位置
DataSetIterator trainIter = new RecordReaderDataSetIterator(recordReader, batchSize, 2, 2);
DataSet allData = trainIter.next();
allData.shuffle(123);
SplitTestAndTrain testAndTrain = allData.splitTestAndTrain(0.65); //Use 65% of data for training
DataSet trainingData = testAndTrain.getTrain();
DataSet testData = testAndTrain.getTest();
//构建网络
MultiLayerConfiguration configuration = new NeuralNetConfiguration.Builder()
.seed(seed)
//.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.updater(new Nesterovs(learningRate, 0.9))
.l2(1e-4)
.list()
.layer(0, new DenseLayer.Builder()
.nIn(numInputs)
.nOut(numHiddenNodes)
.weightInit(WeightInit.XAVIER)
.activation(Activation.TANH)
.build())
.layer(1, new DenseLayer.Builder()
.nIn(numHiddenNodes)
.nOut(numHiddenNodes)
.weightInit(WeightInit.XAVIER)
.activation(Activation.TANH)
.build())
.layer(2, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.nIn(numHiddenNodes)
.nOut(numOutputs)
.weightInit(WeightInit.XAVIER)
.activation(Activation.SOFTMAX)
.build())
.pretrain(false).backprop(true).build();
MultiLayerNetwork model = new MultiLayerNetwork(configuration);
model.init();
//print the score with every 1 iteration
model.setListeners(new ScoreIterationListener(1));
for (int i = 0; i < nEpochs; i++) {
model.fit(trainingData);
}
System.out.println(model.summary());
System.out.println("Evaluate model....");
Evaluation evaluation = new Evaluation(numOutputs);
INDArray features = testData.getFeatureMatrix();
INDArray lables = testData.getLabels();
INDArray predicted = model.output(features, false);
evaluation.eval(lables, predicted);
System.out.println(evaluation.stats());
}
}
| true |
0d49cf9a50f95b8985a1622fcd9f79dda19037cd | Java | B-u-f-f/software-project | /cropWebsite/src/main/java/software/web/LoginPageDao.java | UTF-8 | 1,790 | 2.546875 | 3 | [] | no_license | package software.web.login.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//Project imports
import software.web.database.DatabaseConstants;
public class LoginPageDao extends DatabaseConstants{
Connection con;
public LoginPageDao(){
try {
con = DriverManager.getConnection(DatabaseConstants.getUrl(), DatabaseConstants.getUsername(), DatabaseConstants.getPassword());
}catch(SQLException e){
e.printStackTrace();
}
}
public String check(String email, String pass) {
// String sql = "SELECT * FROM (SELECT EmailID, PasswordHash FROM FarmerAccount UNION SELECT EmailID, PasswordHash FROM CustomerAccount) AS EmailPassword WHERE EmailID = ? AND PasswordHash = ?;";
String sqlCus = "SELECT EmailID, PasswordHash FROM CustomerAccount WHERE EmailID = ? AND PasswordHash = ?;";
String sqlFar = "SELECT EmailID, PasswordHash FROM FarmerAccount WHERE EmailID = ? AND PasswordHash = ?;";
try {
PreparedStatement st = con.prepareStatement(sqlCus);
st.setString(1, email);
st.setString(2, pass);
ResultSet rs = st.executeQuery();
if(rs.next()) {
return "Customer";
}
st = con.prepareStatement(sqlFar);
st.setString(1, email);
st.setString(2, pass);
rs = st.executeQuery();
if(rs.next()) {
return "Farmer";
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
protected void finalize() throws Throwable {
con.close();
}
} | true |
1c77130194331d647770e03ef138a8e464e78956 | Java | robinarehen/car-center-test | /car-center-test/src/main/java/com/asesoftware/carcentertest/service/TipoPersonaService.java | UTF-8 | 637 | 2.109375 | 2 | [] | no_license | package com.asesoftware.carcentertest.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.asesoftware.carcentertest.model.TipoPersona;
import com.asesoftware.carcentertest.respository.TipoPersonaRepository;
@Service
@Transactional(readOnly = true)
public class TipoPersonaService {
private TipoPersonaRepository repository;
public TipoPersonaService(TipoPersonaRepository repository) {
super();
this.repository = repository;
}
public TipoPersona getTipoPersona(String tipoPersona) {
return this.repository.findByNombre(tipoPersona);
}
}
| true |
c2260cf37b91c66b8d34778ae1f090d7081c3b5c | Java | houghmzqqq/HumanResourceManagement | /src/com/HumanResourceManagement/util/CharsetFilter.java | UTF-8 | 969 | 2.484375 | 2 | [] | no_license | package util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class CharsetFilter implements Filter
{
private String charsetEncoding;
private boolean enabled;
public void destroy()
{
charsetEncoding = null;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
if (enabled||charsetEncoding!=null) {
request.setCharacterEncoding(charsetEncoding);
response.setCharacterEncoding(charsetEncoding);
}
chain.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException
{
charsetEncoding=config.getInitParameter("charsetEncoding");
enabled="true".equalsIgnoreCase(config.getInitParameter("enabled").trim());
}
}
| true |
c5d1976ec08daedcdf66f09f765f5060b26caa5c | Java | androsdav/01-java-a-to-z | /06-Multithreading/04-wait-notify/03-lock/src/main/java/com/adidyk/Counter.java | UTF-8 | 472 | 3 | 3 | [
"Apache-2.0"
] | permissive | package com.adidyk;
/** Class Counter.
* @author Didyk Andrey (androsdav@bigmir.net).
* @since 26.03.2018.
* @version 1.0.
*/
class Counter {
/**
* @param counter - is counter.
*/
private int counter;
/**
* addCounter - increments counter by one.
*/
void addCounter() {
this.counter++;
}
/**
* getCounter - returns counter.
* @return - returns counter.
*/
int getCounter() {
return this.counter;
}
} | true |
31faf52cb4591cc3e16afbbe7b4871df52b0cc77 | Java | gayatrisantosh/Katas | /src/main/java/com/audition/org/vending/io/CoinOutputter.java | UTF-8 | 683 | 3.03125 | 3 | [] | no_license | package com.audition.org.vending.io;
import java.util.ArrayList;
import java.util.List;
import com.audition.org.vending.model.Coin;
public class CoinOutputter {
private Double amount = new Double(0.0);
public Double eject(final List<Coin> coins){
for(final Coin coin : coins){
amount += coin.getType().value();
System.out.println(">>>>> Ejecting "+coin.getType());
}
return amount;
}
public Double eject(final Double change){
System.out.println(">>>>> Ejecting "+change.floatValue());
return change;
}
public Double eject(final Coin coin){
final List<Coin> coins = new ArrayList<Coin>();
coins.add(coin);
return eject(coins);
}
}
| true |
dac1f27731e5c65d1c340f2226834fd30d92c0ec | Java | fedespe/Obligatorio_DisenoDesarrolloApp | /CD Entrega 2da Parte/Obligatorio/src/logica/Sistema.java | UTF-8 | 1,498 | 2.28125 | 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 logica;
import java.util.ArrayList;
import utilidades.ObligatorioException;
/**
*
* @author usuario
*/
public class Sistema extends utilidades.Observable{
private SubSistemaUsuario ssu = new SubSistemaUsuario();
private SubSistemaPartida ssp = new SubSistemaPartida();
private static Sistema instancia = new Sistema();
private Sistema(){};
public static Sistema getInstancia() {
return instancia;
}
public Jugador loginJugador(String nombre, String pass) throws ObligatorioException {
return ssu.loginJugador(nombre, pass);
}
public Administrador loginAdministrador(String nombre, String pass) throws ObligatorioException {
return ssu.loginAdministrador(nombre, pass);
}
public void partidasFinalizadas() throws ObligatorioException {
ssp.partidasFinalizadas();
}
public ArrayList<Partida> getPartidas() {
return ssp.getPartidas();
}
public void agregarJugador(Jugador j) throws ObligatorioException {
ssp.agregarJugador(j);
}
public Partida getPartidaParaJugar() {
return ssp.partidaParaJugar();
}
public void logoutJugador(Jugador jug) {
ssu.logoutJugador(jug);
}
public enum Eventos{
actualizacionEnPartida;
}
}
| true |
050046e00a9213ab0c6cc15796cbf272eba7416b | Java | canmogol/NDIServer | /src/main/java/com/fererlab/action/BaseJpaCRUDAction.java | UTF-8 | 20,045 | 2.21875 | 2 | [
"Apache-2.0"
] | permissive | package com.fererlab.action;
import com.fererlab.db.EM;
import com.fererlab.dto.Model;
import com.fererlab.dto.Param;
import com.fererlab.dto.ParamMap;
import org.hibernate.TypeMismatchException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* acm 11/12/12
*/
public class BaseJpaCRUDAction<T extends Model> extends BaseAction implements CRUDAction<T> {
private Class<T> type;
private List<String> fieldNames = new ArrayList<String>();
public BaseJpaCRUDAction(Class<T> type) {
super();
this.type = type;
for (Method m : type.getMethods()) {
if (m.getName().startsWith("set")) {
String fieldName = m.getName().substring(3);
fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);
fieldNames.add(fieldName);
}
}
getXStream().autodetectAnnotations(true);
getXStream().alias(type.getSimpleName(), type);
getXStreamJSON().autodetectAnnotations(true);
getXStreamJSON().alias(type.getSimpleName(), type);
}
public Class<T> getType() {
return type;
}
@Override
public T find(Object id) {
return EM.find(type, id);
}
@Override
public List<T> findAll() {
return findAll(new ParamMap<String, Param<String, Object>>());
}
@Override
public List<T> findAll(Object... keyValueList) {
ParamMap<String, Param<String, Object>> paramMap = new ParamMap<String, Param<String, Object>>();
for (int i = 0; i < keyValueList.length; i = i + 2) {
String key = String.valueOf(keyValueList[i]);
paramMap.put(key, new Param<String, Object>(key, keyValueList[i + 1]));
}
return findAll(paramMap);
}
@Override
@SuppressWarnings("unchecked")
public List<T> findAll(ParamMap<String, Param<String, Object>> keyValuePairs) {
// will use criteria builder
CriteriaBuilder criteriaBuilder = EM.getEntityManager().getCriteriaBuilder();
// select from entity
CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(type);
Root<T> from = criteriaQuery.from(type);
criteriaQuery.select(from);
// will store all predicates
List<Predicate> predicates = new ArrayList<Predicate>();
List<Boolean> andOrList = new ArrayList<Boolean>();
// parameter list
List<ParameterExpression<Object>> parameterExpressionList = new ArrayList<ParameterExpression<Object>>();
List<Object> parameterList = new ArrayList<Object>();
// orderBy may be null
String orderBy = null;
Integer start = null;
Integer limit = null;
if (keyValuePairs != null) {
// set offset, limit and orderBy any if exists
if (keyValuePairs.containsKey("_start") && keyValuePairs.getValue("_start") != null) {
start = Integer.valueOf(keyValuePairs.remove("_start").getValue().toString());
}
if (keyValuePairs.containsKey("_limit") && keyValuePairs.getValue("_limit") != null) {
limit = Integer.valueOf(keyValuePairs.remove("_limit").getValue().toString());
}
if (keyValuePairs.containsKey("_order") && keyValuePairs.getValue("_order") != null) {
orderBy = keyValuePairs.remove("_order").getValue().toString().trim().replace("%20", " ");
}
// for rest of the param list
for (final Param<String, Object> param : keyValuePairs.getParamList()) {
// if model does not have this field than do not add the parameter as a criteria
if (!fieldNames.contains(param.getKey())) {
continue;
}
// add and or for query builder
if (param.getValueSecondary() != null && param.getValueSecondary().equals(false)) {
andOrList.add(Boolean.FALSE);
} else {
andOrList.add(Boolean.TRUE);
}
// create a parameter expression with value's type
ParameterExpression parameterExpression = null;
switch (param.getRelation()) {
case EQ:
parameterExpression = criteriaBuilder.parameter(param.getValue().getClass());
predicates.add(criteriaBuilder.equal(from.get(param.getKey()), parameterExpression));
break;
case LIKE:
parameterExpression = criteriaBuilder.parameter(param.getValue().getClass());
predicates.add(criteriaBuilder.like(from.<String>get(param.getKey()), parameterExpression));
break;
case NE:
parameterExpression = (ParameterExpression<? extends Number>) criteriaBuilder.parameter(param.getValue().getClass());
predicates.add(criteriaBuilder.notEqual(from.<Number>get(param.getKey()), parameterExpression));
break;
case BETWEEN:
parameterExpression = (ParameterExpression<Comparable>) criteriaBuilder.parameter(param.getValue().getClass());
predicates.add(
criteriaBuilder.between(from.<Comparable>get(param.getKey()), (Comparable) param.getValue(), (Comparable) param.getValueSecondary())
);
continue;
case GT:
parameterExpression = (ParameterExpression<? extends Number>) criteriaBuilder.parameter(param.getValue().getClass());
predicates.add(criteriaBuilder.gt(from.<Number>get(param.getKey()), parameterExpression));
break;
case GE:
parameterExpression = (ParameterExpression<? extends Number>) criteriaBuilder.parameter(param.getValue().getClass());
predicates.add(criteriaBuilder.ge(from.<Number>get(param.getKey()), parameterExpression));
break;
case LT:
parameterExpression = (ParameterExpression<? extends Number>) criteriaBuilder.parameter(param.getValue().getClass());
predicates.add(criteriaBuilder.lt(from.<Number>get(param.getKey()), parameterExpression));
break;
case LE:
parameterExpression = (ParameterExpression<? extends Number>) criteriaBuilder.parameter(param.getValue().getClass());
predicates.add(criteriaBuilder.le(from.<Number>get(param.getKey()), parameterExpression));
break;
}
// then add the value(with its new type) to parameterList and the parameter expression to its list
parameterExpressionList.add(parameterExpression);
parameterList.add(param.getValue());
}
// where and|x=1 and|y=2 or|z=3
// set predicates if any
if (predicates.size() > 0) {
List<Predicate> predicateList = new ArrayList<Predicate>();
Predicate predicate;
for (int i = 0; i < predicates.size(); i = i + 2) {
if (i + 1 < predicates.size()) {
Boolean andOr = andOrList.get(i + 1);
if (andOr) {
predicate = criteriaBuilder.and(predicates.get(i), predicates.get(i + 1));
} else {
predicate = criteriaBuilder.or(predicates.get(i), predicates.get(i + 1));
}
predicateList.add(predicate);
} else {
Boolean andOr = andOrList.get(i);
if (andOr) {
predicate = criteriaBuilder.and(predicates.get(i));
} else {
predicate = criteriaBuilder.or(predicates.get(i));
}
predicateList.add(predicate);
}
}
if (predicateList.size() > 0) {
Predicate[] predicateArray = new Predicate[predicateList.size()];
for (int i = 0; i < predicateList.size(); i++) {
predicateArray[i] = predicateList.get(i);
}
criteriaQuery.where(predicateArray);
}
}
}
// set if orderBy is not null
if (orderBy != null) {
String[] orderByAndOrderDirection = orderBy.split(" ");
if (orderByAndOrderDirection.length == 2) { // "id asc" or "id desc"
if (orderByAndOrderDirection[1].equalsIgnoreCase("asc")) {
criteriaQuery.orderBy(criteriaBuilder.asc(from.get(orderByAndOrderDirection[0])));
} else {
criteriaQuery.orderBy(criteriaBuilder.desc(from.get(orderByAndOrderDirection[0])));
}
} else {
criteriaQuery.orderBy(criteriaBuilder.desc(from.get(orderBy)));
}
}
// create query
TypedQuery<T> query = EM.getEntityManager().createQuery(criteriaQuery);
/*
* 1 0 25 0 25
* 2 25 25 25 25
* 3 50 25 50 25
*
*/
// set offset if available
if (start != null) {
query = query.setFirstResult(start);
}
// set limit if available
if (limit != null) {
query = query.setMaxResults(limit);
}
// set parameter values
if (parameterList.size() > 0) {
for (int i = 0; i < parameterList.size(); i++) {
query.setParameter(parameterExpressionList.get(i), parameterList.get(i));
}
}
// return the result list
return query.getResultList();
}
@Override
public Long findCount() {
String queryString = "select count(model) from " + type.getSimpleName() + " model";
Query query = EM.getEntityManager().createQuery(queryString);
return (Long) query.getSingleResult();
}
public T create(Object... keyValueList) throws Exception {
ParamMap<String, Param<String, Object>> paramMap = new ParamMap<String, Param<String, Object>>();
for (int i = 0; i < keyValueList.length; i = i + 2) {
String key = String.valueOf(keyValueList[i]);
paramMap.put(key, new Param<String, Object>(key, keyValueList[i + 1]));
}
return create(paramMap);
}
@Override
@SuppressWarnings("unchecked")
public T create(ParamMap<String, Param<String, Object>> keyValuePairs) throws Exception {
T t = null;
try {
t = type.newInstance();
for (Method method : type.getDeclaredMethods()) {
if (method.getName().startsWith("set")) {
String fieldName = method.getName().substring(3, 4).toLowerCase(Locale.ENGLISH) + method.getName().substring(4);
if (keyValuePairs.containsKey(fieldName)) {
try {
Class<?>[] parameterClasses = method.getParameterTypes();
method = t.getClass().getDeclaredMethod(method.getName(), parameterClasses);
Object value;
if (parameterClasses.length > 0 && type.getPackage().equals(parameterClasses[0].getPackage())) {
Object id;
try {
id = Long.valueOf(keyValuePairs.get(fieldName).getValue().toString());
} catch (Exception e) {
id = keyValuePairs.get(fieldName).getValue();
}
Class<T> relationalT = (Class<T>) parameterClasses[0];
BaseJpaCRUDAction<?> relationalTBaseJpaCRUDAction = new BaseJpaCRUDAction(relationalT);
value = relationalTBaseJpaCRUDAction.find(id);
} else {
value = keyValuePairs.get(fieldName).getValue();
}
try {
method.invoke(t, value);
} catch (IllegalArgumentException iae) {
if (parameterClasses.length > 0) {
try {
// method.invoke(...) should work, this should not be called
Constructor constructor = Class.forName(parameterClasses[0].getName()).getConstructor(String.class);
value = constructor.newInstance(keyValuePairs.get(fieldName).getValue());
method.invoke(t, value);
} catch (NoSuchMethodException e) {
try {
Class c = Class.forName(parameterClasses[0].getName());
Method cm = c.getMethod("valueOf", String.class);
Object obj = cm.invoke(null, keyValuePairs.get(fieldName).getValue().toString().replace("%20", " "));
method.invoke(t, obj);
} catch (Exception ce) {
ce.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
}
EM.persist(t);
} catch (Exception e) {
EM.getEntityManager().clear();
if (EM.getEntityManager().getTransaction() != null && EM.getEntityManager().getTransaction().isActive()) {
EM.getEntityManager().getTransaction().rollback();
}
throw e;
}
return t;
}
public T update(Object id, Object... keyValueList) throws Exception {
ParamMap<String, Param<String, Object>> paramMap = new ParamMap<String, Param<String, Object>>();
for (int i = 0; i < keyValueList.length; i = i + 2) {
String key = String.valueOf(keyValueList[i]);
paramMap.put(key, new Param<String, Object>(key, keyValueList[i + 1]));
}
return update(id, paramMap);
}
@Override
public T update(Object id, ParamMap<String, Param<String, Object>> keyValuePairs) throws Exception {
T t = null;
try {
t = EM.find(type, id);
if (t == null) {
throw new Exception("There is no object found with id: " + id + " of type: " + type);
}
for (Method method : type.getDeclaredMethods()) {
if (method.getName().startsWith("set")) {
String fieldName = method.getName().substring(3, 4).toLowerCase(Locale.ENGLISH) + method.getName().substring(4);
if (keyValuePairs.containsKey(fieldName)) {
try {
Class<?>[] parameterClasses = method.getParameterTypes();
method = t.getClass().getDeclaredMethod(method.getName(), parameterClasses);
Object value = keyValuePairs.get(fieldName).getValue();
try {
method.invoke(t, value);
} catch (IllegalArgumentException iae) {
if (parameterClasses.length > 0) {
try {
// method.invoke(...) should work, this should not be called
Constructor constructor = Class.forName(parameterClasses[0].getName()).getConstructor(String.class);
value = constructor.newInstance(keyValuePairs.get(fieldName).getValue());
method.invoke(t, value);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
}
t = EM.merge(t);
} catch (Exception e) {
EM.getEntityManager().clear();
if (EM.getEntityManager().getTransaction() != null && EM.getEntityManager().getTransaction().isActive()) {
EM.getEntityManager().getTransaction().rollback();
}
throw e;
}
return t;
}
@Override
public T delete(Object id) throws Exception {
try {
T t = EM.find(type, id);
EM.remove(t);
return t;
} catch (Exception e) {
EM.getEntityManager().clear();
if (EM.getEntityManager().getTransaction() != null && EM.getEntityManager().getTransaction().isActive()) {
EM.getEntityManager().getTransaction().rollback();
}
throw e;
}
}
@Override
public List<Object> deleteAll(List<Object> ids) throws Exception {
try {
List<Object> deletedIds = new ArrayList<Object>();
for (Object id : ids) {
T t = null;
try {
t = EM.find(type, id);
} catch (IllegalArgumentException iae) {
if (iae.getCause() instanceof TypeMismatchException) {
id = Long.valueOf(id.toString());
t = EM.find(type, id);
}
}
if (t == null) {
throw new Exception("no object found for this id: " + id);
}
EM.remove(t);
deletedIds.add(id);
}
return deletedIds;
} catch (Exception e) {
EM.getEntityManager().clear();
if (EM.getEntityManager().getTransaction() != null && EM.getEntityManager().getTransaction().isActive()) {
EM.getEntityManager().getTransaction().rollback();
}
throw e;
}
}
}
| true |
24694e445e9256d774732fce6d82d68bb6f3e161 | Java | harris112/JavaProjs | /src/Players.java | UTF-8 | 2,162 | 3.125 | 3 | [] | no_license | package BowlingGame;
public class Players {
public String Player1, Player2, Player3, Player4, Player5, Player6, Player7, Player8;
public Players(String p1, String p2, String p3, String p4, String p5, String p6, String p7, String p8) {
Player1 = p1;
Player2 = p2;
Player3 = p3;
Player4 = p4;
Player5 = p5;
Player6 = p6;
Player7 = p7;
Player8 = p8;
}
public String getPlayer8() {
return Player8;
}
public void setPlayer8(String player8) {
Player8 = player8;
}
public String getPlayer7() {
return Player7;
}
public void setPlayer7(String player7) {
Player7 = player7;
}
public String getPlayer6() {
return Player6;
}
public void setPlayer6(String player6) {
Player6 = player6;
}
public String getPlayer5() {
return Player5;
}
public void setPlayer5(String player5) {
Player5 = player5;
}
public String getPlayer4() {
return Player4;
}
public void setPlayer4(String player4) {
Player4 = player4;
}
public String getPlayer3() {
return Player3;
}
public void setPlayer3(String player3) {
Player3 = player3;
}
public String getPlayer2() {
return Player2;
}
public void setPlayer2(String player2) {
Player2 = player2;
}
public String getPlayer1() {
return Player1;
}
public void setPlayer1(String player1) {
Player1 = player1;
}
@Override
public String toString() {
return "Players{" +
"Player1='" + Player1 + '\'' +
", Player2='" + Player2 + '\'' +
", Player3='" + Player3 + '\'' +
", Player4='" + Player4 + '\'' +
", Player5='" + Player5 + '\'' +
", Player6='" + Player6 + '\'' +
", Player7='" + Player7 + '\'' +
", Player8='" + Player8 + '\'' +
'}';
}
}
| true |
00ab27fb0f7f28a09cec114016cba4c05763d1a0 | Java | sandeepborkartech/src | /com/lms/app/vo/ReportCriteriaVo.java | UTF-8 | 2,449 | 1.960938 | 2 | [] | no_license | package com.lms.app.vo;
import com.lms.app.util.LMSUtility;
public class ReportCriteriaVo
{
private String tobilldate;
private String frombilldate;
private String topaiddate;
private String frompaiddate;
private String customername;
private String paystatus;
private String servicetype;
public String getTopaiddate()
{
return this.topaiddate;
}
public void setTopaiddate(String topaiddate)
{
String toDate;
//String toDate;
if ((topaiddate == "") || (topaiddate == null)) {
toDate = topaiddate;
} else {
toDate = LMSUtility.DBformatDate(topaiddate);
}
this.topaiddate = toDate;
}
public String getFrompaiddate()
{
return this.frompaiddate;
}
public void setFrompaiddate(String frompaiddate)
{
String fromDate;
//String fromDate;
if ((frompaiddate == "") || (frompaiddate == null)) {
fromDate = frompaiddate;
} else {
fromDate = LMSUtility.DBformatDate(frompaiddate);
}
this.frompaiddate = fromDate;
}
public ReportCriteriaVo()
{
this.tobilldate = null;
this.frombilldate = null;
this.customername = null;
this.paystatus = null;
this.servicetype = null;
}
public String getTobilldate()
{
return this.tobilldate;
}
public void setTobilldate(String tobilldate)
{
String toDate;
//String toDate;
if ((tobilldate == "") || (tobilldate == null)) {
toDate = tobilldate;
} else {
toDate = LMSUtility.DBformatDate(tobilldate);
}
this.tobilldate = toDate;
}
public String getFrombilldate()
{
return this.frombilldate;
}
public void setFrombilldate(String frombilldate)
{
String fromDate;
//String fromDate;
if ((frombilldate == "") || (frombilldate == null)) {
fromDate = frombilldate;
} else {
fromDate = LMSUtility.DBformatDate(frombilldate);
}
this.frombilldate = fromDate;
}
public String getPaystatus()
{
return this.paystatus;
}
public void setPaystatus(String paystatus)
{
this.paystatus = paystatus;
}
public String getServicetype()
{
return this.servicetype;
}
public void setServicetype(String servicetype)
{
this.servicetype = servicetype;
}
public String getCustomername()
{
return this.customername;
}
public void setCustomername(String customername)
{
this.customername = customername;
}
}
| true |
ffa1f847fc5e6053032bca1d9a1dbf08704bae44 | Java | karagozidis/springboot-Angular-application | /backend/src/main/java/crm/cloudApp/backend/dto/data/modules/market/ProductMarketProjection.java | UTF-8 | 1,542 | 1.96875 | 2 | [] | no_license | package crm.cloudApp.backend.dto.data.modules.market;
import org.springframework.beans.factory.annotation.Value;
import java.time.Instant;
public interface ProductMarketProjection {
@Value("#{target.id}")
public Long getId();
@Value("#{target.name}")
public String getName();
@Value("#{target.delivery_time_start}")
public Instant getDeliveryTimeStart();
@Value("#{target.delivery_time_end}")
public Instant getDeliveryTimeEnd();
@Value("#{target.period}")
public String getPeriod();
@Value("#{target.product_status}")
public String getProductStatus();
@Value("#{target.closes_at}")
public Instant getClosesAt();
@Value("#{@orderService.buildOrderDTO(" +
"target.buy_id, " +
"target.buy_bid_time, " +
"target.buy_price, " +
"target.buy_quantity, " +
"target.buy_current_price, " +
"target.buy_current_quantity, " +
"target.buy_metadata, " +
"target.buy_order_status, " +
"target.buy_order_direction, " +
"target.buy_order_type, " +
")}")
public SingleOrderDTO getLatestBuyOrder();
@Value("#{@orderService.buildOrderDTO(" +
"target.sell_id, " +
"target.sell_bid_time, " +
"target.sell_price, " +
"target.sell_quantity, " +
"target.sell_current_price, " +
"target.sell_current_quantity, " +
"target.sell_metadata, " +
"target.sell_order_status, " +
"target.sell_order_direction, " +
"target.sell_order_type, " +
")}")
public SingleOrderDTO getLatestSellOrder();
}
| true |
802471957bb6a2fec4384cfa758c70f6f808b51b | Java | idodevjobs/spring-data-rest-xml-config-example | /src/main/java/com/idodevjobs/example/entity/Task.java | UTF-8 | 1,656 | 2.515625 | 3 | [] | no_license | package com.idodevjobs.example.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String description;
private String priority;
private String status;
private boolean archived;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public boolean isArchived() {
return archived;
}
public void setArchived(boolean archived) {
this.archived = archived;
}
@Override
public String toString() {
return "Task{" +
"id=" + id +
", name='" + name + '\'' +
", description='" + description + '\'' +
", priority='" + priority + '\'' +
", status='" + status + '\'' +
", archived=" + archived +
'}';
}
}
| true |
c53bffc93729a4d35d0959ad1d85c16cea4aa31e | Java | miloskubacek/TAMZII_PRO | /app/src/main/java/com/example/onlinedndproject/NewSessActivity.java | UTF-8 | 3,771 | 2.09375 | 2 | [] | no_license | package com.example.onlinedndproject;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class NewSessActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newsess);
Spinner spinner = findViewById(R.id.StorySpinner);
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Postapo");
arrayList.add("Fantasy");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrayList);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(arrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String profName = parent.getItemAtPosition(position).toString();
//Toast.makeText(parent.getContext(), "Selected: " + profName, Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView <?> parent) {
}
});
Button createSButt = (Button)findViewById(R.id.createSButt);
createSButt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText city = (EditText)findViewById(R.id.cityName);
EditText capp = (EditText)findViewById(R.id.editPlayerCapacity);
DatePicker date = (DatePicker)findViewById(R.id.myDatePicker);
String dateS = String.valueOf(date.getYear()) + "/" + String.valueOf(date.getMonth()) + "/" +String.valueOf(date.getDayOfMonth());
Spinner story = (Spinner)findViewById(R.id.StorySpinner);
String input ="\n"+String.valueOf(getIntent().getExtras().getInt("sess_id"))+"," + city.getText().toString() + "," +dateS + "," +capp.getText().toString() + ","+String.valueOf(story.getSelectedItemPosition()+1);
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
}
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
}
File sdCard = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File dir = new File (sdCard.getAbsolutePath());
dir.mkdirs();
File file = new File(dir, "sessions.csv");
int i=0;
try {
BufferedWriter csvWriter = new BufferedWriter(new FileWriter(file, true));
csvWriter.append(input);
csvWriter.flush();
csvWriter.close();
} catch (
IOException e) {
e.printStackTrace();
}
finish();
}
});
}
}
| true |
b167904d44f52e63f07fefd390e62c72df3c62a4 | Java | bellmit/base-repository | /repository-xcrm/src/main/java/com/repository/xcrm/Po/ClassinAwardEnd.java | UTF-8 | 2,107 | 1.929688 | 2 | [] | no_license | package com.repository.xcrm.Po;
import java.util.Date;
public class ClassinAwardEnd {
private Long id;
private String classId;
private String courseId;
private String closeTime;
private String startTime;
private String awardUid;
private String awardTotal;
private Integer status;
private Date createTime;
private Date updateTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getClassId() {
return classId;
}
public void setClassId(String classId) {
this.classId = classId == null ? null : classId.trim();
}
public String getCourseId() {
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId == null ? null : courseId.trim();
}
public String getCloseTime() {
return closeTime;
}
public void setCloseTime(String closeTime) {
this.closeTime = closeTime == null ? null : closeTime.trim();
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime == null ? null : startTime.trim();
}
public String getAwardUid() {
return awardUid;
}
public void setAwardUid(String awardUid) {
this.awardUid = awardUid == null ? null : awardUid.trim();
}
public String getAwardTotal() {
return awardTotal;
}
public void setAwardTotal(String awardTotal) {
this.awardTotal = awardTotal == null ? null : awardTotal.trim();
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
} | true |
4f7525e6ba9e72f0f0e466ae470472a6b40bc58e | Java | braboteam/brabo | /src/service/recipe/RecipeInputService.java | UTF-8 | 2,977 | 2.3125 | 2 | [] | no_license | package service.recipe;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletContext;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service
public class RecipeInputService {
@Autowired
SqlSessionTemplate template;
@Autowired
ServletContext ctx;
// recipe_info 테이블에 데이터 집어넣기
public boolean inputInfo(Map info, MultipartFile iphoto) throws IllegalStateException, IOException {
String path = ctx.getRealPath("/iphoto/" + info.get("id"));
File file = new File(path);
if (!file.exists())
file.mkdirs();
int chk = 0;
if (!iphoto.isEmpty()) {
String rename = (String) info.get("iphoto");
File photo = new File(path, rename);
chk = template.insert("recipe_info.insertInfo", info);
iphoto.transferTo(photo);
}
return chk == 1;
}
// recipe_info 테이블의 pk 값 가져오기
public int getInfoNo(String iphoto) {
return template.selectOne("recipe_info.selectInfoNo", iphoto);
}
// recipe_detail 테이블에 데이터 집어넣기
public boolean inputDetail(String id, Map detail, MultipartFile[] dphoto) throws IllegalStateException, IOException {
String path = ctx.getRealPath("/dphoto/" + id);
File file = new File(path);
if (!file.exists())
file.mkdirs();
int chk = 0;
List steps = (List) detail.get("step");
List recipies = (List) detail.get("recipe");
for (int i = 0; i < steps.size(); i++) {
Map<String, Object> map = new HashMap<>();
String rename = UUID.randomUUID().toString().substring(0, 12) + ".jpg";
File photo = new File(path, rename);
map.put("ino", detail.get("ino"));
map.put("step", steps.get(i));
map.put("recipe", recipies.get(i));
if(!dphoto[i].isEmpty()) {
map.put("dphoto", rename);
dphoto[i].transferTo(photo);
} else {
map.put("dphoto", "default");
}
chk += template.insert("recipe_detail.insertDetail", map);
}
return chk == steps.size();
}
// recipe_final 테이블 - 완성된 요리사진 테이블에 사진 집어넣기
public boolean inputFinal(String id, int ino, MultipartFile[] fphoto) throws IllegalStateException, IOException {
String path = ctx.getRealPath("/fphoto/" + id);
File file = new File(path);
if (!file.exists())
file.mkdirs();
int chk = 0;
if(!fphoto[0].isEmpty()) {
for(int i=0; i< fphoto.length; i++) {
Map<String,Object> map = new HashMap<>();
String rename = UUID.randomUUID().toString().substring(0, 12) + ".jpg";
File photo = new File(path, rename);
map.put("ino", ino);
map.put("fphoto", rename);
chk += template.insert("recipe_final.insertFinal",map);
fphoto[i].transferTo(photo);
}
}
return chk == fphoto.length;
}
}
| true |
8fb1bec8d252fcea978d4b37a6f1d9ba2ad58e16 | Java | akonoroshi/SourceCheck | /CTD/src/edu/isnap/hint/util/KMedoids.java | UTF-8 | 5,272 | 3.34375 | 3 | [] | no_license | package edu.isnap.hint.util;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
/**
* Credit: Java ML Library
*
* Implementation of the K-medoids algorithm. K-medoids is a clustering
* algorithm that is very much like k-means. The main difference between the two
* algorithms is the cluster center they use. K-means uses the average of all
* instances in a cluster, while k-medoids uses the instance that is the closest
* to the mean, i.e. the most 'central' point of the cluster.
*
* Using an actual point of the data set to cluster makes the k-medoids
* algorithm more robust to outliers than the k-means algorithm.
*
*
* @author Thomas Abeel
*
*/
public class KMedoids<T> {
/* Distance measure to measure the distance between instances */
private DistanceMeasure<T> dm;
/* Number of clusters to generate */
private int numberOfClusters;
/* Random generator for selection of candidate medoids */
private Random rg;
/* The maximum number of iterations the algorithm is allowed to run. */
private int maxIterations;
/**
* Creates a new instance of the k-medoids algorithm with the specified
* parameters.
*
* @param numberOfClusters
* the number of clusters to generate
* @param maxIterations
* the maximum number of iteration the algorithm is allowed to
* run
* @param DistanceMeasure
* dm the distance metric to use for measuring the distance
* between instances
*
*/
public KMedoids(int numberOfClusters, int maxIterations, DistanceMeasure<T> dm) {
super();
this.numberOfClusters = numberOfClusters;
this.maxIterations = maxIterations;
this.dm = dm;
rg = new Random(System.currentTimeMillis());
}
public List<List<T>> cluster(List<T> data) {
List<T> medoids = new LinkedList<>();
List<List<T>> output = new LinkedList<>();
for (int i = 0; i < numberOfClusters; i++) {
// TODO: choose non-overlapping medoids
int random = rg.nextInt(data.size());
medoids.add(data.get(random));
output.add(new LinkedList<T>());
}
boolean changed = true;
int count = 0;
while (changed && count++ < maxIterations) {
int[] assignment = assign(medoids, data);
changed = recalculateMedoids(assignment, medoids, output, data);
}
return output;
}
/**
* Assign all instances from the data set to the medoids.
*
* @param medoids candidate medoids
* @param data the data to assign to the medoids
* @return best cluster indices for each instance in the data set
*/
private int[] assign(List<T> medoids, List<T> data) {
int[] out = new int[data.size()];
for (int i = 0; i < data.size(); i++) {
double bestDistance = dm.measure(data.get(i), medoids.get(0));
int bestIndex = 0;
for (int j = 1; j < medoids.size(); j++) {
double tmpDistance = dm.measure(data.get(i), medoids.get(j));
if (tmpDistance < bestDistance) {
bestDistance = tmpDistance;
bestIndex = j;
}
}
out[i] = bestIndex;
}
return out;
}
/**
* Return a array with on each position the clusterIndex to which the
* Instance on that position in the dataset belongs.
*
* @param medoids
* the current set of cluster medoids, will be modified to fit
* the new assignment
* @param assigment
* the new assignment of all instances to the different medoids
* @param output
* the cluster output, this will be modified at the end of the
* method
* @return the
*/
private boolean recalculateMedoids(int[] assignment, List<T> medoids,
List<List<T>> output, List<T> data) {
boolean changed = false;
for (int i = 0; i < numberOfClusters; i++) {
List<T> cluster = output.get(i);
cluster.clear();
for (int j = 0; j < assignment.length; j++) {
if (assignment[j] == i) {
cluster.add(data.get(j));
}
}
if (cluster.size() == 0) { // new random, empty medoid
medoids.set(i, data.get(rg.nextInt(data.size())));
changed = true;
} else {
T medoid = medoids.get(i);
double bestDistance = totalDistance(cluster, medoid);
for (T possibleMedoid : cluster) {
if (possibleMedoid == medoid) continue;
double distance = totalDistance(cluster, possibleMedoid);
if (distance < bestDistance) {
bestDistance = distance;
medoid = possibleMedoid;
changed = true;
}
}
medoids.set(i, medoid);
}
}
return changed;
}
private double totalDistance(List<T> cluster, T medoid) {
double distance = 0;
for (T t : cluster) {
distance += dm.measure(t, medoid);
}
return distance;
}
public interface DistanceMeasure<T> {
double measure(T a, T b);
}
public static void main(String[] args) {
int size = 100;
int max = 300;
List<Integer> data = new LinkedList<>();
for (int i = 0; i < size; i++) {
data.add((int) (Math.random() * max));
}
KMedoids<Integer> km = new KMedoids<>(8, 1000, new DistanceMeasure<Integer>() {
@Override
public double measure(Integer a, Integer b) {
return Math.abs(a - b);
}
});
List<List<Integer>> clusters = km.cluster(data);
System.out.println("Clusters:");
for (int i = 0; i < clusters.size(); i++) {
System.out.println(i + ": " + clusters.get(i));
}
}
}
| true |
031b6721d9a01bdea9f3335fee50b8f914a3388c | Java | aspose-slides/Aspose.Slides-for-Java | /Examples/src/main/java/com/aspose/slides/examples/text/AddingSuperscriptAndSubscriptTextInTextFrame.java | UTF-8 | 2,317 | 2.9375 | 3 | [
"MIT"
] | permissive | package com.aspose.slides.examples.text;
import com.aspose.slides.*;
import com.aspose.slides.examples.RunExamples;
public class AddingSuperscriptAndSubscriptTextInTextFrame
{
public static void main(String[] args)
{
//ExStart:AddingSuperscriptAndSubscriptTextInTextFrame
// The path to the documents directory.
String dataDir = RunExamples.getDataDir_Text();
Presentation presentation = new Presentation();
try
{
// Get slide
ISlide slide = presentation.getSlides().get_Item(0);
// Create text box
IAutoShape shape = slide.getShapes().addAutoShape(ShapeType.Rectangle, 100, 100, 200, 100);
ITextFrame textFrame = shape.getTextFrame();
textFrame.getParagraphs().clear();
// Create paragraph for superscript text
IParagraph superPar = new Paragraph();
// Create portion with usual text
IPortion portion1 = new Portion();
portion1.setText("SlideTitle");
superPar.getPortions().add(portion1);
// Create portion with superscript text
IPortion superPortion = new Portion();
superPortion.getPortionFormat().setEscapement(30);
superPortion.setText("TM");
superPar.getPortions().add(superPortion);
// Create paragraph for subscript text
IParagraph paragraph2 = new Paragraph();
// Create portion with usual text
IPortion portion2 = new Portion();
portion2.setText("a");
paragraph2.getPortions().add(portion2);
// Create portion with subscript text
IPortion subPortion = new Portion();
subPortion.getPortionFormat().setEscapement(-25);
subPortion.setText("i");
paragraph2.getPortions().add(subPortion);
// Add paragraphs to text box
textFrame.getParagraphs().add(superPar);
textFrame.getParagraphs().add(paragraph2);
presentation.save(RunExamples.getOutPath() + "TestOut.pptx", SaveFormat.Pptx);
}
finally
{
if (presentation != null) presentation.dispose();
}
//ExEnd:AddingSuperscriptAndSubscriptTextInTextFrame
}
}
| true |
7f35afc4b455d95c9efbc70eb15e5138a3864646 | Java | marcsue/TrabalhoSBD | /SBD/src/banco/UnidadeDAO.java | UTF-8 | 1,860 | 2.8125 | 3 | [] | no_license | package banco;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import areasUniversidade.Curso;
import areasUniversidade.Unidade;
public class UnidadeDAO
{
private Connection connection;
public UnidadeDAO() throws ClassNotFoundException
{
this.connection = new ConnectionFactory().getConnection();
}
public ArrayList<Unidade> buscaTodas()
{
try
{
ArrayList<Unidade> unidades = new ArrayList<Unidade>();
String sql = "SELECT * FROM unidade;";
PreparedStatement stmt = connection.prepareStatement(sql);
ResultSet resultado = stmt.executeQuery();
while(resultado.next())
{
Unidade uni = new Unidade();
//o set é de unidade academica o objeto, e o get é do banco de dados o paramentro do get tem que ser igual o nome da coluna no Banco
uni.setSigla(resultado.getString("sigla"));
uni.setNome(resultado.getString("nome"));
uni.setTipo(resultado.getInt("tipo_unidade"));
unidades.add(uni);
}
stmt.close();
return unidades;
}
catch (SQLException e)
{
System.out.println(e);
return null;
}
}
public Unidade buscaSigla(String sigla) throws SQLException
{
try
{
Unidade unidadeAC = new Unidade();
String sql = "SELECT * FROM unidade WHERE sigla = ?;";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1,sigla);
ResultSet resultado = stmt.executeQuery();
while(resultado.next())
{
unidadeAC.setSigla(resultado.getString("sigla"));
unidadeAC.setNome(resultado.getString("nome"));
unidadeAC.setTipo(resultado.getInt("tipo_unidade"));
}
stmt.close();
return unidadeAC;
}
catch (SQLException e)
{
return null;
}
}
} | true |
848c230c2cbd5d574cdf12ab28fb9f2b2396243c | Java | diamondq/dq-common-java | /tracing/common-tracing.jaeger/src/main/java/com/diamondq/common/tracing/jaeger/ZipkinReporterProvider.java | UTF-8 | 1,066 | 1.921875 | 2 | [
"Apache-2.0"
] | permissive | package com.diamondq.common.tracing.jaeger;
import com.diamondq.common.config.Config;
import io.jaegertracing.internal.reporters.RemoteReporter;
import io.jaegertracing.spi.Reporter;
import io.jaegertracing.zipkin.ZipkinSender;
import org.jetbrains.annotations.Nullable;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Instance;
import javax.enterprise.inject.Produces;
@ApplicationScoped
public class ZipkinReporterProvider {
@Produces
@Dependent
public @Nullable Reporter getZipkinReporter(Instance<Config> pConfig) {
if ((pConfig.isAmbiguous() == true) || (pConfig.isUnsatisfied() == true)) return null;
Config config = pConfig.get();
String zipkinURL = config.bind("tracing.zipkin.url", String.class);
if (zipkinURL == null) return null;
// Metrics metrics = new Metrics(new StatsFactoryImpl(new NullStatsReporter()));
return new RemoteReporter.Builder().withSender(ZipkinSender.create(zipkinURL))
// .withMetrics(metrics)
.build();
}
}
| true |
9b15b7caffbe868d93bfaf1a02177e391b482d75 | Java | wang-zifu/JavaPractice | /randomfile_6/src/randomfile_6.java | UTF-8 | 264 | 2.59375 | 3 | [] | no_license |
public class randomfile_6 {
public static void main(String[] args){
Pyramid(1);
}
public static void Pyramid(int a){
for(int i = 1; i <= a;i++){
for(int j = 1; j <= i; j++){
System.out.print(i);
}
System.out.println("");
}
}
}
| true |
c5149d2fd2ea2964ee3e8631a7efcf2a0daa8523 | Java | Ufoex/Ferreteria_Alcazar | /src/controlador/ControladorEmpleados.java | UTF-8 | 15,838 | 2.6875 | 3 | [] | no_license | package controlador;
import modelo.ConsultasEmpleados;
import modelo.ModeloEmpleados;
import vista.Empleados;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class ControladorEmpleados implements KeyListener {
//Sirven para agregar las vistas y los controladores por separado
Empleados Empleados = new Empleados();
ModeloEmpleados ModeloEmpleados = new ModeloEmpleados();
ConsultasEmpleados ConsultasEmpleados = new ConsultasEmpleados();
public ControladorEmpleados(){
agregarListener();
Empleados.setVisible(true);
oyentes();
}
private void agregarListener() {
//Listeners del Botón Actualizar
Empleados.actualizar.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
if(validarCampos()==false){
JOptionPane.showMessageDialog(Empleados,"Los campos no deben estar vacios");
}
else{
llenarModeloConVista(); //Llena modelo o datos de vista
if(ConsultasEmpleados.actualizar(ModeloEmpleados)==true){
JOptionPane.showMessageDialog(Empleados, "Datos actualizados correctamente. ");
limpiarCampos();
}else{
JOptionPane.showMessageDialog(Empleados,"No se actualizaron los datos");
}
}
}
@Override
public void mousePressed(MouseEvent e) {
Empleados.actualizar.setIcon(new ImageIcon(getClass().getResource("/imagenes/actualizarSelect.png")));
}
@Override
public void mouseReleased(MouseEvent e) {
Empleados.actualizar.setIcon(new ImageIcon(getClass().getResource("/imagenes/actualizar.png")));
}
@Override
public void mouseEntered(MouseEvent e) {
Empleados.actualizar.setIcon(new ImageIcon(getClass().getResource("/imagenes/actualizarEntered.png")));
Empleados.actualizar.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
@Override
public void mouseExited(MouseEvent e) {
Empleados.actualizar.setIcon(new ImageIcon(getClass().getResource("/imagenes/actualizar.png")));
}
});
//Listeners del Botón Guardar
Empleados.guardar.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
if(validarCampos()==false){
JOptionPane.showMessageDialog(Empleados,"Los campos no deben estar vacios");
}
else{
llenarModeloConVista();
if(ConsultasEmpleados.insertar(ModeloEmpleados)==true){
JOptionPane.showMessageDialog(Empleados, "Datos insertados correctamente. ");
limpiarCampos();
}else{
JOptionPane.showMessageDialog(Empleados,"No se insertaron los datos");
}
}
}
@Override
public void mousePressed(MouseEvent e) {
Empleados.guardar.setIcon(new ImageIcon(getClass().getResource("/imagenes/guardarselect.png")));
}
@Override
public void mouseReleased(MouseEvent e) {
Empleados.guardar.setIcon(new ImageIcon(getClass().getResource("/imagenes/guardar.png")));
}
@Override
public void mouseEntered(MouseEvent e) {
Empleados.guardar.setIcon(new ImageIcon(getClass().getResource("/imagenes/guardarEntered.png")));
Empleados.guardar.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
@Override
public void mouseExited(MouseEvent e) {
Empleados.guardar.setIcon(new ImageIcon(getClass().getResource("/imagenes/guardar.png")));
}
});
//Listeners del Botón Limpiar
Empleados.limpiar.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
limpiarCampos();
}
@Override
public void mousePressed(MouseEvent e) {
Empleados.limpiar.setIcon(new ImageIcon(getClass().getResource("/imagenes/limpiarSelect.png")));
}
@Override
public void mouseReleased(MouseEvent e) {
Empleados.limpiar.setIcon(new ImageIcon(getClass().getResource("/imagenes/limpiar.png")));
}
@Override
public void mouseEntered(MouseEvent e) {
Empleados.limpiar.setIcon(new ImageIcon(getClass().getResource("/imagenes/limpiarEntered.png")));
Empleados.limpiar.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
@Override
public void mouseExited(MouseEvent e) {
Empleados.limpiar.setIcon(new ImageIcon(getClass().getResource("/imagenes/limpiar.png")));
}
});
//Listeners del Botón Eliminar
Empleados.eliminar.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
if(Empleados.IdEmpleado.getText().isEmpty()){
JOptionPane.showMessageDialog(Empleados,"El codigo no debe estar vacio");
}
else{
llenarModeloConVista();
if(ConsultasEmpleados.eliminar(ModeloEmpleados)==true){
JOptionPane.showMessageDialog(Empleados, "Datos eliminados correctamente. ");
limpiarCampos();
}else{
JOptionPane.showMessageDialog(Empleados,"No se eliminaron los datos");
}
}
}
@Override
public void mousePressed(MouseEvent e) {
Empleados.eliminar.setIcon(new ImageIcon(getClass().getResource("/imagenes/eliminarSelect.png")));
}
@Override
public void mouseReleased(MouseEvent e) {
Empleados.eliminar.setIcon(new ImageIcon(getClass().getResource("/imagenes/eliminar.png")));
}
@Override
public void mouseEntered(MouseEvent e) {
Empleados.eliminar.setIcon(new ImageIcon(getClass().getResource("/imagenes/eliminarEntered.png")));
Empleados.eliminar.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
@Override
public void mouseExited(MouseEvent e) {
Empleados.eliminar.setIcon(new ImageIcon(getClass().getResource("/imagenes/eliminar.png")));
}
});
//Listeners del Botón Buscar
Empleados.buscar.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
ControladorBuscarEmpleados VentanaBuscar = new ControladorBuscarEmpleados(ModeloEmpleados);
//llenar la vista con el modelo
llenarVistaConModelo();
}
@Override
public void mousePressed(MouseEvent e) {
Empleados.buscar.setIcon(new ImageIcon(getClass().getResource("/imagenes/buscarSelect.png")));
}
@Override
public void mouseReleased(MouseEvent e) {
Empleados.buscar.setIcon(new ImageIcon(getClass().getResource("/imagenes/buscar.png")));
}
@Override
public void mouseEntered(MouseEvent e) {
Empleados.buscar.setIcon(new ImageIcon(getClass().getResource("/imagenes/buscarEntered.png")));
Empleados.buscar.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
@Override
public void mouseExited(MouseEvent e) {
Empleados.buscar.setIcon(new ImageIcon(getClass().getResource("/imagenes/buscar.png")));
}
});
//Listeners del Botón Salir
Empleados.salir.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
int opcion = JOptionPane.showConfirmDialog(Empleados.salir, "En verdad quieres salir", "Salir", 0, 3);
if (opcion == 0) {
Empleados.dispose();
ControladorVistaMenu test2 = new ControladorVistaMenu();
}
}
@Override
public void mousePressed(MouseEvent e) {
Empleados.salir.setIcon(new ImageIcon(getClass().getResource("/imagenes/clickSalirSelect.png")));
}
@Override
public void mouseReleased(MouseEvent e) {
Empleados.salir.setIcon(new ImageIcon(getClass().getResource("/imagenes/clickSalir.png")));
}
@Override
public void mouseEntered(MouseEvent e) {
Empleados.salir.setIcon(new ImageIcon(getClass().getResource("/imagenes/clickSalir.png")));
Empleados.salir.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
@Override
public void mouseExited(MouseEvent e) {
Empleados.salir.setIcon(new ImageIcon(getClass().getResource("/imagenes/clickSalir.png")));
}
});
}
private void limpiarCampos() {
Empleados.IdEmpleado.setText("");
Empleados.nombre.setText("");
Empleados.apellidoPaterno.setText("");
Empleados.apellidoMaterno.setText("");
Empleados.rfc.setText("");
Empleados.telefono.setText("");
Empleados.sexo.setText("");
Empleados.fechaIngreso.setText("");
Empleados.turno.setText("");
Empleados.colonia.setText("");
Empleados.calle.setText("");
Empleados.numero.setText("");
//Deja el cursor en el campo de codigo
Empleados.IdEmpleado.requestFocus();
}
private boolean validarCampos() {
if (Empleados.IdEmpleado.getText().isEmpty()||
Empleados.nombre.getText().isEmpty() ||
Empleados.apellidoPaterno.getText().isEmpty() ||
Empleados.apellidoMaterno.getText().isEmpty() ||
Empleados.rfc.getText().isEmpty() ||
Empleados.telefono.getText().isEmpty() ||
Empleados.sexo.getText().isEmpty()||
Empleados.fechaIngreso.getText().isEmpty() ||
Empleados.turno.getText().isEmpty() ||
Empleados.colonia.getText().isEmpty() ||
Empleados.calle.getText().isEmpty() ||
Empleados.numero.getText().isEmpty())
{
return false; // algunos campos estan vacios
}
else{
return true; //todos los campos estan llenos
}
}
private void llenarModeloConVista() {
ModeloEmpleados.setIdEmpleado(Integer.parseInt(Empleados.IdEmpleado.getText()));
ModeloEmpleados.setNombre(Empleados.nombre.getText());
ModeloEmpleados.setApellidoPaterno(Empleados.apellidoPaterno.getText());
ModeloEmpleados.setApellidoMaterno(Empleados.apellidoMaterno.getText());
ModeloEmpleados.setRfc(Empleados.rfc.getText());
ModeloEmpleados.setTelefono(Integer.parseInt(Empleados.telefono.getText()));
ModeloEmpleados.setSexo(Empleados.sexo.getText());
ModeloEmpleados.setFechaIngreso(Empleados.fechaIngreso.getText());
ModeloEmpleados.setTurno(Empleados.turno.getText());
ModeloEmpleados.setColonia(Empleados.colonia.getText());
ModeloEmpleados.setCalle(Empleados.calle.getText());
ModeloEmpleados.setNumero(Integer.parseInt(Empleados.numero.getText()));
}
private void llenarVistaConModelo() {
Empleados.IdEmpleado.setText(ModeloEmpleados.getIdEmpleado() +"");
Empleados.nombre.setText(ModeloEmpleados.getNombre());
Empleados.apellidoPaterno.setText(ModeloEmpleados.getApellidoPaterno());
Empleados.apellidoMaterno.setText(ModeloEmpleados.getApellidoMaterno());
Empleados.rfc.setText(ModeloEmpleados.getRfc());
Empleados.telefono.setText(ModeloEmpleados.getTelefono()+"");
Empleados.sexo.setText(ModeloEmpleados.getSexo());
Empleados.fechaIngreso.setText(ModeloEmpleados.getFechaIngreso());
Empleados.turno.setText(ModeloEmpleados.getTurno());
Empleados.colonia.setText(ModeloEmpleados.getColonia());
Empleados.calle.setText(ModeloEmpleados.getCalle());
Empleados.numero.setText(ModeloEmpleados.getNumero()+"");
}
private void oyentes(){
Empleados.IdEmpleado.addKeyListener(this);
Empleados.nombre.addKeyListener(this);
Empleados.apellidoPaterno.addKeyListener(this);
Empleados.apellidoMaterno.addKeyListener(this);
Empleados.rfc.addKeyListener(this);
Empleados.telefono.addKeyListener(this);
Empleados.sexo.addKeyListener(this);
Empleados.fechaIngreso.addKeyListener(this);
Empleados.turno.addKeyListener(this);
Empleados.colonia.addKeyListener(this);
Empleados.calle.addKeyListener(this);
Empleados.numero.addKeyListener(this);
}
@Override
public void keyTyped(KeyEvent e) {
if(e.getSource()==Empleados.IdEmpleado){
if(e.getKeyChar()==e.VK_ENTER){
Empleados.nombre.requestFocus();
}
}else if(e.getSource()==Empleados.nombre){
if(e.getKeyChar()==e.VK_ENTER){
Empleados.apellidoPaterno.requestFocus();
}
}else if(e.getSource()==Empleados.apellidoPaterno){
if(e.getKeyChar()==e.VK_ENTER){
Empleados.apellidoMaterno.requestFocus();
}
}else if(e.getSource()==Empleados.apellidoMaterno){
if(e.getKeyChar()==e.VK_ENTER){
Empleados.rfc.requestFocus();
}
}else if(e.getSource()==Empleados.rfc){
if(e.getKeyChar()==e.VK_ENTER){
Empleados.telefono.requestFocus();
}
}else if (e.getSource()==Empleados.telefono){
if(e.getKeyChar()==e.VK_ENTER){
Empleados.sexo.requestFocus();
}
}else if (e.getSource()==Empleados.sexo){
if(e.getKeyChar()==e.VK_ENTER){
Empleados.fechaIngreso.requestFocus();
}
}else if (e.getSource()==Empleados.fechaIngreso){
if(e.getKeyChar()==e.VK_ENTER){
Empleados.turno.requestFocus();
}
}else if (e.getSource()==Empleados.turno){
if(e.getKeyChar()==e.VK_ENTER){
Empleados.colonia.requestFocus();
}
}else if (e.getSource()==Empleados.colonia){
if(e.getKeyChar()==e.VK_ENTER){
Empleados.calle.requestFocus();
}
}else if (e.getSource()==Empleados.calle){
if(e.getKeyChar()==e.VK_ENTER){
Empleados.numero.requestFocus();
}
}else if (e.getSource()==Empleados.numero){
if(e.getKeyChar()==e.VK_ENTER){
Empleados.guardar.requestFocus();
}
}
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
}
| true |
846e0d51ca797c43381c34898be357f9ba5442b9 | Java | KatieSanderson/AdventOfCode2018 | /src/day03/FindCorrectBoxes.java | UTF-8 | 1,294 | 3.53125 | 4 | [] | no_license | package day03;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Map;
import java.util.Scanner;
public class FindCorrectBoxes {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("input.txt");
Scanner sc = new Scanner(file);
try (Scanner next = new Scanner(file)) {
while (sc.hasNextLine()) {
String currentLine = sc.nextLine();
Map<Character, Integer> currentSums = FindSums.findSums(currentLine);
while (next.hasNextLine()) {
String nextLine = next.nextLine();
Map<Character, Integer> nextSums = FindSums.findSums(nextLine);
int charsDifferent = 0;
for (char c = 'a'; c <= 'z'; c++) {
if (currentSums.get(c) != nextSums.get(c)) {
charsDifferent += Math.abs(currentSums.get(c) - nextSums.get(c));
}
}
if (charsDifferent == 2) {
charsDifferent = 0;
for (int i = 0; i < nextLine.length(); i++) {
if (nextLine.charAt(i) != currentLine.charAt(i)) {
charsDifferent++;
if (charsDifferent > 1) {
System.out.println(" Not a valid solution");
break;
}
} else {
System.out.print(nextLine.charAt(i));
}
}
System.out.println("");
}
}
}
}
sc.close();
}
}
| true |
574c6d711f1bbf7014ad492aa2e06349b60156ab | Java | Joker-Xie/bigdata-project | /comsumer/src/main/java/com/bigdata/myproject/eshop/consumer/HDFSWriter.java | UTF-8 | 921 | 2.578125 | 3 | [] | no_license | package com.bigdata.myproject.eshop.consumer;
/*
* hdfs写入器
* */
public class HDFSWriter {
/*
* 数据写入hdfs中
* hdfs://mycluster/usr/log/2019/03/13/s201.log
* */
private String prePath = "";
private MyFSDataOutputStream out = null;
public void writeLog2HDFS(String path, String log) {
try {
if (!prePath.equals(path)) {
if (out != null) {
out.release();
out = null;
}
out =(MyFSDataOutputStream) HDFSRawStreamPool.getInstance().takeOutputStream(path);
prePath = path;
}
out.write(log.getBytes());
//由于flume收集数据不存在分行现象,需要手动分行
out.write("\r\n".getBytes());
out.hsync();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
09f23c879b4e405b2c9e1df4803dc18bf0edd77c | Java | RaphaelFOURQUET/Test | /Test/src/test/TestScanner.java | ISO-8859-1 | 1,478 | 3.515625 | 4 | [] | no_license | package test;
import java.util.Scanner;
public class TestScanner {
public static void main(String[] args) {
//Auto-generated method stub
//Scanner
Scanner sc = new Scanner(System.in); //RFRF : Creation flux entre.
System.out.println("Veuillez saisir un mot :");
String str1 = sc.nextLine();
System.out.println("Vous avez saisi : \n\t" + str1);
System.out.println("Veuillez saisir un nombre :");
int str2 = sc.nextInt(); //RFRF : erreur si on entre une chaine de caractres : pas facile corriger sans gestion d'exceptions.
System.out.println("Vous avez saisi le nombre : \n\t" + str2);
sc.nextLine(); //RFRF : Flush scanner P37 : Si on veut nextLine() aprs un nextAutre ...
System.out.println("Veuillez saisir un mot :");
String str3 = sc.nextLine();
System.out.println("Vous avez saisi : \n\t" + str3);
System.out.println("D1 : Veuillez saisir un nombre :");
double str4 = sc.nextDouble(); //RFRF : erreur si on entre une chaine de caractres : pas facile corriger sans gestion d'exceptions.
System.out.println("Vous avez saisi le nombre : \n\t" + str4);
System.out.println("D2 : Veuillez saisir un nombre :");
double str4b = sc.nextDouble(); //RFRF : erreur si on entre une chaine de caractres : pas facile corriger sans gestion d'exceptions.
System.out.println("Vous avez saisi le nombre : \n\t" + str4b);
sc.close();
}
}
| true |
d11b660ae09c33769437005a97cb07436b93a5cd | Java | nosalt99/FriendlyTeacher | /app/src/main/java/com/leedopoem/ljh/friendlyteacher/page/newlecture/NewLectureContract.java | UTF-8 | 661 | 1.765625 | 2 | [] | no_license | package com.leedopoem.ljh.friendlyteacher.page.newlecture;
import android.content.Context;
import com.leedopoem.ljh.friendlyteacher.base.BasePresenter;
import com.leedopoem.ljh.friendlyteacher.base.BaseView;
import com.leedopoem.ljh.friendlyteacher.data.entity.Lecture;
/**
* Created by Administrator on 2017/10/21 0021.
*/
public class NewLectureContract {
interface View extends BaseView<NewLectureContract.Presenter> {
void showProgressbar();
void confirmBack();
Lecture getContentLecture();
}
interface Presenter extends BasePresenter {
void publishLecture(Context context);
void confirmBack();
}
} | true |
34da79a5791ed4feedf6875140d0a8bdac72509c | Java | lin826/Synesthesia | /src/player1/MainApp.java | UTF-8 | 179 | 1.648438 | 2 | [] | no_license | package player1;
public class MainApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
p1_Game game = new p1_Game();
game.start();
}
}
| true |
e8b43a9fd818ecc40a74945752a7eed3b06be55f | Java | EricHorvat/itba_ati_2019_Q1 | /src/main/java/ar/ed/itba/ui/listeners/button/filter/menu/tp1/GaussianFilterMenuButtonListener.java | UTF-8 | 418 | 1.65625 | 2 | [] | no_license | package ar.ed.itba.ui.listeners.button.filter.menu.tp1;
import ar.ed.itba.ui.components.MenuOptionButtonFactory;
import ar.ed.itba.ui.listeners.button.filter.menu.MaskFilterMenuButtonListener;
public class GaussianFilterMenuButtonListener extends MaskFilterMenuButtonListener {
public GaussianFilterMenuButtonListener() {
options.add(MenuOptionButtonFactory.gaussianFilterMenuOptionButton(maskSideField));
}
}
| true |
8a0b073265b4bd182f91bed01625a5647d19427b | Java | BhaskarR02/personal-web | /personal-data/src/main/java/com/dashboard/dbService/impl/DashBoardDaoImpl.java | UTF-8 | 736 | 2.0625 | 2 | [] | no_license | package com.dashboard.dbService.impl;
import org.hibernate.Query;
import com.bhaskar.generic.dao.GenericDaoImpl;
import com.dashboard.dbServiceInterface.DashBoardUserDao;
import com.dashboard.entity.DashBoardUser;
import com.infosys.tedge.base.DaException;
public class DashBoardDaoImpl extends GenericDaoImpl<DashBoardUser, String> implements DashBoardUserDao {
public DashBoardDaoImpl(Class<DashBoardUser> type) {
super(type);
// TODO Auto-generated constructor stub
}
public DashBoardUser getLoggerUser() throws DaException {
DashBoardUser dashBoardUser = new DashBoardUser();
Query query = getSession().getNamedQuery("getUser");
dashBoardUser = (DashBoardUser) query.list().get(0);
return dashBoardUser;
}
}
| true |
5a12e7ffe4c1d9eb305afc496ab0b18fbfc0b473 | Java | Bhaskers-Blu-Org1/FHIR | /operation/fhir-operation-bulkdata/src/main/java/com/ibm/fhir/operation/bulkdata/model/PollingLocationResponse.java | UTF-8 | 6,725 | 1.953125 | 2 | [
"Apache-2.0"
] | permissive | /*
* (C) Copyright IBM Corp. 2019, 2020
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.ibm.fhir.operation.bulkdata.model;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.json.Json;
import javax.json.stream.JsonGenerator;
import javax.json.stream.JsonGeneratorFactory;
import com.ibm.fhir.config.FHIRConfigHelper;
import com.ibm.fhir.config.FHIRConfiguration;
/**
* ResponseMetadata to manipulate the response back to the client.
* This response object is intent for the polling location.
*/
public class PollingLocationResponse {
private String transactionTime;
private String request;
private Boolean requiresAccessToken;
private List<Output> output;
private List<Output> error;
public String getTransactionTime() {
return transactionTime;
}
public void setTransactionTime(String transactionTime) {
this.transactionTime = transactionTime;
}
public String getRequest() {
return request;
}
public void setRequest(String request) {
this.request = request;
}
public Boolean getRequiresAccessToken() {
return requiresAccessToken;
}
public void setRequiresAccessToken(Boolean requiresAccessToken) {
this.requiresAccessToken = requiresAccessToken;
}
public List<Output> getOutput() {
return output;
}
public void setOutput(List<Output> output) {
this.output = output;
}
public List<Output> getError() {
return error;
}
public void setError(List<Output> error) {
this.error = error;
}
public static class Output {
private String type;
private String url;
private String count;
private String inputUrl;
// constructor is used for $export
public Output(String type, String url, String count) {
super();
this.type = type;
this.url = url;
this.count = count;
}
// constructor is used for $import
public Output(String type, String url, String count, String inputUrl) {
super();
this.type = type;
this.url = url;
this.count = count;
this.inputUrl = inputUrl;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public String getInputUrl() {
return inputUrl;
}
public void setInputUrl(String inputUrl) {
this.inputUrl = inputUrl;
}
@Override
public String toString() {
return "Output [type=" + type + ", url=" + url + ", count=" + count + ", inputUrl=" + inputUrl + "]";
}
/*
* This is an internal only class not intended to be used out of bulkdata.
* The class serializes the Output into a JSON object.
*/
public static class Writer {
private Writer() {
// No Operation
}
public static void generate(JsonGenerator generatorOutput, Output output) throws IOException {
generatorOutput.writeStartObject();
if (output.getType() != null) {
generatorOutput.write("type", output.getType());
}
if (output.getUrl() != null) {
generatorOutput.write("url", output.getUrl());
}
if (output.getCount() != null) {
generatorOutput.write("count", Long.parseLong(output.getCount()));
}
if (output.getInputUrl() != null) {
generatorOutput.write("inputUrl", output.getInputUrl());
}
generatorOutput.writeEnd();
}
}
}
/*
* This is an internal only class not intended to be used out of bulkdata.
* The class serializes the PollingLocationResponse into a JSON object.
*/
public static class Writer {
private Writer() {
// No Operation
}
public static String generate(PollingLocationResponse response) throws IOException {
Boolean pretty =
FHIRConfigHelper.getBooleanProperty(FHIRConfiguration.PROPERTY_DEFAULT_PRETTY_PRINT, false);
final Map<java.lang.String, Object> properties =
Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, pretty);
final JsonGeneratorFactory factory = Json.createGeneratorFactory(properties);
String o = "{}";
try (StringWriter writer = new StringWriter();) {
try (JsonGenerator generator = factory.createGenerator(writer);) {
generator.writeStartObject();
if (response.getTransactionTime() != null) {
generator.write("transactionTime", response.getTransactionTime());
}
if (response.getRequest() != null) {
generator.write("request", response.getRequest());
}
if (response.getRequiresAccessToken() != null) {
generator.write("requiresAccessToken", response.getRequiresAccessToken());
}
if (response.getOutput() != null) {
// outputs the output array.
generator.writeStartArray("output");
for (Output output : response.getOutput()) {
Output.Writer.generate(generator, output);
}
generator.writeEnd();
}
if (response.getError() != null) {
// outputs the output array.
generator.writeStartArray("error");
for (Output output : response.getError()) {
Output.Writer.generate(generator, output);
}
generator.writeEnd();
}
generator.writeEnd();
}
o = writer.toString();
}
return o;
}
}
} | true |
271393f3b8e22a051d5e83703817a49d3613dd83 | Java | xruiz81/spirit-creacional | /comun-server/src/main/java/com/spirit/inventario/session/GiftcardMovimientoSessionEJB.java | UTF-8 | 1,912 | 2.171875 | 2 | [] | no_license | package com.spirit.inventario.session;
import java.math.BigDecimal;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.spirit.inventario.session.GiftcardMovimientoSessionRemote;
import com.spirit.inventario.session.generated._GiftcardMovimientoSession;
import com.spirit.server.LogService;
import com.spirit.server.Logger;
/**
*
* @author www.versality.com.ec
*
*/
@Stateless
public class GiftcardMovimientoSessionEJB extends _GiftcardMovimientoSession implements GiftcardMovimientoSessionRemote,GiftcardMovimientoSessionLocal {
@PersistenceContext(unitName = "spirit")
private EntityManager manager;
/**
* The logger object.
*/
private static Logger log = LogService.getLogger(GiftcardMovimientoSessionEJB.class);
/*******************************************************************************************************************
* B U S I N E S S M E T H O D S
*******************************************************************************************************************/
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public BigDecimal getValorMinimoGiftcardHistorial(Long idgiftCard)
throws com.spirit.exception.GenericBusinessException
{
BigDecimal countResult=new BigDecimal("0.00");
Query countQuery = manager.createQuery("select min(gc.saldoFinal) from GiftcardMovimientoEJB gc where gc.giftcardId='" + idgiftCard+"'");
List countQueryResult = countQuery.getResultList();
if(countQueryResult.get(0)!=null)
countResult = (BigDecimal) countQueryResult.get(0);
//log.debug("The list size is: " + countResult.intValue());
return countResult;
}
}
| true |
9e436948da6d7cd34fffe1cfb22ccfd1a2353603 | Java | tahmid-chowdhury/ICS4U1-homework | /java/daily/september/review/question1.java | UTF-8 | 404 | 2.828125 | 3 | [] | no_license |
import java.util.Scanner;
public class question1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter name: ");
String name = sc.nextLine();
System.out.println("Enter age: ");
String age = sc.nextLine();
System.out.println("\nName: " + name + "\nAge: " + age);
sc.close();
}
}
| true |
a4fc715a8aca43f2dc379c6ecafe8e1602d4126c | Java | SinhaVidhi/my-notesAPP-project | /notes-app/app/src/main/java/index1/developer/vidhi/com/mynotesapp/Utilities.java | UTF-8 | 2,965 | 2.75 | 3 | [] | no_license | package index1.developer.vidhi.com.mynotesapp;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import java.io.*;
import java.util.ArrayList;
public class Utilities {
public static final String EXTRAS_NOTE_FILENAME = "EXTRAS_NOTE_FILENAME";
public static final String FILE_EXTENSION = ".bin";
public static boolean saveNote(Context context, Note note) {
String filename = String.valueOf(note.getDt()) + FILE_EXTENSION;
FileOutputStream fos;
ObjectOutputStream oos;
try {
fos = context.openFileOutput(filename, context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(note);
oos.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public static ArrayList<Note> getAllSavedNotes(Context context) {
ArrayList<Note> notes = new ArrayList<>();
File filesDir = context.getFilesDir();
ArrayList<String> noteFiles = new ArrayList<>();
for (String file : filesDir.list()) {
if (file.endsWith(FILE_EXTENSION)) {
noteFiles.add(file);
}
}
FileInputStream f1;
ObjectInputStream o1;
for (int i = 0; i < noteFiles.size(); i++) {
try {
f1 = context.openFileInput(noteFiles.get(i));
o1 = new ObjectInputStream(f1);
notes.add((Note) o1.readObject());
f1.close();
o1.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
return notes;
}
public void display(){
// Toast.makeText(getActivity(),"Show",Toast.LENGTH_SHORT).show();
}
public static Note getNoteByFileName(Context context, String fileName) {
File file = new File(context.getFilesDir(), fileName);
if (file.exists() && !file.isDirectory()) { //check if file actually exist
Log.v("UTILITIES", "File exist = " + fileName);
FileInputStream f1;
ObjectInputStream o1;
try {
f1 = context.openFileInput(fileName);
o1 = new ObjectInputStream(f1);
Note note = (Note) o1.readObject();
f1.close();
o1.close();
return note;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
} else {
return null;
}
}
public void onStartMethod(){
}
public static void deleteNote(Context context, String filename) {
File dir = context.getFilesDir();
File f = new File(dir, filename);
if(f.exists())
{
f.delete();
}
}
}
| true |
6115682ab898d855ac2bb557443839377fa25243 | Java | codegagan/ChessProblem | /src/main/java/com/gagan/chess/problem/ChessBoard.java | UTF-8 | 1,819 | 3.6875 | 4 | [] | 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 com.gagan.chess.problem;
import com.gagan.chess.problem.types.Position;
/**
* Represents the Chessboard with Pieces on board positions with each type.
* @author gagssing
*/
public class ChessBoard {
public static final int SIZE = 8; // Since we are considering only one size ChessBoard
private final Piece[][] pieces; // ChessBoard contains pieces
public ChessBoard(){
pieces=new Piece[SIZE][SIZE];
}
/**
* The method places one piece at time on the board according to its given position for the initial setup
* @param piece Piece i.e King etc. to be placed on the ChessBoard
*/
public void add(Piece piece){
final int row = piece.getPosition().getRowIndex();
final int column = piece.getPosition().getColumnIndex();
pieces[row][column]= piece;
}
/**
* provides the backing Array which is storing the pieces.
* @return 2d array of pieces
*/
public Piece[][] getPieces() {
return pieces;
}
/**
*
* @param row row in the 2d array
* @param column column in the 2d array
* @return each Piece according to the row-column indexes.
*/
public Piece getPiece(int row, int column){
return pieces[row][column];
}
/**
*
* @param pos Position object from where the Piece is required
* @return Piece from the array respective to the provided Position object
*/
public Piece getPiece(Position pos){
return getPiece(pos.getRowIndex(), pos.getColumnIndex());
}
}
| true |
d5169f7ce4fde5ce9d8ba713c6a1868bbb3dd07b | Java | Caaarlowsz/xNodusPvP | /src/Nodus/Kits3/Ninja.java | ISO-8859-1 | 4,543 | 2.0625 | 2 | [] | no_license | package Nodus.Kits3;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.player.PlayerToggleSneakEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin;
import Nodus.Event.ServerName;
import Nodus.Main.Habilidade;
import Nodus.Main.Main;
import Nodus.Warp.SetArena;
public class Ninja implements Listener, CommandExecutor {
public static HashMap<Player, Player> a;
public static HashMap<Player, Long> b;
public static List<Player> cooldownbk;
public static Main plugin;
static {
Ninja.a = new HashMap<Player, Player>();
Ninja.b = new HashMap<Player, Long>();
Ninja.cooldownbk = new ArrayList<Player>();
}
public Ninja(final Main main) {
Ninja.plugin = main;
}
public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) {
final Player p = (Player) sender;
if (label.equalsIgnoreCase("ninja")) {
if (!Main.usandokit.contains(p.getName())) {
if (p.hasPermission("kit.ninja")) {
p.sendMessage(String.valueOf(ServerName.nomedokit) + "Ninja");
p.playSound(p.getLocation(), Sound.NOTE_PLING, 4.0f, 4.0f);
Main.usandokit.add(p.getName());
Main.ninja.add(sender.getName());
p.getInventory().clear();
final ItemStack espada = new ItemStack(Material.STONE_SWORD);
final ItemMeta espadameta = espada.getItemMeta();
espadameta.setDisplayName("cSword");
Habilidade.setAbility(p, "Ninja");
p.getInventory().addItem(new ItemStack[] { espada });
Main.giveSoup(p, 34);
p.getInventory().setItem(8, new ItemStack(Material.COMPASS));
SetArena.TeleportArenaRandom(p);
} else {
p.sendMessage(ChatColor.translateAlternateColorCodes('&',
Ninja.plugin.getConfig().getString("Sem_Permiss\u00c3o_Kit")));
}
} else {
p.sendMessage(ChatColor.translateAlternateColorCodes('&',
Ninja.plugin.getConfig().getString("Um_Kit_Por_Vida")));
}
return true;
}
return false;
}
@EventHandler
public void a(final EntityDamageByEntityEvent paramEntityDamageByEntityEvent) {
if (paramEntityDamageByEntityEvent.getDamager() instanceof Player
&& paramEntityDamageByEntityEvent.getEntity() instanceof Player) {
final Player localPlayer1 = (Player) paramEntityDamageByEntityEvent.getDamager();
final Player localPlayer2 = (Player) paramEntityDamageByEntityEvent.getEntity();
if (Main.ninja.contains(localPlayer1.getName())) {
Ninja.a.put(localPlayer1, localPlayer2);
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask((Plugin) Ninja.plugin,
(Runnable) new Runnable() {
@Override
public void run() {
Ninja.cooldownbk.remove(localPlayer1);
}
}, 200L);
}
}
}
@EventHandler
public void a(final PlayerToggleSneakEvent paramPlayerToggleSneakEvent) {
final Player localPlayer1 = paramPlayerToggleSneakEvent.getPlayer();
if (paramPlayerToggleSneakEvent.isSneaking() && Main.ninja.contains(localPlayer1.getName())
&& Ninja.a.containsKey(localPlayer1)) {
final Player localPlayer2 = Ninja.a.get(localPlayer1);
if (localPlayer2 != null && !localPlayer2.isDead()) {
String str = null;
if (Ninja.b.get(localPlayer1) != null) {
final long l = Ninja.b.get(localPlayer1) - System.currentTimeMillis();
final DecimalFormat localDecimalFormat = new DecimalFormat("##");
final int i = (int) l / 1000;
str = localDecimalFormat.format(i);
}
if (Ninja.b.get(localPlayer1) == null || Ninja.b.get(localPlayer1) < System.currentTimeMillis()) {
if (localPlayer1.getLocation().distance(localPlayer2.getLocation()) < 100.0) {
localPlayer1.teleport(localPlayer2.getLocation());
localPlayer1.sendMessage(ChatColor.GREEN + "Teleportado");
Ninja.b.put(localPlayer1, System.currentTimeMillis() + 10000L);
} else {
localPlayer1.sendMessage(ChatColor.RED + "O Ultimo jogador hitado esta muito longe!");
}
} else {
localPlayer1.sendMessage("9lCooldown f> 6" + str + " segundos!");
}
}
}
}
}
| true |
9650ff394059197d7b9b451779eeac187d90901e | Java | ronny7blanco/LAB-APP | /src/main/java/com/clinico/lab/models/services/ExamenesRealizadosService.java | UTF-8 | 1,096 | 2.046875 | 2 | [] | no_license | package com.clinico.lab.models.services;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.clinico.lab.models.dao.IExamenesRealizadosDao;
import com.clinico.lab.models.entities.ExamenesRealizados;
@Service
public class ExamenesRealizadosService implements IExamenesRealizadosService {
@Autowired
private IExamenesRealizadosDao examenesRealizadosDao;
@Override
@Transactional(readOnly = true)
public List<ExamenesRealizados> findAll() {
return examenesRealizadosDao.findAll();
}
@Override
@Transactional
public ExamenesRealizados save(ExamenesRealizados examenesRealizados) {
return examenesRealizadosDao.save(examenesRealizados);
}
@Override
@Transactional(readOnly = true)
public Optional<ExamenesRealizados> findById(Long id) {
return examenesRealizadosDao.findById(id);
}
@Override
@Transactional()
public void delete(Long id) {
examenesRealizadosDao.deleteById(id);
}
}
| true |
a4edf2b2cbe598e4cf0b458c93c265b007d3849b | Java | irfanhasan/juneau | /juneau-core/juneau-marshall/src/main/java/org/apache/juneau/uon/UonSerializerBuilder.java | UTF-8 | 18,847 | 2.078125 | 2 | [
"Apache-2.0"
] | permissive | // ***************************************************************************************************************************
// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
// * with the License. You may obtain a copy of the License at *
// * *
// * http://www.apache.org/licenses/LICENSE-2.0 *
// * *
// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an *
// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the *
// * specific language governing permissions and limitations under the License. *
// ***************************************************************************************************************************
package org.apache.juneau.uon;
import static org.apache.juneau.uon.UonSerializer.*;
import java.util.*;
import org.apache.juneau.*;
import org.apache.juneau.http.*;
import org.apache.juneau.serializer.*;
import org.apache.juneau.urlencoding.*;
/**
* Builder class for building instances of UON serializers.
*/
public class UonSerializerBuilder extends SerializerBuilder {
/**
* Constructor, default settings.
*/
public UonSerializerBuilder() {
super();
}
/**
* Constructor.
*
* @param propertyStore The initial configuration settings for this builder.
*/
public UonSerializerBuilder(PropertyStore propertyStore) {
super(propertyStore);
}
@Override /* CoreObjectBuilder */
public UonSerializer build() {
return new UonSerializer(propertyStore);
}
//--------------------------------------------------------------------------------
// Properties
//--------------------------------------------------------------------------------
/**
* <b>Configuration property:</b> Encode non-valid URI characters.
*
* <ul>
* <li><b>Name:</b> <js>"UonSerializer.encodeChars"</js>
* <li><b>Data type:</b> <code>Boolean</code>
* <li><b>Default:</b> <jk>false</jk> for {@link UonSerializer}, <jk>true</jk> for {@link UrlEncodingSerializer}
* <li><b>Session-overridable:</b> <jk>true</jk>
* </ul>
*
* <p>
* Encode non-valid URI characters with <js>"%xx"</js> constructs.
*
* <p>
* If <jk>true</jk>, non-valid URI characters will be converted to <js>"%xx"</js> sequences.
* Set to <jk>false</jk> if parameter value is being passed to some other code that will already perform
* URL-encoding of non-valid URI characters.
*
* <h5 class='section'>Notes:</h5>
* <ul>
* <li>This is equivalent to calling <code>property(<jsf>UON_encodeChars</jsf>, value)</code>.
* <li>This introduces a slight performance penalty.
* </ul>
*
* @param value The new value for this property.
* @return This object (for method chaining).
* @see UonSerializer#UON_encodeChars
*/
public UonSerializerBuilder encodeChars(boolean value) {
return property(UON_encodeChars, value);
}
/**
* Shortcut for calling <code>setEncodeChars(true)</code>.
*
* @return This object (for method chaining).
*/
public UonSerializerBuilder encoding() {
return encodeChars(true);
}
/**
* <b>Configuration property:</b> Format to use for query/form-data/header values.
*
* <ul>
* <li><b>Name:</b> <js>"UrlEncodingSerializer.paramFormat"</js>
* <li><b>Data type:</b> <code>ParamFormat</code>
* <li><b>Default:</b> <jsf>UON</jsf>
* <li><b>Session-overridable:</b> <jk>true</jk>
* </ul>
*
* <p>
* Specifies the format to use for URL GET parameter keys and values.
*
* <h5 class='section'>Notes:</h5>
* <ul>
* <li>This is equivalent to calling <code>property(<jsf>UON_paramFormat</jsf>, value)</code>.
* </ul>
*
* @param value The new value for this property.
* @return This object (for method chaining).
* @see UonSerializer#UON_paramFormat
*/
public UonSerializerBuilder paramFormat(ParamFormat value) {
return property(UON_paramFormat, value);
}
@Override /* SerializerBuilder */
public UonSerializerBuilder maxDepth(int value) {
super.maxDepth(value);
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder initialDepth(int value) {
super.initialDepth(value);
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder detectRecursions(boolean value) {
super.detectRecursions(value);
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder ignoreRecursions(boolean value) {
super.ignoreRecursions(value);
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder useWhitespace(boolean value) {
super.useWhitespace(value);
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder ws() {
super.ws();
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder maxIndent(int value) {
super.maxIndent(value);
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder addBeanTypeProperties(boolean value) {
super.addBeanTypeProperties(value);
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder quoteChar(char value) {
super.quoteChar(value);
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder sq() {
super.sq();
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder trimNullProperties(boolean value) {
super.trimNullProperties(value);
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder trimEmptyCollections(boolean value) {
super.trimEmptyCollections(value);
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder trimEmptyMaps(boolean value) {
super.trimEmptyMaps(value);
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder trimStrings(boolean value) {
super.trimStrings(value);
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder uriContext(UriContext value) {
super.uriContext(value);
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder uriResolution(UriResolution value) {
super.uriResolution(value);
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder uriRelativity(UriRelativity value) {
super.uriRelativity(value);
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder sortCollections(boolean value) {
super.sortCollections(value);
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder sortMaps(boolean value) {
super.sortMaps(value);
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder abridged(boolean value) {
super.abridged(value);
return this;
}
@Override /* SerializerBuilder */
public UonSerializerBuilder listener(Class<? extends SerializerListener> value) {
super.listener(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder beansRequireDefaultConstructor(boolean value) {
super.beansRequireDefaultConstructor(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder beansRequireSerializable(boolean value) {
super.beansRequireSerializable(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder beansRequireSettersForGetters(boolean value) {
super.beansRequireSettersForGetters(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder beansRequireSomeProperties(boolean value) {
super.beansRequireSomeProperties(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder beanMapPutReturnsOldValue(boolean value) {
super.beanMapPutReturnsOldValue(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder beanConstructorVisibility(Visibility value) {
super.beanConstructorVisibility(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder beanClassVisibility(Visibility value) {
super.beanClassVisibility(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder beanFieldVisibility(Visibility value) {
super.beanFieldVisibility(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder methodVisibility(Visibility value) {
super.methodVisibility(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder useJavaBeanIntrospector(boolean value) {
super.useJavaBeanIntrospector(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder useInterfaceProxies(boolean value) {
super.useInterfaceProxies(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder ignoreUnknownBeanProperties(boolean value) {
super.ignoreUnknownBeanProperties(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder ignoreUnknownNullBeanProperties(boolean value) {
super.ignoreUnknownNullBeanProperties(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder ignorePropertiesWithoutSetters(boolean value) {
super.ignorePropertiesWithoutSetters(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder ignoreInvocationExceptionsOnGetters(boolean value) {
super.ignoreInvocationExceptionsOnGetters(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder ignoreInvocationExceptionsOnSetters(boolean value) {
super.ignoreInvocationExceptionsOnSetters(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder sortProperties(boolean value) {
super.sortProperties(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder notBeanPackages(String...values) {
super.notBeanPackages(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder notBeanPackages(Collection<String> values) {
super.notBeanPackages(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder setNotBeanPackages(String...values) {
super.setNotBeanPackages(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder setNotBeanPackages(Collection<String> values) {
super.setNotBeanPackages(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder removeNotBeanPackages(String...values) {
super.removeNotBeanPackages(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder removeNotBeanPackages(Collection<String> values) {
super.removeNotBeanPackages(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder notBeanClasses(Class<?>...values) {
super.notBeanClasses(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder notBeanClasses(Collection<Class<?>> values) {
super.notBeanClasses(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder setNotBeanClasses(Class<?>...values) {
super.setNotBeanClasses(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder setNotBeanClasses(Collection<Class<?>> values) {
super.setNotBeanClasses(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder removeNotBeanClasses(Class<?>...values) {
super.removeNotBeanClasses(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder removeNotBeanClasses(Collection<Class<?>> values) {
super.removeNotBeanClasses(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder beanFilters(Class<?>...values) {
super.beanFilters(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder beanFilters(Collection<Class<?>> values) {
super.beanFilters(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder setBeanFilters(Class<?>...values) {
super.setBeanFilters(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder setBeanFilters(Collection<Class<?>> values) {
super.setBeanFilters(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder removeBeanFilters(Class<?>...values) {
super.removeBeanFilters(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder removeBeanFilters(Collection<Class<?>> values) {
super.removeBeanFilters(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder pojoSwaps(Class<?>...values) {
super.pojoSwaps(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder pojoSwaps(Collection<Class<?>> values) {
super.pojoSwaps(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder setPojoSwaps(Class<?>...values) {
super.setPojoSwaps(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder setPojoSwaps(Collection<Class<?>> values) {
super.setPojoSwaps(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder removePojoSwaps(Class<?>...values) {
super.removePojoSwaps(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder removePojoSwaps(Collection<Class<?>> values) {
super.removePojoSwaps(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder implClasses(Map<Class<?>,Class<?>> values) {
super.implClasses(values);
return this;
}
@Override /* CoreObjectBuilder */
public <T> UonSerializerBuilder implClass(Class<T> interfaceClass, Class<? extends T> implClass) {
super.implClass(interfaceClass, implClass);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder includeProperties(Map<String,String> values) {
super.includeProperties(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder includeProperties(String beanClassName, String properties) {
super.includeProperties(beanClassName, properties);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder includeProperties(Class<?> beanClass, String properties) {
super.includeProperties(beanClass, properties);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder excludeProperties(Map<String,String> values) {
super.excludeProperties(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder excludeProperties(String beanClassName, String properties) {
super.excludeProperties(beanClassName, properties);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder excludeProperties(Class<?> beanClass, String properties) {
super.excludeProperties(beanClass, properties);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder beanDictionary(Class<?>...values) {
super.beanDictionary(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder beanDictionary(Collection<Class<?>> values) {
super.beanDictionary(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder setBeanDictionary(Class<?>...values) {
super.setBeanDictionary(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder setBeanDictionary(Collection<Class<?>> values) {
super.setBeanDictionary(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder removeFromBeanDictionary(Class<?>...values) {
super.removeFromBeanDictionary(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder removeFromBeanDictionary(Collection<Class<?>> values) {
super.removeFromBeanDictionary(values);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder beanTypePropertyName(String value) {
super.beanTypePropertyName(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder defaultParser(Class<?> value) {
super.defaultParser(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder locale(Locale value) {
super.locale(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder timeZone(TimeZone value) {
super.timeZone(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder mediaType(MediaType value) {
super.mediaType(value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder debug() {
super.debug();
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder property(String name, Object value) {
super.property(name, value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder properties(Map<String,Object> properties) {
super.properties(properties);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder addToProperty(String name, Object value) {
super.addToProperty(name, value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder putToProperty(String name, Object key, Object value) {
super.putToProperty(name, key, value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder putToProperty(String name, Object value) {
super.putToProperty(name, value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder removeFromProperty(String name, Object value) {
super.removeFromProperty(name, value);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder classLoader(ClassLoader classLoader) {
super.classLoader(classLoader);
return this;
}
@Override /* CoreObjectBuilder */
public UonSerializerBuilder apply(PropertyStore copyFrom) {
super.apply(copyFrom);
return this;
}
} | true |
c2220bff92e057467e99d3a7d705b820a4247b7d | Java | chinasoProject/MyCommon | /basecomponent/src/main/java/com/finalwy/basecomponent/utils/TextColorChangeUtils.java | UTF-8 | 2,937 | 2.71875 | 3 | [] | no_license | package com.finalwy.basecomponent.utils;
import android.content.Context;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;
/**
* 文字变色工具类
*
* @author wy
* @Date 2020-02-18
*/
public class TextColorChangeUtils {
/***
*通过Resources内的颜色实现文字变色龙
*
* @param context 上下文
* @param textView 文字变色控件
* @param textColor 文字固有颜色
* @param startColor 开始半段文字color
* @param endColor 结束半段 文字color
* @param startStart 前半段开始变色文字下标
* @param startEnd 前半段结束变色文字下标
* @param endStart 后半段开始变色文字下标
* @param endEnd 后半段结束变色文字下标
* @param text 变色的文字内容
* @return 返回变色结果
*/
public static TextView interTextColorForResources(Context context, TextView textView, int textColor, int startColor,
int endColor, int startStart, int startEnd, int endStart, int endEnd, String text) {
textView.setTextColor(context.getResources().getColor(textColor));
SpannableStringBuilder style = new SpannableStringBuilder(text);
style.setSpan(new ForegroundColorSpan(context.getResources().getColor(startColor)), startStart, startEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
style.setSpan(new ForegroundColorSpan(context.getResources().getColor(endColor)), endStart, endEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(style);
return textView;
}
/**
* 通过 ParseColor 的形式实现变色
*
* @param textView 文字变色控件
* @param textColor 文字固有颜色
* @param startColor 开始半段文字color
* @param endColor 结束半段文字color
* @param startStart 前半段开始变色文字下标
* @param startEnd 后半段开始变色文字下标
* @param endStart 后半段结束变色文字下标
* @param endEnd 后半段结束变色文字下标
* @param text 变色的文字内容
* @return 返回变色结果
*/
public static TextView interTextColorForParseColor(TextView textView, String textColor, String startColor, String endColor, int startStart, int startEnd, int endStart, int endEnd, String text) {
textView.setTextColor(Color.parseColor(textColor));
SpannableStringBuilder style = new SpannableStringBuilder(text);
style.setSpan(new ForegroundColorSpan(Color.parseColor(startColor)), startStart, startEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
style.setSpan(new ForegroundColorSpan(Color.parseColor(endColor)), endStart, endEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return textView;
}
}
| true |
10b310d684a4402ad09b67b3a5e9fabb6e88effd | Java | dpwls1379/magazine | /src/service/Magazine/MagazineUpdateForm.java | UTF-8 | 776 | 2.09375 | 2 | [] | no_license | package service.Magazine;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import controller.CommandProcess;
import dao.MagazineDao;
import model.Magazine;
public class MagazineUpdateForm implements CommandProcess {
@Override
public String requestPro(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
int ma_num=Integer.parseInt(request.getParameter("ma_num"));
String pageNum=request.getParameter("pageNum");
Magazine magazine=new Magazine();
MagazineDao md=MagazineDao.getInstance();
magazine=md.select(ma_num);
request.setAttribute("magazine", magazine);
request.setAttribute("pageNum", pageNum);
return "updateForm.jsp";
}
}
| true |
2741de60c999bf0789c76cbaf545f6abc2f84a66 | Java | cvaughan1/Lab2 | /src/Adventure/Lab2Adventure.java | UTF-8 | 2,118 | 3.8125 | 4 | [] | no_license | package Adventure;
import java.util.Scanner;
public class Lab2Adventure {
public static void main(String[] args) {
//Enter name into variable
Scanner sc = new Scanner(System.in);
System.out.println("Welcome! What is your name?(enter your name)");
String enteredName = sc.nextLine();
//Enter game answer into variable
Scanner sc1 = new Scanner(System.in);
System.out.println("Would you like to play a game?(enter yes or no)");
String enteredGameAnswer = sc1.nextLine();
switch (enteredGameAnswer){
case "no":
System.out.println("You coward!! Go home.");
break;
case "yes":
System.out.println("Excellent! You are walking across a field and you encounter a fire-breathing dragon! What would you do??(enter \"face the beast\" or \"run away\")");
String faceOrRun = sc1.nextLine();
switch (faceOrRun){
case "run away":
System.out.println("You coward!! Go home.");
break;
case "face the beast":
System.out.println("You approach the dragon. You see that he has __ heads! (enter\"1\" or \"2\" or \"3\"):");
int headsNumber = sc1.nextInt();
System.out.println("No one has ever faced a " + headsNumber + "-headed dragon before!");
System.out.println("Choose your weapon!(enter \"slingshot\" or \"sword\" or \"bow and arrow\")");
}
Scanner sc3 = new Scanner(System.in);
String yourWeapon = sc3.nextLine();
System.out.println("Armed with your " + yourWeapon + ", you approach the dragon.");
System.out.println("It stares at you with its ______ eyes. (enter \"red\" or \"blue\")");
Scanner sc4 = new Scanner(System.in);
String dragonEye = sc4.nextLine();
switch (dragonEye){
case "red":
System.out.println("Oh thank goodness! Red-eyed dragons are friendly. You pet it and become friends. You name the dragon _______.(enter a name)");
Scanner sc5 = new Scanner(System.in);
String dragonName = sc5.nextLine();
System.out.println( enteredName + " and " + dragonName + " live happily ever after.");
sc.close();
sc1.close();
sc3.close();
}
}
}
}
| true |
771d2951e6dba97c3bc4537b4971b98e912d78f0 | Java | livefront/bridge | /bridge/src/main/java/com/livefront/bridge/disk/FileDiskHandler.java | UTF-8 | 7,470 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | package com.livefront.bridge.disk;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* A simple implementation of {@link DiskHandler} that saves the requested data to individual files.
* Similar to {@link android.content.SharedPreferences}, this implementation will begin loading the
* saved data into memory as soon as it is constructed and block on the first call until all data
* is loaded (or some cutoff is reached).
*/
public class FileDiskHandler implements DiskHandler {
private static final String DIRECTORY_NAME = "com.livefront.bridge";
/**
* Time to wait (in milliseconds) while loading the initial data in the background. After this
* timeout data will continue to load in the background but some calls to
* {@link FileDiskHandler#getBytes(String)} may then block on-demand.
*/
private static final long BACKGROUND_WAIT_TIMEOUT_MS = 1000;
private final File mDirectory;
private final Future<?> mPendingLoadFuture;
private final Map<String, byte[]> mKeyByteMap = new ConcurrentHashMap<>();
/**
* Determines whether the {@link #waitForFilesToLoad()} call has completed in some way.
*/
private volatile boolean mIsLoadedOrTimedOut = false;
/**
* Creates the handler and begins loading its data into memory on a background thread.
*
* @param context The {@link Context} used to derive the file-storage location.
* @param executorService An {@link ExecutorService} that can be used to place the initial data
* loading on a background thread.
*/
public FileDiskHandler(@NonNull Context context,
@NonNull ExecutorService executorService) {
mDirectory = context.getDir(DIRECTORY_NAME, Context.MODE_PRIVATE);
// Load all the files into memory in the background.
mPendingLoadFuture = executorService.submit(new Runnable() {
@Override
public void run() {
loadAllFiles();
}
});
}
@Override
public void clearAll() {
cancelFileLoading();
mKeyByteMap.clear();
deleteFilesByKey(null);
}
@Override
public void clear(@NonNull String key) {
cancelFileLoading();
mKeyByteMap.remove(key);
deleteFilesByKey(key);
}
@Nullable
@Override
public byte[] getBytes(@NonNull String key) {
waitForFilesToLoad();
return getBytesInternal(key);
}
@Override
public void putBytes(@NonNull final String key, @NonNull final byte[] bytes) {
// Place the data in memory first
mKeyByteMap.put(key, bytes);
// Write the data to disk
File file = new File(mDirectory, key);
FileOutputStream outStream;
try {
outStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// If there is a problem with the file we'll simply abort.
return;
}
try {
outStream.write(bytes);
} catch (IOException e) {
// Ignore
} finally {
try {
outStream.close();
} catch (IOException e) {
// Ignore
}
}
}
/**
* Cancels any pending file loading that happens at startup.
*/
private void cancelFileLoading() {
mPendingLoadFuture.cancel(true);
}
/**
* Deletes all files associated with the given {@code key}. If the key is {@code null}, then
* all stored files will be deleted.
*
* @param key The key associated with the data to delete (or {@code null} if all data should be
* deleted).
*/
private void deleteFilesByKey(@Nullable String key) {
File[] files = mDirectory.listFiles();
if (files == null) {
return;
}
for (File file : files) {
if (key == null || getFileNameForKey(key).equals(file.getName())) {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
}
}
@Nullable
private byte[] getBytesFromDisk(@NonNull String key) {
File file = getFileByKey(key);
if (file == null) {
return null;
}
FileInputStream inputStream;
try {
inputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
return null;
}
byte[] bytes = new byte[(int) file.length()];
try {
//noinspection ResultOfMethodCallIgnored
inputStream.read(bytes);
} catch (IOException e) {
return null;
} finally {
try {
inputStream.close();
} catch (IOException e) {
// Ignore
}
}
return bytes;
}
@Nullable
private byte[] getBytesInternal(@NonNull String key) {
// Check for data loaded into memory from the initial load
byte[] cachedBytes = mKeyByteMap.get(key);
if (cachedBytes != null) {
return cachedBytes;
}
// Get bytes from disk and place into memory if necessary
byte[] bytes = getBytesFromDisk(key);
if (bytes != null) {
mKeyByteMap.put(key, bytes);
}
return bytes;
}
private String getFileNameForKey(@NonNull String key) {
// For now the key and filename are equivalent
return key;
}
@Nullable
private File getFileByKey(@NonNull String key) {
File[] files = mDirectory.listFiles();
if (files == null) {
return null;
}
for (File file : files) {
if (getFileNameForKey(key).equals(file.getName())) {
return file;
}
}
return null;
}
private String getKeyForFileName(@NonNull String fileName) {
// For now the key and filename are equivalent
return fileName;
}
private void loadAllFiles() {
File[] files = mDirectory.listFiles();
if (files == null) {
return;
}
for (File file : files) {
// Populate the cached map
String key = getKeyForFileName(file.getName());
getBytesInternal(key);
}
}
private void waitForFilesToLoad() {
if (mIsLoadedOrTimedOut) {
// No need to wait.
return;
}
try {
mPendingLoadFuture.get(BACKGROUND_WAIT_TIMEOUT_MS, TimeUnit.SECONDS);
} catch (CancellationException |
InterruptedException |
ExecutionException |
TimeoutException e) {
// We've made a best effort to load the data in the background. We can simply proceed
// here.
}
mIsLoadedOrTimedOut = true;
}
}
| true |
1d35f350c24e096391e568053b0cea9a01adfbbe | Java | FethiEfe/Introduction-To-Java-Programming | /JavaPractice/src/chapter02/SumDigit.java | UTF-8 | 401 | 3.421875 | 3 | [] | no_license | package chapter02;
import java.util.Scanner;
public class SumDigit {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number");
int number = input.nextInt();
int digit1 = number % 10 ;
number /= 10 ;
int digit2 = number % 10 ;
int digit3 = number / 10 ;
System.out.println(digit1 + digit2 + digit3);
}
}
| true |
d1ccb23edffef99ffce4849ba839341569644739 | Java | ndamiens/news | /src/org/webfr/news/NetActivity.java | UTF-8 | 896 | 2.328125 | 2 | [] | no_license | package org.webfr.news;
import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.app.AlertDialog.Builder;
import android.app.AlertDialog;
abstract public class NetActivity extends Activity {
public boolean testReseau() {
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo == null)
return false;
State networkState = networkInfo.getState();
return networkState == State.CONNECTED;
}
public void dlgSansReseau() {
Builder dlgBuilder = new AlertDialog.Builder(this);
dlgBuilder.setTitle("Pas de réseau");
dlgBuilder.setMessage("Un accès à Internet est nécessaire");
dlgBuilder.setNeutralButton("ok",null);
dlgBuilder.show();
}
}
| true |
bb4c2b9fb16bad92bfa7ae98bcbdccfce863f6f3 | Java | grey0207/spring-boot-demo | /spring-boot-validation/src/main/java/demo/model/BaseModel.java | UTF-8 | 281 | 2.046875 | 2 | [] | no_license | package demo.model;
import lombok.Data;
import java.util.Date;
@Data
public class BaseModel {
private Date timestamp = new Date();
private Integer status = 200;
private Object data;
public BaseModel(Object data){
this.data = data;
}
}
| true |
66ab0f47440a938f56d82b5a3ad96ba2342aac26 | Java | allo86/SimpleTwitter-Reloaded | /app/src/main/java/com/codepath/apps/allotweets/model/Size.java | UTF-8 | 842 | 2.3125 | 2 | [
"Apache-2.0",
"MIT"
] | permissive | package com.codepath.apps.allotweets.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.parceler.Parcel;
/**
* Created by ALLO on 3/8/16.
*/
@Parcel
public class Size {
@SerializedName("w")
@Expose
int width;
@SerializedName("h")
@Expose
int height;
@SerializedName("resize")
@Expose
String resize;
public Size() {
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getResize() {
return resize;
}
public void setResize(String resize) {
this.resize = resize;
}
}
| true |
0c9a7cc8922194a7aef9d56ed50be12bab8b7d64 | Java | jimsush/IHN | /IHNServer/src/main/java/com/ihn/server/internal/launch/service/ExternalProcessMgr.java | UTF-8 | 2,181 | 2.328125 | 2 | [] | no_license | package com.ihn.server.internal.launch.service;
import java.util.List;
//import org.apache.commons.collections.CollectionUtils;
import org.springframework.util.CollectionUtils;
import com.ihn.server.internal.launch.BizContext;
public class ExternalProcessMgr implements BaseService{
private List<ExternalService> externalServices;
public void setExternalServices(List<ExternalService> externalServices) {
this.externalServices = externalServices;
}
@Override
public boolean init() {
boolean needWait=false;
if(CollectionUtils.isEmpty(externalServices))
return needWait;
for(ExternalService service : externalServices){
BizContext.getLogger().info("will start "+service.getServiceName());
try{
if(!service.checkIsRun()){
needWait=true;
service.start();
BizContext.getLogger().info(service.getServiceName()+" start finished.");
}else{
BizContext.getLogger().info(service.getServiceName()+" have running.");
}
if(!service.isInited()){
needWait=true;
service.init();
BizContext.getLogger().info(service.getServiceName()+" init finished.");
}else{
BizContext.getLogger().info(service.getServiceName()+" have inited.");
}
BizContext.getLogger().info(service.getServiceName()+" start ok!");
}catch(Exception ex){
BizContext.getLogger().warn("",ex);
}
}
BizContext.getLogger().info("External process finished.");
return needWait;
}
@Override
public void destroy() {
if(CollectionUtils.isEmpty(externalServices))
return;
for(ExternalService service : externalServices){
try{
service.stop();
}catch(Exception ex){
BizContext.getLogger().warn("",ex);
}
}
}
}
| true |
1ae776176f0e88bbebdccfd997965867be918d37 | Java | whvixd/study | /demo/src/main/java/com/github/whvixd/demo/jdk/thread/ReentrantLockDemo.java | UTF-8 | 886 | 3.328125 | 3 | [] | no_license | package com.github.whvixd.demo.jdk.thread;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;
/**
* Created by wangzhx on 2020/5/12.
*/
public class ReentrantLockDemo {
private volatile int count;
private final ReentrantLock lock = new ReentrantLock(true);
public void add() {
lock.lock();
try {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
System.out.println(Thread.currentThread().getName()+" add,count:"+count);
}finally {
lock.unlock();
}
}
public static void main(String[] args) {
ReentrantLockDemo demo = new ReentrantLockDemo();
IntStream.range(0, 100).forEach(e ->
new Thread(demo::add).start());
}
}
| true |
1fd27f326404031e352edb6715bb1417e9beed43 | Java | gitter-badger/katharsis-framework | /katharsis-examples/wildfly-example/src/main/java/io/katharsis/example/wildfly/endpoints/UserRepository.java | UTF-8 | 2,333 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | package io.katharsis.example.wildfly.endpoints;
import io.katharsis.example.wildfly.model.User;
import io.katharsis.queryParams.QueryParams;
import io.katharsis.repository.ResourceRepository;
import io.katharsis.resource.exception.ResourceNotFoundException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
public class UserRepository implements ResourceRepository<User, String> {
private Set<User> users = new LinkedHashSet<>();
public UserRepository() {
List<String> interests = new ArrayList<>();
interests.add("coding");
interests.add("art");
users.add(new User(UUID.randomUUID().toString(), "grogdj@gmail.com", "grogdj", "grogj", "dj", interests));
users.add(new User(UUID.randomUUID().toString(), "bot@gmail.com", "bot", "bot", "harry", interests));
users.add(new User(UUID.randomUUID().toString(), "evilbot@gmail.com", "evilbot", "bot", "john", interests));
}
@Override
public synchronized User findOne(String id, QueryParams requestParams) {
return users.stream()
.filter(u -> u.getId().equals(id))
.findFirst()
.orElseThrow(() -> new ResourceNotFoundException("users/" + id));
}
@Override
public synchronized Iterable<User> findAll(QueryParams requestParams) {
return users;
}
@Override
public synchronized Iterable<User> findAll(Iterable<String> ids, QueryParams requestParams) {
return users.stream()
.filter(u ->
StreamSupport.stream(ids.spliterator(), false)
.filter(id -> u.getId().equals(id))
.findFirst()
.isPresent())
.collect(Collectors.toList());
}
@Override
public synchronized void delete(String id) {
Iterator<User> usersIterator = users.iterator();
while (usersIterator.hasNext()) {
if (usersIterator.next().getId().equals(id)) {
usersIterator.remove();
}
}
}
@Override
public synchronized <S extends User> S save(S user) {
if (user.getId() == null) {
user.setId(UUID.randomUUID().toString());
}
users.add(user);
return user;
}
}
| true |
ad2f9ab0b37402f420ec606146196f6f29ff6a92 | Java | ppaushya/CapStore | /src/test/java/SubmittingFeedback/StepDef.java | UTF-8 | 1,057 | 2.234375 | 2 | [] | no_license | package SubmittingFeedback;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import com.capstore.model.Feedback;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class StepDef {
private WebDriver webdriver;
private WebElement element;
@Before
public void setUp() {
System.setProperty("webdriver.chrome.driver","C:\\Users\\mbommath\\Downloads\\chromedriver.exe" );
webdriver=new ChromeDriver();
}
@Given("^Feedback form$")
public void feedback_form() throws Throwable {
//Feedback feedback= new Feedback(1, 1, 1, 5, 5, "Good!", 1);
}
@When("^'Submit' button is clicked$")
public void submit_button_is_clicked() throws Throwable {
}
@Then("^store feedback in database$")
public void store_feedback_in_database() throws Throwable {
}
@Then("^Update ratings$")
public void update_ratings() throws Throwable {
}
}
| true |
da5a5be7ea78057c64df1e91cf01964a2b0d81d8 | Java | kieuthiendev123/appbanhang | /app/src/main/java/com/example/mrbuggy/appbanhangonlie/activity/LaptopActivity.java | UTF-8 | 7,345 | 1.875 | 2 | [] | no_license | package com.example.mrbuggy.appbanhangonlie.activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.mrbuggy.appbanhangonlie.R;
import com.example.mrbuggy.appbanhangonlie.adapter.LapTopAdapter;
import com.example.mrbuggy.appbanhangonlie.model.Sanphamnew;
import com.example.mrbuggy.appbanhangonlie.ultil.CheckConnection;
import com.example.mrbuggy.appbanhangonlie.ultil.Server;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class LaptopActivity extends AppCompatActivity {
Toolbar toolbar;
ListView lvDt;
LapTopAdapter lapTopAdapter;
ArrayList<Sanphamnew> arrayList;
int idLT = 0;
int page = 1;
View proCessbar;
boolean isLoading = false;
mHandler mHandler;
boolean limmitData = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_laptop);
anhXa();
if(CheckConnection.haveNetworkConnection(getApplicationContext())){
getIdSp();
ActionTooBar();
getData(page);
loadMore();
}else {
CheckConnection.ShowToast_Short(getApplicationContext(),"bạn kiểm tra lại Internt");
}
}
private void anhXa() {
toolbar = (Toolbar) findViewById(R.id.tbLaptop);
lvDt = (ListView) findViewById(R.id.lvLaptop);
arrayList = new ArrayList<>();
lapTopAdapter = new LapTopAdapter(getApplicationContext(),arrayList);
lvDt.setAdapter(lapTopAdapter);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
proCessbar = inflater.inflate(R.layout.progerbass,null);
mHandler = new mHandler();
}
public void getIdSp() {
idLT = getIntent().getIntExtra("idloaisp",-1);
}
private void ActionTooBar() {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
private void loadMore() {
lvDt.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(),ChiTietSanPham.class);
intent.putExtra("Thongtinsanpham",arrayList.get(position));
startActivity(intent);
}
});
lvDt.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount != 0 && isLoading == false && limmitData == false){
isLoading = true;
ThreadData threadData = new ThreadData();
threadData.start();
}
}
});
}
public void getData(int pages) {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String duongDan = Server.duongDienThoai+String.valueOf(pages);
StringRequest stringRequest = new StringRequest(Request.Method.POST, duongDan, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
int id = 0;
String tenLT = "";
Integer giaLT = 0;
String hinhAnhLT = "";
String moTaLT = "";
int idLTsp = 0;
if(response != null && response.length() != 2){
lvDt.removeFooterView(proCessbar);
try {
JSONArray jsonArray = new JSONArray(response);
for(int i = 0; i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
id = jsonObject.getInt("id");
tenLT = jsonObject.getString("tensp");
giaLT = jsonObject.getInt("giasp");
hinhAnhLT = jsonObject.getString("hinhanhsp");
moTaLT = jsonObject.getString("motasp");
idLTsp = jsonObject.getInt("idsanpham");
arrayList.add(new Sanphamnew(id,tenLT,giaLT,hinhAnhLT,moTaLT,idLTsp));
lapTopAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}else {
limmitData = true;
lvDt.removeFooterView(proCessbar);
CheckConnection.ShowToast_Short(getApplicationContext(),"Đã hết dữ liệu");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> param = new HashMap<String,String>();
param.put("idsanpham",String.valueOf(idLT));
return param;
}
};
requestQueue.add(stringRequest);
}
public class mHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 0:
lvDt.addFooterView(proCessbar);
break;
case 1:
page++;
getData(page);
isLoading= false;
break;
}
super.handleMessage(msg);
}
}
public class ThreadData extends Thread{
@Override
public void run() {
mHandler.sendEmptyMessage(0);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message message = mHandler.obtainMessage(1);
mHandler.sendMessage(message);
super.run();
}
}
}
| true |
a542b09b9503e7aa3bcac3b8c7e950b2c7814a97 | Java | IceHarley/annot-vc | /src/main/java/com/bikesandwheels/config/GuiConfig.java | UTF-8 | 1,443 | 2.125 | 2 | [] | no_license | package com.bikesandwheels.config;
import com.bikesandwheels.gui.controller.*;
import com.bikesandwheels.gui.model.*;
import com.bikesandwheels.gui.view.*;
import com.bikesandwheels.interactors.Scanner;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
@Configuration
@Profile({Profiles.LIVE, Profiles.DB_FILE, Profiles.DB_IN_MEMORY})
public class GuiConfig {
public static final String PROPERTY_GUI_DEFAULT_SEARCH_PATH = "gui.default_search_path";
@Bean
public MainFrame mainFrame(Environment environment) {
return new MainFrame();
}
@Bean
public RevisionsTable revisionsTable() {
return new RevisionsTable();
}
@Bean
RevisionsTableModel revisionsTableModel() {
return new RevisionsTableModel();
}
@Bean
public Scanner scanner() {
return new Scanner();
}
@Bean
public ScanPanel scanPanel() {
return new ScanPanel();
}
@Bean
public ScanModel scanModel(Environment environment) {
ScanModel model = new ScanModel();
model.setDefaultSearchPath(environment.getProperty(PROPERTY_GUI_DEFAULT_SEARCH_PATH));
return model;
}
@Bean
public ScanController scanController() {
return new ScanController();
}
@Bean
public RevisionsTableController revisionsTableController() {
return new RevisionsTableController();
}
}
| true |
22a4ad7b8bd634adda0bed8bc23eff53d2e2fa0c | Java | lyhq/JavaSE | /DesignPatterns/src/com/lyhq/design/patterns/Proxy/Static/Sourceable.java | UTF-8 | 244 | 2.515625 | 3 | [] | no_license | package com.lyhq.design.patterns.Proxy.Static;
/**
* 接口,代理类和被代理类都实现这个接口
* @author yangrun
* @date 2018年11月22日
*/
public interface Sourceable {
//目标方法
public void method();
}
| true |
17a18e5d257a0ddca5c2c5f78dd5cce12a5579f9 | Java | Clement1229/BankAccount | /src/main/java/com/revature/service/Service.java | UTF-8 | 996 | 2.234375 | 2 | [] | no_license | package com.revature.service;
import java.util.List;
import com.revature.dao.Dao;
import com.revature.dao.DaoImpl;
import com.revature.domain.Account;
import com.revature.domain.Transaction;
import com.revature.domain.User;
public class Service {
Dao dao = new DaoImpl();
public void createUser(User user) {
dao.createUser(user);
}
public User getUserByUsernamePassword(String userName, String password) {
return dao.getUserByUsernamePassword(userName,password);
}
public void deposit(Account account, User user, double amount) {
dao.deposit(account, user, amount);
}
public void withdraw(Account account, User user, double amount) {
dao.withdraw(account, user, amount);
}
public double getBalance(Account account, User user) {
return dao.getBalance(account, user);
}
public Account getAccountByUid(int uid) {
return dao.getAccountByUid(uid);
}
public List<Transaction> viewTransactionHistory(Account account){
return dao.viewTransactionHistory(account);
}
}
| true |
bc37f548c3688eaa9993dabbf6d64281383a9a37 | Java | liuwj620/queue | /src/com/suntendy/queue/yydt/domain/Yydt.java | UTF-8 | 1,361 | 2.515625 | 3 | [] | no_license | package com.suntendy.queue.yydt.domain;
public class Yydt {
private String id;
private String name; //大厅名称
private String blddz; //大厅地址
private String yyts; //可预约天数
private String yysd; //每天可预约时段(多个时段用#分隔)
private String operation; //操作
public Yydt() {
super();
}
public Yydt( String name, String blddz, String yyts, String yysd) {
super();
this.name = name;
this.blddz = blddz;
this.yyts = yyts;
this.yysd = yysd;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBlddz() {
return blddz;
}
public void setBlddz(String blddz) {
this.blddz = blddz;
}
public String getYyts() {
return yyts;
}
public void setYyts(String yyts) {
this.yyts = yyts;
}
public String getYysd() {
return yysd;
}
public void setYysd(String yysd) {
this.yysd = yysd;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
@Override
public String toString() {
return "Yydt [id=" + id + ", name=" + name + ", blddz=" + blddz
+ ", yyts=" + yyts + ", yysd=" + yysd + ", operation="
+ operation + "]";
}
}
| true |
bd9dfad0d100c4cb5af530885e6c97c8254950f1 | Java | chxt100016/well | /wellassist-web/src/main/java/org/wella/entity/Option.java | UTF-8 | 5,658 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | package org.wella.entity;
/**
* 码表
*/
public class Option {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column wa_option.id
*
* @mbggenerated Thu Jun 08 10:48:16 CST 2017
*/
private Long id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column wa_option.code_value
*
* @mbggenerated Thu Jun 08 10:48:16 CST 2017
*/
private String codeValue;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column wa_option.code_key
*
* @mbggenerated Thu Jun 08 10:48:16 CST 2017
*/
private String codeKey;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column wa_option.code_order
*
* @mbggenerated Thu Jun 08 10:48:16 CST 2017
*/
private Short codeOrder;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column wa_option.code_column
*
* @mbggenerated Thu Jun 08 10:48:16 CST 2017
*/
private String codeColumn;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column wa_option.code_table
*
* @mbggenerated Thu Jun 08 10:48:16 CST 2017
*/
private String codeTable;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column wa_option.id
*
* @return the value of wa_option.id
*
* @mbggenerated Thu Jun 08 10:48:16 CST 2017
*/
public Long getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column wa_option.id
*
* @param id the value for wa_option.id
*
* @mbggenerated Thu Jun 08 10:48:16 CST 2017
*/
public void setId(Long id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column wa_option.code_value
*
* @return the value of wa_option.code_value
*
* @mbggenerated Thu Jun 08 10:48:16 CST 2017
*/
public String getCodeValue() {
return codeValue;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column wa_option.code_value
*
* @param codeValue the value for wa_option.code_value
*
* @mbggenerated Thu Jun 08 10:48:16 CST 2017
*/
public void setCodeValue(String codeValue) {
this.codeValue = codeValue == null ? null : codeValue.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column wa_option.code_key
*
* @return the value of wa_option.code_key
*
* @mbggenerated Thu Jun 08 10:48:16 CST 2017
*/
public String getCodeKey() {
return codeKey;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column wa_option.code_key
*
* @param codeKey the value for wa_option.code_key
*
* @mbggenerated Thu Jun 08 10:48:16 CST 2017
*/
public void setCodeKey(String codeKey) {
this.codeKey = codeKey == null ? null : codeKey.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column wa_option.code_order
*
* @return the value of wa_option.code_order
*
* @mbggenerated Thu Jun 08 10:48:16 CST 2017
*/
public Short getCodeOrder() {
return codeOrder;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column wa_option.code_order
*
* @param codeOrder the value for wa_option.code_order
*
* @mbggenerated Thu Jun 08 10:48:16 CST 2017
*/
public void setCodeOrder(Short codeOrder) {
this.codeOrder = codeOrder;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column wa_option.code_column
*
* @return the value of wa_option.code_column
*
* @mbggenerated Thu Jun 08 10:48:16 CST 2017
*/
public String getCodeColumn() {
return codeColumn;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column wa_option.code_column
*
* @param codeColumn the value for wa_option.code_column
*
* @mbggenerated Thu Jun 08 10:48:16 CST 2017
*/
public void setCodeColumn(String codeColumn) {
this.codeColumn = codeColumn == null ? null : codeColumn.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column wa_option.code_table
*
* @return the value of wa_option.code_table
*
* @mbggenerated Thu Jun 08 10:48:16 CST 2017
*/
public String getCodeTable() {
return codeTable;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column wa_option.code_table
*
* @param codeTable the value for wa_option.code_table
*
* @mbggenerated Thu Jun 08 10:48:16 CST 2017
*/
public void setCodeTable(String codeTable) {
this.codeTable = codeTable == null ? null : codeTable.trim();
}
} | true |
a4f043b57dd569beb3cbfb1c2840268eedc07cb7 | Java | MrLeedom/My_Interview_Algorithm | /DataStructuresAndAlgorithms/com/list/MiddleNode.java | UTF-8 | 1,228 | 3.875 | 4 | [] | no_license | package com.list;
/**
* @author:leedom
* @date: 6/11/19 4:19 PM
* Description: 经典题目 : 求链表的中间节点
* 采用快慢指针来做,慢指针一次走一步,快指针一次走两步,不过要区分奇数偶数链表情况,采用举例法来做:
* 1->2->3->4->null mid:3
* 1->2->3->4->5->null mid:3
* License: (C)Copyright 2019
*/
public class MiddleNode {
public Node findMidNode(Node head) {
if(head == null || head.next == null) {
return null;
}
Node slow = head;
Node fast = head.next;
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return fast == null ? slow : slow.next;
}
public static void main(String[] args){
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(3);
Node node5 = new Node(8);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
MiddleNode list = new MiddleNode();
System.out.println(list.findMidNode(node1).next.value);
}
}
| true |
3a03c76ac5f384d38015e68887866d4561cff2d7 | Java | oisnull/hwl | /app/src/main/java/com/hwl/beta/net/circle/body/GetCircleInfosRequest.java | UTF-8 | 1,472 | 1.945313 | 2 | [] | no_license | package com.hwl.beta.net.circle.body;
import com.hwl.beta.net.circle.NetCircleMatchInfo;
import java.util.List;
public class GetCircleInfosRequest {
/// <summary>
/// 当前登录的用户id
/// </summary>
private long UserId;
private long ViewUserId;
/// <summary>
/// 如果有值,则获取比这个值小的数据列表
/// </summary>
private long MinCircleId;
private int PageIndex;
private int Count;
private List<NetCircleMatchInfo> CircleMatchInfos;
public long getViewUserId() {
return ViewUserId;
}
public void setViewUserId(long viewUserId) {
ViewUserId = viewUserId;
}
public List<NetCircleMatchInfo> getCircleMatchInfos() {
return CircleMatchInfos;
}
public void setCircleMatchInfos(List<NetCircleMatchInfo> circleMatchInfos) {
CircleMatchInfos = circleMatchInfos;
}
public long getUserId() {
return UserId;
}
public void setUserId(long userId) {
UserId = userId;
}
public long getMinCircleId() {
return MinCircleId;
}
public void setMinCircleId(long minCircleId) {
MinCircleId = minCircleId;
}
public int getPageIndex() {
return PageIndex;
}
public void setPageIndex(int pageIndex) {
PageIndex = pageIndex;
}
public int getCount() {
return Count;
}
public void setCount(int count) {
Count = count;
}
}
| true |
620f05a6ebd1cfab59b30a504a972e842c83a279 | Java | LeeKejin/DesignPattern | /src/main/java/com/designpattern/iterator/CourseIteratorImpl.java | UTF-8 | 659 | 3.4375 | 3 | [] | no_license | package com.designpattern.iterator;
import java.util.List;
public class CourseIteratorImpl implements CourseIterator
{
private List courses;
private int position = 0;
public CourseIteratorImpl( List courses )
{
this.courses = courses;
}
public Course nextCourse()
{
if ( position < courses.size() )
{
Course course = ( Course ) courses.get( position );
System.out.println( "Position:" + position );
position++;
return course;
}
return null;
}
public boolean isLastCourse()
{
return position >= courses.size();
}
}
| true |
5f1c3a810e8dc0548592cae8b52faf2f7190c880 | Java | Poobatqv/java-study | /src/main/java/com/forezp/test/ProtectSubTest.java | UTF-8 | 475 | 2.34375 | 2 | [] | no_license | package com.forezp.test;
import com.forezp.thinking.chapter7.ProtectTest;
/**
* Created by forezp on 2017/11/30.
*/
public class ProtectSubTest extends ProtectTest {
public static void main(String[] args) {
ProtectSubTest protectSubTest=new ProtectSubTest();
// protectSubTest.print();
// 不写protected private public 则为包内访问权限,protected包含包内访问权限
//但是 包内访问权限不等于protected
}
}
| true |
dfd5d66817b75b93ec9768750fe2b7276b84c622 | Java | joshiraez/techTest | /src/test/java/calculators/OrderPriceCalculatorShould.java | UTF-8 | 2,289 | 2.75 | 3 | [] | no_license | package calculators;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.contentOf;
class OrderPriceCalculatorShould {
private final static String ORDERS_CSV = "orders.csv";
private final static String PRODUCTS_CSV = "products.csv";
private final static String RESULT_CSV = "result.csv";
private static final String TASK = "orderPrices";
private final static Path OUT_DIRECTORY = Paths.get(".");
@ParameterizedTest
@ValueSource(strings = {
"whenThereAreNoOrdersOrderPricesWillHaveNoOrders",
"whenThereAreOneOrderWithOneItemGetThePriceOfThatItem",
"whenThereIsOneOrderWithMultipleProductsThePriceShouldBeTheSumOfPrices",
"whenThereIsMultipleOrdersYouGetTheSumPriceOfItsProductsForEachOrder"
})
void priceOrderIsGeneratedCorrectly(String testCase) throws IOException {
//Given
final OrderPriceCalculator orderPriceCalculator = buildCalculator(testCase);
final File expected = getExpected(testCase);
//When
final File result = orderPriceCalculator.calculateOrderPrices();
//Then
assertThat(result).exists();
assertThat(contentOf(result))
.isEqualToIgnoringNewLines(contentOf(expected));
}
//Utils
private File getResourceFile(final String testName, final String fileName) {
final String pathToFile = "/" + TASK + "/" + testName + "/" + fileName;
return new File(getClass().getResource(pathToFile).getFile());
}
private OrderPriceCalculator buildCalculator(final String testName) {
return new OrderPriceCalculator(getProducts(testName), getOrders(testName), OUT_DIRECTORY);
}
private File getProducts(String testName) {
return getResourceFile(testName, PRODUCTS_CSV);
}
private File getOrders(String testName) {
return getResourceFile(testName, ORDERS_CSV);
}
private File getExpected(String testName) {
return getResourceFile(testName, RESULT_CSV);
}
}
| true |
e7b500523f3b207d087b6faf2e2f99bb6a6ae173 | Java | zasdsd/gaode_movemapLocation | /src/com/amap/map2d/demo/tjr/MoveLactionActivity.java | UTF-8 | 11,932 | 1.742188 | 2 | [] | no_license | package com.amap.map2d.demo.tjr;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMap.OnCameraChangeListener;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.amap.api.services.poisearch.PoiSearch.Query;
import com.amap.api.services.poisearch.PoiSearch.SearchBound;
import com.amap.map2d.demo.R;
public class MoveLactionActivity extends Activity implements LocationSource,
AMapLocationListener, OnCameraChangeListener, OnGeocodeSearchListener,
OnPoiSearchListener {
private AMap aMap;
private MapView mapView;
private OnLocationChangedListener mListener;
private AMapLocationClient mlocationClient;
private AMapLocationClientOption mLocationOption;
// 设置不显示zoom
private UiSettings mUiSettings;
// 地图上标记
// private Marker regeoMarker;
// 这个是地理反编译
// private GeocodeSearch geocoderSearch;
// 查询
private Query query;
private PoiSearch poiSearch;
private ListView lvList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.move_location);
mapView = (MapView) findViewById(R.id.map);
mapView.onCreate(savedInstanceState);// 此方法必须重写
lvList = (ListView) findViewById(R.id.lvList);
init();
}
// /**
// * 响应逆地理编码
// */
// public void getAddress(final LatLonPoint latLonPoint) {
// RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200,
// GeocodeSearch.AMAP);//
// 第一个参数表示一个Latlng,第二参数表示范围多少米,第三个参数表示是火系坐标系还是GPS原生坐标系
// geocoderSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
// }
/**
* 初始化AMap对象
*/
private void init() {
if (aMap == null) {
aMap = mapView.getMap();
mUiSettings = aMap.getUiSettings();
mUiSettings.setZoomControlsEnabled(false);// 不显示zoom按钮
setUpMap();
}
}
// private void setUpMarket() {
// regeoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
// .icon(BitmapDescriptorFactory
// .defaultMarker(BitmapDescriptorFactory.HUE_RED)));
// }
/**
* 设置一些amap的属性
*/
private void setUpMap() {
// 自定义系统定位小蓝点
MyLocationStyle myLocationStyle = new MyLocationStyle();
myLocationStyle.myLocationIcon(BitmapDescriptorFactory
.fromResource(R.drawable.location_marker));// 设置小蓝点的图标
myLocationStyle.strokeColor(Color.TRANSPARENT);// 设置圆形的边框颜色
myLocationStyle.radiusFillColor(Color.TRANSPARENT);//
// 设置圆形的填充颜色
// myLocationStyle.anchor(1, 1);// 设置小蓝点的锚点
myLocationStyle.strokeWidth(0.0f);// 设置圆形的边框粗细
aMap.setMyLocationStyle(myLocationStyle);
aMap.setLocationSource(this);// 设置定位监听
aMap.setOnCameraChangeListener(this);// 对amap添加移动地图事件监听器
aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位,false表示隐藏定位层并不可触发定位,默认是false
// aMap.setMyLocationType()
aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
// 这里是地理位置搜索
// geocoderSearch = new GeocodeSearch(this);
// geocoderSearch.setOnGeocodeSearchListener(this);
}
/**
* 方法必须重写
*/
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
/**
* 方法必须重写
*/
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
deactivate();
}
/**
* 方法必须重写
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
/**
* 方法必须重写
*/
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
/**
* 定位成功后回调函数
*/
@Override
public void onLocationChanged(AMapLocation amapLocation) {
if (mListener != null && amapLocation != null) {
if (amapLocation != null && amapLocation.getErrorCode() == 0) {
mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
if (mlocationClient.isStarted()) {
mlocationClient.stopLocation();
}
LatLonPoint llp = new LatLonPoint(amapLocation.getLatitude(),
amapLocation.getLongitude());
// getAddress(llp);
querySreach(llp, amapLocation.getCity());
Log.e("AmapErr", "定位 " + amapLocation.getLongitude() + ": "
+ amapLocation.getLatitude());
} else {
String errText = "定位失败," + amapLocation.getErrorCode() + ": "
+ amapLocation.getErrorInfo();
Log.e("AmapErr", errText);
}
}
}
/**
* 激活定位
*/
@Override
public void activate(OnLocationChangedListener listener) {
Log.e("AmapErr", "activate OnLocationChangedListener");
mListener = listener;
if (mlocationClient == null) {
mlocationClient = new AMapLocationClient(this);
mLocationOption = new AMapLocationClientOption();
// 设置定位监听
mlocationClient.setLocationListener(this);
// 设置为高精度定位模式
mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
// 设置定位参数
mlocationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求,为了减少电量消耗或网络流量消耗,
// 注意设置合适的定位时间的间隔(最小间隔支持为2000ms),并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后,在合适的生命周期调用onDestroy()方法
// 在单次定位情况下,定位无论成功与否,都无需调用stopLocation()方法移除请求,定位sdk内部会移除
mlocationClient.startLocation();
}
}
/**
* 停止定位
*/
@Override
public void deactivate() {
mListener = null;
if (mlocationClient != null) {
mlocationClient.stopLocation();
mlocationClient.onDestroy();
}
mlocationClient = null;
}
@Override
public void onCameraChange(CameraPosition cameraPosition) {
// TODO Auto-generated method stub
}
@Override
public void onCameraChangeFinish(CameraPosition cameraPosition) {
LatLonPoint llp = new LatLonPoint(cameraPosition.target.latitude,
cameraPosition.target.longitude);
// getAddress(llp);
querySreach(llp, null);
}
// /**
// * marker点击时跳动一下
// */
// public void jumpPoint(final Marker marker) {
// final Handler handler = new Handler();
// final long start = SystemClock.uptimeMillis();
// Projection proj = aMap.getProjection();
// Point startPoint = proj.toScreenLocation(Constants.XIAN);
// startPoint.offset(0, -100);
// final LatLng startLatLng = proj.fromScreenLocation(startPoint);
// final long duration = 1500;
//
// final BounceInterpolator interpolator = new BounceInterpolator();
// handler.post(new Runnable() {
// @Override
// public void run() {
// long elapsed = SystemClock.uptimeMillis() - start;
// float t = interpolator.getInterpolation((float) elapsed
// / duration);
// double lng = t * Constants.XIAN.longitude + (1 - t)
// * startLatLng.longitude;
// double lat = t * Constants.XIAN.latitude + (1 - t)
// * startLatLng.latitude;
// marker.setPosition(new LatLng(lat, lng));
// if (t < 1.0) {
// handler.postDelayed(this, 16);
// }
// }
// });
// }
@Override
public void onGeocodeSearched(GeocodeResult arg0, int arg1) {
// ToastUtil.show(MoveLactionActivity.this, "onGeocodeSearched");
}
/**
* 这里是坐标转地名
*/
@Override
public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
if (rCode == 0) {
if (result != null && result.getRegeocodeAddress() != null
&& result.getRegeocodeAddress().getFormatAddress() != null) {
// aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
// AMapUtil.convertToLatLng(latLonPoint), 15));
// regeoMarker.setPosition(AMapUtil.convertToLatLng(latLonPoint));
// ToastUtil.show(MoveLactionActivity.this, result
// .getRegeocodeAddress().getFormatAddress());
} else {
// ToastUtil.show(MoveLactionActivity.this, R.string.no_result);
}
} else if (rCode == 27) {
// ToastUtil.show(MoveLactionActivity.this, R.string.error_network);
} else if (rCode == 32) {
// ToastUtil.show(MoveLactionActivity.this, R.string.error_key);
} else {
// ToastUtil.show(MoveLactionActivity.this,
// getString(R.string.error_other) + rCode);
}
}
private void querySreach(final LatLonPoint latLonPoint, final String city) {
query = new PoiSearch.Query("", "", null);// 第一个参数表示搜索字符串,第二个参数表示poi搜索类型,第三个参数表示poi搜索区域(空字符串代表全国)
query.setPageSize(10);// 设置每页最多返回多少条poiitem
query.setPageNum(0);// 设置查第一页
query.setLimitDiscount(false);
query.setLimitGroupbuy(false);
if (latLonPoint != null) {
poiSearch = new PoiSearch(this, query);
poiSearch.setOnPoiSearchListener(this);
poiSearch.setBound(new SearchBound(latLonPoint, 2000, true));//
// 设置搜索区域为以lp点为圆心,其周围2000米范围
/*
* List<LatLonPoint> list = new ArrayList<LatLonPoint>();
* list.add(lp);
* list.add(AMapUtil.convertToLatLonPoint(Constants.BEIJING));
* poiSearch.setBound(new SearchBound(list));// 设置多边形poi搜索范围
*/
poiSearch.searchPOIAsyn();// 异步搜索
}
}
@Override
public void onPoiSearched(PoiResult result, int rCode) {
if (rCode == 0) {
if (result != null && result.getQuery() != null) {// 搜索poi的结果
if (result.getQuery().equals(query)) {// 是否是同一条
PoiItem poiItem = null;
// 取得第一页的poiitem数据,页数从数字0开始
if (result.getPois() != null && result.getPois().size() > 0) {
lvList.setAdapter(getMenuAdapter(result.getPois()));
for (int i = 0; i < result.getPois().size(); i++) {
poiItem = result.getPois().get(i);
Log.e("AmapErr",
"poiItem is " + poiItem.toString());
}
}
}
} else {
}
}
}
private SimpleAdapter getMenuAdapter(ArrayList<PoiItem> itemArray) {
ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < itemArray.size(); i++) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("itemText", itemArray.get(i));
data.add(map);
}
SimpleAdapter simperAdapter = new SimpleAdapter(this, data,
R.layout.menu_item, new String[] { "itemText" },
new int[] { R.id.tvText });
return simperAdapter;
}
}
| true |
02060040ba9a75723b43e6c2f34e74570148d846 | Java | manassahoo-dev/job-portal | /backend/src/main/java/com/dbs/uwh/backend/service/JobService.java | UTF-8 | 3,271 | 2.359375 | 2 | [] | no_license | package com.dbs.uwh.backend.service;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dbs.uwh.backend.dao.JobDao;
import com.dbs.uwh.backend.dao.StudentJobDao;
import com.dbs.uwh.backend.model.Job;
import com.dbs.uwh.backend.model.StudentJob;
import com.dbs.uwh.backend.model.User;
import com.dbs.uwh.backend.model.constant.Status;
import com.dbs.uwh.backend.request.StudentJobRequest;
@Service
public class JobService extends GenericService<Job, Long> {
@Autowired
JobDao jobDao;
@Autowired
StudentJobDao studentJobDao;
public HashMap<String, Integer> JobStats() {
List<Job> jobs = jobDao.findAll();
HashMap<String, Integer> jobStats = new HashMap<String, Integer>();
int completed = 0;
int inProgress = 0;
for (Job job: jobs) {
if (job.getStatus() == Status.COMPLETED) {
completed++;
} else if (job.getStatus() == Status.INPROGRESS) {
inProgress++;
}
}
jobStats.put("total", jobs.size());
jobStats.put("Completed", completed);
jobStats.put("InProgress", inProgress);
return jobStats;
}
public List<Job> findByCategoryId(Long categoryId) {
return jobDao.findByCategories_categoryId(categoryId);
}
public void deleteById(Long id) {
jobDao.deleteJobCategory(id);
jobDao.deleteById(id);
}
@Transactional
public Job create(Job job) {
Job entity = jobDao.save(job);
Long categoryId = job.getCategoryId();
Long jobId = job.getId();
boolean isExists = jobDao.existsJobByCategories_categoryIdAndCategories_jobId(categoryId, jobId);
if (!isExists)
jobDao.saveJobCategory(categoryId, jobId);
return entity;
}
public void createStudentJobDetail(StudentJobRequest studentJobRequest) {
for (Long stId : studentJobRequest.getStudentIds()) {
Optional<StudentJob> studentJob = studentJobDao.getByStudentIdAndJobId(stId, studentJobRequest.getJobId());
StudentJob stJob = studentJob.orElseGet(StudentJob::new);
Job job = new Job();
job.setId(studentJobRequest.getJobId());
User user = new User();
user.setId(stId);
stJob.setJob(job);
stJob.setStudent(user);
if (studentJobRequest.getType().equalsIgnoreCase("applied")) {
stJob.setApplied(true);
stJob.setAppliedDate(LocalDate.now());
} else if (studentJobRequest.getType().equalsIgnoreCase("interviewed")) {
stJob.setApplied(true);
stJob.setInterviewed(true);
stJob.setInterviewedDate(LocalDate.now());
} else if (studentJobRequest.getType().equalsIgnoreCase("placed")) {
stJob.setApplied(true);
stJob.setInterviewed(true);
stJob.setPlaced(true);
stJob.setPlacedDate(LocalDate.now());
}
studentJobDao.save(stJob);
}
}
public List<Long> getJobStudentDetails(Long jobId, String type) {
if (type.equalsIgnoreCase("applied")) {
return jobDao.getStudentJobDetailByJobIdAndJobApplied(jobId);
} else if (type.equalsIgnoreCase("interviewed")) {
return jobDao.getStudentJobDetailByJobIdAndInterviewed(jobId);
} else if (type.equalsIgnoreCase("placed"))
{
return jobDao.getStudentJobDetailByJobIdAndPlaced(jobId);
}
return null;
}
}
| true |
252df19bec7e5d1f1be6ac2e026ce42a1ec7dc63 | Java | STAMP-project/dspot-experiments | /benchmark/test/org/apache/mahout/math/ssvd/SequentialOutOfCoreSvdTest.java | UTF-8 | 4,125 | 2.28125 | 2 | [] | no_license | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.mahout.math.ssvd;
import Functions.ABS;
import Functions.PLUS;
import com.google.common.collect.Lists;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.apache.mahout.common.MahoutTestCase;
import org.apache.mahout.math.Matrix;
import org.apache.mahout.math.SingularValueDecomposition;
import org.apache.mahout.math.Vector;
import org.junit.Test;
public final class SequentialOutOfCoreSvdTest extends MahoutTestCase {
private File tmpDir;
@Test
public void testSingularValues() throws IOException {
Matrix A = SequentialOutOfCoreSvdTest.lowRankMatrix(tmpDir, "A", 200, 970, 1020);
List<File> partsOfA = Arrays.asList(tmpDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File file, String fileName) {
return fileName.matches("A-.*");
}
}));
// rearrange A to make sure we don't depend on lexical ordering.
partsOfA = Lists.reverse(partsOfA);
SequentialOutOfCoreSvd s = new SequentialOutOfCoreSvd(partsOfA, tmpDir, 100, 210);
SequentialBigSvd svd = new SequentialBigSvd(A, 100);
Vector reference = viewPart(0, 6);
Vector actual = viewPart(0, 6);
SequentialOutOfCoreSvdTest.assertEquals(0, reference.minus(actual).maxValue(), 1.0E-9);
s.computeU(partsOfA, tmpDir);
Matrix u = SequentialOutOfCoreSvdTest.readBlockMatrix(Arrays.asList(tmpDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File file, String fileName) {
return fileName.matches("U-.*");
}
})));
s.computeV(tmpDir, A.columnSize());
Matrix v = SequentialOutOfCoreSvdTest.readBlockMatrix(Arrays.asList(tmpDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File file, String fileName) {
return fileName.matches("V-.*");
}
})));
// The values in A are pretty big so this is a pretty tight relative tolerance
SequentialOutOfCoreSvdTest.assertEquals(0, A.minus(u.times(new org.apache.mahout.math.DiagonalMatrix(s.getSingularValues())).times(v.transpose())).aggregate(PLUS, ABS), 1.0E-7);
}
@Test
public void testLeftVectors() throws IOException {
Matrix A = SequentialOutOfCoreSvdTest.lowRankMatrixInMemory(20, 20);
SequentialBigSvd s = new SequentialBigSvd(A, 6);
SingularValueDecomposition svd = new SingularValueDecomposition(A);
// can only check first few singular vectors
Matrix u1 = svd.getU().viewPart(0, 20, 0, 3).assign(ABS);
Matrix u2 = s.getU().viewPart(0, 20, 0, 3).assign(ABS);
SequentialOutOfCoreSvdTest.assertEquals(u1, u2);
}
@Test
public void testRightVectors() throws IOException {
Matrix A = SequentialOutOfCoreSvdTest.lowRankMatrixInMemory(20, 20);
SequentialBigSvd s = new SequentialBigSvd(A, 6);
SingularValueDecomposition svd = new SingularValueDecomposition(A);
Matrix v1 = svd.getV().viewPart(0, 20, 0, 3).assign(ABS);
Matrix v2 = s.getV().viewPart(0, 20, 0, 3).assign(ABS);
SequentialOutOfCoreSvdTest.assertEquals(v1, v2);
}
}
| true |
ec03b8d765223ea5d3d9bc2f40757e929c45a58a | Java | NEW-MIKE/JRecyclerView | /skeleton/src/main/java/com/jepack/skeleton/SkeletonUtil.java | UTF-8 | 2,687 | 2.0625 | 2 | [] | no_license | package com.jepack.skeleton;
import android.os.Bundle;
import android.support.annotation.IntDef;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.ethanhua.skeleton.R;
import com.ethanhua.skeleton.Skeleton;
import com.ethanhua.skeleton.SkeletonScreen;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* TODO Add class comments here.
* Created by zhanghaihai on 2018/6/5.
*/
public class SkeletonUtil {
public final static int IMG_TXT_LIST = 0;
public final static int IMG_LIST = 0;
@IntDef({IMG_TXT_LIST})
@Retention(RetentionPolicy.SOURCE)
public @interface SKELETON_TYPE{};
public static SkeletonScreen showSkeleton(View view, int type, RecyclerView.Adapter adapter){
switch (type){
case IMG_TXT_LIST:
return showImgListSkeleton(view, adapter);
}
return null;
}
public static SkeletonScreen showImgListSkeleton(View view, RecyclerView.Adapter adapter){
if(view instanceof RecyclerView) {
RecyclerView recyclerView = (RecyclerView) view;
recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext(), LinearLayoutManager.VERTICAL, false));
return Skeleton.bind(recyclerView)
.adapter(adapter)
.shimmer(true)
.angle(20)
.frozen(false)
.duration(1200)
.count(10)
.load(R.layout.item_skeleton_news)
.show(); //default count is 10
}else{
return null;
}
}
public static SkeletonScreen showListSkeleton(View view, RecyclerView.Adapter adapter, @LayoutRes int itemSkeleton, RecyclerView.LayoutManager layoutManager){
if(view instanceof RecyclerView) {
RecyclerView recyclerView = (RecyclerView) view;
recyclerView.setLayoutManager(layoutManager);
return Skeleton.bind(recyclerView)
.adapter(adapter)
.shimmer(true)
.angle(20)
.frozen(false)
.duration(1200)
.count(10)
.load(itemSkeleton)
.show(); //default count is 10
}else{
return null;
}
}
}
| true |
abf1560f23b6712a395450544240b848f14175c3 | Java | lvtraveler/tiny-tomcat | /simple-web-server/src/main/java/com/tinyseries/tinytomcat/Request.java | UTF-8 | 2,313 | 2.8125 | 3 | [] | no_license | package com.tinyseries.tinytomcat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* 表示请求值
*/
public class Request {
private InputStream input;
private String uri;
// private String request;
public Request(InputStream input) {
this.input = input;
}
public void parse() {
StringBuilder request = new StringBuilder(2048);
int i;
byte[] buffer = new byte[2048];
try {
i = input.read(buffer);
}
catch (IOException e) {
e.printStackTrace();
i = -1;
}
for (int j=0; j<i; j++) {
request.append((char) buffer[j]);
}
//错误的方法,会被read方法阻塞,等待未关闭的socket
/*StringBuffer request = new StringBuffer(2048);
int i;
byte[] buffer = new byte[2048];
try {
while((i = input.read(buffer))!=-1){
for (int j=0; j<i; j++) {
request.append((char) buffer[j]);
}
}
} catch (IOException e) {
e.printStackTrace();
}*/
System.out.println(request.toString());
// this.request=request.toString();
uri = parseUri(request.toString());
/* StringBuilder request = new StringBuilder(2048);
String line;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) {
while ((line=reader.readLine())!=null){
request.append(line);
request.append("\r\n");
System.out.println(line);
}
uri = parseUri(request.toString());
}catch (IOException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}*/
}
private String parseUri(String requestString) {
int index1, index2;
index1 = requestString.indexOf(' ');
if (index1 != -1) {
index2 = requestString.indexOf(' ', index1 + 1);
if (index2 > index1)
return requestString.substring(index1 + 1, index2);
}
return null;
}
public String getUri() {
return uri;
}
} | true |
f57620a289c5691bc851fb547382a618cc54d552 | Java | huynhhoangdong/IoT4U | /app/src/main/java/com/example/admin/iot4u/MQTT/ControlDevicePubSubActivity.java | UTF-8 | 4,408 | 1.789063 | 2 | [] | no_license | package com.example.admin.iot4u.MQTT;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.mobileconnectors.iot.AWSIotKeystoreHelper;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttClientStatusCallback;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttLastWillAndTestament;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttManager;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttNewMessageCallback;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttQos;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.iot.AWSIotClient;
import com.amazonaws.services.iot.model.AttachPrincipalPolicyRequest;
import com.amazonaws.services.iot.model.CreateKeysAndCertificateRequest;
import com.amazonaws.services.iot.model.CreateKeysAndCertificateResult;
import com.example.admin.iot4u.R;
import java.io.UnsupportedEncodingException;
import java.security.KeyStore;
public class ControlDevicePubSubActivity extends AppCompatActivity implements View.OnClickListener{
static final String LOG_TAG = ControlDevicePubSub.class.getCanonicalName();
private Button btnON;
private Button btnOFF;
private Button btnRED;
private Button btnGREEN;
private Button btnBLUE;
private ImageButton imgBtnOnOff;
private String messageAWS;
private TextView tvTest;
boolean onStatus = true;
private ControlDevicePubSub pubSubAWS;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.control_device_pubsub);
btnON = findViewById(R.id.btnON);
btnON.setOnClickListener(this);
btnOFF = findViewById(R.id.btnOFF);
btnOFF.setOnClickListener(this);
btnRED = findViewById(R.id.btnRED);
btnRED.setOnClickListener(this);
btnGREEN = findViewById(R.id.btnGREEN);
btnGREEN.setOnClickListener(this);
btnBLUE = findViewById(R.id.btnBLUE);
btnBLUE.setOnClickListener(this);
imgBtnOnOff = findViewById(R.id.imgBtnOnOff);
imgBtnOnOff.setOnClickListener(this);
tvTest = findViewById(R.id.tvTest);
//Get Data from DeviceListAdapter
Intent intent = getIntent();
String udid = intent.getStringExtra("UDID");
pubSubAWS = new ControlDevicePubSub(this,udid);
pubSubAWS.initialAWS();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnON:
messageAWS = "{\"FUNCTION\":\"ON\"}";
imgBtnOnOff.setImageResource(R.drawable.power_off_button);
break;
case R.id.btnOFF:
messageAWS = "{\"FUNCTION\":\"OFF\"}";
imgBtnOnOff.setImageResource(R.drawable.power_on_button);
break;
case R.id.btnRED:
messageAWS = "{\"FUNCTION\":\"RED\"}";
break;
case R.id.btnGREEN:
messageAWS = "{\"FUNCTION\":\"GREEN\"}";
break;
case R.id.btnBLUE:
messageAWS = "{\"FUNCTION\":\"BLUE\"}";
break;
case R.id.imgBtnOnOff:
if(onStatus) {
messageAWS = "{\"FUNCTION\":\"ON\"}";
imgBtnOnOff.setImageResource(R.drawable.power_off_button);
//Toast.makeText(this, "Image Click ON", Toast.LENGTH_SHORT).show();
onStatus = false;
} else {
messageAWS = "{\"FUNCTION\":\"OFF\"}";
imgBtnOnOff.setImageResource(R.drawable.power_on_button);
//Toast.makeText(this, "Image Click OFF", Toast.LENGTH_SHORT).show();
onStatus = true;
}
break;
}
try {
pubSubAWS.publishAWS(messageAWS);
} catch (Exception e) {
Log.e(LOG_TAG, "Publish error.", e);
}
}
}
| true |
f06e17d36edd6bfe89f509b841512203e61ee159 | Java | umanggoel/ds | /POC/src/com/company/arrays/FlowerBed.java | UTF-8 | 1,655 | 3.546875 | 4 | [] | no_license | package com.company.arrays;
public class FlowerBed {
public static void main(String[] args) {
FlowerBed flowerBed = new FlowerBed();
int a[] = {1,0,0,0,1};
System.out.println(flowerBed.canPlaceFlowers(a, 1));
}
// public boolean canPlaceFlowers(int[] f, int n) {
//
// int len = f.length;
// for(int i = 0 ;i<len;i++) {
// if(f[i] == 0){
// if(canplace(f, n, len, i)) return true;
// }
// }
//
// return false;
// }
//
// boolean canplace(int[] f, int n, int len, int start) {
// if(n == 0) return true;
//
// for(int i = start ;i<len;i++) {
// if(f[i] == 0 && issafe(f, i, len)) {
// f[i] = 1;
// if(canplace(f, n-1, len, i+1)) return true;
// f[i] = 0;
// }
// }
//
// return false;
//
// }
//
// boolean issafe(int[] f, int i, int len) {
// if(!(i-1 > 0 && f[i-1] == 0 || i-1< 0)) return false;
// if(!(i+1 < len && f[i+1] == 0 || i+1 >= len)) return false;
// return true;
// }
public boolean canPlaceFlowers(int[] f, int n) {
if(n == 0) return true;
int len = f.length;
int count = 0;
for(int i = 0 ;i<len;i++) {
if(f[i] == 0 && issafe(f,i, len)){
f[i] = 1;
count++;
}
}
return count >= n;
}
boolean issafe(int[] f, int i, int len) {
if(!(i-1 > 0 && f[i-1] == 0 || i-1< 0)) return false;
if(!(i+1 < len && f[i+1] == 0 || i+1 >= len)) return false;
return true;
}
}
| true |
97cfa115e8059f0f54f369792783e6573d8c6934 | Java | TheCallOfCthulhu/dark-sea | /WelcomeToRaptureCity/src/Randomek.java | UTF-8 | 310 | 3.09375 | 3 | [] | no_license | import java.util.Random;
public class Randomek {
public static void main(String[] args) {
Random rd = new Random ();
int gen1 = rd.nextInt(50); //Nahodne cisla od 0 - 50
int gen2 = rd.nextInt(50)+10; //Nahodne cisla od 10 - 60
System.out.println(gen1);
System.out.println(gen2);
}
}
| true |
a5c31db2b12b588f612fea9d1c02816df0e17784 | Java | elyas145/MagicRealm | /MagicRealm/src/lwjglview/graphics/LWJGLGraphics.java | UTF-8 | 21,721 | 1.921875 | 2 | [] | no_license | package lwjglview.graphics;
import lwjglview.graphics.shader.GLShaderHandler;
import lwjglview.graphics.shader.ShaderType;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import client.ControllerMain;
import config.GraphicsConfiguration;
import utils.handler.Handler;
import utils.math.Mathf;
import utils.math.linear.Matrix;
import utils.resources.ResourceHandler;
import view.selection.CursorListener;
import view.selection.CursorSelection;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL12.*;
import static org.lwjgl.opengl.GL13.*;
import static org.lwjgl.opengl.GL14.*;
import static org.lwjgl.opengl.GL30.*;
import static org.lwjgl.system.MemoryUtil.*;
public final class LWJGLGraphics {
public static final float FOV = Mathf.PI / 2;
public static final int LAYER0 = 0;
public static final int LAYER1 = LAYER0 + 1;
public static final int LAYER2 = LAYER1 + 1;
public static final int LAYER3 = LAYER2 + 1;
public static final int LAYER4 = LAYER3 + 1;
public static final int LAYER5 = LAYER4 + 1;
public static final int LAYER6 = LAYER5 + 1;
public static final int LAYER7 = LAYER6 + 1;
public static final int LAYER8 = LAYER7 + 1;
public static final int LAYER9 = LAYER8 + 1;
public static final int MAX_LAYERS = LAYER9 + 1;
public LWJGLGraphics(ResourceHandler rh) {
init(rh);
control = null;
}
public LWJGLGraphics(ResourceHandler rh, ControllerMain cm) {
init(rh);
control = cm;
}
public void enableDepth() {
glEnable(GL_DEPTH_TEST);
}
public void disableDepth() {
glDisable(GL_DEPTH_TEST);
}
public void setCursorListener(CursorListener listen) {
cursorListener = listen;
}
public void saveState(MVPState st) {
synchronized (state) {
state.copyTo(st);
}
}
public void loadState(MVPState st) {
synchronized (state) {
st.copyTo(state);
}
}
public GLPrimitives getPrimitiveTool() {
return primitives;
}
public void resetViewMatrix() {
synchronized (state) {
state.viewMatrix.identity();
updateViewMatrix();
}
}
public void rotateCameraX(float ang) {
synchronized (buffer) {
buffer.rotateX(ang);
applyCameraTransform(buffer);
}
}
public void rotateCameraY(float ang) {
synchronized (buffer) {
buffer.rotateY(ang);
applyCameraTransform(buffer);
}
}
public void rotateCameraZ(float ang) {
synchronized (buffer) {
buffer.rotateZ(ang);
applyCameraTransform(buffer);
}
}
public void translateCamera(float x, float y, float z) {
synchronized (buffer) {
buffer.translate(x, y, z);
applyCameraTransform(buffer);
}
}
public void applyCameraTransform(Matrix mat) {
synchronized (state) {
mat.multiply(state.viewMatrix, state.viewMatrix);
updateViewMatrix();
}
}
public void resetModelMatrix() {
synchronized (state) {
state.modelMatrix.identity();
updateModelViewMatrix();
}
}
public void rotateModelX(float ang) {
synchronized (buffer) {
buffer.rotateX(ang);
applyModelTransform(buffer);
}
}
public void rotateModelY(float ang) {
synchronized (buffer) {
buffer.rotateY(ang);
applyModelTransform(buffer);
}
}
public void rotateModelZ(float ang) {
synchronized (buffer) {
buffer.rotateZ(ang);
applyModelTransform(buffer);
}
}
public void scaleModel(float f) {
synchronized (buffer) {
buffer.scale(f, f, f, 1f);
applyModelTransform(buffer);
}
}
public void translateModel(float x, float y, float z) {
synchronized (buffer) {
buffer.translate(x, y, z);
applyModelTransform(buffer);
}
}
public void applyModelTransform(Matrix mat) {
synchronized (state) {
mat.multiply(state.modelMatrix, state.modelMatrix);
updateModelViewMatrix();
}
}
public void getPixel(int x, int y, ByteBuffer buff) {
glReadPixels(x, height - y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, buff);
}
public int createFrameBuffer() {
return createFrameBuffer(FOV);
}
public int createFrameBuffer(float fov) {
return createFrameBuffer(width, height, fov);
}
public int createFrameBuffer(int width, int height) {
return createFrameBuffer(width, height, FOV);
}
public int createFrameBuffer(int width, int height, float fov) {
int buff = glGenFramebuffers();
frameBuffers.put(buff, new FrameBufferInfo(width, height, fov));
return buff;
}
public void bindFrameBuffer(int fb) {
glBindFramebuffer(GL_FRAMEBUFFER, fb);
}
public void bindMainBuffer() {
bindFrameBuffer(0);
}
public void useFrameBuffer(int fb) {
bindFrameBuffer(fb);
FrameBufferInfo info = frameBuffers.get(fb);
onResize(info.width, info.height, info.fov);
}
public void releaseFrameBuffer() {
useFrameBuffer(0);
}
public void bindFrameBufferTexture(int fb, int texID) {
bindFrameBuffer(fb);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, texID, 0);
int depth = glGenRenderbuffers();
glBindRenderbuffer(GL_RENDERBUFFER, depth);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width,
height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER, depth);
releaseFrameBuffer();
}
public int generateBufferTexture(int buff) {
FrameBufferInfo fbi = frameBuffers.get(buff);
int id = createTexture(fbi.width, fbi.height, false);
bindFrameBufferTexture(buff, id);
return id;
}
public int createTexture(int width, int height, boolean accurate) {
return loadTexture(null, height, width, accurate);
}
public void setClearColor(float r, float g, float b, float a) {
glClearColor(r, g, b, a);
}
public int loadTexture(ByteBuffer rawData, int height, int width,
boolean accurate) {
int texID = glGenTextures();
glBindTexture(GL_TEXTURE_2D, texID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
accurate ? GL_LINEAR : GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
accurate ? GL_LINEAR : GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA,
GL_UNSIGNED_BYTE, rawData);
return texID;
}
public void updateTexture(int location, ByteBuffer rawData, int height,
int width) {
bindTexture(location);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA,
GL_UNSIGNED_BYTE, rawData);
}
public int loadTextureArray(ByteBuffer rawData, int number, int height,
int width, boolean accurate) {
int texID = glGenTextures();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D_ARRAY, texID);
glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGB8, width, height, number, 0,
GL_RGBA, GL_UNSIGNED_BYTE, rawData);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER,
accurate ? GL_LINEAR : GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER,
accurate ? GL_LINEAR : GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S,
GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T,
GL_CLAMP_TO_EDGE);
return texID;
}
public void bindTextureArray(int location) {
bindTextureArray(location, 0);
}
public void bindTextureArray(int location, int unit) {
glActiveTexture(GL_TEXTURE0 + unit);
glBindTexture(GL_TEXTURE_2D_ARRAY, location);
}
public void bindTexture(int location) {
bindTexture(location, 0);
}
public void bindTexture(int location, int unit) {
glActiveTexture(GL_TEXTURE0 + unit);
glBindTexture(GL_TEXTURE_2D, location);
}
public GLShaderHandler getShaders() {
return shaders;
}
public void updateModelUniform(String name) {
updateModelUniform(getShaders().getType(), name);
}
public void updateModelUniform(ShaderType st, String name) {
getShaders().setUniformMatrixValue(st, name, state.modelMatrix);
}
public void updateViewUniform(String name) {
updateViewUniform(getShaders().getType(), name);
}
public void updateViewUniform(ShaderType st, String name) {
shaders.setUniformMatrixValue(st, name, state.viewInverseMatrix);
}
public void updateModelViewUniform(String name) {
updateModelViewUniform(getShaders().getType(), name);
}
public void updateModelViewUniform(ShaderType st, String name) {
shaders.setUniformMatrixValue(st, name, state.modelViewMatrix);
}
public void updateProjectionUniform(String name) {
updateProjectionUniform(getShaders().getType(), name);
}
public void updateProjectionUniform(ShaderType st, String name) {
shaders.setUniformMatrixValue(st, name, state.viewInverseMatrix);
}
public void updateMVPUniform(String name) {
updateMVPUniform(getShaders().getType(), name);
}
public void updateMVPUniform(ShaderType st, String name) {
shaders.setUniformMatrixValue(st, name, state.modelViewProjectionMatrix);
}
public float getAspectRatio() {
return width / (float) height;
}
public void callList(int lst) {
glCallList(lst);
}
public int startList() {
int lst = glGenLists(1);
glNewList(lst, GL_COMPILE);
return lst;
}
public int startQuadList() {
int lst = startList();
startQuads();
return lst;
}
public int startTriangleList() {
int lst = startList();
startTriangles();
return lst;
}
public void startTriangles() {
glBegin(GL_TRIANGLES);
}
public void startQuads() {
glBegin(GL_QUADS);
}
public void endPrimitives() {
glEnd();
}
public void endList() {
endPrimitives();
glEndList();
}
public void setVertex(int vertLen, FloatBuffer verts) {
switch (vertLen) {
case 1:
glVertex2f(verts.get(0), 0f);
break;
case 2:
glVertex2f(verts.get(0), verts.get(1));
break;
case 3:
glVertex3f(verts.get(0), verts.get(1), verts.get(2));
break;
case 4:
glVertex4f(verts.get(0), verts.get(1), verts.get(2), verts.get(3));
break;
}
}
public void setTextureCoordinate(int texLen, FloatBuffer texCoord) {
switch (texLen) {
case 1:
glTexCoord1f(texCoord.get(0));
break;
case 2:
glTexCoord2f(texCoord.get(0), texCoord.get(1));
break;
case 3:
glTexCoord3f(texCoord.get(0), texCoord.get(1), texCoord.get(2));
break;
case 4:
glTexCoord4f(texCoord.get(0), texCoord.get(1), texCoord.get(2),
texCoord.get(3));
break;
}
}
public void setNormal(int normLen, FloatBuffer normal) {
switch (normLen) {
case 1:
glNormal3f(normal.get(0), 0f, 0f);
break;
case 2:
glNormal3f(normal.get(0), normal.get(1), 0f);
break;
case 3:
glNormal3f(normal.get(0), normal.get(1), normal.get(2));
break;
}
}
public void start() {
running = true;
runThread.start();
}
public void stop() {
running = false;
if (runThread != null) {
try {
runThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void prepareLayer(Handler<LWJGLGraphics> handle, int layer) {
checkLayer(layer);
drawables[layer].addPreparation(handle);
}
public void finishLayer(Handler<LWJGLGraphics> handle, int layer) {
checkLayer(layer);
drawables[layer].addFinalization(handle);
}
public void enableLayerDepth(int layer) {
checkLayer(layer);
drawables[layer].addPreparation(new Handler<LWJGLGraphics>() {
@Override
public void handle(LWJGLGraphics gfx) {
gfx.enableDepth();
}
});
}
public void disableLayerDepth(int layer) {
checkLayer(layer);
drawables[layer].addPreparation(new Handler<LWJGLGraphics>() {
@Override
public void handle(LWJGLGraphics gfx) {
gfx.disableDepth();
}
});
}
public void clearLayerDepth(int layer) {
checkLayer(layer);
drawables[layer].addPreparation(new Handler<LWJGLGraphics>() {
@Override
public void handle(LWJGLGraphics graphics) {
graphics.clearDepthBuffer();
}
});
}
public void addDrawable(LWJGLDrawable dr) {
addDrawable(dr, LAYER0);
}
public void addDrawable(LWJGLDrawable dr, int layer) {
checkLayer(layer);
drawables[layer].addDrawable((LWJGLDrawable) dr);
}
public void removeDrawable(LWJGLDrawable dr, int layer) {
checkLayer(layer);
drawables[layer].removeDrawable(dr);
}
public void addAllDrawables(Iterable<? extends LWJGLDrawable> drbls) {
for (LWJGLDrawable dr : drbls) {
addDrawable(dr);
}
}
public void addAllDrawables(Iterable<? extends LWJGLDrawable> drbls,
int layer) {
for (LWJGLDrawable dr : drbls) {
addDrawable(dr, layer);
}
}
public void clearColourBuffer() {
glClear(GL_COLOR_BUFFER_BIT);
}
public void clearDepthBuffer() {
glClear(GL_DEPTH_BUFFER_BIT);
}
public void clearActiveBuffers() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
private void init(ResourceHandler rh) {
self = this;
primitives = new GLPrimitives(this);
state = new MVPState();
updateViewMatrix();
drawables = new LayerStorage[MAX_LAYERS];
for (int i = 0; i < drawables.length; ++i) {
drawables[i] = new LayerStorage();
}
shaders = new GLShaderHandler(rh);
width = GraphicsConfiguration.INITIAL_WINDOW_WIDTH;
height = GraphicsConfiguration.INITIAL_WINDOW_HEIGHT;
runThread = new Thread(new Runnable() {
@Override
public void run() {
initGL();
mainLoop();
}
});
buffer = Matrix.identity(4);
frameBuffers = new HashMap<Integer, FrameBufferInfo>();
}
private void checkLayer(int layer) {
if (layer < 0 || layer >= MAX_LAYERS) {
throw new RuntimeException("The provided layer " + layer
+ " excedes the maximum number of layers " + MAX_LAYERS);
}
}
private void initGL() {
errorCallback = errorCallbackPrint(System.err);
glfwSetErrorCallback(errorCallback);
if (glfwInit() != GL_TRUE) {
throw new IllegalStateException("Unable to initialize GLFW");
}
glfwDefaultWindowHints(); // optional, the current window hints are
// already the default
glfwWindowHint(GLFW_VISIBLE, GL_FALSE); // the window will stay hidden
// after creation
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); // the window will be resizable
// Get the resolution of the primary monitor
ByteBuffer vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
// Create the window
width = GLFWvidmode.width(vidmode);
height = GLFWvidmode.height(vidmode);
frameBuffers.put(0, new FrameBufferInfo(width, height, FOV));
window = glfwCreateWindow(width, height, "LWJGLGraphics",
glfwGetPrimaryMonitor(), NULL);
if (window == NULL)
throw new RuntimeException("Failed to create the GLFW window");
// Setup a key callback. It will be called every time a key is pressed,
// repeated or released.
keyCallback = new GLFWKeyCallback() {
@Override
public void invoke(long window, int key, int scancode, int action,
int mods) {
//if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
}
};
glfwSetKeyCallback(window, keyCallback);
windowSizeCallback = new GLFWWindowSizeCallback() {
@Override
public void invoke(long window, int width, int height) {
onResize(width, height, FOV);
}
};
glfwSetWindowSizeCallback(window, windowSizeCallback);
windowCloseCallback = new GLFWWindowCloseCallback() {
@Override
public void invoke(long window) {
exit();
}
};
glfwSetWindowCloseCallback(window, windowCloseCallback);
mousePositionCallback = new GLFWCursorPosCallback() {
@Override
public void invoke(long window, double xpos, double ypos) {
if (cursorListener != null) {
cursorListener.onMove((int) xpos, (int) ypos);
}
}
};
glfwSetCursorPosCallback(window, mousePositionCallback);
mouseClickCallback = new GLFWMouseButtonCallback() {
@Override
public void invoke(long window, int button, int action, int mods) {
if (cursorListener != null) {
CursorSelection butt;
if (button == GLFW_MOUSE_BUTTON_LEFT
|| button == GLFW_MOUSE_BUTTON_RIGHT) {
if (button == GLFW_MOUSE_BUTTON_LEFT) {
butt = CursorSelection.PRIMARY;
} else {
butt = CursorSelection.SECONDARY;
}
cursorListener.onSelection(butt, action == GLFW_PRESS);
}
}
}
};
glfwSetMouseButtonCallback(window, mouseClickCallback);
// Make the OpenGL context current
glfwMakeContextCurrent(window);
// Enable v-sync
glfwSwapInterval(0);
GLContext.createFromCurrent();
glEnable(GL_TEXTURE_2D);
glEnable(GL_TEXTURE_2D_ARRAY);
glEnable(GL_TEXTURE_3D);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Make the window visible
glfwShowWindow(window);
onResize(width, height, FOV);
// Set the clear color
setClearColor(.1f, .2f, 1f, 0f);
System.out.println("Loading shaders");
GLShaderHandler shaders = getShaders();
try {
synchronized (shaders) {
for (ShaderType st : ShaderType.values()) {
shaders.loadShaderProgram(st);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("Done loading shaders");
}
private void exit() {
if (control != null) {
control.exit();
glfwSetWindowShouldClose(window, GL_FALSE);
} else {
running = false;
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
private void updateMVP() {
state.projectionMatrix.multiply(state.modelViewMatrix,
state.modelViewProjectionMatrix);
}
private void updateViewMatrix() {
state.viewMatrix.inverse(state.viewInverseMatrix);
updateModelViewMatrix();
}
private void updateModelViewMatrix() {
state.viewInverseMatrix.multiply(state.modelMatrix,
state.modelViewMatrix);
updateMVP();
}
private void onResize(int w, int h, float fov) {
width = w;
height = h;
glViewport(0, 0, width, height);
float ar = getAspectRatio();
synchronized (state) {
state.projectionMatrix.perspective(fov, ar, .1f, 10f);
updateMVP();
}
}
private void drawAll() {
for (LayerStorage layer : drawables) {
layer.draw();
}
}
private void mainLoop() {
while (running && glfwWindowShouldClose(window) == GL_FALSE) {
drawAll();
glfwSwapBuffers(window); // swap the color buffers
// Poll for window events. The key callback above will only be
// invoked during this call.
glfwPollEvents();
}
running = false;
}
public class MVPState {
public MVPState() {
projectionMatrix = Matrix.identity(4);
viewMatrix = Matrix.identity(4);
viewInverseMatrix = Matrix.identity(4);
modelMatrix = Matrix.identity(4);
modelViewMatrix = Matrix.identity(4);
modelViewProjectionMatrix = Matrix.identity(4);
}
public void copyTo(MVPState state) {
state.projectionMatrix.copyFrom(projectionMatrix);
state.viewMatrix.copyFrom(viewMatrix);
state.viewInverseMatrix.copyFrom(viewInverseMatrix);
state.modelMatrix.copyFrom(modelMatrix);
state.modelViewMatrix.copyFrom(modelViewMatrix);
state.modelViewProjectionMatrix.copyFrom(modelViewProjectionMatrix);
}
public String toString() {
return "Projection: " + projectionMatrix + "\n" + "View: "
+ viewMatrix + "\n" + "View inverse: " + viewInverseMatrix
+ "\n" + "Model: " + modelMatrix + "\n" + "ModelView: "
+ modelViewMatrix + "\n" + "MVP: "
+ modelViewProjectionMatrix;
}
protected Matrix projectionMatrix;
protected Matrix viewMatrix;
protected Matrix viewInverseMatrix;
protected Matrix modelMatrix;
protected Matrix modelViewMatrix;
protected Matrix modelViewProjectionMatrix;
}
private class LayerStorage {
private Set<LWJGLDrawable> drawables;
private List<Handler<LWJGLGraphics>> prepare;
private List<Handler<LWJGLGraphics>> finalize;
public LayerStorage() {
drawables = new HashSet<LWJGLDrawable>();
prepare = new ArrayList<Handler<LWJGLGraphics>>();
finalize = new ArrayList<Handler<LWJGLGraphics>>();
}
public void addFinalization(Handler<LWJGLGraphics> fin) {
synchronized (finalize) {
finalize.add(fin);
}
}
public void addPreparation(Handler<LWJGLGraphics> prep) {
synchronized (prepare) {
prepare.add(prep);
}
}
public void addDrawable(LWJGLDrawable drble) {
synchronized (drawables) {
drawables.add(drble);
}
}
public void removeDrawable(LWJGLDrawable drble) {
synchronized (drawables) {
drawables.remove(drble);
}
}
public void draw() {
synchronized (prepare) {
for (Handler<LWJGLGraphics> prep : prepare) {
prep.handle(self);
}
}
synchronized (drawables) {
for (LWJGLDrawable drble : drawables) {
drble.draw(self);
}
}
synchronized (finalize) {
for (Handler<LWJGLGraphics> fin : finalize) {
fin.handle(self);
}
}
}
}
private static class FrameBufferInfo {
public FrameBufferInfo(int w, int h, float fv) {
width = w;
height = h;
fov = fv;
}
public int width, height;
public float fov;
}
private LWJGLGraphics self;
private boolean running;
private GLPrimitives primitives;
private MVPState state;
private int width;
private int height;
private LayerStorage[] drawables;
private long window;
private GLShaderHandler shaders;
private GLFWErrorCallback errorCallback;
private GLFWKeyCallback keyCallback;
private GLFWWindowSizeCallback windowSizeCallback;
private GLFWWindowCloseCallback windowCloseCallback;
private GLFWCursorPosCallback mousePositionCallback;
private GLFWMouseButtonCallback mouseClickCallback;
private Map<Integer, FrameBufferInfo> frameBuffers;
private CursorListener cursorListener;
private ControllerMain control;
private Thread runThread;
private Matrix buffer;
}
| true |